diff --git a/assets/Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js b/assets/Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js similarity index 90% rename from assets/Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js rename to assets/Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js index 0d331708676ac47d843205a14ce6157263f47fd4..40f4550daf655c5df3442b31eeafabe22ddea21f 100644 --- a/assets/Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js +++ b/assets/Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js @@ -1 +1 @@ -import{d,m as c,u as f,r as s,v,x as p,y as x,o as y,c as h,z as _}from"./index-BQKiy4UR.js";const w=d({__name:"Basic",props:{modelValue:{default:""},modelModifiers:{}},emits:c(["submit"],["update:modelValue"]),setup(n,{emit:u}){const r=u,e=f(n,"modelValue"),a=s(),o=s("auto");function i(t){t.code==="Enter"&&!t.shiftKey&&(t.preventDefault(),r("submit",e.value))}return v(e,()=>{o.value="auto",requestAnimationFrame(()=>{a.value&&(o.value=`${a.value.scrollHeight}px`)})},{immediate:!0}),(t,l)=>p((y(),h("textarea",{ref_key:"textareaRef",ref:a,"onUpdate:modelValue":l[0]||(l[0]=m=>e.value=m),style:_({height:o.value}),onKeydown:i},null,36)),[[x,e.value]])}});export{w as _}; +import{d,m as c,u as f,r as s,v,x as p,y as x,o as y,c as h,z as _}from"./index-CQudhZin.js";const w=d({__name:"Basic",props:{modelValue:{default:""},modelModifiers:{}},emits:c(["submit"],["update:modelValue"]),setup(n,{emit:u}){const r=u,e=f(n,"modelValue"),a=s(),o=s("auto");function i(t){t.code==="Enter"&&!t.shiftKey&&(t.preventDefault(),r("submit",e.value))}return v(e,()=>{o.value="auto",requestAnimationFrame(()=>{a.value&&(o.value=`${a.value.scrollHeight}px`)})},{immediate:!0}),(t,l)=>p((y(),h("textarea",{ref_key:"textareaRef",ref:a,"onUpdate:modelValue":l[0]||(l[0]=m=>e.value=m),style:_({height:o.value}),onKeydown:i},null,36)),[[x,e.value]])}});export{w as _}; diff --git a/assets/CardDetailDialog-DUkJNKcl.js b/assets/CardDetailDialog-DUkJNKcl.js new file mode 100644 index 0000000000000000000000000000000000000000..31ac811e72f1d659c5c570f763243a22cce48d96 --- /dev/null +++ b/assets/CardDetailDialog-DUkJNKcl.js @@ -0,0 +1 @@ +import{_ as o}from"./CardDetailDialog.vue_vue_type_script_setup_true_lang-BN5mx1Hz.js";import"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js";import"./index-CQudhZin.js";import"./index-CAP_srMr.js";import"./floating-ui.core-CgBsuaUc.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./airi-card-Bpd1towy.js";import"./mini_xsschema-P_8cZcRg.js";import"./consciousness-BmgC4h1A.js";import"./providers-Y3Mr8_DF.js";import"./index-LHmcipjy.js";import"./speech-nVAae-rt.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";export{o as default}; diff --git a/assets/CardDetailDialog-HhbPTSqa.js b/assets/CardDetailDialog-HhbPTSqa.js deleted file mode 100644 index a45124b7631af184ff86d98e17ff67d7bf25b882..0000000000000000000000000000000000000000 --- a/assets/CardDetailDialog-HhbPTSqa.js +++ /dev/null @@ -1 +0,0 @@ -import{_ as o}from"./CardDetailDialog.vue_vue_type_script_setup_true_lang-CmdVZPFO.js";import"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js";import"./index-BQKiy4UR.js";import"./index-D1N6XcGk.js";import"./floating-ui.core-CgBsuaUc.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./airi-card-BqSQR9SZ.js";import"./mini_xsschema-P_8cZcRg.js";import"./consciousness-DS3QILRV.js";import"./providers-kjOpfeNb.js";import"./index-LHmcipjy.js";import"./speech-Db_L6FBm.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";export{o as default}; diff --git a/assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-CmdVZPFO.js b/assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-BN5mx1Hz.js similarity index 95% rename from assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-CmdVZPFO.js rename to assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-BN5mx1Hz.js index 9789c4f4f5eef5a9c93f1de7ac86a6b8cb967032..d6195aeb3297f7f0afd3be18a774806a6d7560e7 100644 --- a/assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-CmdVZPFO.js +++ b/assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-BN5mx1Hz.js @@ -1 +1 @@ -import{_ as O,a as E}from"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as F,g as U,s as q,h as x,r as L,c as l,o as n,F as f,i as m,b as o,w as k,e,j as v,k as u,t as i,n as $,l as D}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import{u as R}from"./airi-card-BqSQR9SZ.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import"./mini_xsschema-P_8cZcRg.js";import{n as G,I as J,$ as K,P as Q,B as W}from"./index-D1N6XcGk.js";const X={key:0,class:"w-full flex flex-col gap-5"},Y={flex:"~ col","gap-3":""},Z={flex:"~ row","items-center":"","justify-between":""},ee={flex:"~ row","items-center":"","gap-2":""},te={key:0,class:"flex items-center gap-1 rounded-full bg-primary-100 px-2 py-0.5 text-xs text-primary-600 font-medium dark:bg-primary-900/40 dark:text-primary-400"},ae={"mt-1":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},re={"font-medium":""},se={flex:"~ row","gap-2":""},oe={class:"mt-4"},le={class:"border-b border-neutral-200 dark:border-neutral-700"},ne={class:"flex justify-center -mb-px sm:justify-start space-x-1"},ie=["onClick"],de={class:"flex items-center gap-1"},ue={key:0},ce=["innerHTML"],me={key:1},ve=["innerHTML"],pe={key:2},ge={flex:"~ col","max-h-60":"","gap-4":"","overflow-auto":"","pr-1":"","sm:max-h-80":""},xe={key:0,flex:"~ col","gap-2":""},be={"text-lg":"","text-neutral-500":"","font-medium":"","dark:text-neutral-400":""},fe=["innerHTML"],he={key:3},_e={grid:"~ cols-1 sm:cols-3","gap-4":""},ke={flex:"~ col",bg:"white/60 dark:black/30","gap-1":"","rounded-lg":"","p-3":"",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40"},we={flex:"~ row","items-center":"","gap-2":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},ye={truncate:"","font-medium":""},Ce={flex:"~ col",bg:"white/60 dark:black/30","gap-2":"","rounded-lg":"","p-3":"",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40"},Ie={flex:"~ row","items-center":"","gap-2":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},Te={truncate:"","font-medium":""},Ve={flex:"~ col",bg:"white/60 dark:black/30","gap-2":"","rounded-lg":"","p-3":"",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40"},He={flex:"~ row","items-center":"","gap-2":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},Le={truncate:"","font-medium":""},$e={key:1,bg:"neutral-50/50 dark:neutral-900/50","rounded-xl":"","p-8":"","text-center":"",border:"~ neutral-200/50 dark:neutral-700/30",shadow:"sm"},Oe=F({__name:"CardDetailDialog",props:{modelValue:{type:Boolean},cardId:null},emits:["update:modelValue"],setup(j,{emit:A}){const b=j,B=A,{t:d}=U(),w=R(),{removeCard:N}=w,{activeCardId:M}=q(w),a=x(()=>{if(b.cardId)return w.getCard(b.cardId)}),y=x(()=>{var t,c,r,g,S;if(!a.value||!((c=(t=a.value.extensions)==null?void 0:t.airi)!=null&&c.modules))return{consciousness:"",speech:"",voice:""};const s=a.value.extensions.airi.modules;return{consciousness:((r=s.consciousness)==null?void 0:r.model)||"",speech:((g=s.speech)==null?void 0:g.model)||"",voice:((S=s.speech)==null?void 0:S.voice_id)||""}}),C=x(()=>a.value?{personality:a.value.personality,scenario:a.value.scenario,systemPrompt:a.value.systemPrompt,postHistoryInstructions:a.value.postHistoryInstructions}:{}),h=x(()=>b.cardId===M.value),I=L(!1);function P(){I.value=!0,setTimeout(()=>{M.value=b.cardId,I.value=!1},300)}function T(s){return s==null?void 0:s.replace(/\{\{(.*?)\}\}/g,'{{ $1 }}').trim()}const _=L(!1);function z(){a.value&&(N(b.cardId),B("update:modelValue",!1)),_.value=!1}const V=L(""),H=x(()=>{var t,c;const s=[];return(t=a.value)!=null&&t.description&&s.push({id:"description",label:d("settings.pages.card.description_label"),icon:"i-solar:document-text-linear"}),(c=a.value)!=null&&c.notes&&s.push({id:"notes",label:d("settings.pages.card.creator_notes"),icon:"i-solar:notes-linear"}),Object.values(C.value).some(r=>!!r)&&s.push({id:"character",label:d("settings.pages.card.character"),icon:"i-solar:user-rounded-linear"}),s.push({id:"modules",label:d("settings.pages.card.modules"),icon:"i-solar:tuning-square-linear"}),s}),p=x({get:()=>{var s;return H.value.find(t=>t.id===V.value)?V.value:((s=H.value[0])==null?void 0:s.id)||""},set:s=>{V.value=s}});return(s,t)=>{var c;return n(),l(f,null,[m(o(G),{open:j.modelValue,"onUpdate:open":t[0]||(t[0]=r=>B("update:modelValue",r))},{default:k(()=>[m(o(J),null,{default:k(()=>[m(o(K),{class:"data-[state=open]:animate-fadeIn data-[state=closed]:animate-fadeOut fixed inset-0 z-100 bg-black/50 backdrop-blur-sm"}),m(o(Q),{class:"data-[state=open]:animate-contentShow data-[state=closed]:animate-contentHide fixed left-1/2 top-1/2 z-100 m-0 max-h-[90vh] max-w-6xl w-[92vw] flex flex-col overflow-auto border border-neutral-200 rounded-xl bg-white p-5 shadow-xl 2xl:w-[60vw] lg:w-[80vw] md:w-[85vw] xl:w-[70vw] -translate-x-1/2 -translate-y-1/2 dark:border-neutral-700 dark:bg-neutral-800 sm:p-6"},{default:k(()=>[a.value?(n(),l("div",X,[e("div",Y,[e("div",Z,[e("div",null,[e("div",ee,[m(o(W),{"text-2xl":"","font-bold":"",class:"from-primary-500 to-primary-400 bg-gradient-to-r bg-clip-text text-transparent"},{default:k(()=>[u(i(a.value.name),1)]),_:1}),h.value?(n(),l("div",te,[t[3]||(t[3]=e("div",{"i-solar:check-circle-bold-duotone":"","text-xs":""},null,-1)),u(" "+i(o(d)("settings.pages.card.active_badge")),1)])):v("",!0)]),e("div",ae,[u(" v"+i(a.value.version)+" ",1),a.value.creator?(n(),l(f,{key:0},[u(" · "+i(o(d)("settings.pages.card.created_by"))+" ",1),e("span",re,i(a.value.creator),1)],64)):v("",!0)])]),e("div",se,[m(o(O),{variant:"primary",icon:h.value?"i-solar:check-circle-bold-duotone":"i-solar:play-circle-broken",label:h.value?o(d)("settings.pages.card.active"):o(d)("settings.pages.card.activate"),disabled:h.value,class:$({"animate-pulse":I.value}),onClick:P},null,8,["icon","label","disabled","class"])])]),e("div",oe,[e("div",le,[e("div",ne,[(n(!0),l(f,null,D(H.value,r=>(n(),l("button",{key:r.id,class:$(["px-4 py-2 text-sm font-medium",[p.value===r.id?"text-primary-600 dark:text-primary-400 border-b-2 border-primary-500 dark:border-primary-400":"text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300"]]),onClick:g=>p.value=r.id},[e("div",de,[e("div",{class:$(r.icon)},null,2),u(" "+i(r.label),1)])],10,ie))),128))])])]),p.value==="notes"&&a.value.notes?(n(),l("div",ue,[e("div",{bg:"white/60 dark:black/30",border:"~ neutral-200/50 dark:neutral-700/30","max-h-60":"","overflow-auto":"","whitespace-pre-line":"","rounded-lg":"","p-4":"","text-neutral-700":"","sm:max-h-80":"","dark:text-neutral-300":"",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40",innerHTML:T(a.value.notes)},null,8,ce)])):v("",!0),p.value==="description"&&a.value.description?(n(),l("div",me,[e("div",{bg:"white/60 dark:black/30","max-h-60":"","overflow-auto":"","whitespace-pre-line":"","rounded-lg":"","p-4":"","sm:max-h-80":"",text:"neutral-600 dark:neutral-300",border:"~ neutral-200/50 dark:neutral-700/30",innerHTML:T(a.value.description)},null,8,ve)])):v("",!0),p.value==="character"&&Object.values(C.value).some(r=>!!r)?(n(),l("div",pe,[e("div",ge,[(n(!0),l(f,null,D(C.value,(r,g)=>(n(),l(f,{key:g},[r?(n(),l("div",xe,[e("h2",be,i(o(d)(`settings.pages.card.${g.toLowerCase()}`)),1),e("div",{bg:"white/60 dark:black/30",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40","max-h-none":"","overflow-auto":"","whitespace-pre-line":"","rounded-lg":"","p-3":"","text-neutral-700":"","dark:text-neutral-300":"",innerHTML:T(r)},null,8,fe)])):v("",!0)],64))),128))])])):v("",!0),p.value==="modules"?(n(),l("div",he,[e("div",_e,[e("div",ke,[e("span",we,[t[4]||(t[4]=e("div",{"i-lucide:ghost":""},null,-1)),u(" "+i(o(d)("settings.pages.card.consciousness.model")),1)]),e("div",ye,i(y.value.consciousness??"default"),1)]),e("div",Ce,[e("span",Ie,[t[5]||(t[5]=e("div",{"i-lucide:mic":""},null,-1)),u(" "+i(o(d)("settings.pages.card.speech.model")),1)]),e("div",Te,i(y.value.speech??"default"),1)]),e("div",Ve,[e("span",He,[t[6]||(t[6]=e("div",{"i-lucide:music":""},null,-1)),u(" "+i(o(d)("settings.pages.card.speech.voice")),1)]),e("div",Le,i(y.value.voice??"default"),1)])])])):v("",!0)])])):(n(),l("div",$e,[t[7]||(t[7]=e("div",{"i-solar:card-search-broken":"","mx-auto":"","mb-3":"","text-6xl":"","text-neutral-400":""},null,-1)),u(" "+i(o(d)("settings.pages.card.card_not_found")),1)]))]),_:1})]),_:1})]),_:1},8,["open"]),m(E,{modelValue:_.value,"onUpdate:modelValue":t[1]||(t[1]=r=>_.value=r),"card-name":(c=a.value)==null?void 0:c.name,onConfirm:z,onCancel:t[2]||(t[2]=r=>_.value=!1)},null,8,["modelValue","card-name"])],64)}}});export{Oe as _}; +import{_ as O,a as E}from"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as F,g as U,s as q,h as x,r as L,c as l,o as n,F as f,i as m,b as o,w as k,e,j as v,k as u,t as i,n as $,l as D}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import{u as R}from"./airi-card-Bpd1towy.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import"./mini_xsschema-P_8cZcRg.js";import{n as G,I as J,$ as K,P as Q,B as W}from"./index-CAP_srMr.js";const X={key:0,class:"w-full flex flex-col gap-5"},Y={flex:"~ col","gap-3":""},Z={flex:"~ row","items-center":"","justify-between":""},ee={flex:"~ row","items-center":"","gap-2":""},te={key:0,class:"flex items-center gap-1 rounded-full bg-primary-100 px-2 py-0.5 text-xs text-primary-600 font-medium dark:bg-primary-900/40 dark:text-primary-400"},ae={"mt-1":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},re={"font-medium":""},se={flex:"~ row","gap-2":""},oe={class:"mt-4"},le={class:"border-b border-neutral-200 dark:border-neutral-700"},ne={class:"flex justify-center -mb-px sm:justify-start space-x-1"},ie=["onClick"],de={class:"flex items-center gap-1"},ue={key:0},ce=["innerHTML"],me={key:1},ve=["innerHTML"],pe={key:2},ge={flex:"~ col","max-h-60":"","gap-4":"","overflow-auto":"","pr-1":"","sm:max-h-80":""},xe={key:0,flex:"~ col","gap-2":""},be={"text-lg":"","text-neutral-500":"","font-medium":"","dark:text-neutral-400":""},fe=["innerHTML"],he={key:3},_e={grid:"~ cols-1 sm:cols-3","gap-4":""},ke={flex:"~ col",bg:"white/60 dark:black/30","gap-1":"","rounded-lg":"","p-3":"",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40"},we={flex:"~ row","items-center":"","gap-2":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},ye={truncate:"","font-medium":""},Ce={flex:"~ col",bg:"white/60 dark:black/30","gap-2":"","rounded-lg":"","p-3":"",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40"},Ie={flex:"~ row","items-center":"","gap-2":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},Te={truncate:"","font-medium":""},Ve={flex:"~ col",bg:"white/60 dark:black/30","gap-2":"","rounded-lg":"","p-3":"",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40"},He={flex:"~ row","items-center":"","gap-2":"","text-sm":"","text-neutral-500":"","dark:text-neutral-400":""},Le={truncate:"","font-medium":""},$e={key:1,bg:"neutral-50/50 dark:neutral-900/50","rounded-xl":"","p-8":"","text-center":"",border:"~ neutral-200/50 dark:neutral-700/30",shadow:"sm"},Oe=F({__name:"CardDetailDialog",props:{modelValue:{type:Boolean},cardId:null},emits:["update:modelValue"],setup(j,{emit:A}){const b=j,B=A,{t:d}=U(),w=R(),{removeCard:N}=w,{activeCardId:M}=q(w),a=x(()=>{if(b.cardId)return w.getCard(b.cardId)}),y=x(()=>{var t,c,r,g,S;if(!a.value||!((c=(t=a.value.extensions)==null?void 0:t.airi)!=null&&c.modules))return{consciousness:"",speech:"",voice:""};const s=a.value.extensions.airi.modules;return{consciousness:((r=s.consciousness)==null?void 0:r.model)||"",speech:((g=s.speech)==null?void 0:g.model)||"",voice:((S=s.speech)==null?void 0:S.voice_id)||""}}),C=x(()=>a.value?{personality:a.value.personality,scenario:a.value.scenario,systemPrompt:a.value.systemPrompt,postHistoryInstructions:a.value.postHistoryInstructions}:{}),h=x(()=>b.cardId===M.value),I=L(!1);function P(){I.value=!0,setTimeout(()=>{M.value=b.cardId,I.value=!1},300)}function T(s){return s==null?void 0:s.replace(/\{\{(.*?)\}\}/g,'{{ $1 }}').trim()}const _=L(!1);function z(){a.value&&(N(b.cardId),B("update:modelValue",!1)),_.value=!1}const V=L(""),H=x(()=>{var t,c;const s=[];return(t=a.value)!=null&&t.description&&s.push({id:"description",label:d("settings.pages.card.description_label"),icon:"i-solar:document-text-linear"}),(c=a.value)!=null&&c.notes&&s.push({id:"notes",label:d("settings.pages.card.creator_notes"),icon:"i-solar:notes-linear"}),Object.values(C.value).some(r=>!!r)&&s.push({id:"character",label:d("settings.pages.card.character"),icon:"i-solar:user-rounded-linear"}),s.push({id:"modules",label:d("settings.pages.card.modules"),icon:"i-solar:tuning-square-linear"}),s}),p=x({get:()=>{var s;return H.value.find(t=>t.id===V.value)?V.value:((s=H.value[0])==null?void 0:s.id)||""},set:s=>{V.value=s}});return(s,t)=>{var c;return n(),l(f,null,[m(o(G),{open:j.modelValue,"onUpdate:open":t[0]||(t[0]=r=>B("update:modelValue",r))},{default:k(()=>[m(o(J),null,{default:k(()=>[m(o(K),{class:"data-[state=open]:animate-fadeIn data-[state=closed]:animate-fadeOut fixed inset-0 z-100 bg-black/50 backdrop-blur-sm"}),m(o(Q),{class:"data-[state=open]:animate-contentShow data-[state=closed]:animate-contentHide fixed left-1/2 top-1/2 z-100 m-0 max-h-[90vh] max-w-6xl w-[92vw] flex flex-col overflow-auto border border-neutral-200 rounded-xl bg-white p-5 shadow-xl 2xl:w-[60vw] lg:w-[80vw] md:w-[85vw] xl:w-[70vw] -translate-x-1/2 -translate-y-1/2 dark:border-neutral-700 dark:bg-neutral-800 sm:p-6"},{default:k(()=>[a.value?(n(),l("div",X,[e("div",Y,[e("div",Z,[e("div",null,[e("div",ee,[m(o(W),{"text-2xl":"","font-bold":"",class:"from-primary-500 to-primary-400 bg-gradient-to-r bg-clip-text text-transparent"},{default:k(()=>[u(i(a.value.name),1)]),_:1}),h.value?(n(),l("div",te,[t[3]||(t[3]=e("div",{"i-solar:check-circle-bold-duotone":"","text-xs":""},null,-1)),u(" "+i(o(d)("settings.pages.card.active_badge")),1)])):v("",!0)]),e("div",ae,[u(" v"+i(a.value.version)+" ",1),a.value.creator?(n(),l(f,{key:0},[u(" · "+i(o(d)("settings.pages.card.created_by"))+" ",1),e("span",re,i(a.value.creator),1)],64)):v("",!0)])]),e("div",se,[m(o(O),{variant:"primary",icon:h.value?"i-solar:check-circle-bold-duotone":"i-solar:play-circle-broken",label:h.value?o(d)("settings.pages.card.active"):o(d)("settings.pages.card.activate"),disabled:h.value,class:$({"animate-pulse":I.value}),onClick:P},null,8,["icon","label","disabled","class"])])]),e("div",oe,[e("div",le,[e("div",ne,[(n(!0),l(f,null,D(H.value,r=>(n(),l("button",{key:r.id,class:$(["px-4 py-2 text-sm font-medium",[p.value===r.id?"text-primary-600 dark:text-primary-400 border-b-2 border-primary-500 dark:border-primary-400":"text-neutral-500 dark:text-neutral-400 hover:text-neutral-700 dark:hover:text-neutral-300"]]),onClick:g=>p.value=r.id},[e("div",de,[e("div",{class:$(r.icon)},null,2),u(" "+i(r.label),1)])],10,ie))),128))])])]),p.value==="notes"&&a.value.notes?(n(),l("div",ue,[e("div",{bg:"white/60 dark:black/30",border:"~ neutral-200/50 dark:neutral-700/30","max-h-60":"","overflow-auto":"","whitespace-pre-line":"","rounded-lg":"","p-4":"","text-neutral-700":"","sm:max-h-80":"","dark:text-neutral-300":"",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40",innerHTML:T(a.value.notes)},null,8,ce)])):v("",!0),p.value==="description"&&a.value.description?(n(),l("div",me,[e("div",{bg:"white/60 dark:black/30","max-h-60":"","overflow-auto":"","whitespace-pre-line":"","rounded-lg":"","p-4":"","sm:max-h-80":"",text:"neutral-600 dark:neutral-300",border:"~ neutral-200/50 dark:neutral-700/30",innerHTML:T(a.value.description)},null,8,ve)])):v("",!0),p.value==="character"&&Object.values(C.value).some(r=>!!r)?(n(),l("div",pe,[e("div",ge,[(n(!0),l(f,null,D(C.value,(r,g)=>(n(),l(f,{key:g},[r?(n(),l("div",xe,[e("h2",be,i(o(d)(`settings.pages.card.${g.toLowerCase()}`)),1),e("div",{bg:"white/60 dark:black/30",border:"~ neutral-200/50 dark:neutral-700/30",transition:"all duration-200",hover:"bg-white/80 dark:bg-black/40","max-h-none":"","overflow-auto":"","whitespace-pre-line":"","rounded-lg":"","p-3":"","text-neutral-700":"","dark:text-neutral-300":"",innerHTML:T(r)},null,8,fe)])):v("",!0)],64))),128))])])):v("",!0),p.value==="modules"?(n(),l("div",he,[e("div",_e,[e("div",ke,[e("span",we,[t[4]||(t[4]=e("div",{"i-lucide:ghost":""},null,-1)),u(" "+i(o(d)("settings.pages.card.consciousness.model")),1)]),e("div",ye,i(y.value.consciousness??"default"),1)]),e("div",Ce,[e("span",Ie,[t[5]||(t[5]=e("div",{"i-lucide:mic":""},null,-1)),u(" "+i(o(d)("settings.pages.card.speech.model")),1)]),e("div",Te,i(y.value.speech??"default"),1)]),e("div",Ve,[e("span",He,[t[6]||(t[6]=e("div",{"i-lucide:music":""},null,-1)),u(" "+i(o(d)("settings.pages.card.speech.voice")),1)]),e("div",Le,i(y.value.voice??"default"),1)])])])):v("",!0)])])):(n(),l("div",$e,[t[7]||(t[7]=e("div",{"i-solar:card-search-broken":"","mx-auto":"","mb-3":"","text-6xl":"","text-neutral-400":""},null,-1)),u(" "+i(o(d)("settings.pages.card.card_not_found")),1)]))]),_:1})]),_:1})]),_:1},8,["open"]),m(E,{modelValue:_.value,"onUpdate:modelValue":t[1]||(t[1]=r=>_.value=r),"card-name":(c=a.value)==null?void 0:c.name,onConfirm:z,onCancel:t[2]||(t[2]=r=>_.value=!1)},null,8,["modelValue","card-name"])],64)}}});export{Oe as _}; diff --git a/assets/CardListItem-Bcpy7sq6.js b/assets/CardListItem-Bcpy7sq6.js new file mode 100644 index 0000000000000000000000000000000000000000..643a3bbda10d2ad997b9735aa0cec6abf7d953c7 --- /dev/null +++ b/assets/CardListItem-Bcpy7sq6.js @@ -0,0 +1 @@ +import{_ as o}from"./CardListItem.vue_vue_type_script_setup_true_lang-B94Ybzjh.js";import"./index-CQudhZin.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import"./floating-ui.core-CgBsuaUc.js";export{o as default}; diff --git a/assets/CardListItem-DLmu0uN_.js b/assets/CardListItem-DLmu0uN_.js deleted file mode 100644 index cfd834ca53757cbca4c037b4b545500f47602912..0000000000000000000000000000000000000000 --- a/assets/CardListItem-DLmu0uN_.js +++ /dev/null @@ -1 +0,0 @@ -import{_ as o}from"./CardListItem.vue_vue_type_script_setup_true_lang-BYBvY3lt.js";import"./index-BQKiy4UR.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import"./floating-ui.core-CgBsuaUc.js";export{o as default}; diff --git a/assets/CardListItem.vue_vue_type_script_setup_true_lang-BYBvY3lt.js b/assets/CardListItem.vue_vue_type_script_setup_true_lang-B94Ybzjh.js similarity index 81% rename from assets/CardListItem.vue_vue_type_script_setup_true_lang-BYBvY3lt.js rename to assets/CardListItem.vue_vue_type_script_setup_true_lang-B94Ybzjh.js index a6b37d83849d059c5598c27285947eacb9d0d229..134af88707a1565a08529485765d4eb6c6e41d8c 100644 --- a/assets/CardListItem.vue_vue_type_script_setup_true_lang-BYBvY3lt.js +++ b/assets/CardListItem.vue_vue_type_script_setup_true_lang-B94Ybzjh.js @@ -1 +1 @@ -import{d as M,r as s,H,c as p,o as d,f as R,z as V,_ as F,A as I,w as N,e as t,j as v,t as l,V as k,n as h,b as W}from"./index-BQKiy4UR.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";const D=M({__name:"CursorFloating",props:{intensity:{default:1.5}},setup(r){const n=r,o=s(null),a=s(""),e=s("50% 50%"),i=s("50% 50%"),y=s(.5);function w(c){if(!o.value)return;const u=o.value,x=u.getBoundingClientRect(),$=c.clientX-x.left,C=c.clientY-x.top,z=u.offsetWidth,B=u.offsetHeight,f=Math.abs(Math.floor(100/z*$)-100),m=Math.abs(Math.floor(100/B*C)-100),b=50+(f-50)/1.5,g=50+(m-50)/1.5,A=50+(f-50)/7,P=50+(m-50)/7,S=(b-50)/1.5*.2*n.intensity,X=(g-50)/2*-1*.2*n.intensity,Y=50-f+(50-m),j=.5+Math.abs(Y)*.008*n.intensity;a.value=`perspective(1200px) rotateX(${X}deg) rotateY(${S}deg) scale3d(${1+.015*n.intensity}, ${1+.015*n.intensity}, ${1+.015*n.intensity})`,e.value=`${b}% ${g}%`,i.value=`${A}% ${P}%`,y.value=j}function _(){a.value="perspective(1200px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)",e.value="50% 50%",i.value="50% 50%",y.value=.5}return H(()=>{a.value="perspective(1200px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)"}),(c,u)=>(d(),p("div",{ref_key:"cardRef",ref:o,class:"card-hover-effect",style:V({transform:a.value,"--effect-intensity":r.intensity}),onMousemove:w,onMouseleave:_},[R(c.$slots,"default",{},void 0,!0)],36))}}),E=F(D,[["__scopeId","data-v-895421da"]]),L={relative:"",flex:"~ col 1","justify-between":"","gap-3":"","overflow-hidden":"","rounded-lg":"",bg:"white dark:neutral-900","p-5":"",transition:"all ease-in-out duration-400",after:"content-empty absolute inset-0 z--2 w-full h-full bg-dotted-[neutral-200/80] bg-size-10px mask-image-[linear-gradient(165deg,white_30%,transparent_50%)] transition-all duration-400 ease-in-out",hover:"after:bg-dotted-[primary-300/50] dark:after:bg-dotted-[primary-200/20] text-primary-600/80 dark:text-primary-300/80"},O={"z-1":"",flex:"","items-start":"","justify-between":"","gap-2":""},q={"flex-1":"",truncate:"","text-lg":"","font-bold":""},G={key:0,"shrink-0":"","rounded-md":"","p-1":"",bg:"primary-100 dark:primary-900/40",text:"primary-600 dark:primary-400"},J={key:0,"line-clamp-3":"","min-h-40px":"","flex-1":"","text-sm":"",text:"neutral-500 dark:neutral-400"},K={"z-1":"",flex:"","items-center":"","justify-between":"","text-xs":"",text:"neutral-500 dark:neutral-400"},Q={flex:"","items-center":"","gap-1.5":""},T={flex:"","items-center":"","gap-0.5":""},U={flex:"","items-center":"","gap-0.5":""},Z={flex:"","items-center":"","justify-end":"","px-2":"","py-1.5":""},ee=["disabled"],se=M({__name:"CardListItem",props:{id:null,name:null,description:null,isActive:{type:Boolean},isSelected:{type:Boolean},version:null,consciousnessModel:null,voiceModel:null},emits:["select","activate","delete"],setup(r,{emit:n}){const o=n;return(a,e)=>(d(),I(W(E),{relative:"","min-h-120px":"",flex:"~ col","cursor-pointer":"","overflow-hidden":"","rounded-xl":"",class:h([r.isSelected?"border-2 border-primary-400 dark:border-primary-600":"border-2 border-neutral-100 dark:border-neutral-800/25"]),bg:"neutral-200/50 dark:neutral-800/50","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",transition:"all ease-in-out duration-400",before:"content-empty absolute inset-0 z-0 w-25% h-full transition-all duration-400 ease-in-out bg-gradient-to-r from-primary-500/0 to-primary-500/0 dark:from-primary-400/0 dark:to-primary-400/0 mask-image-[linear-gradient(120deg,white_100%)] opacity-0",hover:"before:opacity-100 before:bg-gradient-to-r before:from-primary-500/20 before:via-primary-500/10 before:to-transparent before:dark:from-primary-400/20 before:dark:via-primary-400/10 before:dark:to-transparent",onClick:e[2]||(e[2]=i=>o("select"))},{default:N(()=>[t("div",L,[t("div",O,[t("h3",q,l(r.name),1),r.isActive?(d(),p("div",G,e[3]||(e[3]=[t("div",{"i-solar:check-circle-bold-duotone":"","text-sm":""},null,-1)]))):v("",!0)]),r.description?(d(),p("p",J,l(r.description),1)):v("",!0),t("div",K,[t("div",null,"v"+l(r.version),1),t("div",Q,[t("div",T,[e[4]||(e[4]=t("div",{"i-lucide:ghost":"","text-xs":""},null,-1)),t("span",null,l(r.consciousnessModel),1)]),t("div",U,[e[5]||(e[5]=t("div",{"i-lucide:mic":"","text-xs":""},null,-1)),t("span",null,l(r.voiceModel),1)])])])]),t("div",Z,[t("button",{"rounded-lg":"","p-1.5":"","transition-colors":"",hover:"bg-neutral-200 dark:bg-neutral-700/50",disabled:r.isActive,onClick:e[0]||(e[0]=k(i=>o("activate"),["stop"]))},[t("div",{class:h([r.isActive?"i-solar:check-circle-bold-duotone text-primary-500 dark:text-primary-400":"i-solar:play-circle-broken text-neutral-500 dark:text-neutral-400"])},null,2)],8,ee),r.id!=="default"?(d(),p("button",{key:0,"rounded-lg":"","p-1.5":"","transition-colors":"",hover:"bg-neutral-200 dark:bg-neutral-700/50",onClick:e[1]||(e[1]=k(i=>o("delete"),["stop"]))},e[6]||(e[6]=[t("div",{"i-solar:trash-bin-trash-linear":"",text:"neutral-500 dark:neutral-400"},null,-1)]))):v("",!0)])]),_:1},8,["class"]))}});export{se as _}; +import{d as M,r as s,H,c as p,o as d,f as R,z as F,_ as I,A as N,w as V,e as t,j as v,t as l,X as k,n as h,b as W}from"./index-CQudhZin.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";const D=M({__name:"CursorFloating",props:{intensity:{default:1.5}},setup(r){const n=r,o=s(null),a=s(""),e=s("50% 50%"),i=s("50% 50%"),y=s(.5);function w(c){if(!o.value)return;const u=o.value,x=u.getBoundingClientRect(),$=c.clientX-x.left,C=c.clientY-x.top,z=u.offsetWidth,B=u.offsetHeight,f=Math.abs(Math.floor(100/z*$)-100),m=Math.abs(Math.floor(100/B*C)-100),b=50+(f-50)/1.5,g=50+(m-50)/1.5,X=50+(f-50)/7,A=50+(m-50)/7,P=(b-50)/1.5*.2*n.intensity,S=(g-50)/2*-1*.2*n.intensity,Y=50-f+(50-m),j=.5+Math.abs(Y)*.008*n.intensity;a.value=`perspective(1200px) rotateX(${S}deg) rotateY(${P}deg) scale3d(${1+.015*n.intensity}, ${1+.015*n.intensity}, ${1+.015*n.intensity})`,e.value=`${b}% ${g}%`,i.value=`${X}% ${A}%`,y.value=j}function _(){a.value="perspective(1200px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)",e.value="50% 50%",i.value="50% 50%",y.value=.5}return H(()=>{a.value="perspective(1200px) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)"}),(c,u)=>(d(),p("div",{ref_key:"cardRef",ref:o,class:"card-hover-effect",style:F({transform:a.value,"--effect-intensity":r.intensity}),onMousemove:w,onMouseleave:_},[R(c.$slots,"default",{},void 0,!0)],36))}}),E=I(D,[["__scopeId","data-v-895421da"]]),L={relative:"",flex:"~ col 1","justify-between":"","gap-3":"","overflow-hidden":"","rounded-lg":"",bg:"white dark:neutral-900","p-5":"",transition:"all ease-in-out duration-400",after:"content-empty absolute inset-0 z--2 w-full h-full bg-dotted-[neutral-200/80] bg-size-10px mask-image-[linear-gradient(165deg,white_30%,transparent_50%)] transition-all duration-400 ease-in-out",hover:"after:bg-dotted-[primary-300/50] dark:after:bg-dotted-[primary-200/20] text-primary-600/80 dark:text-primary-300/80"},O={"z-1":"",flex:"","items-start":"","justify-between":"","gap-2":""},q={"flex-1":"",truncate:"","text-lg":"","font-bold":""},G={key:0,"shrink-0":"","rounded-md":"","p-1":"",bg:"primary-100 dark:primary-900/40",text:"primary-600 dark:primary-400"},J={key:0,"line-clamp-3":"","min-h-40px":"","flex-1":"","text-sm":"",text:"neutral-500 dark:neutral-400"},K={"z-1":"",flex:"","items-center":"","justify-between":"","text-xs":"",text:"neutral-500 dark:neutral-400"},Q={flex:"","items-center":"","gap-1.5":""},T={flex:"","items-center":"","gap-0.5":""},U={flex:"","items-center":"","gap-0.5":""},Z={flex:"","items-center":"","justify-end":"","px-2":"","py-1.5":""},ee=["disabled"],se=M({__name:"CardListItem",props:{id:null,name:null,description:null,isActive:{type:Boolean},isSelected:{type:Boolean},version:null,consciousnessModel:null,voiceModel:null},emits:["select","activate","delete"],setup(r,{emit:n}){const o=n;return(a,e)=>(d(),N(W(E),{relative:"","min-h-120px":"",flex:"~ col","cursor-pointer":"","overflow-hidden":"","rounded-xl":"",class:h([r.isSelected?"border-2 border-primary-400 dark:border-primary-600":"border-2 border-neutral-100 dark:border-neutral-800/25"]),bg:"neutral-200/50 dark:neutral-800/50","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",transition:"all ease-in-out duration-400",before:"content-empty absolute inset-0 z-0 w-25% h-full transition-all duration-400 ease-in-out bg-gradient-to-r from-primary-500/0 to-primary-500/0 dark:from-primary-400/0 dark:to-primary-400/0 mask-image-[linear-gradient(120deg,white_100%)] opacity-0",hover:"before:opacity-100 before:bg-gradient-to-r before:from-primary-500/20 before:via-primary-500/10 before:to-transparent before:dark:from-primary-400/20 before:dark:via-primary-400/10 before:dark:to-transparent",onClick:e[2]||(e[2]=i=>o("select"))},{default:V(()=>[t("div",L,[t("div",O,[t("h3",q,l(r.name),1),r.isActive?(d(),p("div",G,e[3]||(e[3]=[t("div",{"i-solar:check-circle-bold-duotone":"","text-sm":""},null,-1)]))):v("",!0)]),r.description?(d(),p("p",J,l(r.description),1)):v("",!0),t("div",K,[t("div",null,"v"+l(r.version),1),t("div",Q,[t("div",T,[e[4]||(e[4]=t("div",{"i-lucide:ghost":"","text-xs":""},null,-1)),t("span",null,l(r.consciousnessModel),1)]),t("div",U,[e[5]||(e[5]=t("div",{"i-lucide:mic":"","text-xs":""},null,-1)),t("span",null,l(r.voiceModel),1)])])])]),t("div",Z,[t("button",{"rounded-lg":"","p-1.5":"","transition-colors":"",hover:"bg-neutral-200 dark:bg-neutral-700/50",disabled:r.isActive,onClick:e[0]||(e[0]=k(i=>o("activate"),["stop"]))},[t("div",{class:h([r.isActive?"i-solar:check-circle-bold-duotone text-primary-500 dark:text-primary-400":"i-solar:play-circle-broken text-neutral-500 dark:text-neutral-400"])},null,2)],8,ee),r.id!=="default"?(d(),p("button",{key:0,"rounded-lg":"","p-1.5":"","transition-colors":"",hover:"bg-neutral-200 dark:bg-neutral-700/50",onClick:e[1]||(e[1]=k(i=>o("delete"),["stop"]))},e[6]||(e[6]=[t("div",{"i-solar:trash-bin-trash-linear":"",text:"neutral-500 dark:neutral-400"},null,-1)]))):v("",!0)])]),_:1},8,["class"]))}});export{se as _}; diff --git a/assets/Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js b/assets/Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js similarity index 82% rename from assets/Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js rename to assets/Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js index 8f72bdf666fe9142c839acee065df440cdc77b91..0cb8adaa92acb0997d7bc3b5e48270c086ce7594 100644 --- a/assets/Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js +++ b/assets/Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js @@ -1 +1 @@ -import{_ as d}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{d as p,m,u as f,B as c,c as b,o as v,f as r,i as V,e as s,k,t as u,C as i,D as y,b as C,w as g,j as x,E as B}from"./index-BQKiy4UR.js";const _={op50:""},M=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");c(()=>{t.default!=null&&(e.value=!!t.default)});function n(l){return e.value=l,l}return(l,a)=>(v(),b("div",null,[r(l.$slots,"trigger",i(y({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]=w=>e.value=!e.value)},[s("span",null,u(t.label??"Collapsable"),1),a[1]||(a[1]=k()),s("span",_,u(e.value?"▲":"▼"),1)])]),V(C(d),null,{default:g(()=>[e.value?r(l.$slots,"default",i(B({key:0},{visible:e.value,setVisible:n}))):x("",!0)]),_:3})]))}});export{M as _}; +import{_ as d}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{d as p,m,u as f,B as c,c as b,o as v,f as r,i as V,e as s,k,t as u,C as i,D as y,b as C,w as g,j as x,E as B}from"./index-CQudhZin.js";const _={op50:""},M=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");c(()=>{t.default!=null&&(e.value=!!t.default)});function n(l){return e.value=l,l}return(l,a)=>(v(),b("div",null,[r(l.$slots,"trigger",i(y({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]=w=>e.value=!e.value)},[s("span",null,u(t.label??"Collapsable"),1),a[1]||(a[1]=k()),s("span",_,u(e.value?"▲":"▼"),1)])]),V(C(d),null,{default:g(()=>[e.value?r(l.$slots,"default",i(B({key:0},{visible:e.value,setVisible:n}))):x("",!0)]),_:3})]))}});export{M as _}; diff --git a/assets/ColorPalette.vue_vue_type_script_setup_true_lang-CuLfdqu0.js b/assets/ColorPalette.vue_vue_type_script_setup_true_lang-1nqX-kcz.js similarity index 87% rename from assets/ColorPalette.vue_vue_type_script_setup_true_lang-CuLfdqu0.js rename to assets/ColorPalette.vue_vue_type_script_setup_true_lang-1nqX-kcz.js index 120515e3c79ecbc935c04fcdcfafa6295500970e..631fadacd9c057756230c8354b0567bc27f53e75 100644 --- a/assets/ColorPalette.vue_vue_type_script_setup_true_lang-CuLfdqu0.js +++ b/assets/ColorPalette.vue_vue_type_script_setup_true_lang-1nqX-kcz.js @@ -1 +1 @@ -import{_ as k}from"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import{d as c,A as m,o as i,w as l,e as n,n as u,f as y,k as f,t as g,G as C,c as d,j as b,F as v,l as h,i as s,b as e,z as w,O as x}from"./index-BQKiy4UR.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{W as S,j as $,q as z,U as B,G as E,H as F}from"./index-D1N6XcGk.js";const V=["onClick"],j={flex:"","gap-1.5":""},q=c({__name:"Section",props:{title:null,icon:null,innerClass:null,expand:{type:Boolean,default:!0}},setup(t){return(r,_)=>(i(),m(k,{default:t.expand},{trigger:l(o=>[n("button",{class:"w-full flex items-center justify-between rounded-lg px-4 py-3 outline-none transition-all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",onClick:a=>o.setVisible(!o.visible)},[n("div",j,[n("div",{class:u(t.icon),"size-6":""},null,2),f(" "+g(t.title),1)]),n("div",{"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-250",class:u({"rotate-180":o.visible})},null,2)],8,V)]),default:l(()=>[n("div",{grid:"","gap-4":"","p-4":"",class:u(t.innerClass)},[y(r.$slots,"default")],2)]),_:3},8,["default"]))}}),H={key:0,flex:"","gap-2":""},A=c({__name:"ColorPalette",props:{colors:null},setup(t){const r=C();return(_,o)=>t.colors.length?(i(),d("div",H,[(i(!0),d(v,null,h(t.colors,({hex:a,name:p})=>(i(),m(e(F),{key:a||"default"},{default:l(()=>[s(e(S),null,{default:l(()=>[s(e($),{transition:"all ease-in-out duration-250","size-6":"","cursor-pointer":"","rounded-full":"","bg-primary-500":"",style:w(a?{background:a}:{"--theme-colors-hue":e(x)}),class:u(e(r).isColorSelectedForPrimary(a)?"scale-150 mx-1":"hover:scale-110"),onClick:N=>e(r).applyPrimaryColorFrom(a)},null,8,["style","class","onClick"]),s(e(z),null,{default:l(()=>[s(e(B),{bg:"white dark:neutral-800","rounded-lg":"","px-3":"","py-1.5":"","text-sm":"","shadow-md":""},{default:l(()=>[f(g(p)+" ",1),s(e(E),{"fill-white":"","dark:fill-neutral-800":""})]),_:2},1024)]),_:2},1024)]),_:2},1024)]),_:2},1024))),128))])):b("",!0)}});export{q as _,A as a}; +import{_ as k}from"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import{d as c,A as m,o as i,w as l,e as n,n as u,f as y,k as f,t as g,G as C,c as d,j as b,F as v,l as h,i as s,b as e,z as w,O as x}from"./index-CQudhZin.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{W as S,j as $,q as z,U as B,G as E,H as F}from"./index-CAP_srMr.js";const V=["onClick"],j={flex:"","gap-1.5":""},q=c({__name:"Section",props:{title:null,icon:null,innerClass:null,expand:{type:Boolean,default:!0}},setup(t){return(r,_)=>(i(),m(k,{default:t.expand},{trigger:l(o=>[n("button",{class:"w-full flex items-center justify-between rounded-lg px-4 py-3 outline-none transition-all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",onClick:a=>o.setVisible(!o.visible)},[n("div",j,[n("div",{class:u(t.icon),"size-6":""},null,2),f(" "+g(t.title),1)]),n("div",{"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-250",class:u({"rotate-180":o.visible})},null,2)],8,V)]),default:l(()=>[n("div",{grid:"","gap-4":"","p-4":"",class:u(t.innerClass)},[y(r.$slots,"default")],2)]),_:3},8,["default"]))}}),H={key:0,flex:"","gap-2":""},A=c({__name:"ColorPalette",props:{colors:null},setup(t){const r=C();return(_,o)=>t.colors.length?(i(),d("div",H,[(i(!0),d(v,null,h(t.colors,({hex:a,name:p})=>(i(),m(e(F),{key:a||"default"},{default:l(()=>[s(e(S),null,{default:l(()=>[s(e($),{transition:"all ease-in-out duration-250","size-6":"","cursor-pointer":"","rounded-full":"","bg-primary-500":"",style:w(a?{background:a}:{"--theme-colors-hue":e(x)}),class:u(e(r).isColorSelectedForPrimary(a)?"scale-150 mx-1":"hover:scale-110"),onClick:N=>e(r).applyPrimaryColorFrom(a)},null,8,["style","class","onClick"]),s(e(z),null,{default:l(()=>[s(e(B),{bg:"white dark:neutral-800","rounded-lg":"","px-3":"","py-1.5":"","text-sm":"","shadow-md":""},{default:l(()=>[f(g(p)+" ",1),s(e(E),{"fill-white":"","dark:fill-neutral-800":""})]),_:2},1024)]),_:2},1024)]),_:2},1024)]),_:2},1024))),128))])):b("",!0)}});export{q as _,A as a}; diff --git a/assets/DeleteCardDialog-BgA6bpCe.js b/assets/DeleteCardDialog-BgA6bpCe.js new file mode 100644 index 0000000000000000000000000000000000000000..82ea00a71ebafb73c9fbeb743da4795bcef65abf --- /dev/null +++ b/assets/DeleteCardDialog-BgA6bpCe.js @@ -0,0 +1 @@ +import{a as o}from"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js";import"./index-CQudhZin.js";import"./index-CAP_srMr.js";import"./floating-ui.core-CgBsuaUc.js";export{o as default}; diff --git a/assets/DeleteCardDialog-CGam42wc.js b/assets/DeleteCardDialog-CGam42wc.js deleted file mode 100644 index d19465d5b77986fc69e337780833b0a137373938..0000000000000000000000000000000000000000 --- a/assets/DeleteCardDialog-CGam42wc.js +++ /dev/null @@ -1 +0,0 @@ -import{a as o}from"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js";import"./index-BQKiy4UR.js";import"./index-D1N6XcGk.js";import"./floating-ui.core-CgBsuaUc.js";export{o as default}; diff --git a/assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js b/assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js similarity index 93% rename from assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js rename to assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js index 58f0ebfa6f81946133a48af83a7aca0ca0ebd561..6ae96725986f9933309a69472a6e80a7f66b98b6 100644 --- a/assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js +++ b/assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js @@ -1 +1 @@ -import{d as k,h as p,c as r,o as d,n as g,e as m,j as h,f as _,t as i,g as w,A as C,w as n,i as t,b as e,k as x}from"./index-BQKiy4UR.js";import{A as V,k as B,O as N,V as z,F as D,M as j,N as A,T as O}from"./index-D1N6XcGk.js";const S=["disabled"],T={class:"flex flex-row items-center justify-center gap-2"},$={key:0,class:"i-lucide:loader-circle animate-spin"},F={key:2},y=k({__name:"Button",props:{icon:null,label:null,disabled:{type:Boolean,default:!1},loading:{type:Boolean,default:!1},variant:{default:"primary"},size:{default:"md"},block:{type:Boolean,default:!1}},setup(a){const s=a,l=p(()=>s.disabled||s.loading),o={primary:"bg-primary-500 hover:bg-primary-600 dark:bg-primary-400 dark:hover:bg-primary-500 text-white",secondary:"bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-600 dark:hover:bg-neutral-500 text-neutral-900 dark:text-neutral-100",danger:"bg-red-500 hover:bg-red-600 dark:bg-red-400 dark:hover:bg-red-500 text-white"},c={sm:"px-3 py-1.5 text-xs",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base"},u=p(()=>["rounded-lg font-medium outline-none transition-all duration-200 ease-in-out","disabled:cursor-not-allowed disabled:opacity-50",s.block?"w-full":"",c[s.size],o[s.variant],{"opacity-50 cursor-not-allowed":l.value},"focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-neutral-900","focus:ring-primary-500/50 dark:focus:ring-primary-400/50"]);return(b,f)=>(d(),r("button",{disabled:l.value,class:g(u.value)},[m("div",T,[a.loading?(d(),r("div",$)):a.icon?(d(),r("div",{key:1,class:g(a.icon)},null,2)):h("",!0),a.label?(d(),r("span",F,i(a.label),1)):_(b.$slots,"default",{key:3})])],10,S))}}),I={class:"flex flex-row justify-end gap-3"},H=k({__name:"DeleteCardDialog",props:{modelValue:{type:Boolean},cardName:null},emits:["update:modelValue","confirm","cancel"],setup(a,{emit:s}){const l=s,{t:o}=w();function c(){l("update:modelValue",!1),l("cancel")}function u(){l("update:modelValue",!1),l("confirm")}return(b,f)=>(d(),C(e(O),{open:a.modelValue,"onUpdate:open":f[0]||(f[0]=v=>l("update:modelValue",v))},{default:n(()=>[t(e(V),null,{default:n(()=>[t(e(B),{class:"data-[state=open]:animate-fadeIn data-[state=closed]:animate-fadeOut fixed inset-0 z-100 bg-black/50"}),t(e(N),{class:"data-[state=open]:animate-contentShow data-[state=closed]:animate-contentHide fixed left-1/2 top-1/2 z-100 max-w-md w-full border border-neutral-200 rounded-xl bg-white p-6 shadow-xl -translate-x-1/2 -translate-y-1/2 dark:border-neutral-700 dark:bg-neutral-800"},{default:n(()=>[t(e(z),{class:"mb-4 text-xl font-bold"},{default:n(()=>[x(i(e(o)("settings.pages.card.delete_card")),1)]),_:1}),t(e(D),{class:"mb-6"},{default:n(()=>[x(i(e(o)("settings.pages.card.delete_confirmation"))+" ",1),m("b",null,'"'+i(a.cardName||"")+'"',1)]),_:1}),m("div",I,[t(e(j),{"as-child":""},{default:n(()=>[t(e(y),{variant:"secondary",label:e(o)("settings.pages.card.cancel"),onClick:c},null,8,["label"])]),_:1}),t(e(A),{"as-child":""},{default:n(()=>[t(e(y),{variant:"danger",label:e(o)("settings.pages.card.delete"),onClick:u},null,8,["label"])]),_:1})])]),_:1})]),_:1})]),_:1},8,["open"]))}});export{y as _,H as a}; +import{d as k,h as p,c as r,o as d,n as g,e as m,j as h,f as _,t as i,g as w,A as C,w as n,i as t,b as e,k as x}from"./index-CQudhZin.js";import{A as V,k as B,O as N,V as z,F as D,M as j,N as A,T as O}from"./index-CAP_srMr.js";const S=["disabled"],T={class:"flex flex-row items-center justify-center gap-2"},$={key:0,class:"i-lucide:loader-circle animate-spin"},F={key:2},y=k({__name:"Button",props:{icon:null,label:null,disabled:{type:Boolean,default:!1},loading:{type:Boolean,default:!1},variant:{default:"primary"},size:{default:"md"},block:{type:Boolean,default:!1}},setup(a){const s=a,l=p(()=>s.disabled||s.loading),o={primary:"bg-primary-500 hover:bg-primary-600 dark:bg-primary-400 dark:hover:bg-primary-500 text-white",secondary:"bg-neutral-100 hover:bg-neutral-200 dark:bg-neutral-600 dark:hover:bg-neutral-500 text-neutral-900 dark:text-neutral-100",danger:"bg-red-500 hover:bg-red-600 dark:bg-red-400 dark:hover:bg-red-500 text-white"},c={sm:"px-3 py-1.5 text-xs",md:"px-4 py-2 text-sm",lg:"px-6 py-3 text-base"},u=p(()=>["rounded-lg font-medium outline-none transition-all duration-200 ease-in-out","disabled:cursor-not-allowed disabled:opacity-50",s.block?"w-full":"",c[s.size],o[s.variant],{"opacity-50 cursor-not-allowed":l.value},"focus:ring-2 focus:ring-offset-2 focus:ring-offset-white dark:focus:ring-offset-neutral-900","focus:ring-primary-500/50 dark:focus:ring-primary-400/50"]);return(b,f)=>(d(),r("button",{disabled:l.value,class:g(u.value)},[m("div",T,[a.loading?(d(),r("div",$)):a.icon?(d(),r("div",{key:1,class:g(a.icon)},null,2)):h("",!0),a.label?(d(),r("span",F,i(a.label),1)):_(b.$slots,"default",{key:3})])],10,S))}}),I={class:"flex flex-row justify-end gap-3"},H=k({__name:"DeleteCardDialog",props:{modelValue:{type:Boolean},cardName:null},emits:["update:modelValue","confirm","cancel"],setup(a,{emit:s}){const l=s,{t:o}=w();function c(){l("update:modelValue",!1),l("cancel")}function u(){l("update:modelValue",!1),l("confirm")}return(b,f)=>(d(),C(e(O),{open:a.modelValue,"onUpdate:open":f[0]||(f[0]=v=>l("update:modelValue",v))},{default:n(()=>[t(e(V),null,{default:n(()=>[t(e(B),{class:"data-[state=open]:animate-fadeIn data-[state=closed]:animate-fadeOut fixed inset-0 z-100 bg-black/50"}),t(e(N),{class:"data-[state=open]:animate-contentShow data-[state=closed]:animate-contentHide fixed left-1/2 top-1/2 z-100 max-w-md w-full border border-neutral-200 rounded-xl bg-white p-6 shadow-xl -translate-x-1/2 -translate-y-1/2 dark:border-neutral-700 dark:bg-neutral-800"},{default:n(()=>[t(e(z),{class:"mb-4 text-xl font-bold"},{default:n(()=>[x(i(e(o)("settings.pages.card.delete_card")),1)]),_:1}),t(e(D),{class:"mb-6"},{default:n(()=>[x(i(e(o)("settings.pages.card.delete_confirmation"))+" ",1),m("b",null,'"'+i(a.cardName||"")+'"',1)]),_:1}),m("div",I,[t(e(j),{"as-child":""},{default:n(()=>[t(e(y),{variant:"secondary",label:e(o)("settings.pages.card.cancel"),onClick:c},null,8,["label"])]),_:1}),t(e(A),{"as-child":""},{default:n(()=>[t(e(y),{variant:"danger",label:e(o)("settings.pages.card.delete"),onClick:u},null,8,["label"])]),_:1})])]),_:1})]),_:1})]),_:1},8,["open"]))}});export{y as _,H as a}; diff --git a/assets/FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js b/assets/FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js similarity index 81% rename from assets/FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js rename to assets/FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js index e48904b59340011661dd3af98257c8c9e5ed0e84..77c948943052041cf436da611491960454f8cd72 100644 --- a/assets/FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js +++ b/assets/FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js @@ -1 +1 @@ -import{_ as u}from"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import{d as i,m as c,u as p,c as o,o as n,e as l,i as m,k as _,j as x,t as d,n as f}from"./index-BQKiy4UR.js";const V={"max-w-full":""},h={flex:"~ col gap-4"},y={class:"flex items-center gap-1 text-sm font-medium"},v={key:0,class:"text-red-500"},k={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},N=i({__name:"FieldInput",props:c({label:null,description:null,placeholder:null,required:{type:Boolean},type:null,inputClass:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,a=p(t,"modelValue");return(C,s)=>(n(),o("div",V,[l("label",h,[l("div",null,[l("div",y,[_(d(e.label)+" ",1),e.required!==!1?(n(),o("span",v,"*")):x("",!0)]),l("div",k,d(e.description),1)]),m(u,{modelValue:a.value,"onUpdate:modelValue":s[0]||(s[0]=r=>a.value=r),type:e.type,placeholder:e.placeholder,class:f(e.inputClass)},null,8,["modelValue","type","placeholder","class"])])]))}});export{N as _}; +import{_ as u}from"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import{d as i,m as c,u as p,c as o,o as n,e as l,i as m,k as _,j as x,t as d,n as f}from"./index-CQudhZin.js";const V={"max-w-full":""},h={flex:"~ col gap-4"},y={class:"flex items-center gap-1 text-sm font-medium"},v={key:0,class:"text-red-500"},k={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},N=i({__name:"FieldInput",props:c({label:null,description:null,placeholder:null,required:{type:Boolean},type:null,inputClass:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,a=p(t,"modelValue");return(C,s)=>(n(),o("div",V,[l("label",h,[l("div",null,[l("div",y,[_(d(e.label)+" ",1),e.required!==!1?(n(),o("span",v,"*")):x("",!0)]),l("div",k,d(e.description),1)]),m(u,{modelValue:a.value,"onUpdate:modelValue":s[0]||(s[0]=r=>a.value=r),type:e.type,placeholder:e.placeholder,class:f(e.inputClass)},null,8,["modelValue","type","placeholder","class"])])]))}});export{N as _}; diff --git a/assets/FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js b/assets/FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js similarity index 82% rename from assets/FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js rename to assets/FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js index 7fa2745c5d20ee9bac3313cb020075679498e5a6..e458e7c771205e8c92bb3a4a697abf7b94267c83 100644 --- a/assets/FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js +++ b/assets/FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js @@ -1 +1 @@ -import{d as m,c as g,o as c,z as M,f as k,_ as B,r as V,bh as E,H as P,I as T,e as f,A as y,w as _,i as $,F as I,bi as N,E as w,bj as D,be as S,b as d,bd as z,bs as L,h as v,bI as j,ba as U,bJ as H,v as K,l as G,b8 as W,bK as X,j as Y,bB as J,V as Q,u as C,m as A,t as x,x as Z,y as ee}from"./index-BQKiy4UR.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";const te=m({__name:"Volumed",props:{perspective:null,transform:null},setup(t){return(e,n)=>(c(),g("div",{class:"volumed",style:M({perspective:`${t.perspective}px`,transform:t.transform})},[k(e.$slots,"default",{},void 0,!0)],4))}}),ae=B(te,[["__scopeId","data-v-568551bc"]]),ne=m({__name:"CursorMomentum",props:{baseSpeed:{default:.1},friction:{default:.95},momentumFactor:{default:.005}},setup(t,{expose:e}){const n=t,o=V(1),l=V(0);let r=0;const a=E(()=>n.friction),u=E(()=>n.baseSpeed),p=E(()=>n.momentumFactor);function h(s){r||(r=s);const b=s-r;r=s,o.value=u.value+(o.value-u.value)*a.value,l.value+=o.value*b,requestAnimationFrame(h)}function i(s){const b=Math.sqrt(s.movementX**2+s.movementY**2);o.value+=b*p.value}return P(()=>{window.addEventListener("mousemove",i),requestAnimationFrame(h)}),T(()=>{window.removeEventListener("mousemove",i)}),e({momentum:o,currentValue:l}),(s,b)=>k(s.$slots,"default",{momentum:o.value,currentValue:l.value})}}),le=m({__name:"TestDummyMarkerFlat",props:{size:null},setup(t){return(e,n)=>(c(),g("div",{class:"test-dummy-flat",style:M({width:`${t.size}px`,height:`${t.size}px`})},n[0]||(n[0]=[f("div",{class:"marker"},null,-1)]),4))}}),oe=B(le,[["__scopeId","data-v-b4ef37ac"]]),Ie=m({__name:"TestDummyMarker",setup(t){return(e,n)=>(c(),y(ne,{"base-speed":.1,friction:.95,"momentum-factor":5e-4},{default:_(({currentValue:o})=>[$(ae,{perspective:800,transform:"rotateX(45deg) translateY(3px)"},{default:_(()=>[$(oe,{size:24,style:M({transform:`rotate(${o}deg)`})},null,8,["style"])]),_:2},1024)]),_:1}))}});function R(t){return t?t.flatMap(e=>e.type===I?R(e.children):[e]):[]}const re=m({name:"PrimitiveSlot",inheritAttrs:!1,setup(t,{attrs:e,slots:n}){return()=>{var p,h;if(!n.default)return null;const o=R(n.default()),l=o.findIndex(i=>i.type!==N);if(l===-1)return o;const r=o[l];(p=r.props)==null||delete p.ref;const a=r.props?w(e,r.props):e;e.class&&((h=r.props)!=null&&h.class)&&delete r.props.class;const u=D(r,a);for(const i in a)i.startsWith("on")&&(u.props||(u.props={}),u.props[i]=a[i]);return o.length===1?u:(o[l]=u,o)}}}),se=["area","img","input"],q=m({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(t,{attrs:e,slots:n}){const o=t.asChild?"template":t.as;return typeof o=="string"&&se.includes(o)?()=>S(o,e):o!=="template"?()=>S(t.as,e,{default:n.default}):()=>S(re,e,{default:n.default})}}),ue=m({__name:"VisuallyHidden",props:{feature:{default:"focusable"},asChild:{type:Boolean},as:{default:"span"}},setup(t){return(e,n)=>(c(),y(d(q),{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:_(()=>[k(e.$slots,"default")]),_:3},8,["as","as-child","aria-hidden","data-hidden","tabindex"]))}});function ie(t,e){const n=`${t}Context`,o=Symbol(n);return[a=>{const u=z(o,a);if(u||u===null)return u;throw new Error(`Injection \`${o.toString()}\` not found. Component must be used within ${Array.isArray(t)?`one of the following components: ${t.join(", ")}`:`\`${t}\``}`)},a=>(L(o,a),a)]}function O(){const t=U(),e=V(),n=v(()=>{var a,u;return["#text","#comment"].includes((a=e.value)==null?void 0:a.$el.nodeName)?(u=e.value)==null?void 0:u.$el.nextElementSibling:j(e)}),o=Object.assign({},t.exposed),l={};for(const a in t.props)Object.defineProperty(l,a,{enumerable:!0,configurable:!0,get:()=>t.props[a]});if(Object.keys(o).length>0)for(const a in o)Object.defineProperty(l,a,{enumerable:!0,configurable:!0,get:()=>o[a]});Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>t.vnode.el}),t.exposed=l;function r(a){e.value=a,a&&(Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>a instanceof Element?a:a.$el}),t.exposed=l)}return{forwardRef:r,currentRef:e,currentElement:n}}function de(){const t=V(),e=v(()=>{var n,o;return["#text","#comment"].includes((n=t.value)==null?void 0:n.$el.nodeName)?(o=t.value)==null?void 0:o.$el.nextElementSibling:j(t)});return{primitiveElement:t,currentElement:e}}function ce(t){return v(()=>{var e;return H(t)?!!((e=j(t))!=null&&e.closest("form")):!0})}const F=m({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:n,currentElement:o}=de(),l=v(()=>e.checked??e.value);return K(l,(r,a)=>{if(!o.value)return;const u=o.value,p=window.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(p,"value").set;if(i&&r!==a){const s=new Event("input",{bubbles:!0}),b=new Event("change",{bubbles:!0});i.call(u,r),u.dispatchEvent(s),u.dispatchEvent(b)}}),(r,a)=>(c(),y(ue,w({ref_key:"primitiveElement",ref:n},{...e,...r.$attrs},{as:"input"}),null,16))}}),me=m({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,n=v(()=>typeof e.value=="object"&&Array.isArray(e.value)&&e.value.length===0&&e.required),o=v(()=>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((l,r)=>typeof l=="object"?Object.entries(l).map(([a,u])=>({name:`[${e.name}][${r}][${a}]`,value:u})):{name:`[${e.name}][${r}]`,value:l}):e.value!==null&&typeof e.value=="object"&&!Array.isArray(e.value)?Object.entries(e.value).map(([l,r])=>({name:`[${e.name}][${l}]`,value:r})):[]);return(l,r)=>n.value?(c(),y(F,w({key:l.name},{...e,...l.$attrs},{name:l.name,value:l.value}),null,16,["name","value"])):(c(!0),g(I,{key:1},G(o.value,a=>(c(),y(F,w({key:a.name,ref_for:!0},{...e,...l.$attrs},{name:a.name,value:a.value}),null,16,["name","value"]))),128))}}),[pe,fe]=ie("SwitchRoot"),ve=m({__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 n=t,o=e,{disabled:l}=W(n),r=X(n,"modelValue",o,{defaultValue:n.defaultValue,passive:n.modelValue===void 0});function a(){l.value||(r.value=!r.value)}const{forwardRef:u,currentElement:p}=O(),h=ce(p),i=v(()=>{var s;return n.id&&p.value?(s=document.querySelector(`[for="${n.id}"]`))==null?void 0:s.innerText:void 0});return fe({modelValue:r,toggleCheck:a,disabled:l}),(s,b)=>(c(),y(d(q),w(s.$attrs,{id:s.id,ref:d(u),role:"switch",type:s.as==="button"?"button":void 0,value:s.value,"aria-label":s.$attrs["aria-label"]||i.value,"aria-checked":d(r),"aria-required":s.required,"data-state":d(r)?"checked":"unchecked","data-disabled":d(l)?"":void 0,"as-child":s.asChild,as:s.as,disabled:d(l),onClick:a,onKeydown:J(Q(a,["prevent"]),["enter"])}),{default:_(()=>[k(s.$slots,"default",{modelValue:d(r)}),d(h)&&s.name?(c(),y(d(me),{key:0,type:"checkbox",name:s.name,disabled:d(l),required:s.required,value:s.value,checked:!!d(r)},null,8,["name","disabled","required","value","checked"])):Y("",!0)]),_:3},16,["id","type","value","aria-label","aria-checked","aria-required","data-state","data-disabled","as-child","as","disabled","onKeydown"]))}}),he=m({__name:"SwitchThumb",props:{asChild:{type:Boolean},as:{default:"span"}},setup(t){const e=pe();return O(),(n,o)=>{var l;return c(),y(d(q),{"data-state":(l=d(e).modelValue)!=null&&l.value?"checked":"unchecked","data-disabled":d(e).disabled.value?"":void 0,"as-child":n.asChild,as:n.as},{default:_(()=>[k(n.$slots,"default")]),_:3},8,["data-state","data-disabled","as-child","as"])}}}),be=m({__name:"Checkbox",props:{modelValue:{type:Boolean,required:!0},modelModifiers:{}},emits:["update:modelValue"],setup(t){const e=C(t,"modelValue");return(n,o)=>(c(),y(d(ve),{modelValue:e.value,"onUpdate:modelValue":o[0]||(o[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:_(()=>[$(d(he),{"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"]))}}),ye={flex:"~ col gap-4"},_e={flex:"~ row","items-center":"","gap-2":""},ge={flex:"1"},xe={class:"flex items-center gap-1 text-sm font-medium"},Ve={class:"text-xs text-neutral-500 dark:text-neutral-400"},Re=m({__name:"FieldCheckbox",props:A({label:null,description:null},{modelValue:{type:Boolean,required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,n=C(t,"modelValue");return(o,l)=>(c(),g("label",ye,[f("div",_e,[f("div",ge,[f("div",xe,x(e.label),1),f("div",Ve,x(e.description),1)]),$(be,{modelValue:n.value,"onUpdate:modelValue":l[0]||(l[0]=r=>n.value=r)},null,8,["modelValue"])])]))}}),$e=["min","max","step"],we=m({__name:"Range",props:A({min:{default:0},max:{default:100},step:{default:1},disabled:{type:Boolean,default:!1},thumbColor:{default:"#9090906e"},trackColor:{default:"gray"},trackValueColor:{default:"red"}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,n=C(t,"modelValue"),o=v(()=>e.min*1e4),l=v(()=>e.max*1e4),r=v(()=>e.step*1e4),a=V(),u=v({get:()=>n.value*1e4,set:i=>{n.value=i/1e4,p()}});P(()=>{p()});function p(){a.value&&(a.value.style.setProperty("--value",a.value.value),a.value.style.setProperty("--min",a.value.min?a.value.min:e.min.toString()),a.value.style.setProperty("--max",a.value.max?a.value.max:e.max.toString()))}function h(i){const s=i.target;s.style.setProperty("--value",s.value)}return(i,s)=>Z((c(),g("input",{ref_key:"sliderRef",ref:a,"onUpdate:modelValue":s[0]||(s[0]=b=>u.value=b),type:"range",min:o.value,max:l.value,step:r.value,class:"slider-progress form_input-range",onInput:h},null,40,$e)),[[ee,u.value,void 0,{number:!0}]])}}),ke=B(we,[["__scopeId","data-v-d88ffd28"]]),Ce={flex:"~ col gap-4"},Ee={flex:"~ row","items-center":"","gap-2":""},Se={flex:"1"},Me={class:"flex items-center gap-1 text-sm font-medium"},Be={class:"text-xs text-neutral-500 dark:text-neutral-400"},je={"font-mono":""},Ae={flex:"~ row","items-center":"","gap-2":""},Oe=m({__name:"FieldRange",props:A({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,n=C(t,"modelValue");return(o,l)=>{var r;return c(),g("label",Ce,[f("div",Ee,[f("div",Se,[f("div",Me,x(t.label),1),f("div",Be,x(t.description),1)]),f("span",je,x(((r=e.formatValue)==null?void 0:r.call(e,n.value))||n.value),1)]),f("div",Ae,[$(ke,{modelValue:n.value,"onUpdate:modelValue":l[0]||(l[0]=a=>n.value=a),min:t.min||0,max:t.max||1,step:t.step||.01,"w-full":""},null,8,["modelValue","min","max","step"])])])}}});export{Oe as _,Re as a,Ie as b}; +import{d as m,c as g,o as c,z as M,f as k,_ as B,r as V,aL as E,H as P,I as T,e as f,A as b,w as _,i as $,F as I,aM as N,E as w,aN as D,aI as S,b as d,aH as L,aX as z,h as v,bb as j,aE as H,bc as U,v as K,l as X,aC as G,bd as W,j as Y,b4 as J,X as Q,u as C,m as A,t as x,x as Z,y as ee}from"./index-CQudhZin.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";const te=m({__name:"Volumed",props:{perspective:null,transform:null},setup(t){return(e,n)=>(c(),g("div",{class:"volumed",style:M({perspective:`${t.perspective}px`,transform:t.transform})},[k(e.$slots,"default",{},void 0,!0)],4))}}),ae=B(te,[["__scopeId","data-v-568551bc"]]),ne=m({__name:"CursorMomentum",props:{baseSpeed:{default:.1},friction:{default:.95},momentumFactor:{default:.005}},setup(t,{expose:e}){const n=t,o=V(1),l=V(0);let r=0;const a=E(()=>n.friction),u=E(()=>n.baseSpeed),p=E(()=>n.momentumFactor);function h(s){r||(r=s);const y=s-r;r=s,o.value=u.value+(o.value-u.value)*a.value,l.value+=o.value*y,requestAnimationFrame(h)}function i(s){const y=Math.sqrt(s.movementX**2+s.movementY**2);o.value+=y*p.value}return P(()=>{window.addEventListener("mousemove",i),requestAnimationFrame(h)}),T(()=>{window.removeEventListener("mousemove",i)}),e({momentum:o,currentValue:l}),(s,y)=>k(s.$slots,"default",{momentum:o.value,currentValue:l.value})}}),le=m({__name:"TestDummyMarkerFlat",props:{size:null},setup(t){return(e,n)=>(c(),g("div",{class:"test-dummy-flat",style:M({width:`${t.size}px`,height:`${t.size}px`})},n[0]||(n[0]=[f("div",{class:"marker"},null,-1)]),4))}}),oe=B(le,[["__scopeId","data-v-b4ef37ac"]]),Ie=m({__name:"TestDummyMarker",setup(t){return(e,n)=>(c(),b(ne,{"base-speed":.1,friction:.95,"momentum-factor":5e-4},{default:_(({currentValue:o})=>[$(ae,{perspective:800,transform:"rotateX(45deg) translateY(3px)"},{default:_(()=>[$(oe,{size:24,style:M({transform:`rotate(${o}deg)`})},null,8,["style"])]),_:2},1024)]),_:1}))}});function R(t){return t?t.flatMap(e=>e.type===I?R(e.children):[e]):[]}const re=m({name:"PrimitiveSlot",inheritAttrs:!1,setup(t,{attrs:e,slots:n}){return()=>{var p,h;if(!n.default)return null;const o=R(n.default()),l=o.findIndex(i=>i.type!==N);if(l===-1)return o;const r=o[l];(p=r.props)==null||delete p.ref;const a=r.props?w(e,r.props):e;e.class&&((h=r.props)!=null&&h.class)&&delete r.props.class;const u=D(r,a);for(const i in a)i.startsWith("on")&&(u.props||(u.props={}),u.props[i]=a[i]);return o.length===1?u:(o[l]=u,o)}}}),se=["area","img","input"],q=m({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(t,{attrs:e,slots:n}){const o=t.asChild?"template":t.as;return typeof o=="string"&&se.includes(o)?()=>S(o,e):o!=="template"?()=>S(t.as,e,{default:n.default}):()=>S(re,e,{default:n.default})}}),ue=m({__name:"VisuallyHidden",props:{feature:{default:"focusable"},asChild:{type:Boolean},as:{default:"span"}},setup(t){return(e,n)=>(c(),b(d(q),{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:_(()=>[k(e.$slots,"default")]),_:3},8,["as","as-child","aria-hidden","data-hidden","tabindex"]))}});function ie(t,e){const n=`${t}Context`,o=Symbol(n);return[a=>{const u=L(o,a);if(u||u===null)return u;throw new Error(`Injection \`${o.toString()}\` not found. Component must be used within ${Array.isArray(t)?`one of the following components: ${t.join(", ")}`:`\`${t}\``}`)},a=>(z(o,a),a)]}function O(){const t=H(),e=V(),n=v(()=>{var a,u;return["#text","#comment"].includes((a=e.value)==null?void 0:a.$el.nodeName)?(u=e.value)==null?void 0:u.$el.nextElementSibling:j(e)}),o=Object.assign({},t.exposed),l={};for(const a in t.props)Object.defineProperty(l,a,{enumerable:!0,configurable:!0,get:()=>t.props[a]});if(Object.keys(o).length>0)for(const a in o)Object.defineProperty(l,a,{enumerable:!0,configurable:!0,get:()=>o[a]});Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>t.vnode.el}),t.exposed=l;function r(a){e.value=a,a&&(Object.defineProperty(l,"$el",{enumerable:!0,configurable:!0,get:()=>a instanceof Element?a:a.$el}),t.exposed=l)}return{forwardRef:r,currentRef:e,currentElement:n}}function de(){const t=V(),e=v(()=>{var n,o;return["#text","#comment"].includes((n=t.value)==null?void 0:n.$el.nodeName)?(o=t.value)==null?void 0:o.$el.nextElementSibling:j(t)});return{primitiveElement:t,currentElement:e}}function ce(t){return v(()=>{var e;return U(t)?!!((e=j(t))!=null&&e.closest("form")):!0})}const F=m({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:n,currentElement:o}=de(),l=v(()=>e.checked??e.value);return K(l,(r,a)=>{if(!o.value)return;const u=o.value,p=window.HTMLInputElement.prototype,i=Object.getOwnPropertyDescriptor(p,"value").set;if(i&&r!==a){const s=new Event("input",{bubbles:!0}),y=new Event("change",{bubbles:!0});i.call(u,r),u.dispatchEvent(s),u.dispatchEvent(y)}}),(r,a)=>(c(),b(ue,w({ref_key:"primitiveElement",ref:n},{...e,...r.$attrs},{as:"input"}),null,16))}}),me=m({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,n=v(()=>typeof e.value=="object"&&Array.isArray(e.value)&&e.value.length===0&&e.required),o=v(()=>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((l,r)=>typeof l=="object"?Object.entries(l).map(([a,u])=>({name:`[${e.name}][${r}][${a}]`,value:u})):{name:`[${e.name}][${r}]`,value:l}):e.value!==null&&typeof e.value=="object"&&!Array.isArray(e.value)?Object.entries(e.value).map(([l,r])=>({name:`[${e.name}][${l}]`,value:r})):[]);return(l,r)=>n.value?(c(),b(F,w({key:l.name},{...e,...l.$attrs},{name:l.name,value:l.value}),null,16,["name","value"])):(c(!0),g(I,{key:1},X(o.value,a=>(c(),b(F,w({key:a.name,ref_for:!0},{...e,...l.$attrs},{name:a.name,value:a.value}),null,16,["name","value"]))),128))}}),[pe,fe]=ie("SwitchRoot"),ve=m({__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 n=t,o=e,{disabled:l}=G(n),r=W(n,"modelValue",o,{defaultValue:n.defaultValue,passive:n.modelValue===void 0});function a(){l.value||(r.value=!r.value)}const{forwardRef:u,currentElement:p}=O(),h=ce(p),i=v(()=>{var s;return n.id&&p.value?(s=document.querySelector(`[for="${n.id}"]`))==null?void 0:s.innerText:void 0});return fe({modelValue:r,toggleCheck:a,disabled:l}),(s,y)=>(c(),b(d(q),w(s.$attrs,{id:s.id,ref:d(u),role:"switch",type:s.as==="button"?"button":void 0,value:s.value,"aria-label":s.$attrs["aria-label"]||i.value,"aria-checked":d(r),"aria-required":s.required,"data-state":d(r)?"checked":"unchecked","data-disabled":d(l)?"":void 0,"as-child":s.asChild,as:s.as,disabled:d(l),onClick:a,onKeydown:J(Q(a,["prevent"]),["enter"])}),{default:_(()=>[k(s.$slots,"default",{modelValue:d(r)}),d(h)&&s.name?(c(),b(d(me),{key:0,type:"checkbox",name:s.name,disabled:d(l),required:s.required,value:s.value,checked:!!d(r)},null,8,["name","disabled","required","value","checked"])):Y("",!0)]),_:3},16,["id","type","value","aria-label","aria-checked","aria-required","data-state","data-disabled","as-child","as","disabled","onKeydown"]))}}),he=m({__name:"SwitchThumb",props:{asChild:{type:Boolean},as:{default:"span"}},setup(t){const e=pe();return O(),(n,o)=>{var l;return c(),b(d(q),{"data-state":(l=d(e).modelValue)!=null&&l.value?"checked":"unchecked","data-disabled":d(e).disabled.value?"":void 0,"as-child":n.asChild,as:n.as},{default:_(()=>[k(n.$slots,"default")]),_:3},8,["data-state","data-disabled","as-child","as"])}}}),ye=m({__name:"Checkbox",props:{modelValue:{type:Boolean,required:!0},modelModifiers:{}},emits:["update:modelValue"],setup(t){const e=C(t,"modelValue");return(n,o)=>(c(),b(d(ve),{modelValue:e.value,"onUpdate:modelValue":o[0]||(o[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:_(()=>[$(d(he),{"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"]))}}),be={flex:"~ col gap-4"},_e={flex:"~ row","items-center":"","gap-2":""},ge={flex:"1"},xe={class:"flex items-center gap-1 text-sm font-medium"},Ve={class:"text-xs text-neutral-500 dark:text-neutral-400"},Re=m({__name:"FieldCheckbox",props:A({label:null,description:null},{modelValue:{type:Boolean,required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,n=C(t,"modelValue");return(o,l)=>(c(),g("label",be,[f("div",_e,[f("div",ge,[f("div",xe,x(e.label),1),f("div",Ve,x(e.description),1)]),$(ye,{modelValue:n.value,"onUpdate:modelValue":l[0]||(l[0]=r=>n.value=r)},null,8,["modelValue"])])]))}}),$e=["min","max","step"],we=m({__name:"Range",props:A({min:{default:0},max:{default:100},step:{default:1},disabled:{type:Boolean,default:!1},thumbColor:{default:"#9090906e"},trackColor:{default:"gray"},trackValueColor:{default:"red"}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(t){const e=t,n=C(t,"modelValue"),o=v(()=>e.min*1e4),l=v(()=>e.max*1e4),r=v(()=>e.step*1e4),a=V(),u=v({get:()=>n.value*1e4,set:i=>{n.value=i/1e4,p()}});P(()=>{p()});function p(){a.value&&(a.value.style.setProperty("--value",a.value.value),a.value.style.setProperty("--min",a.value.min?a.value.min:e.min.toString()),a.value.style.setProperty("--max",a.value.max?a.value.max:e.max.toString()))}function h(i){const s=i.target;s.style.setProperty("--value",s.value)}return(i,s)=>Z((c(),g("input",{ref_key:"sliderRef",ref:a,"onUpdate:modelValue":s[0]||(s[0]=y=>u.value=y),type:"range",min:o.value,max:l.value,step:r.value,class:"slider-progress form_input-range",onInput:h},null,40,$e)),[[ee,u.value,void 0,{number:!0}]])}}),ke=B(we,[["__scopeId","data-v-d88ffd28"]]),Ce={flex:"~ col gap-4"},Ee={flex:"~ row","items-center":"","gap-2":""},Se={flex:"1"},Me={class:"flex items-center gap-1 text-sm font-medium"},Be={class:"text-xs text-neutral-500 dark:text-neutral-400"},je={"font-mono":""},Ae={flex:"~ row","items-center":"","gap-2":""},Oe=m({__name:"FieldRange",props:A({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,n=C(t,"modelValue");return(o,l)=>{var r;return c(),g("label",Ce,[f("div",Ee,[f("div",Se,[f("div",Me,x(t.label),1),f("div",Be,x(t.description),1)]),f("span",je,x(((r=e.formatValue)==null?void 0:r.call(e,n.value))||n.value),1)]),f("div",Ae,[$(ke,{modelValue:n.value,"onUpdate:modelValue":l[0]||(l[0]=a=>n.value=a),min:t.min||0,max:t.max||1,step:t.step||.01,"w-full":""},null,8,["modelValue","min","max","step"])])])}}});export{Oe as _,Re as a,Ie as b}; diff --git a/assets/HeaderLink-CnrAQmsl.js b/assets/HeaderLink-DVu0ldr4.js similarity index 81% rename from assets/HeaderLink-CnrAQmsl.js rename to assets/HeaderLink-DVu0ldr4.js index 0ab0a4e37027c40f651d1cd484258db58d39ba33..a28e42905363640db83904f33e05606fe2309f74 100644 --- a/assets/HeaderLink-CnrAQmsl.js +++ b/assets/HeaderLink-DVu0ldr4.js @@ -1 +1 @@ -import{d as r,bt as c,A as l,b as e,P as d,o as s,w as _,c as t,e as a,_ as i}from"./index-BQKiy4UR.js";const k="/assets/logo-dark-CO0kwKsz.svg",p="/assets/logo-D6zeZTFl.svg",u=["src"],m=["src"],g=r({__name:"HeaderLink",setup(x){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(g,[["__scopeId","data-v-496b6cde"]]);export{w as H}; +import{d as r,aY as c,A as l,b as e,P as d,o as s,w as _,c as t,e as a,_ as i}from"./index-CQudhZin.js";const k="/assets/logo-dark-CO0kwKsz.svg",p="/assets/logo-D6zeZTFl.svg",u=["src"],m=["src"],g=r({__name:"HeaderLink",setup(x){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(g,[["__scopeId","data-v-496b6cde"]]);export{w as H}; diff --git a/assets/IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js b/assets/IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js similarity index 95% rename from assets/IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js rename to assets/IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js index 883612c072312d5737efc50337a27bb13fe6622f..8a8c968716f8cbe8d251aea3c377afefdcd61f8b 100644 --- a/assets/IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js +++ b/assets/IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js @@ -1 +1 @@ -import{d as m,r as s,v as p,h,c as f,o as x,z as l,e as u,n as y}from"./index-BQKiy4UR.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",{fixed:"","inset-0":"","bg-primary-500":"","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,r as s,v as p,h,c as f,o as x,z as l,e as u,n as y}from"./index-CQudhZin.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",{fixed:"","inset-0":"","bg-primary-500":"","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-DqA2VeX5.js b/assets/IconStatusItem-CzuT67Cw.js similarity index 94% rename from assets/IconStatusItem-DqA2VeX5.js rename to assets/IconStatusItem-CzuT67Cw.js index ddac0e1bcba80575352f65ca5cda55ce9ab12a57..700420d885b7aecbd90234ff963a077a3ceb811a 100644 --- a/assets/IconStatusItem-DqA2VeX5.js +++ b/assets/IconStatusItem-CzuT67Cw.js @@ -1 +1 @@ -import{d as u,N as c,c as e,o as n,i as d,e as o,w as m,j as a,t as i,n as s,_}from"./index-BQKiy4UR.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";const p={flex:"~ col",bg:"neutral-50 dark:neutral-800",border:"neutral-100 dark:neutral-800/25 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(I,w)=>{const l=c("RouterLink");return n(),e("div",p,[d(l,{flex:"~ row",class:"menu-icon-status-item-link",bg:"white dark:neutral-900",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,i(t.title),1),o("div",k,[o("span",null,i(t.description),1)])]),t.icon?(n(),e("div",{key:0,class:s(["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:s(["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))])])}}}),B=_(b,[["__scopeId","data-v-6e5b5c9c"]]);export{B as I}; +import{d as u,N as c,c as e,o as n,i as d,e as o,w as m,j as a,t as i,n as s,_}from"./index-CQudhZin.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";const p={flex:"~ col",bg:"neutral-50 dark:neutral-800",border:"neutral-100 dark:neutral-800/25 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(I,w)=>{const l=c("RouterLink");return n(),e("div",p,[d(l,{flex:"~ row",class:"menu-icon-status-item-link",bg:"white dark:neutral-900",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,i(t.title),1),o("div",k,[o("span",null,i(t.description),1)])]),t.icon?(n(),e("div",{key:0,class:s(["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:s(["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))])])}}}),B=_(b,[["__scopeId","data-v-6e5b5c9c"]]);export{B as I}; diff --git a/assets/Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js b/assets/Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js similarity index 91% rename from assets/Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js rename to assets/Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js index 136c29cc811c990c9d6ad169048d3a89749d0f81..2462d33e371ebcfe84fe9deeb7b9794c25934691 100644 --- a/assets/Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js +++ b/assets/Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js @@ -1 +1 @@ -import{d as r,m as n,u,x as s,J as d,o as i,c as m}from"./index-BQKiy4UR.js";const p=["type"],x=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(),m("input",{"onUpdate:modelValue":a[0]||(a[0]=o=>t.value=o),type:l.type||"text",border:"focus:primary-300 dark:focus:primary-400/50 2 solid neutral-100 dark:neutral-900",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-50 dark:neutral-950 focus:neutral-50 dark:focus:neutral-900"},null,8,p)),[[d,t.value]])}});export{x as _}; +import{d as r,m as n,u,x as s,J as d,o as i,c as m}from"./index-CQudhZin.js";const p=["type"],x=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(),m("input",{"onUpdate:modelValue":a[0]||(a[0]=o=>t.value=o),type:l.type||"text",border:"focus:primary-300 dark:focus:primary-400/50 2 solid neutral-100 dark:neutral-900",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-50 dark:neutral-950 focus:neutral-50 dark:focus:neutral-900"},null,8,p)),[[d,t.value]])}});export{x as _}; diff --git a/assets/InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js b/assets/InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js similarity index 96% rename from assets/InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js rename to assets/InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js index d39e8f24032e9fa402c9ebfd59c74ac9401c7494..0de41260bae10386c99eeb95c75c6742681c4cfa 100644 --- a/assets/InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js +++ b/assets/InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js @@ -1 +1 @@ -import{d as g,m as b,u as v,r as p,a as y,c as i,o as n,n as m,b as t,e as l,f as x}from"./index-BQKiy4UR.js";const k=["accept","multiple"],h={key:0,text:"center","text-sm":""},D={key:1,text:"center","text-sm":""},C=g({__name:"InputFile",props:b({accept:null,multiple:{type:Boolean}},{modelValue:{required:!1,default:()=>[]},modelModifiers:{}}),emits:["update:modelValue"],setup(o){const d=v(o,"modelValue"),u=p(),a=p(!1),r=y(a,150);function f(s){const e=s.target;e.files&&e.files.length>0&&(u.value=e.files[0]),d.value=Array.from(e.files||[]),a.value=!1}return(s,e)=>(n(),i("label",{relative:"",class:m(["min-h-[120px] flex flex-col cursor-pointer items-center justify-center rounded-xl p-6",[t(r)?"border-primary-400 dark:border-primary-600 hover:border-primary-300 dark:hover:border-primary-700":"border-neutral-200 dark:border-neutral-700 hover:border-primary-300 dark:hover:border-primary-700",t(r)?"bg-primary-50/5 dark:bg-primary-900/5":"bg-white/60 dark:bg-black/30 hover:bg-white/80 dark:hover:bg-black/40"]]),border:"dashed 2",transition:"all duration-300","cursor-pointer":"","opacity-95":"",hover:"scale-100 opacity-100 shadow-md dark:shadow-lg",onDragover:e[0]||(e[0]=c=>a.value=!0),onDragleave:e[1]||(e[1]=c=>a.value=!1)},[l("input",{type:"file",accept:o.accept,multiple:o.multiple,"cursor-pointer":"",class:"absolute inset-0 h-full w-full opacity-0",onChange:f},null,40,k),x(s.$slots,"default",{isDragging:t(r),firstFile:u.value,files:d.value},()=>[l("div",{class:m(["flex flex-col items-center",[t(r)?"text-primary-500 dark:text-primary-400":"text-neutral-400 dark:text-neutral-500"]])},[e[2]||(e[2]=l("div",{"i-solar:upload-square-line-duotone":"","mb-2":"","text-5xl":""},null,-1)),e[3]||(e[3]=l("p",{"font-medium":"",text:"center lg"}," Upload ",-1)),t(r)?(n(),i("p",h," Release to upload ")):(n(),i("p",D," Click or drag and drop a file here "))],2)])],34))}});export{C as _}; +import{d as g,m as b,u as v,r as p,a as y,c as i,o as n,n as m,b as t,e as l,f as x}from"./index-CQudhZin.js";const k=["accept","multiple"],h={key:0,text:"center","text-sm":""},D={key:1,text:"center","text-sm":""},C=g({__name:"InputFile",props:b({accept:null,multiple:{type:Boolean}},{modelValue:{required:!1,default:()=>[]},modelModifiers:{}}),emits:["update:modelValue"],setup(o){const d=v(o,"modelValue"),u=p(),a=p(!1),r=y(a,150);function f(s){const e=s.target;e.files&&e.files.length>0&&(u.value=e.files[0]),d.value=Array.from(e.files||[]),a.value=!1}return(s,e)=>(n(),i("label",{relative:"",class:m(["min-h-[120px] flex flex-col cursor-pointer items-center justify-center rounded-xl p-6",[t(r)?"border-primary-400 dark:border-primary-600 hover:border-primary-300 dark:hover:border-primary-700":"border-neutral-200 dark:border-neutral-700 hover:border-primary-300 dark:hover:border-primary-700",t(r)?"bg-primary-50/5 dark:bg-primary-900/5":"bg-white/60 dark:bg-black/30 hover:bg-white/80 dark:hover:bg-black/40"]]),border:"dashed 2",transition:"all duration-300","cursor-pointer":"","opacity-95":"",hover:"scale-100 opacity-100 shadow-md dark:shadow-lg",onDragover:e[0]||(e[0]=c=>a.value=!0),onDragleave:e[1]||(e[1]=c=>a.value=!1)},[l("input",{type:"file",accept:o.accept,multiple:o.multiple,"cursor-pointer":"",class:"absolute inset-0 h-full w-full opacity-0",onChange:f},null,40,k),x(s.$slots,"default",{isDragging:t(r),firstFile:u.value,files:d.value},()=>[l("div",{class:m(["flex flex-col items-center",[t(r)?"text-primary-500 dark:text-primary-400":"text-neutral-400 dark:text-neutral-500"]])},[e[2]||(e[2]=l("div",{"i-solar:upload-square-line-duotone":"","mb-2":"","text-5xl":""},null,-1)),e[3]||(e[3]=l("p",{"font-medium":"",text:"center lg"}," Upload ",-1)),t(r)?(n(),i("p",h," Release to upload ")):(n(),i("p",D," Click or drag and drop a file here "))],2)])],34))}});export{C as _}; diff --git a/assets/Model.vue_vue_type_script_setup_true_lang-Dx1Lxvvu.js b/assets/Model.vue_vue_type_script_setup_true_lang-PK96Pm-_.js similarity index 79% rename from assets/Model.vue_vue_type_script_setup_true_lang-Dx1Lxvvu.js rename to assets/Model.vue_vue_type_script_setup_true_lang-PK96Pm-_.js index 6433e2888d244b7c7af2920a02ff4b71bff8104d..664a75686737e8eb183b808e0019003239166455 100644 --- a/assets/Model.vue_vue_type_script_setup_true_lang-Dx1Lxvvu.js +++ b/assets/Model.vue_vue_type_script_setup_true_lang-PK96Pm-_.js @@ -1 +1 @@ -import{e as P,T as Y,A as re,L as C,a as $,D as ue,I as se,l as R,M as de,b as T}from"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{bv as ce,d as G,r as f,v as p,H as N,I as X,c as j,o as q,f as U,bh as z,h as O,bt as ve,bw as pe,b4 as fe,s as he,G as me,au as ge,bx as Me,F as we,e as ye,by as be}from"./index-BQKiy4UR.js";import{r as Se}from"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";const xe=o=>Math.max(0,Math.min(1,o||0)),B=o=>Math.round(xe(o)*255),Fe=ce("rgb"),Be=o=>{if(o===void 0)return;let l=B(o.r),t=B(o.g),d=B(o.b);return"#"+(1<<24|l<<16|t<<8|d).toString(16).slice(1)},Pe=o=>Be(Fe(o)),Ee=G({__name:"Canvas",props:{width:null,height:null},setup(o,{expose:l}){const t=o,d=f(),e=f(),i=f();async function c(n){C.registerTicker($),P.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()),N(async()=>d.value&&await c(d.value)),X(()=>{var n;return(n=e.value)==null?void 0:n.destroy()});async function F(){return new Promise(g=>{if(!i.value||!e.value)return g(null);e.value.render(),i.value.toBlob(g)})}return l({captureFrame:F}),(n,g)=>(q(),j("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 Ce(){let o=-1,l,t=-1;function d(e,i){(i>=o||il.app),d=z(()=>l.paused),e=f(),i=f(0),c=f(0),y=O(()=>Math.max(0,Math.min(100,l.mouthOpenSize))),F=ve(),n=pe(be),g=O(()=>n.between("sm","md").value||n.smaller("sm").value),W=Ce(),I=fe(new ue({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 h=l.height*.95/c.value*r,s=l.width*.95/i.value*r,m=Math.min(h,s);a.value.scale.set(m,m)}const{live2dModelFile:b,loadingLive2dModel:M,live2dCurrentMotion:K,availableLive2dMotions:Q,live2dLoadSource:S,live2dModelUrl:k,themeColorsHue:Z,themeColorsHueDynamic:_}=he(me()),ee=f({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 C;S.value==="file"?await T.setupLive2DModel(a,[b.value]):S.value==="url"&&await T.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,h=r.coreModel,s=r.motionManager;h.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 R.setItem("live2dModel",b.value),M.value=!1}async function te(){if(!t.value)return;C.registerTicker($),P.add(Y),P.add(se);const a=await R.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,de.FORCE)}const oe=ge(()=>{e.value&&(e.value.x=l.width/2,e.value.y=l.height,D(e))},100),A=f(),w=f(0);function x(){if(e.value){const a=getComputedStyle(A.value).backgroundColor;I.value.color=Number(Pe(a).replace("#","0x")),e.value.filters=[I.value]}}p([()=>l.width,()=>l.height],()=>oe()),p(F,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,h;a?(r=t.value)==null||r.stop():(h=t.value)==null||h.start()}),Me(M,a=>{a&&ae()},{debounce:1e3}),N(x),X(()=>{var a;cancelAnimationFrame(w.value),e.value&&((a=t.value)==null||a.stage.removeChild(e.value))}),(a,r)=>(q(),j(we,null,[ye("div",{ref_key:"dropShadowColorComputer",ref:A,hidden:"",bg:"primary-400 dark:primary-500"},null,512),U(a.$slots,"default")],64))}});export{Le as _,Ee as a,H as r}; +import{e as P,T as Y,A as re,L as C,a as $,D as ue,I as se,l as R,M as de,b as T}from"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{a_ as ce,d as G,r as f,v as p,H as N,I as X,c as j,o as q,f as U,aL as z,h as O,aY as ve,a$ as pe,ay as fe,s as he,G as me,aw as ge,b0 as Me,F as we,e as ye,b1 as be}from"./index-CQudhZin.js";import{r as Se}from"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";const xe=o=>Math.max(0,Math.min(1,o||0)),B=o=>Math.round(xe(o)*255),Fe=ce("rgb"),Be=o=>{if(o===void 0)return;let l=B(o.r),t=B(o.g),d=B(o.b);return"#"+(1<<24|l<<16|t<<8|d).toString(16).slice(1)},Pe=o=>Be(Fe(o)),Le=G({__name:"Canvas",props:{width:null,height:null},setup(o,{expose:l}){const t=o,d=f(),e=f(),i=f();async function c(n){C.registerTicker($),P.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()),N(async()=>d.value&&await c(d.value)),X(()=>{var n;return(n=e.value)==null?void 0:n.destroy()});async function F(){return new Promise(g=>{if(!i.value||!e.value)return g(null);e.value.render(),i.value.toBlob(g)})}return l({captureFrame:F}),(n,g)=>(q(),j("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 Ce(){let o=-1,l,t=-1;function d(e,i){(i>=o||il.app),d=z(()=>l.paused),e=f(),i=f(0),c=f(0),y=O(()=>Math.max(0,Math.min(100,l.mouthOpenSize))),F=ve(),n=pe(be),g=O(()=>n.between("sm","md").value||n.smaller("sm").value),W=Ce(),I=fe(new ue({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 h=l.height*.95/c.value*r,s=l.width*.95/i.value*r,m=Math.min(h,s);a.value.scale.set(m,m)}const{live2dModelFile:b,loadingLive2dModel:M,live2dCurrentMotion:K,availableLive2dMotions:Q,live2dLoadSource:S,live2dModelUrl:_,themeColorsHue:Z,themeColorsHueDynamic:k}=he(me()),ee=f({group:"Idle",index:0});async function ae(){var E;if(!t.value)return;e.value&&(t.value.stage.removeChild(e.value),e.value.destroy(),e.value=void 0);const a=new C;S.value==="file"?await T.setupLive2DModel(a,[b.value]):S.value==="url"&&await T.setupLive2DModel(a,_.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,h=r.coreModel,s=r.motionManager;h.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&&((E=s.motionGroups[s.groups.idle])==null||E.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 R.setItem("live2dModel",b.value),M.value=!1}async function te(){if(!t.value)return;C.registerTicker($),P.add(Y),P.add(se);const a=await R.getItem("live2dModel");if(a){b.value=a,S.value="file",M.value=!0;return}if(_.value){S.value="url",M.value=!0;return}M.value=!1}async function le(a,r){await e.value.motion(a,r,de.FORCE)}const oe=ge(()=>{e.value&&(e.value.x=l.width/2,e.value.y=l.height,D(e))},100),A=f(),w=f(0);function x(){if(e.value){const a=getComputedStyle(A.value).backgroundColor;I.value.color=Number(Pe(a).replace("#","0x")),e.value.filters=[I.value]}}p([()=>l.width,()=>l.height],()=>oe()),p(F,x,{immediate:!0}),p([e,Z],x);function L(){x(),w.value=requestAnimationFrame(L)}return p(k,()=>{k.value?w.value=requestAnimationFrame(L):(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,h;a?(r=t.value)==null||r.stop():(h=t.value)==null||h.start()}),Me(M,a=>{a&&ae()},{debounce:1e3}),N(x),X(()=>{var a;cancelAnimationFrame(w.value),e.value&&((a=t.value)==null||a.stage.removeChild(e.value))}),(a,r)=>(q(),j(we,null,[ye("div",{ref_key:"dropShadowColorComputer",ref:A,hidden:"",bg:"primary-400 dark:primary-500"},null,512),U(a.$slots,"default")],64))}});export{Ee as _,Le as a,H as r}; diff --git a/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js b/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js similarity index 78% rename from assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js rename to assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js index 9e2db57d306f6892c9aa3b70200979eb64bdfc73..127734c0af36c5a06c180fb82542f20802a32ba4 100644 --- a/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js +++ b/assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js @@ -1 +1 @@ -import{_ as t}from"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{d as u,m as n,g as m,u as p,h as c,A as f,o as v,b as a}from"./index-BQKiy4UR.js";const g=u({__name:"ProviderApiKeyInput",props:n({providerName:null,placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const l=e,{t:d}=m(),o=p(e,"modelValue"),i=c(()=>l.description||`API Key for ${l.providerName}`);return(V,r)=>(v(),f(a(t),{modelValue:o.value,"onUpdate:modelValue":r[0]||(r[0]=s=>o.value=s),label:e.label||a(d)("settings.pages.providers.common.fields.field.api-key.label"),description:i.value,placeholder:e.placeholder,required:e.required,type:"password"},null,8,["modelValue","label","description","placeholder","required"]))}});export{g as _}; +import{_ as t}from"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{d as u,m as n,g as m,u as p,h as c,A as f,o as v,b as a}from"./index-CQudhZin.js";const g=u({__name:"ProviderApiKeyInput",props:n({providerName:null,placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(e){const l=e,{t:d}=m(),o=p(e,"modelValue"),i=c(()=>l.description||`API Key for ${l.providerName}`);return(V,r)=>(v(),f(a(t),{modelValue:o.value,"onUpdate:modelValue":r[0]||(r[0]=s=>o.value=s),label:e.label||a(d)("settings.pages.providers.common.fields.field.api-key.label"),description:i.value,placeholder:e.placeholder,required:e.required,type:"password"},null,8,["modelValue","label","description","placeholder","required"]))}});export{g as _}; diff --git a/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js b/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js similarity index 81% rename from assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js rename to assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js index c3d45f01a0fc906bea04174ab7030b090c75963b..1371b1072d9ecaee4d502fd69a008198fbfd5c9c 100644 --- a/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js +++ b/assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js @@ -1 +1 @@ -import{_ as p}from"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import{d,r as m,A as u,o as c,w as n,e,f,t as _,n as v,m as b,u as V,b as g}from"./index-BQKiy4UR.js";import{_ as x}from"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";const h=["onClick"],B={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},w={"mt-4":""},U=d({__name:"ProviderAdvancedSettings",props:{title:null,initialVisible:{type:Boolean}},setup(l){const a=m(l.initialVisible||!1);function s(){a.value=!a.value}return(o,i)=>(c(),u(p,{"w-full":""},{trigger:n(r=>[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:()=>r.setVisible(!r.visible)&&s()},[e("h2",B,[e("span",null,_(l.title||"Advanced"),1)]),e("div",{transform:"",transition:"transform duration-250",class:v({"rotate-180":r.visible})},i[0]||(i[0]=[e("div",{"i-solar:alt-arrow-down-bold-duotone":""},null,-1)]),2)],8,h)]),default:n(()=>[e("div",w,[f(o.$slots,"default")])]),_:3}))}}),$=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=V(l,"modelValue");return(s,o)=>(c(),u(g(x),{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{U as _,$ as a}; +import{_ as p}from"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import{d,r as m,A as u,o as c,w as n,e,f,t as _,n as v,m as b,u as V,b as g}from"./index-CQudhZin.js";import{_ as x}from"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";const h=["onClick"],B={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},w={"mt-4":""},U=d({__name:"ProviderAdvancedSettings",props:{title:null,initialVisible:{type:Boolean}},setup(l){const a=m(l.initialVisible||!1);function s(){a.value=!a.value}return(o,i)=>(c(),u(p,{"w-full":""},{trigger:n(r=>[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:()=>r.setVisible(!r.visible)&&s()},[e("h2",B,[e("span",null,_(l.title||"Advanced"),1)]),e("div",{transform:"",transition:"transform duration-250",class:v({"rotate-180":r.visible})},i[0]||(i[0]=[e("div",{"i-solar:alt-arrow-down-bold-duotone":""},null,-1)]),2)],8,h)]),default:n(()=>[e("div",w,[f(o.$slots,"default")])]),_:3}))}}),$=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=V(l,"modelValue");return(s,o)=>(c(),u(g(x),{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{U as _,$ as a}; diff --git a/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js b/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js similarity index 94% rename from assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js rename to assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js index d5c06a3a4732153a8240c5f66d2f72455a4c4558..20fcc4f7f9913b74fa8d10d1f83a93015194a024 100644 --- a/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js +++ b/assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js @@ -1 +1 @@ -import{d as o,c as s,o as a,e,f as i,j as u,t as l}from"./index-BQKiy4UR.js";const c={flex:"~ col gap-6"},f={flex:"~ row","items-center":"","justify-between":""},x={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},m={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",f,[e("div",null,[e("h2",x,l(t.title||"Basic"),1),e("div",m,[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")]))}}),p={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",p,[i(r.$slots,"default")]))}});export{k as _,g as a}; +import{d as o,c as s,o as a,e,f as i,j as u,t as l}from"./index-CQudhZin.js";const c={flex:"~ col gap-6"},f={flex:"~ row","items-center":"","justify-between":""},x={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},m={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",f,[e("div",null,[e("h2",x,l(t.title||"Basic"),1),e("div",m,[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")]))}}),p={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",p,[i(r.$slots,"default")]))}});export{k as _,g as a}; diff --git a/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js b/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js similarity index 90% rename from assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js rename to assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js index fc7640695b37cd04f90cb576aeb18a5dd60a2933..8fa19778944b31c607c2c8f422a6a0f0271491f1 100644 --- a/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js +++ b/assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js @@ -1 +1 @@ -import{d as a,K as i,c as o,o as t,f as s,x as l,e as c,n as d,F as p}from"./index-BQKiy4UR.js";const u={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":""},_=a({__name:"ProviderSettingsLayout",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function}},setup(e){return(n,v)=>{const r=i("motion");return t(),o(p,null,[s(n.$slots,"default"),l((t(),o("div",u,[c("div",{text:"60",class:d(e.providerIcon||e.providerIconColor)},null,2)])),[[r]])],64)}}});export{_}; +import{d as a,K as i,c as o,o as t,f as s,x as l,e as c,n as d,F as p}from"./index-CQudhZin.js";const u={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":""},_=a({__name:"ProviderSettingsLayout",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function}},setup(e){return(n,v)=>{const r=i("motion");return t(),o(p,null,[s(n.$slots,"default"),l((t(),o("div",u,[c("div",{text:"60",class:d(e.providerIcon||e.providerIconColor)},null,2)])),[[r]])],64)}}});export{_}; diff --git a/assets/RadioCardSimple-DdnP6Fc5.js b/assets/RadioCardSimple-B-Oog_Qf.js similarity index 89% rename from assets/RadioCardSimple-DdnP6Fc5.js rename to assets/RadioCardSimple-B-Oog_Qf.js index 97c995dafa7e1d2511b0be8888922d9a415e3f8b..2f188786bf4e3df97dfca22a72194fe54769fb6c 100644 --- a/assets/RadioCardSimple-DdnP6Fc5.js +++ b/assets/RadioCardSimple-B-Oog_Qf.js @@ -1 +1 @@ -import{d as g,m as f,u as w,r as b,c as n,o as d,n as o,x as V,e as t,bH as I,j as v,t as c,i as $,w as S,V as k,b as B,_ as C,h as T,y as z,F as E,l as N,A as D}from"./index-BQKiy4UR.js";import{_ as P}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import{_ as U}from"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";const q=["checked","name","value"],L={class:"relative mr-3 mt-0.5 flex-shrink-0"},j={class:"w-full flex flex-col gap-2"},F={class:"flex items-center"},A={key:0,class:"relative"},H=["title"],Q={key:1,class:"mt-2"},G=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 s(){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]=u=>a.value=u),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"absolute opacity-0"},null,8,q),[[I,a.value]]),t("div",L,[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",j,[t("div",F,[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,[$(B(P),null,{default:S(()=>[!m.value||!e.showExpandCollapse?(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(s,["prevent"])},c(e.description),11,H)):(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(s,["prevent"])},c(e.description),3))]),_:1}),e.showExpandCollapse&&e.description.length>e.expandCollapseThreshold?(d(),n("button",{key:0,class:"mt-0.5 inline-flex items-center text-xs text-primary-500 dark:text-primary-600",onClick:k(s,["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",Q,[$(B(U),{modelValue:a.value,"onUpdate:modelValue":r[1]||(r[1]=u=>a.value=u),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))}}),J=C(G,[["__scopeId","data-v-86a9d442"]]),K={class:"radio-card-detail-many-select"},O={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},W=["placeholder"],X={class:"mt-4 space-y-2"},Y={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},Z={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"},_={class:"flex flex-col"},ee={class:"font-medium"},te={class:"text-sm text-amber-600 dark:text-amber-400"},ae={class:"relative"},le=g({__name:"RadioCardManySelect",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"},showMore:{type:Boolean,default:!0}},{modelValue:{required:!0},modelModifiers:{}}),emits:f(["update:customValue"],["update:modelValue"]),setup(e,{emit:a}){const m=e,s=a,x=w(e,"modelValue"),r=b(""),u=b(!1),R=b(""),h=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 M(p){R.value=p,s("update:customValue",p)}return(p,l)=>(d(),n("div",K,[e.searchable?(d(),n("div",O,[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]=i=>r.value=i),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,W),[[z,r.value]])])):v("",!0),t("div",X,[r.value?(d(),n("div",Y,c(e.searchResultsText.replace("{count}",h.value.length.toString()).replace("{total}",e.items.length.toString())),1)):v("",!0),r.value&&h.value.length===0?(d(),n("div",Z,[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",_,[t("span",ee,c(e.searchNoResultsTitle),1),t("span",te,c(e.searchNoResultsDescription.replace("{query}",r.value)),1)])])):v("",!0),t("div",ae,[t("div",{class:o(["grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto pb-4 scrollbar-none",[u.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(E,null,N(h.value,i=>(d(),D(J,{id:i.id,key:i.id,modelValue:x.value,"onUpdate:modelValue":l[1]||(l[1]=y=>x.value=y),value:i.id,title:i.name,description:i.description,deprecated:i.deprecated,"show-expand-collapse":e.showMore,"expand-collapse-threshold":100,"show-custom-input":i.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]=y=>M(y))},null,8,["id","modelValue","value","title","description","deprecated","show-expand-collapse","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([u.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([u.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]=i=>u.value=!u.value)},[t("span",null,c(u.value?e.collapseButtonText:e.expandButtonText),1),t("div",{class:o([u.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),me=C(le,[["__scopeId","data-v-7ad6d626"]]),re=["checked","name","value"],oe={flex:"~ col","min-h-16":"","w-full":"","items-start":"","justify-center":"","pb-2":"","pl-5":"","pr-4":"","pt-2":""},de=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,s)=>(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":s[0]||(s[0]=x=>a.value=x),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"absolute opacity-0 [&:checked+div]:border-primary-500 [&:checked+div_.radio-dot]:opacity-100 dark:[&:checked+div]:border-primary-400"},null,8,re),[[I,a.value]]),s[1]||(s[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",oe,[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)]),s[2]||(s[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))}}),ve=C(de,[["__scopeId","data-v-ab9cd9e1"]]);export{me as R,ve as a}; +import{d as g,m as f,u as w,r as b,c as n,o as d,n as o,x as V,e as t,ba as I,j as v,t as c,i as $,w as S,X as k,b as B,_ as C,h as T,y as z,F as E,l as N,A as D}from"./index-CQudhZin.js";import{_ as P}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import{_ as U}from"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";const q=["checked","name","value"],L={class:"relative mr-3 mt-0.5 flex-shrink-0"},j={class:"w-full flex flex-col gap-2"},F={class:"flex items-center"},A={key:0,class:"relative"},Q=["title"],X={key:1,class:"mt-2"},G=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 s(){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]=u=>a.value=u),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"absolute opacity-0"},null,8,q),[[I,a.value]]),t("div",L,[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",j,[t("div",F,[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,[$(B(P),null,{default:S(()=>[!m.value||!e.showExpandCollapse?(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(s,["prevent"])},c(e.description),11,Q)):(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(s,["prevent"])},c(e.description),3))]),_:1}),e.showExpandCollapse&&e.description.length>e.expandCollapseThreshold?(d(),n("button",{key:0,class:"mt-0.5 inline-flex items-center text-xs text-primary-500 dark:text-primary-600",onClick:k(s,["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",X,[$(B(U),{modelValue:a.value,"onUpdate:modelValue":r[1]||(r[1]=u=>a.value=u),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))}}),H=C(G,[["__scopeId","data-v-86a9d442"]]),J={class:"radio-card-detail-many-select"},K={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},O=["placeholder"],W={class:"mt-4 space-y-2"},Y={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},Z={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"},_={class:"flex flex-col"},ee={class:"font-medium"},te={class:"text-sm text-amber-600 dark:text-amber-400"},ae={class:"relative"},le=g({__name:"RadioCardManySelect",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"},showMore:{type:Boolean,default:!0}},{modelValue:{required:!0},modelModifiers:{}}),emits:f(["update:customValue"],["update:modelValue"]),setup(e,{emit:a}){const m=e,s=a,x=w(e,"modelValue"),r=b(""),u=b(!1),R=b(""),h=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 M(p){R.value=p,s("update:customValue",p)}return(p,l)=>(d(),n("div",J,[e.searchable?(d(),n("div",K,[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]=i=>r.value=i),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,O),[[z,r.value]])])):v("",!0),t("div",W,[r.value?(d(),n("div",Y,c(e.searchResultsText.replace("{count}",h.value.length.toString()).replace("{total}",e.items.length.toString())),1)):v("",!0),r.value&&h.value.length===0?(d(),n("div",Z,[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",_,[t("span",ee,c(e.searchNoResultsTitle),1),t("span",te,c(e.searchNoResultsDescription.replace("{query}",r.value)),1)])])):v("",!0),t("div",ae,[t("div",{class:o(["grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto pb-4 scrollbar-none",[u.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(E,null,N(h.value,i=>(d(),D(H,{id:i.id,key:i.id,modelValue:x.value,"onUpdate:modelValue":l[1]||(l[1]=y=>x.value=y),value:i.id,title:i.name,description:i.description,deprecated:i.deprecated,"show-expand-collapse":e.showMore,"expand-collapse-threshold":100,"show-custom-input":i.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]=y=>M(y))},null,8,["id","modelValue","value","title","description","deprecated","show-expand-collapse","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([u.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([u.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]=i=>u.value=!u.value)},[t("span",null,c(u.value?e.collapseButtonText:e.expandButtonText),1),t("div",{class:o([u.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),me=C(le,[["__scopeId","data-v-7ad6d626"]]),re=["checked","name","value"],oe={flex:"~ col","min-h-16":"","w-full":"","items-start":"","justify-center":"","pb-2":"","pl-5":"","pr-4":"","pt-2":""},de=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,s)=>(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":s[0]||(s[0]=x=>a.value=x),checked:a.value===e.value,type:"radio",name:e.name,value:e.value,class:"absolute opacity-0 [&:checked+div]:border-primary-500 [&:checked+div_.radio-dot]:opacity-100 dark:[&:checked+div]:border-primary-400"},null,8,re),[[I,a.value]]),s[1]||(s[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",oe,[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)]),s[2]||(s[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))}}),ve=C(de,[["__scopeId","data-v-ab9cd9e1"]]);export{me as R,ve as a}; diff --git a/assets/Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js b/assets/Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js similarity index 99% rename from assets/Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js rename to assets/Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js index 521b73c47ce93523931438c6e01512ecd92685da..5fe5cd0f9a99e6f323faf829c1e6400893489a88 100644 --- a/assets/Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js +++ b/assets/Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js @@ -1 +1 @@ -import{d as U,bz as je,bA as Ve,N as te,c as ie,o as B,e as A,j as ce,F as qe,A as le,f as V,z as Z,bB as Ge,n as ze,b3 as Ue,bC as Xe,w as fe,i as Ye,E as Ke,C as Ze,D as Qe}from"./index-BQKiy4UR.js";import{c as Je,r as Q,o as et,j as tt,s as it,f as ot,d as st,a as nt}from"./floating-ui.core-CgBsuaUc.js";function m(e){var t;return((t=e.ownerDocument)==null?void 0:t.defaultView)||window}function _(e){return m(e).getComputedStyle(e)}const ge=Math.min,k=Math.max,q=Math.round;function Ae(e){const t=_(e);let i=parseFloat(t.width),o=parseFloat(t.height);const s=e.offsetWidth,n=e.offsetHeight,r=q(i)!==s||q(o)!==n;return r&&(i=s,o=n),{width:i,height:o,fallback:r}}function N(e){return Be(e)?(e.nodeName||"").toLowerCase():""}let I;function He(){if(I)return I;const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?(I=e.brands.map(t=>t.brand+"/"+t.version).join(" "),I):navigator.userAgent}function b(e){return e instanceof m(e).HTMLElement}function C(e){return e instanceof m(e).Element}function Be(e){return e instanceof m(e).Node}function me(e){return typeof ShadowRoot>"u"?!1:e instanceof m(e).ShadowRoot||e instanceof ShadowRoot}function X(e){const{overflow:t,overflowX:i,overflowY:o,display:s}=_(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+i)&&!["inline","contents"].includes(s)}function rt(e){return["table","td","th"].includes(N(e))}function oe(e){const t=/firefox/i.test(He()),i=_(e),o=i.backdropFilter||i.WebkitBackdropFilter;return i.transform!=="none"||i.perspective!=="none"||!!o&&o!=="none"||t&&i.willChange==="filter"||t&&!!i.filter&&i.filter!=="none"||["transform","perspective"].some(s=>i.willChange.includes(s))||["paint","layout","strict","content"].some(s=>{const n=i.contain;return n!=null&&n.includes(s)})}function Oe(){return!/^((?!chrome|android).)*safari/i.test(He())}function de(e){return["html","body","#document"].includes(N(e))}function ke(e){return C(e)?e:e.contextElement}const Le={x:1,y:1};function O(e){const t=ke(e);if(!b(t))return Le;const i=t.getBoundingClientRect(),{width:o,height:s,fallback:n}=Ae(t);let r=(n?q(i.width):i.width)/o,a=(n?q(i.height):i.height)/s;return r&&Number.isFinite(r)||(r=1),a&&Number.isFinite(a)||(a=1),{x:r,y:a}}function R(e,t,i,o){var s,n;t===void 0&&(t=!1),i===void 0&&(i=!1);const r=e.getBoundingClientRect(),a=ke(e);let l=Le;t&&(o?C(o)&&(l=O(o)):l=O(e));const d=a?m(a):window,c=!Oe()&&i;let h=(r.left+(c&&((s=d.visualViewport)==null?void 0:s.offsetLeft)||0))/l.x,u=(r.top+(c&&((n=d.visualViewport)==null?void 0:n.offsetTop)||0))/l.y,y=r.width/l.x,v=r.height/l.y;if(a){const g=m(a),T=o&&C(o)?m(o):o;let f=g.frameElement;for(;f&&o&&T!==g;){const $=O(f),F=f.getBoundingClientRect(),ue=getComputedStyle(f);F.x+=(f.clientLeft+parseFloat(ue.paddingLeft))*$.x,F.y+=(f.clientTop+parseFloat(ue.paddingTop))*$.y,h*=$.x,u*=$.y,y*=$.x,v*=$.y,h+=F.x,u+=F.y,f=m(f).frameElement}}return{width:y,height:v,top:u,right:h+y,bottom:u+v,left:h,x:h,y:u}}function P(e){return((Be(e)?e.ownerDocument:e.document)||window.document).documentElement}function Y(e){return C(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Me(e){return R(P(e)).left+Y(e).scrollLeft}function D(e){if(N(e)==="html")return e;const t=e.assignedSlot||e.parentNode||me(e)&&e.host||P(e);return me(t)?t.host:t}function Re(e){const t=D(e);return de(t)?t.ownerDocument.body:b(t)&&X(t)?t:Re(t)}function G(e,t){var i;t===void 0&&(t=[]);const o=Re(e),s=o===((i=e.ownerDocument)==null?void 0:i.body),n=m(o);return s?t.concat(n,n.visualViewport||[],X(o)?o:[]):t.concat(o,G(o))}function we(e,t,i){return t==="viewport"?Q(function(o,s){const n=m(o),r=P(o),a=n.visualViewport;let l=r.clientWidth,d=r.clientHeight,c=0,h=0;if(a){l=a.width,d=a.height;const u=Oe();(u||!u&&s==="fixed")&&(c=a.offsetLeft,h=a.offsetTop)}return{width:l,height:d,x:c,y:h}}(e,i)):C(t)?Q(function(o,s){const n=R(o,!0,s==="fixed"),r=n.top+o.clientTop,a=n.left+o.clientLeft,l=b(o)?O(o):{x:1,y:1};return{width:o.clientWidth*l.x,height:o.clientHeight*l.y,x:a*l.x,y:r*l.y}}(t,i)):Q(function(o){const s=P(o),n=Y(o),r=o.ownerDocument.body,a=k(s.scrollWidth,s.clientWidth,r.scrollWidth,r.clientWidth),l=k(s.scrollHeight,s.clientHeight,r.scrollHeight,r.clientHeight);let d=-n.scrollLeft+Me(o);const c=-n.scrollTop;return _(r).direction==="rtl"&&(d+=k(s.clientWidth,r.clientWidth)-a),{width:a,height:l,x:d,y:c}}(P(e)))}function ye(e){return b(e)&&_(e).position!=="fixed"?e.offsetParent:null}function ve(e){const t=m(e);let i=ye(e);for(;i&&rt(i)&&_(i).position==="static";)i=ye(i);return i&&(N(i)==="html"||N(i)==="body"&&_(i).position==="static"&&!oe(i))?t:i||function(o){let s=D(o);for(;b(s)&&!de(s);){if(oe(s))return s;s=D(s)}return null}(e)||t}function at(e,t,i){const o=b(t),s=P(t),n=R(e,!0,i==="fixed",t);let r={scrollLeft:0,scrollTop:0};const a={x:0,y:0};if(o||!o&&i!=="fixed")if((N(t)!=="body"||X(s))&&(r=Y(t)),b(t)){const l=R(t,!0);a.x=l.x+t.clientLeft,a.y=l.y+t.clientTop}else s&&(a.x=Me(s));return{x:n.left+r.scrollLeft-a.x,y:n.top+r.scrollTop-a.y,width:n.width,height:n.height}}const lt={getClippingRect:function(e){let{element:t,boundary:i,rootBoundary:o,strategy:s}=e;const n=i==="clippingAncestors"?function(d,c){const h=c.get(d);if(h)return h;let u=G(d).filter(T=>C(T)&&N(T)!=="body"),y=null;const v=_(d).position==="fixed";let g=v?D(d):d;for(;C(g)&&!de(g);){const T=_(g),f=oe(g);(v?f||y:f||T.position!=="static"||!y||!["absolute","fixed"].includes(y.position))?y=T:u=u.filter($=>$!==g),g=D(g)}return c.set(d,u),u}(t,this._c):[].concat(i),r=[...n,o],a=r[0],l=r.reduce((d,c)=>{const h=we(t,c,s);return d.top=k(h.top,d.top),d.right=ge(h.right,d.right),d.bottom=ge(h.bottom,d.bottom),d.left=k(h.left,d.left),d},we(t,a,s));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}},convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{rect:t,offsetParent:i,strategy:o}=e;const s=b(i),n=P(i);if(i===n)return t;let r={scrollLeft:0,scrollTop:0},a={x:1,y:1};const l={x:0,y:0};if((s||!s&&o!=="fixed")&&((N(i)!=="body"||X(n))&&(r=Y(i)),b(i))){const d=R(i);a=O(i),l.x=d.x+i.clientLeft,l.y=d.y+i.clientTop}return{width:t.width*a.x,height:t.height*a.y,x:t.x*a.x-r.scrollLeft*a.x+l.x,y:t.y*a.y-r.scrollTop*a.y+l.y}},isElement:C,getDimensions:function(e){return b(e)?Ae(e):e.getBoundingClientRect()},getOffsetParent:ve,getDocumentElement:P,getScale:O,async getElementRects(e){let{reference:t,floating:i,strategy:o}=e;const s=this.getOffsetParent||ve,n=this.getDimensions;return{reference:at(t,await s(i),o),floating:{x:0,y:0,...await n(i)}}},getClientRects:e=>Array.from(e.getClientRects()),isRTL:e=>_(e).direction==="rtl"},dt=(e,t,i)=>{const o=new Map,s={platform:lt,...i},n={...s.platform,_c:o};return Je(e,t,{...s,platform:n})},H={disabled:!1,distance:5,skidding:0,container:"body",boundary:void 0,instantMove:!1,disposeTimeout:150,popperTriggers:[],strategy:"absolute",preventOverflow:!0,flip:!0,shift:!0,overflowPadding:0,arrowPadding:0,arrowOverflow:!0,autoHideOnMousedown:!1,themes:{tooltip:{placement:"top",triggers:["hover","focus","touch"],hideTriggers:e=>[...e,"click"],delay:{show:200,hide:0},handleResize:!1,html:!1,loadingContent:"..."},dropdown:{placement:"bottom",triggers:["click"],delay:0,handleResize:!0,autoHide:!0},menu:{$extend:"dropdown",triggers:["hover","focus"],popperTriggers:["hover"],delay:{show:0,hide:400}}}};function se(e,t){let i=H.themes[e]||{},o;do o=i[t],typeof o>"u"?i.$extend?i=H.themes[i.$extend]||{}:(i=null,o=H[t]):i=null;while(i);return o}function pt(e){const t=[e];let i=H.themes[e]||{};do i.$extend&&!i.$resetCss?(t.push(i.$extend),i=H.themes[i.$extend]||{}):i=null;while(i);return t.map(o=>`v-popper--theme-${o}`)}function $e(e){const t=[e];let i=H.themes[e]||{};do i.$extend?(t.push(i.$extend),i=H.themes[i.$extend]||{}):i=null;while(i);return t}let E=!1;if(typeof window<"u"){E=!1;try{const e=Object.defineProperty({},"passive",{get(){E=!0}});window.addEventListener("test",null,e)}catch{}}let De=!1;typeof window<"u"&&typeof navigator<"u"&&(De=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream);const ht=["auto","top","bottom","left","right"].reduce((e,t)=>e.concat([t,`${t}-start`,`${t}-end`]),[]),_e={hover:"mouseenter",focus:"focus",click:"click",touch:"touchstart",pointer:"pointerdown"},be={hover:"mouseleave",focus:"blur",click:"click",touch:"touchend",pointer:"pointerup"};function Te(e,t){const i=e.indexOf(t);i!==-1&&e.splice(i,1)}function J(){return new Promise(e=>requestAnimationFrame(()=>{requestAnimationFrame(e)}))}const w=[];let z=null;const Se={};function xe(e){let t=Se[e];return t||(t=Se[e]=[]),t}let ne=function(){};typeof window<"u"&&(ne=window.Element);function p(e){return function(t){return se(t.theme,e)}}const ee="__floating-vue__popper",Ee=()=>U({name:"VPopper",provide(){return{[ee]:{parentPopper:this}}},inject:{[ee]:{default:null}},props:{theme:{type:String,required:!0},targetNodes:{type:Function,required:!0},referenceNode:{type:Function,default:null},popperNode:{type:Function,required:!0},shown:{type:Boolean,default:!1},showGroup:{type:String,default:null},ariaId:{default:null},disabled:{type:Boolean,default:p("disabled")},positioningDisabled:{type:Boolean,default:p("positioningDisabled")},placement:{type:String,default:p("placement"),validator:e=>ht.includes(e)},delay:{type:[String,Number,Object],default:p("delay")},distance:{type:[Number,String],default:p("distance")},skidding:{type:[Number,String],default:p("skidding")},triggers:{type:Array,default:p("triggers")},showTriggers:{type:[Array,Function],default:p("showTriggers")},hideTriggers:{type:[Array,Function],default:p("hideTriggers")},popperTriggers:{type:Array,default:p("popperTriggers")},popperShowTriggers:{type:[Array,Function],default:p("popperShowTriggers")},popperHideTriggers:{type:[Array,Function],default:p("popperHideTriggers")},container:{type:[String,Object,ne,Boolean],default:p("container")},boundary:{type:[String,ne],default:p("boundary")},strategy:{type:String,validator:e=>["absolute","fixed"].includes(e),default:p("strategy")},autoHide:{type:[Boolean,Function],default:p("autoHide")},handleResize:{type:Boolean,default:p("handleResize")},instantMove:{type:Boolean,default:p("instantMove")},eagerMount:{type:Boolean,default:p("eagerMount")},popperClass:{type:[String,Array,Object],default:p("popperClass")},computeTransformOrigin:{type:Boolean,default:p("computeTransformOrigin")},autoMinSize:{type:Boolean,default:p("autoMinSize")},autoSize:{type:[Boolean,String],default:p("autoSize")},autoMaxSize:{type:Boolean,default:p("autoMaxSize")},autoBoundaryMaxSize:{type:Boolean,default:p("autoBoundaryMaxSize")},preventOverflow:{type:Boolean,default:p("preventOverflow")},overflowPadding:{type:[Number,String],default:p("overflowPadding")},arrowPadding:{type:[Number,String],default:p("arrowPadding")},arrowOverflow:{type:Boolean,default:p("arrowOverflow")},flip:{type:Boolean,default:p("flip")},shift:{type:Boolean,default:p("shift")},shiftCrossAxis:{type:Boolean,default:p("shiftCrossAxis")},noAutoFocus:{type:Boolean,default:p("noAutoFocus")},disposeTimeout:{type:Number,default:p("disposeTimeout")}},emits:{show:()=>!0,hide:()=>!0,"update:shown":e=>!0,"apply-show":()=>!0,"apply-hide":()=>!0,"close-group":()=>!0,"close-directive":()=>!0,"auto-hide":()=>!0,resize:()=>!0},data(){return{isShown:!1,isMounted:!1,skipTransition:!1,classes:{showFrom:!1,showTo:!1,hideFrom:!1,hideTo:!0},result:{x:0,y:0,placement:"",strategy:this.strategy,arrow:{x:0,y:0,centerOffset:0},transformOrigin:null},randomId:`popper_${[Math.random(),Date.now()].map(e=>e.toString(36).substring(2,10)).join("_")}`,shownChildren:new Set,lastAutoHide:!0,pendingHide:!1,containsGlobalTarget:!1,isDisposed:!0,mouseDownContains:!1}},computed:{popperId(){return this.ariaId!=null?this.ariaId:this.randomId},shouldMountContent(){return this.eagerMount||this.isMounted},slotData(){return{popperId:this.popperId,isShown:this.isShown,shouldMountContent:this.shouldMountContent,skipTransition:this.skipTransition,autoHide:typeof this.autoHide=="function"?this.lastAutoHide:this.autoHide,show:this.show,hide:this.hide,handleResize:this.handleResize,onResize:this.onResize,classes:{...this.classes,popperClass:this.popperClass},result:this.positioningDisabled?null:this.result,attrs:this.$attrs}},parentPopper(){var e;return(e=this[ee])==null?void 0:e.parentPopper},hasPopperShowTriggerHover(){var e,t;return((e=this.popperTriggers)==null?void 0:e.includes("hover"))||((t=this.popperShowTriggers)==null?void 0:t.includes("hover"))}},watch:{shown:"$_autoShowHide",disabled(e){e?this.dispose():this.init()},async container(){this.isShown&&(this.$_ensureTeleport(),await this.$_computePosition())},triggers:{handler:"$_refreshListeners",deep:!0},positioningDisabled:"$_refreshListeners",...["placement","distance","skidding","boundary","strategy","overflowPadding","arrowPadding","preventOverflow","shift","shiftCrossAxis","flip"].reduce((e,t)=>(e[t]="$_computePosition",e),{})},created(){this.autoMinSize&&console.warn('[floating-vue] `autoMinSize` option is deprecated. Use `autoSize="min"` instead.'),this.autoMaxSize&&console.warn("[floating-vue] `autoMaxSize` option is deprecated. Use `autoBoundaryMaxSize` instead.")},mounted(){this.init(),this.$_detachPopperNode()},activated(){this.$_autoShowHide()},deactivated(){this.hide()},beforeUnmount(){this.dispose()},methods:{show({event:e=null,skipDelay:t=!1,force:i=!1}={}){var o,s;(o=this.parentPopper)!=null&&o.lockedChild&&this.parentPopper.lockedChild!==this||(this.pendingHide=!1,(i||!this.disabled)&&(((s=this.parentPopper)==null?void 0:s.lockedChild)===this&&(this.parentPopper.lockedChild=null),this.$_scheduleShow(e,t),this.$emit("show"),this.$_showFrameLocked=!0,requestAnimationFrame(()=>{this.$_showFrameLocked=!1})),this.$emit("update:shown",!0))},hide({event:e=null,skipDelay:t=!1}={}){var i;if(!this.$_hideInProgress){if(this.shownChildren.size>0){this.pendingHide=!0;return}if(this.hasPopperShowTriggerHover&&this.$_isAimingPopper()){this.parentPopper&&(this.parentPopper.lockedChild=this,clearTimeout(this.parentPopper.lockedChildTimer),this.parentPopper.lockedChildTimer=setTimeout(()=>{this.parentPopper.lockedChild===this&&(this.parentPopper.lockedChild.hide({skipDelay:t}),this.parentPopper.lockedChild=null)},1e3));return}((i=this.parentPopper)==null?void 0:i.lockedChild)===this&&(this.parentPopper.lockedChild=null),this.pendingHide=!1,this.$_scheduleHide(e,t),this.$emit("hide"),this.$emit("update:shown",!1)}},init(){var e;this.isDisposed&&(this.isDisposed=!1,this.isMounted=!1,this.$_events=[],this.$_preventShow=!1,this.$_referenceNode=((e=this.referenceNode)==null?void 0:e.call(this))??this.$el,this.$_targetNodes=this.targetNodes().filter(t=>t.nodeType===t.ELEMENT_NODE),this.$_popperNode=this.popperNode(),this.$_innerNode=this.$_popperNode.querySelector(".v-popper__inner"),this.$_arrowNode=this.$_popperNode.querySelector(".v-popper__arrow-container"),this.$_swapTargetAttrs("title","data-original-title"),this.$_detachPopperNode(),this.triggers.length&&this.$_addEventListeners(),this.shown&&this.show())},dispose(){this.isDisposed||(this.isDisposed=!0,this.$_removeEventListeners(),this.hide({skipDelay:!0}),this.$_detachPopperNode(),this.isMounted=!1,this.isShown=!1,this.$_updateParentShownChildren(!1),this.$_swapTargetAttrs("data-original-title","title"))},async onResize(){this.isShown&&(await this.$_computePosition(),this.$emit("resize"))},async $_computePosition(){if(this.isDisposed||this.positioningDisabled)return;const e={strategy:this.strategy,middleware:[]};(this.distance||this.skidding)&&e.middleware.push(et({mainAxis:this.distance,crossAxis:this.skidding}));const t=this.placement.startsWith("auto");if(t?e.middleware.push(tt({alignment:this.placement.split("-")[1]??""})):e.placement=this.placement,this.preventOverflow&&(this.shift&&e.middleware.push(it({padding:this.overflowPadding,boundary:this.boundary,crossAxis:this.shiftCrossAxis})),!t&&this.flip&&e.middleware.push(ot({padding:this.overflowPadding,boundary:this.boundary}))),e.middleware.push(st({element:this.$_arrowNode,padding:this.arrowPadding})),this.arrowOverflow&&e.middleware.push({name:"arrowOverflow",fn:({placement:o,rects:s,middlewareData:n})=>{let r;const{centerOffset:a}=n.arrow;return o.startsWith("top")||o.startsWith("bottom")?r=Math.abs(a)>s.reference.width/2:r=Math.abs(a)>s.reference.height/2,{data:{overflow:r}}}}),this.autoMinSize||this.autoSize){const o=this.autoSize?this.autoSize:this.autoMinSize?"min":null;e.middleware.push({name:"autoSize",fn:({rects:s,placement:n,middlewareData:r})=>{var a;if((a=r.autoSize)!=null&&a.skip)return{};let l,d;return n.startsWith("top")||n.startsWith("bottom")?l=s.reference.width:d=s.reference.height,this.$_innerNode.style[o==="min"?"minWidth":o==="max"?"maxWidth":"width"]=l!=null?`${l}px`:null,this.$_innerNode.style[o==="min"?"minHeight":o==="max"?"maxHeight":"height"]=d!=null?`${d}px`:null,{data:{skip:!0},reset:{rects:!0}}}})}(this.autoMaxSize||this.autoBoundaryMaxSize)&&(this.$_innerNode.style.maxWidth=null,this.$_innerNode.style.maxHeight=null,e.middleware.push(nt({boundary:this.boundary,padding:this.overflowPadding,apply:({availableWidth:o,availableHeight:s})=>{this.$_innerNode.style.maxWidth=o!=null?`${o}px`:null,this.$_innerNode.style.maxHeight=s!=null?`${s}px`:null}})));const i=await dt(this.$_referenceNode,this.$_popperNode,e);Object.assign(this.result,{x:i.x,y:i.y,placement:i.placement,strategy:i.strategy,arrow:{...i.middlewareData.arrow,...i.middlewareData.arrowOverflow}})},$_scheduleShow(e,t=!1){if(this.$_updateParentShownChildren(!0),this.$_hideInProgress=!1,clearTimeout(this.$_scheduleTimer),z&&this.instantMove&&z.instantMove&&z!==this.parentPopper){z.$_applyHide(!0),this.$_applyShow(!0);return}t?this.$_applyShow():this.$_scheduleTimer=setTimeout(this.$_applyShow.bind(this),this.$_computeDelay("show"))},$_scheduleHide(e,t=!1){if(this.shownChildren.size>0){this.pendingHide=!0;return}this.$_updateParentShownChildren(!1),this.$_hideInProgress=!0,clearTimeout(this.$_scheduleTimer),this.isShown&&(z=this),t?this.$_applyHide():this.$_scheduleTimer=setTimeout(this.$_applyHide.bind(this),this.$_computeDelay("hide"))},$_computeDelay(e){const t=this.delay;return parseInt(t&&t[e]||t||0)},async $_applyShow(e=!1){clearTimeout(this.$_disposeTimer),clearTimeout(this.$_scheduleTimer),this.skipTransition=e,!this.isShown&&(this.$_ensureTeleport(),await J(),await this.$_computePosition(),await this.$_applyShowEffect(),this.positioningDisabled||this.$_registerEventListeners([...G(this.$_referenceNode),...G(this.$_popperNode)],"scroll",()=>{this.$_computePosition()}))},async $_applyShowEffect(){if(this.$_hideInProgress)return;if(this.computeTransformOrigin){const t=this.$_referenceNode.getBoundingClientRect(),i=this.$_popperNode.querySelector(".v-popper__wrapper"),o=i.parentNode.getBoundingClientRect(),s=t.x+t.width/2-(o.left+i.offsetLeft),n=t.y+t.height/2-(o.top+i.offsetTop);this.result.transformOrigin=`${s}px ${n}px`}this.isShown=!0,this.$_applyAttrsToTarget({"aria-describedby":this.popperId,"data-popper-shown":""});const e=this.showGroup;if(e){let t;for(let i=0;i0){this.pendingHide=!0,this.$_hideInProgress=!1;return}if(clearTimeout(this.$_scheduleTimer),!this.isShown)return;this.skipTransition=e,Te(w,this),w.length===0&&document.body.classList.remove("v-popper--some-open");for(const i of $e(this.theme)){const o=xe(i);Te(o,this),o.length===0&&document.body.classList.remove(`v-popper--some-open--${i}`)}z===this&&(z=null),this.isShown=!1,this.$_applyAttrsToTarget({"aria-describedby":void 0,"data-popper-shown":void 0}),clearTimeout(this.$_disposeTimer);const t=this.disposeTimeout;t!==null&&(this.$_disposeTimer=setTimeout(()=>{this.$_popperNode&&(this.$_detachPopperNode(),this.isMounted=!1)},t)),this.$_removeEventListeners("scroll"),this.$emit("apply-hide"),this.classes.showFrom=!1,this.classes.showTo=!1,this.classes.hideFrom=!0,this.classes.hideTo=!1,await J(),this.classes.hideFrom=!1,this.classes.hideTo=!0},$_autoShowHide(){this.shown?this.show():this.hide()},$_ensureTeleport(){if(this.isDisposed)return;let e=this.container;if(typeof e=="string"?e=window.document.querySelector(e):e===!1&&(e=this.$_targetNodes[0].parentNode),!e)throw new Error("No container for popover: "+this.container);e.appendChild(this.$_popperNode),this.isMounted=!0},$_addEventListeners(){const e=i=>{this.isShown&&!this.$_hideInProgress||(i.usedByTooltip=!0,!this.$_preventShow&&this.show({event:i}))};this.$_registerTriggerListeners(this.$_targetNodes,_e,this.triggers,this.showTriggers,e),this.$_registerTriggerListeners([this.$_popperNode],_e,this.popperTriggers,this.popperShowTriggers,e);const t=i=>{i.usedByTooltip||this.hide({event:i})};this.$_registerTriggerListeners(this.$_targetNodes,be,this.triggers,this.hideTriggers,t),this.$_registerTriggerListeners([this.$_popperNode],be,this.popperTriggers,this.popperHideTriggers,t)},$_registerEventListeners(e,t,i){this.$_events.push({targetNodes:e,eventType:t,handler:i}),e.forEach(o=>o.addEventListener(t,i,E?{passive:!0}:void 0))},$_registerTriggerListeners(e,t,i,o,s){let n=i;o!=null&&(n=typeof o=="function"?o(n):o),n.forEach(r=>{const a=t[r];a&&this.$_registerEventListeners(e,a,s)})},$_removeEventListeners(e){const t=[];this.$_events.forEach(i=>{const{targetNodes:o,eventType:s,handler:n}=i;!e||e===s?o.forEach(r=>r.removeEventListener(s,n)):t.push(i)}),this.$_events=t},$_refreshListeners(){this.isDisposed||(this.$_removeEventListeners(),this.$_addEventListeners())},$_handleGlobalClose(e,t=!1){this.$_showFrameLocked||(this.hide({event:e}),e.closePopover?this.$emit("close-directive"):this.$emit("auto-hide"),t&&(this.$_preventShow=!0,setTimeout(()=>{this.$_preventShow=!1},300)))},$_detachPopperNode(){this.$_popperNode.parentNode&&this.$_popperNode.parentNode.removeChild(this.$_popperNode)},$_swapTargetAttrs(e,t){for(const i of this.$_targetNodes){const o=i.getAttribute(e);o&&(i.removeAttribute(e),i.setAttribute(t,o))}},$_applyAttrsToTarget(e){for(const t of this.$_targetNodes)for(const i in e){const o=e[i];o==null?t.removeAttribute(i):t.setAttribute(i,o)}},$_updateParentShownChildren(e){let t=this.parentPopper;for(;t;)e?t.shownChildren.add(this.randomId):(t.shownChildren.delete(this.randomId),t.pendingHide&&t.hide()),t=t.parentPopper},$_isAimingPopper(){const e=this.$_referenceNode.getBoundingClientRect();if(L>=e.left&&L<=e.right&&M>=e.top&&M<=e.bottom){const t=this.$_popperNode.getBoundingClientRect(),i=L-S,o=M-x,s=t.left+t.width/2-S+(t.top+t.height/2)-x+t.width+t.height,n=S+i*s,r=x+o*s;return W(S,x,n,r,t.left,t.top,t.left,t.bottom)||W(S,x,n,r,t.left,t.top,t.right,t.top)||W(S,x,n,r,t.right,t.top,t.right,t.bottom)||W(S,x,n,r,t.left,t.bottom,t.right,t.bottom)}return!1}},render(){return this.$slots.default(this.slotData)}});if(typeof document<"u"&&typeof window<"u"){if(De){const e=E?{passive:!0,capture:!0}:!0;document.addEventListener("touchstart",t=>Ce(t),e),document.addEventListener("touchend",t=>Pe(t,!0),e)}else window.addEventListener("mousedown",e=>Ce(e),!0),window.addEventListener("click",e=>Pe(e,!1),!0);window.addEventListener("resize",ft)}function Ce(e,t){for(let i=0;i=0;o--){const s=w[o];try{const n=s.containsGlobalTarget=s.mouseDownContains||s.popperNode().contains(e.target);s.pendingHide=!1,requestAnimationFrame(()=>{if(s.pendingHide=!1,!i[s.randomId]&&Ne(s,n,e)){if(s.$_handleGlobalClose(e,t),!e.closeAllPopover&&e.closePopover&&n){let a=s.parentPopper;for(;a;)i[a.randomId]=!0,a=a.parentPopper;return}let r=s.parentPopper;for(;r&&Ne(r,r.containsGlobalTarget,e);)r.$_handleGlobalClose(e,t),r=r.parentPopper}})}catch{}}}function Ne(e,t,i){return i.closeAllPopover||i.closePopover&&t||ct(e,i)&&!t}function ct(e,t){if(typeof e.autoHide=="function"){const i=e.autoHide(t);return e.lastAutoHide=i,i}return e.autoHide}function ft(){for(let e=0;e{S=L,x=M,L=e.clientX,M=e.clientY},E?{passive:!0}:void 0);function W(e,t,i,o,s,n,r,a){const l=((r-s)*(t-n)-(a-n)*(e-s))/((a-n)*(i-e)-(r-s)*(o-t)),d=((i-e)*(t-n)-(o-t)*(e-s))/((a-n)*(i-e)-(r-s)*(o-t));return l>=0&&l<=1&&d>=0&&d<=1}const gt={extends:Ee()},pe=(e,t)=>{const i=e.__vccOpts||e;for(const[o,s]of t)i[o]=s;return i};function mt(e,t,i,o,s,n){return B(),ie("div",{ref:"reference",class:ze(["v-popper",{"v-popper--shown":e.slotData.isShown}])},[V(e.$slots,"default",Ze(Qe(e.slotData)))],2)}const wt=pe(gt,[["render",mt]]);function yt(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");if(t>0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);var i=e.indexOf("Trident/");if(i>0){var o=e.indexOf("rv:");return parseInt(e.substring(o+3,e.indexOf(".",o)),10)}var s=e.indexOf("Edge/");return s>0?parseInt(e.substring(s+5,e.indexOf(".",s)),10):-1}let j;function re(){re.init||(re.init=!0,j=yt()!==-1)}var K={name:"ResizeObserver",props:{emitOnMount:{type:Boolean,default:!1},ignoreWidth:{type:Boolean,default:!1},ignoreHeight:{type:Boolean,default:!1}},emits:["notify"],mounted(){re(),Ue(()=>{this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitOnMount&&this.emitSize()});const e=document.createElement("object");this._resizeObject=e,e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex",-1),e.onload=this.addResizeHandlers,e.type="text/html",j&&this.$el.appendChild(e),e.data="about:blank",j||this.$el.appendChild(e)},beforeUnmount(){this.removeResizeHandlers()},methods:{compareAndNotify(){(!this.ignoreWidth&&this._w!==this.$el.offsetWidth||!this.ignoreHeight&&this._h!==this.$el.offsetHeight)&&(this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitSize())},emitSize(){this.$emit("notify",{width:this._w,height:this._h})},addResizeHandlers(){this._resizeObject.contentDocument.defaultView.addEventListener("resize",this.compareAndNotify),this.compareAndNotify()},removeResizeHandlers(){this._resizeObject&&this._resizeObject.onload&&(!j&&this._resizeObject.contentDocument&&this._resizeObject.contentDocument.defaultView.removeEventListener("resize",this.compareAndNotify),this.$el.removeChild(this._resizeObject),this._resizeObject.onload=null,this._resizeObject=null)}}};const vt=Xe();je("data-v-b329ee4c");const $t={class:"resize-observer",tabindex:"-1"};Ve();const _t=vt((e,t,i,o,s,n)=>(B(),le("div",$t)));K.render=_t;K.__scopeId="data-v-b329ee4c";K.__file="src/components/ResizeObserver.vue";const Fe=(e="theme")=>({computed:{themeClass(){return pt(this[e])}}}),bt=U({name:"VPopperContent",components:{ResizeObserver:K},mixins:[Fe()],props:{popperId:String,theme:String,shown:Boolean,mounted:Boolean,skipTransition:Boolean,autoHide:Boolean,handleResize:Boolean,classes:Object,result:Object},emits:["hide","resize"],methods:{toPx(e){return e!=null&&!isNaN(e)?`${e}px`:null}}}),Tt=["id","aria-hidden","tabindex","data-popper-placement"],St={ref:"inner",class:"v-popper__inner"},xt=A("div",{class:"v-popper__arrow-outer"},null,-1),Ct=A("div",{class:"v-popper__arrow-inner"},null,-1),Pt=[xt,Ct];function Nt(e,t,i,o,s,n){const r=te("ResizeObserver");return B(),ie("div",{id:e.popperId,ref:"popover",class:ze(["v-popper__popper",[e.themeClass,e.classes.popperClass,{"v-popper__popper--shown":e.shown,"v-popper__popper--hidden":!e.shown,"v-popper__popper--show-from":e.classes.showFrom,"v-popper__popper--show-to":e.classes.showTo,"v-popper__popper--hide-from":e.classes.hideFrom,"v-popper__popper--hide-to":e.classes.hideTo,"v-popper__popper--skip-transition":e.skipTransition,"v-popper__popper--arrow-overflow":e.result&&e.result.arrow.overflow,"v-popper__popper--no-positioning":!e.result}]]),style:Z(e.result?{position:e.result.strategy,transform:`translate3d(${Math.round(e.result.x)}px,${Math.round(e.result.y)}px,0)`}:void 0),"aria-hidden":e.shown?"false":"true",tabindex:e.autoHide?0:void 0,"data-popper-placement":e.result?e.result.placement:void 0,onKeyup:t[2]||(t[2]=Ge(a=>e.autoHide&&e.$emit("hide"),["esc"]))},[A("div",{class:"v-popper__backdrop",onClick:t[0]||(t[0]=a=>e.autoHide&&e.$emit("hide"))}),A("div",{class:"v-popper__wrapper",style:Z(e.result?{transformOrigin:e.result.transformOrigin}:void 0)},[A("div",St,[e.mounted?(B(),ie(qe,{key:0},[A("div",null,[V(e.$slots,"default")]),e.handleResize?(B(),le(r,{key:0,onNotify:t[1]||(t[1]=a=>e.$emit("resize",a))})):ce("",!0)],64)):ce("",!0)],512),A("div",{ref:"arrow",class:"v-popper__arrow-container",style:Z(e.result?{left:e.toPx(e.result.arrow.x),top:e.toPx(e.result.arrow.y)}:void 0)},Pt,4)],4)],46,Tt)}const Ie=pe(bt,[["render",Nt]]),We={methods:{show(...e){return this.$refs.popper.show(...e)},hide(...e){return this.$refs.popper.hide(...e)},dispose(...e){return this.$refs.popper.dispose(...e)},onResize(...e){return this.$refs.popper.onResize(...e)}}};let ae=function(){};typeof window<"u"&&(ae=window.Element);const zt=U({name:"VPopperWrapper",components:{Popper:wt,PopperContent:Ie},mixins:[We,Fe("finalTheme")],props:{theme:{type:String,default:null},referenceNode:{type:Function,default:null},shown:{type:Boolean,default:!1},showGroup:{type:String,default:null},ariaId:{default:null},disabled:{type:Boolean,default:void 0},positioningDisabled:{type:Boolean,default:void 0},placement:{type:String,default:void 0},delay:{type:[String,Number,Object],default:void 0},distance:{type:[Number,String],default:void 0},skidding:{type:[Number,String],default:void 0},triggers:{type:Array,default:void 0},showTriggers:{type:[Array,Function],default:void 0},hideTriggers:{type:[Array,Function],default:void 0},popperTriggers:{type:Array,default:void 0},popperShowTriggers:{type:[Array,Function],default:void 0},popperHideTriggers:{type:[Array,Function],default:void 0},container:{type:[String,Object,ae,Boolean],default:void 0},boundary:{type:[String,ae],default:void 0},strategy:{type:String,default:void 0},autoHide:{type:[Boolean,Function],default:void 0},handleResize:{type:Boolean,default:void 0},instantMove:{type:Boolean,default:void 0},eagerMount:{type:Boolean,default:void 0},popperClass:{type:[String,Array,Object],default:void 0},computeTransformOrigin:{type:Boolean,default:void 0},autoMinSize:{type:Boolean,default:void 0},autoSize:{type:[Boolean,String],default:void 0},autoMaxSize:{type:Boolean,default:void 0},autoBoundaryMaxSize:{type:Boolean,default:void 0},preventOverflow:{type:Boolean,default:void 0},overflowPadding:{type:[Number,String],default:void 0},arrowPadding:{type:[Number,String],default:void 0},arrowOverflow:{type:Boolean,default:void 0},flip:{type:Boolean,default:void 0},shift:{type:Boolean,default:void 0},shiftCrossAxis:{type:Boolean,default:void 0},noAutoFocus:{type:Boolean,default:void 0},disposeTimeout:{type:Number,default:void 0}},emits:{show:()=>!0,hide:()=>!0,"update:shown":e=>!0,"apply-show":()=>!0,"apply-hide":()=>!0,"close-group":()=>!0,"close-directive":()=>!0,"auto-hide":()=>!0,resize:()=>!0},computed:{finalTheme(){return this.theme??this.$options.vPopperTheme}},methods:{getTargetNodes(){return Array.from(this.$el.children).filter(e=>e!==this.$refs.popperContent.$el)}}});function At(e,t,i,o,s,n){const r=te("PopperContent"),a=te("Popper");return B(),le(a,Ke({ref:"popper"},e.$props,{theme:e.finalTheme,"target-nodes":e.getTargetNodes,"popper-node":()=>e.$refs.popperContent.$el,class:[e.themeClass],onShow:t[0]||(t[0]=()=>e.$emit("show")),onHide:t[1]||(t[1]=()=>e.$emit("hide")),"onUpdate:shown":t[2]||(t[2]=l=>e.$emit("update:shown",l)),onApplyShow:t[3]||(t[3]=()=>e.$emit("apply-show")),onApplyHide:t[4]||(t[4]=()=>e.$emit("apply-hide")),onCloseGroup:t[5]||(t[5]=()=>e.$emit("close-group")),onCloseDirective:t[6]||(t[6]=()=>e.$emit("close-directive")),onAutoHide:t[7]||(t[7]=()=>e.$emit("auto-hide")),onResize:t[8]||(t[8]=()=>e.$emit("resize"))}),{default:fe(({popperId:l,isShown:d,shouldMountContent:c,skipTransition:h,autoHide:u,show:y,hide:v,handleResize:g,onResize:T,classes:f,result:$})=>[V(e.$slots,"default",{shown:d,show:y,hide:v}),Ye(r,{ref:"popperContent","popper-id":l,theme:e.finalTheme,shown:d,mounted:c,"skip-transition":h,"auto-hide":u,"handle-resize":g,classes:f,result:$,onHide:v,onResize:T},{default:fe(()=>[V(e.$slots,"popper",{shown:d,hide:v})]),_:2},1032,["popper-id","theme","shown","mounted","skip-transition","auto-hide","handle-resize","classes","result","onHide","onResize"])]),_:3},16,["theme","target-nodes","popper-node","class"])}const he=pe(zt,[["render",At]]),Ht={...he,name:"VDropdown",vPopperTheme:"dropdown"};({...he});({...he});U({name:"VTooltipDirective",components:{Popper:Ee(),PopperContent:Ie},mixins:[We],inheritAttrs:!1,props:{theme:{type:String,default:"tooltip"},html:{type:Boolean,default:e=>se(e.theme,"html")},content:{type:[String,Number,Function],default:null},loadingContent:{type:String,default:e=>se(e.theme,"loadingContent")},targetNodes:{type:Function,required:!0}},data(){return{asyncContent:null}},computed:{isContentAsync(){return typeof this.content=="function"},loading(){return this.isContentAsync&&this.asyncContent==null},finalContent(){return this.isContentAsync?this.loading?this.loadingContent:this.asyncContent:this.content}},watch:{content:{handler(){this.fetchContent(!0)},immediate:!0},async finalContent(){await this.$nextTick(),this.$refs.popper.onResize()}},created(){this.$_fetchId=0},methods:{fetchContent(e){if(typeof this.content=="function"&&this.$_isShown&&(e||!this.$_loading&&this.asyncContent==null)){this.asyncContent=null,this.$_loading=!0;const t=++this.$_fetchId,i=this.content(this);i.then?i.then(o=>this.onResult(t,o)):this.onResult(t,i)}},onResult(e,t){e===this.$_fetchId&&(this.$_loading=!1,this.asyncContent=t)},onShow(){this.$_isShown=!0,this.fetchContent()},onHide(){this.$_isShown=!1}}});const kt=Ht;export{kt as k}; +import{d as U,b2 as je,b3 as Ve,N as te,c as ie,o as B,e as A,j as ce,F as qe,A as le,f as V,z as Z,b4 as Ge,n as ze,ax as Ue,b5 as Xe,w as fe,i as Ye,E as Ke,C as Ze,D as Qe}from"./index-CQudhZin.js";import{c as Je,r as Q,o as et,j as tt,s as it,f as ot,d as st,a as nt}from"./floating-ui.core-CgBsuaUc.js";function m(e){var t;return((t=e.ownerDocument)==null?void 0:t.defaultView)||window}function _(e){return m(e).getComputedStyle(e)}const ge=Math.min,k=Math.max,q=Math.round;function Ae(e){const t=_(e);let i=parseFloat(t.width),o=parseFloat(t.height);const s=e.offsetWidth,n=e.offsetHeight,r=q(i)!==s||q(o)!==n;return r&&(i=s,o=n),{width:i,height:o,fallback:r}}function N(e){return Be(e)?(e.nodeName||"").toLowerCase():""}let I;function He(){if(I)return I;const e=navigator.userAgentData;return e&&Array.isArray(e.brands)?(I=e.brands.map(t=>t.brand+"/"+t.version).join(" "),I):navigator.userAgent}function b(e){return e instanceof m(e).HTMLElement}function C(e){return e instanceof m(e).Element}function Be(e){return e instanceof m(e).Node}function me(e){return typeof ShadowRoot>"u"?!1:e instanceof m(e).ShadowRoot||e instanceof ShadowRoot}function X(e){const{overflow:t,overflowX:i,overflowY:o,display:s}=_(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+i)&&!["inline","contents"].includes(s)}function rt(e){return["table","td","th"].includes(N(e))}function oe(e){const t=/firefox/i.test(He()),i=_(e),o=i.backdropFilter||i.WebkitBackdropFilter;return i.transform!=="none"||i.perspective!=="none"||!!o&&o!=="none"||t&&i.willChange==="filter"||t&&!!i.filter&&i.filter!=="none"||["transform","perspective"].some(s=>i.willChange.includes(s))||["paint","layout","strict","content"].some(s=>{const n=i.contain;return n!=null&&n.includes(s)})}function Oe(){return!/^((?!chrome|android).)*safari/i.test(He())}function de(e){return["html","body","#document"].includes(N(e))}function ke(e){return C(e)?e:e.contextElement}const Le={x:1,y:1};function O(e){const t=ke(e);if(!b(t))return Le;const i=t.getBoundingClientRect(),{width:o,height:s,fallback:n}=Ae(t);let r=(n?q(i.width):i.width)/o,a=(n?q(i.height):i.height)/s;return r&&Number.isFinite(r)||(r=1),a&&Number.isFinite(a)||(a=1),{x:r,y:a}}function R(e,t,i,o){var s,n;t===void 0&&(t=!1),i===void 0&&(i=!1);const r=e.getBoundingClientRect(),a=ke(e);let l=Le;t&&(o?C(o)&&(l=O(o)):l=O(e));const d=a?m(a):window,c=!Oe()&&i;let h=(r.left+(c&&((s=d.visualViewport)==null?void 0:s.offsetLeft)||0))/l.x,u=(r.top+(c&&((n=d.visualViewport)==null?void 0:n.offsetTop)||0))/l.y,y=r.width/l.x,v=r.height/l.y;if(a){const g=m(a),T=o&&C(o)?m(o):o;let f=g.frameElement;for(;f&&o&&T!==g;){const $=O(f),F=f.getBoundingClientRect(),ue=getComputedStyle(f);F.x+=(f.clientLeft+parseFloat(ue.paddingLeft))*$.x,F.y+=(f.clientTop+parseFloat(ue.paddingTop))*$.y,h*=$.x,u*=$.y,y*=$.x,v*=$.y,h+=F.x,u+=F.y,f=m(f).frameElement}}return{width:y,height:v,top:u,right:h+y,bottom:u+v,left:h,x:h,y:u}}function P(e){return((Be(e)?e.ownerDocument:e.document)||window.document).documentElement}function Y(e){return C(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Me(e){return R(P(e)).left+Y(e).scrollLeft}function D(e){if(N(e)==="html")return e;const t=e.assignedSlot||e.parentNode||me(e)&&e.host||P(e);return me(t)?t.host:t}function Re(e){const t=D(e);return de(t)?t.ownerDocument.body:b(t)&&X(t)?t:Re(t)}function G(e,t){var i;t===void 0&&(t=[]);const o=Re(e),s=o===((i=e.ownerDocument)==null?void 0:i.body),n=m(o);return s?t.concat(n,n.visualViewport||[],X(o)?o:[]):t.concat(o,G(o))}function we(e,t,i){return t==="viewport"?Q(function(o,s){const n=m(o),r=P(o),a=n.visualViewport;let l=r.clientWidth,d=r.clientHeight,c=0,h=0;if(a){l=a.width,d=a.height;const u=Oe();(u||!u&&s==="fixed")&&(c=a.offsetLeft,h=a.offsetTop)}return{width:l,height:d,x:c,y:h}}(e,i)):C(t)?Q(function(o,s){const n=R(o,!0,s==="fixed"),r=n.top+o.clientTop,a=n.left+o.clientLeft,l=b(o)?O(o):{x:1,y:1};return{width:o.clientWidth*l.x,height:o.clientHeight*l.y,x:a*l.x,y:r*l.y}}(t,i)):Q(function(o){const s=P(o),n=Y(o),r=o.ownerDocument.body,a=k(s.scrollWidth,s.clientWidth,r.scrollWidth,r.clientWidth),l=k(s.scrollHeight,s.clientHeight,r.scrollHeight,r.clientHeight);let d=-n.scrollLeft+Me(o);const c=-n.scrollTop;return _(r).direction==="rtl"&&(d+=k(s.clientWidth,r.clientWidth)-a),{width:a,height:l,x:d,y:c}}(P(e)))}function ye(e){return b(e)&&_(e).position!=="fixed"?e.offsetParent:null}function ve(e){const t=m(e);let i=ye(e);for(;i&&rt(i)&&_(i).position==="static";)i=ye(i);return i&&(N(i)==="html"||N(i)==="body"&&_(i).position==="static"&&!oe(i))?t:i||function(o){let s=D(o);for(;b(s)&&!de(s);){if(oe(s))return s;s=D(s)}return null}(e)||t}function at(e,t,i){const o=b(t),s=P(t),n=R(e,!0,i==="fixed",t);let r={scrollLeft:0,scrollTop:0};const a={x:0,y:0};if(o||!o&&i!=="fixed")if((N(t)!=="body"||X(s))&&(r=Y(t)),b(t)){const l=R(t,!0);a.x=l.x+t.clientLeft,a.y=l.y+t.clientTop}else s&&(a.x=Me(s));return{x:n.left+r.scrollLeft-a.x,y:n.top+r.scrollTop-a.y,width:n.width,height:n.height}}const lt={getClippingRect:function(e){let{element:t,boundary:i,rootBoundary:o,strategy:s}=e;const n=i==="clippingAncestors"?function(d,c){const h=c.get(d);if(h)return h;let u=G(d).filter(T=>C(T)&&N(T)!=="body"),y=null;const v=_(d).position==="fixed";let g=v?D(d):d;for(;C(g)&&!de(g);){const T=_(g),f=oe(g);(v?f||y:f||T.position!=="static"||!y||!["absolute","fixed"].includes(y.position))?y=T:u=u.filter($=>$!==g),g=D(g)}return c.set(d,u),u}(t,this._c):[].concat(i),r=[...n,o],a=r[0],l=r.reduce((d,c)=>{const h=we(t,c,s);return d.top=k(h.top,d.top),d.right=ge(h.right,d.right),d.bottom=ge(h.bottom,d.bottom),d.left=k(h.left,d.left),d},we(t,a,s));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}},convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{rect:t,offsetParent:i,strategy:o}=e;const s=b(i),n=P(i);if(i===n)return t;let r={scrollLeft:0,scrollTop:0},a={x:1,y:1};const l={x:0,y:0};if((s||!s&&o!=="fixed")&&((N(i)!=="body"||X(n))&&(r=Y(i)),b(i))){const d=R(i);a=O(i),l.x=d.x+i.clientLeft,l.y=d.y+i.clientTop}return{width:t.width*a.x,height:t.height*a.y,x:t.x*a.x-r.scrollLeft*a.x+l.x,y:t.y*a.y-r.scrollTop*a.y+l.y}},isElement:C,getDimensions:function(e){return b(e)?Ae(e):e.getBoundingClientRect()},getOffsetParent:ve,getDocumentElement:P,getScale:O,async getElementRects(e){let{reference:t,floating:i,strategy:o}=e;const s=this.getOffsetParent||ve,n=this.getDimensions;return{reference:at(t,await s(i),o),floating:{x:0,y:0,...await n(i)}}},getClientRects:e=>Array.from(e.getClientRects()),isRTL:e=>_(e).direction==="rtl"},dt=(e,t,i)=>{const o=new Map,s={platform:lt,...i},n={...s.platform,_c:o};return Je(e,t,{...s,platform:n})},H={disabled:!1,distance:5,skidding:0,container:"body",boundary:void 0,instantMove:!1,disposeTimeout:150,popperTriggers:[],strategy:"absolute",preventOverflow:!0,flip:!0,shift:!0,overflowPadding:0,arrowPadding:0,arrowOverflow:!0,autoHideOnMousedown:!1,themes:{tooltip:{placement:"top",triggers:["hover","focus","touch"],hideTriggers:e=>[...e,"click"],delay:{show:200,hide:0},handleResize:!1,html:!1,loadingContent:"..."},dropdown:{placement:"bottom",triggers:["click"],delay:0,handleResize:!0,autoHide:!0},menu:{$extend:"dropdown",triggers:["hover","focus"],popperTriggers:["hover"],delay:{show:0,hide:400}}}};function se(e,t){let i=H.themes[e]||{},o;do o=i[t],typeof o>"u"?i.$extend?i=H.themes[i.$extend]||{}:(i=null,o=H[t]):i=null;while(i);return o}function pt(e){const t=[e];let i=H.themes[e]||{};do i.$extend&&!i.$resetCss?(t.push(i.$extend),i=H.themes[i.$extend]||{}):i=null;while(i);return t.map(o=>`v-popper--theme-${o}`)}function $e(e){const t=[e];let i=H.themes[e]||{};do i.$extend?(t.push(i.$extend),i=H.themes[i.$extend]||{}):i=null;while(i);return t}let E=!1;if(typeof window<"u"){E=!1;try{const e=Object.defineProperty({},"passive",{get(){E=!0}});window.addEventListener("test",null,e)}catch{}}let De=!1;typeof window<"u"&&typeof navigator<"u"&&(De=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream);const ht=["auto","top","bottom","left","right"].reduce((e,t)=>e.concat([t,`${t}-start`,`${t}-end`]),[]),_e={hover:"mouseenter",focus:"focus",click:"click",touch:"touchstart",pointer:"pointerdown"},be={hover:"mouseleave",focus:"blur",click:"click",touch:"touchend",pointer:"pointerup"};function Te(e,t){const i=e.indexOf(t);i!==-1&&e.splice(i,1)}function J(){return new Promise(e=>requestAnimationFrame(()=>{requestAnimationFrame(e)}))}const w=[];let z=null;const Se={};function xe(e){let t=Se[e];return t||(t=Se[e]=[]),t}let ne=function(){};typeof window<"u"&&(ne=window.Element);function p(e){return function(t){return se(t.theme,e)}}const ee="__floating-vue__popper",Ee=()=>U({name:"VPopper",provide(){return{[ee]:{parentPopper:this}}},inject:{[ee]:{default:null}},props:{theme:{type:String,required:!0},targetNodes:{type:Function,required:!0},referenceNode:{type:Function,default:null},popperNode:{type:Function,required:!0},shown:{type:Boolean,default:!1},showGroup:{type:String,default:null},ariaId:{default:null},disabled:{type:Boolean,default:p("disabled")},positioningDisabled:{type:Boolean,default:p("positioningDisabled")},placement:{type:String,default:p("placement"),validator:e=>ht.includes(e)},delay:{type:[String,Number,Object],default:p("delay")},distance:{type:[Number,String],default:p("distance")},skidding:{type:[Number,String],default:p("skidding")},triggers:{type:Array,default:p("triggers")},showTriggers:{type:[Array,Function],default:p("showTriggers")},hideTriggers:{type:[Array,Function],default:p("hideTriggers")},popperTriggers:{type:Array,default:p("popperTriggers")},popperShowTriggers:{type:[Array,Function],default:p("popperShowTriggers")},popperHideTriggers:{type:[Array,Function],default:p("popperHideTriggers")},container:{type:[String,Object,ne,Boolean],default:p("container")},boundary:{type:[String,ne],default:p("boundary")},strategy:{type:String,validator:e=>["absolute","fixed"].includes(e),default:p("strategy")},autoHide:{type:[Boolean,Function],default:p("autoHide")},handleResize:{type:Boolean,default:p("handleResize")},instantMove:{type:Boolean,default:p("instantMove")},eagerMount:{type:Boolean,default:p("eagerMount")},popperClass:{type:[String,Array,Object],default:p("popperClass")},computeTransformOrigin:{type:Boolean,default:p("computeTransformOrigin")},autoMinSize:{type:Boolean,default:p("autoMinSize")},autoSize:{type:[Boolean,String],default:p("autoSize")},autoMaxSize:{type:Boolean,default:p("autoMaxSize")},autoBoundaryMaxSize:{type:Boolean,default:p("autoBoundaryMaxSize")},preventOverflow:{type:Boolean,default:p("preventOverflow")},overflowPadding:{type:[Number,String],default:p("overflowPadding")},arrowPadding:{type:[Number,String],default:p("arrowPadding")},arrowOverflow:{type:Boolean,default:p("arrowOverflow")},flip:{type:Boolean,default:p("flip")},shift:{type:Boolean,default:p("shift")},shiftCrossAxis:{type:Boolean,default:p("shiftCrossAxis")},noAutoFocus:{type:Boolean,default:p("noAutoFocus")},disposeTimeout:{type:Number,default:p("disposeTimeout")}},emits:{show:()=>!0,hide:()=>!0,"update:shown":e=>!0,"apply-show":()=>!0,"apply-hide":()=>!0,"close-group":()=>!0,"close-directive":()=>!0,"auto-hide":()=>!0,resize:()=>!0},data(){return{isShown:!1,isMounted:!1,skipTransition:!1,classes:{showFrom:!1,showTo:!1,hideFrom:!1,hideTo:!0},result:{x:0,y:0,placement:"",strategy:this.strategy,arrow:{x:0,y:0,centerOffset:0},transformOrigin:null},randomId:`popper_${[Math.random(),Date.now()].map(e=>e.toString(36).substring(2,10)).join("_")}`,shownChildren:new Set,lastAutoHide:!0,pendingHide:!1,containsGlobalTarget:!1,isDisposed:!0,mouseDownContains:!1}},computed:{popperId(){return this.ariaId!=null?this.ariaId:this.randomId},shouldMountContent(){return this.eagerMount||this.isMounted},slotData(){return{popperId:this.popperId,isShown:this.isShown,shouldMountContent:this.shouldMountContent,skipTransition:this.skipTransition,autoHide:typeof this.autoHide=="function"?this.lastAutoHide:this.autoHide,show:this.show,hide:this.hide,handleResize:this.handleResize,onResize:this.onResize,classes:{...this.classes,popperClass:this.popperClass},result:this.positioningDisabled?null:this.result,attrs:this.$attrs}},parentPopper(){var e;return(e=this[ee])==null?void 0:e.parentPopper},hasPopperShowTriggerHover(){var e,t;return((e=this.popperTriggers)==null?void 0:e.includes("hover"))||((t=this.popperShowTriggers)==null?void 0:t.includes("hover"))}},watch:{shown:"$_autoShowHide",disabled(e){e?this.dispose():this.init()},async container(){this.isShown&&(this.$_ensureTeleport(),await this.$_computePosition())},triggers:{handler:"$_refreshListeners",deep:!0},positioningDisabled:"$_refreshListeners",...["placement","distance","skidding","boundary","strategy","overflowPadding","arrowPadding","preventOverflow","shift","shiftCrossAxis","flip"].reduce((e,t)=>(e[t]="$_computePosition",e),{})},created(){this.autoMinSize&&console.warn('[floating-vue] `autoMinSize` option is deprecated. Use `autoSize="min"` instead.'),this.autoMaxSize&&console.warn("[floating-vue] `autoMaxSize` option is deprecated. Use `autoBoundaryMaxSize` instead.")},mounted(){this.init(),this.$_detachPopperNode()},activated(){this.$_autoShowHide()},deactivated(){this.hide()},beforeUnmount(){this.dispose()},methods:{show({event:e=null,skipDelay:t=!1,force:i=!1}={}){var o,s;(o=this.parentPopper)!=null&&o.lockedChild&&this.parentPopper.lockedChild!==this||(this.pendingHide=!1,(i||!this.disabled)&&(((s=this.parentPopper)==null?void 0:s.lockedChild)===this&&(this.parentPopper.lockedChild=null),this.$_scheduleShow(e,t),this.$emit("show"),this.$_showFrameLocked=!0,requestAnimationFrame(()=>{this.$_showFrameLocked=!1})),this.$emit("update:shown",!0))},hide({event:e=null,skipDelay:t=!1}={}){var i;if(!this.$_hideInProgress){if(this.shownChildren.size>0){this.pendingHide=!0;return}if(this.hasPopperShowTriggerHover&&this.$_isAimingPopper()){this.parentPopper&&(this.parentPopper.lockedChild=this,clearTimeout(this.parentPopper.lockedChildTimer),this.parentPopper.lockedChildTimer=setTimeout(()=>{this.parentPopper.lockedChild===this&&(this.parentPopper.lockedChild.hide({skipDelay:t}),this.parentPopper.lockedChild=null)},1e3));return}((i=this.parentPopper)==null?void 0:i.lockedChild)===this&&(this.parentPopper.lockedChild=null),this.pendingHide=!1,this.$_scheduleHide(e,t),this.$emit("hide"),this.$emit("update:shown",!1)}},init(){var e;this.isDisposed&&(this.isDisposed=!1,this.isMounted=!1,this.$_events=[],this.$_preventShow=!1,this.$_referenceNode=((e=this.referenceNode)==null?void 0:e.call(this))??this.$el,this.$_targetNodes=this.targetNodes().filter(t=>t.nodeType===t.ELEMENT_NODE),this.$_popperNode=this.popperNode(),this.$_innerNode=this.$_popperNode.querySelector(".v-popper__inner"),this.$_arrowNode=this.$_popperNode.querySelector(".v-popper__arrow-container"),this.$_swapTargetAttrs("title","data-original-title"),this.$_detachPopperNode(),this.triggers.length&&this.$_addEventListeners(),this.shown&&this.show())},dispose(){this.isDisposed||(this.isDisposed=!0,this.$_removeEventListeners(),this.hide({skipDelay:!0}),this.$_detachPopperNode(),this.isMounted=!1,this.isShown=!1,this.$_updateParentShownChildren(!1),this.$_swapTargetAttrs("data-original-title","title"))},async onResize(){this.isShown&&(await this.$_computePosition(),this.$emit("resize"))},async $_computePosition(){if(this.isDisposed||this.positioningDisabled)return;const e={strategy:this.strategy,middleware:[]};(this.distance||this.skidding)&&e.middleware.push(et({mainAxis:this.distance,crossAxis:this.skidding}));const t=this.placement.startsWith("auto");if(t?e.middleware.push(tt({alignment:this.placement.split("-")[1]??""})):e.placement=this.placement,this.preventOverflow&&(this.shift&&e.middleware.push(it({padding:this.overflowPadding,boundary:this.boundary,crossAxis:this.shiftCrossAxis})),!t&&this.flip&&e.middleware.push(ot({padding:this.overflowPadding,boundary:this.boundary}))),e.middleware.push(st({element:this.$_arrowNode,padding:this.arrowPadding})),this.arrowOverflow&&e.middleware.push({name:"arrowOverflow",fn:({placement:o,rects:s,middlewareData:n})=>{let r;const{centerOffset:a}=n.arrow;return o.startsWith("top")||o.startsWith("bottom")?r=Math.abs(a)>s.reference.width/2:r=Math.abs(a)>s.reference.height/2,{data:{overflow:r}}}}),this.autoMinSize||this.autoSize){const o=this.autoSize?this.autoSize:this.autoMinSize?"min":null;e.middleware.push({name:"autoSize",fn:({rects:s,placement:n,middlewareData:r})=>{var a;if((a=r.autoSize)!=null&&a.skip)return{};let l,d;return n.startsWith("top")||n.startsWith("bottom")?l=s.reference.width:d=s.reference.height,this.$_innerNode.style[o==="min"?"minWidth":o==="max"?"maxWidth":"width"]=l!=null?`${l}px`:null,this.$_innerNode.style[o==="min"?"minHeight":o==="max"?"maxHeight":"height"]=d!=null?`${d}px`:null,{data:{skip:!0},reset:{rects:!0}}}})}(this.autoMaxSize||this.autoBoundaryMaxSize)&&(this.$_innerNode.style.maxWidth=null,this.$_innerNode.style.maxHeight=null,e.middleware.push(nt({boundary:this.boundary,padding:this.overflowPadding,apply:({availableWidth:o,availableHeight:s})=>{this.$_innerNode.style.maxWidth=o!=null?`${o}px`:null,this.$_innerNode.style.maxHeight=s!=null?`${s}px`:null}})));const i=await dt(this.$_referenceNode,this.$_popperNode,e);Object.assign(this.result,{x:i.x,y:i.y,placement:i.placement,strategy:i.strategy,arrow:{...i.middlewareData.arrow,...i.middlewareData.arrowOverflow}})},$_scheduleShow(e,t=!1){if(this.$_updateParentShownChildren(!0),this.$_hideInProgress=!1,clearTimeout(this.$_scheduleTimer),z&&this.instantMove&&z.instantMove&&z!==this.parentPopper){z.$_applyHide(!0),this.$_applyShow(!0);return}t?this.$_applyShow():this.$_scheduleTimer=setTimeout(this.$_applyShow.bind(this),this.$_computeDelay("show"))},$_scheduleHide(e,t=!1){if(this.shownChildren.size>0){this.pendingHide=!0;return}this.$_updateParentShownChildren(!1),this.$_hideInProgress=!0,clearTimeout(this.$_scheduleTimer),this.isShown&&(z=this),t?this.$_applyHide():this.$_scheduleTimer=setTimeout(this.$_applyHide.bind(this),this.$_computeDelay("hide"))},$_computeDelay(e){const t=this.delay;return parseInt(t&&t[e]||t||0)},async $_applyShow(e=!1){clearTimeout(this.$_disposeTimer),clearTimeout(this.$_scheduleTimer),this.skipTransition=e,!this.isShown&&(this.$_ensureTeleport(),await J(),await this.$_computePosition(),await this.$_applyShowEffect(),this.positioningDisabled||this.$_registerEventListeners([...G(this.$_referenceNode),...G(this.$_popperNode)],"scroll",()=>{this.$_computePosition()}))},async $_applyShowEffect(){if(this.$_hideInProgress)return;if(this.computeTransformOrigin){const t=this.$_referenceNode.getBoundingClientRect(),i=this.$_popperNode.querySelector(".v-popper__wrapper"),o=i.parentNode.getBoundingClientRect(),s=t.x+t.width/2-(o.left+i.offsetLeft),n=t.y+t.height/2-(o.top+i.offsetTop);this.result.transformOrigin=`${s}px ${n}px`}this.isShown=!0,this.$_applyAttrsToTarget({"aria-describedby":this.popperId,"data-popper-shown":""});const e=this.showGroup;if(e){let t;for(let i=0;i0){this.pendingHide=!0,this.$_hideInProgress=!1;return}if(clearTimeout(this.$_scheduleTimer),!this.isShown)return;this.skipTransition=e,Te(w,this),w.length===0&&document.body.classList.remove("v-popper--some-open");for(const i of $e(this.theme)){const o=xe(i);Te(o,this),o.length===0&&document.body.classList.remove(`v-popper--some-open--${i}`)}z===this&&(z=null),this.isShown=!1,this.$_applyAttrsToTarget({"aria-describedby":void 0,"data-popper-shown":void 0}),clearTimeout(this.$_disposeTimer);const t=this.disposeTimeout;t!==null&&(this.$_disposeTimer=setTimeout(()=>{this.$_popperNode&&(this.$_detachPopperNode(),this.isMounted=!1)},t)),this.$_removeEventListeners("scroll"),this.$emit("apply-hide"),this.classes.showFrom=!1,this.classes.showTo=!1,this.classes.hideFrom=!0,this.classes.hideTo=!1,await J(),this.classes.hideFrom=!1,this.classes.hideTo=!0},$_autoShowHide(){this.shown?this.show():this.hide()},$_ensureTeleport(){if(this.isDisposed)return;let e=this.container;if(typeof e=="string"?e=window.document.querySelector(e):e===!1&&(e=this.$_targetNodes[0].parentNode),!e)throw new Error("No container for popover: "+this.container);e.appendChild(this.$_popperNode),this.isMounted=!0},$_addEventListeners(){const e=i=>{this.isShown&&!this.$_hideInProgress||(i.usedByTooltip=!0,!this.$_preventShow&&this.show({event:i}))};this.$_registerTriggerListeners(this.$_targetNodes,_e,this.triggers,this.showTriggers,e),this.$_registerTriggerListeners([this.$_popperNode],_e,this.popperTriggers,this.popperShowTriggers,e);const t=i=>{i.usedByTooltip||this.hide({event:i})};this.$_registerTriggerListeners(this.$_targetNodes,be,this.triggers,this.hideTriggers,t),this.$_registerTriggerListeners([this.$_popperNode],be,this.popperTriggers,this.popperHideTriggers,t)},$_registerEventListeners(e,t,i){this.$_events.push({targetNodes:e,eventType:t,handler:i}),e.forEach(o=>o.addEventListener(t,i,E?{passive:!0}:void 0))},$_registerTriggerListeners(e,t,i,o,s){let n=i;o!=null&&(n=typeof o=="function"?o(n):o),n.forEach(r=>{const a=t[r];a&&this.$_registerEventListeners(e,a,s)})},$_removeEventListeners(e){const t=[];this.$_events.forEach(i=>{const{targetNodes:o,eventType:s,handler:n}=i;!e||e===s?o.forEach(r=>r.removeEventListener(s,n)):t.push(i)}),this.$_events=t},$_refreshListeners(){this.isDisposed||(this.$_removeEventListeners(),this.$_addEventListeners())},$_handleGlobalClose(e,t=!1){this.$_showFrameLocked||(this.hide({event:e}),e.closePopover?this.$emit("close-directive"):this.$emit("auto-hide"),t&&(this.$_preventShow=!0,setTimeout(()=>{this.$_preventShow=!1},300)))},$_detachPopperNode(){this.$_popperNode.parentNode&&this.$_popperNode.parentNode.removeChild(this.$_popperNode)},$_swapTargetAttrs(e,t){for(const i of this.$_targetNodes){const o=i.getAttribute(e);o&&(i.removeAttribute(e),i.setAttribute(t,o))}},$_applyAttrsToTarget(e){for(const t of this.$_targetNodes)for(const i in e){const o=e[i];o==null?t.removeAttribute(i):t.setAttribute(i,o)}},$_updateParentShownChildren(e){let t=this.parentPopper;for(;t;)e?t.shownChildren.add(this.randomId):(t.shownChildren.delete(this.randomId),t.pendingHide&&t.hide()),t=t.parentPopper},$_isAimingPopper(){const e=this.$_referenceNode.getBoundingClientRect();if(L>=e.left&&L<=e.right&&M>=e.top&&M<=e.bottom){const t=this.$_popperNode.getBoundingClientRect(),i=L-S,o=M-x,s=t.left+t.width/2-S+(t.top+t.height/2)-x+t.width+t.height,n=S+i*s,r=x+o*s;return W(S,x,n,r,t.left,t.top,t.left,t.bottom)||W(S,x,n,r,t.left,t.top,t.right,t.top)||W(S,x,n,r,t.right,t.top,t.right,t.bottom)||W(S,x,n,r,t.left,t.bottom,t.right,t.bottom)}return!1}},render(){return this.$slots.default(this.slotData)}});if(typeof document<"u"&&typeof window<"u"){if(De){const e=E?{passive:!0,capture:!0}:!0;document.addEventListener("touchstart",t=>Ce(t),e),document.addEventListener("touchend",t=>Pe(t,!0),e)}else window.addEventListener("mousedown",e=>Ce(e),!0),window.addEventListener("click",e=>Pe(e,!1),!0);window.addEventListener("resize",ft)}function Ce(e,t){for(let i=0;i=0;o--){const s=w[o];try{const n=s.containsGlobalTarget=s.mouseDownContains||s.popperNode().contains(e.target);s.pendingHide=!1,requestAnimationFrame(()=>{if(s.pendingHide=!1,!i[s.randomId]&&Ne(s,n,e)){if(s.$_handleGlobalClose(e,t),!e.closeAllPopover&&e.closePopover&&n){let a=s.parentPopper;for(;a;)i[a.randomId]=!0,a=a.parentPopper;return}let r=s.parentPopper;for(;r&&Ne(r,r.containsGlobalTarget,e);)r.$_handleGlobalClose(e,t),r=r.parentPopper}})}catch{}}}function Ne(e,t,i){return i.closeAllPopover||i.closePopover&&t||ct(e,i)&&!t}function ct(e,t){if(typeof e.autoHide=="function"){const i=e.autoHide(t);return e.lastAutoHide=i,i}return e.autoHide}function ft(){for(let e=0;e{S=L,x=M,L=e.clientX,M=e.clientY},E?{passive:!0}:void 0);function W(e,t,i,o,s,n,r,a){const l=((r-s)*(t-n)-(a-n)*(e-s))/((a-n)*(i-e)-(r-s)*(o-t)),d=((i-e)*(t-n)-(o-t)*(e-s))/((a-n)*(i-e)-(r-s)*(o-t));return l>=0&&l<=1&&d>=0&&d<=1}const gt={extends:Ee()},pe=(e,t)=>{const i=e.__vccOpts||e;for(const[o,s]of t)i[o]=s;return i};function mt(e,t,i,o,s,n){return B(),ie("div",{ref:"reference",class:ze(["v-popper",{"v-popper--shown":e.slotData.isShown}])},[V(e.$slots,"default",Ze(Qe(e.slotData)))],2)}const wt=pe(gt,[["render",mt]]);function yt(){var e=window.navigator.userAgent,t=e.indexOf("MSIE ");if(t>0)return parseInt(e.substring(t+5,e.indexOf(".",t)),10);var i=e.indexOf("Trident/");if(i>0){var o=e.indexOf("rv:");return parseInt(e.substring(o+3,e.indexOf(".",o)),10)}var s=e.indexOf("Edge/");return s>0?parseInt(e.substring(s+5,e.indexOf(".",s)),10):-1}let j;function re(){re.init||(re.init=!0,j=yt()!==-1)}var K={name:"ResizeObserver",props:{emitOnMount:{type:Boolean,default:!1},ignoreWidth:{type:Boolean,default:!1},ignoreHeight:{type:Boolean,default:!1}},emits:["notify"],mounted(){re(),Ue(()=>{this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitOnMount&&this.emitSize()});const e=document.createElement("object");this._resizeObject=e,e.setAttribute("aria-hidden","true"),e.setAttribute("tabindex",-1),e.onload=this.addResizeHandlers,e.type="text/html",j&&this.$el.appendChild(e),e.data="about:blank",j||this.$el.appendChild(e)},beforeUnmount(){this.removeResizeHandlers()},methods:{compareAndNotify(){(!this.ignoreWidth&&this._w!==this.$el.offsetWidth||!this.ignoreHeight&&this._h!==this.$el.offsetHeight)&&(this._w=this.$el.offsetWidth,this._h=this.$el.offsetHeight,this.emitSize())},emitSize(){this.$emit("notify",{width:this._w,height:this._h})},addResizeHandlers(){this._resizeObject.contentDocument.defaultView.addEventListener("resize",this.compareAndNotify),this.compareAndNotify()},removeResizeHandlers(){this._resizeObject&&this._resizeObject.onload&&(!j&&this._resizeObject.contentDocument&&this._resizeObject.contentDocument.defaultView.removeEventListener("resize",this.compareAndNotify),this.$el.removeChild(this._resizeObject),this._resizeObject.onload=null,this._resizeObject=null)}}};const vt=Xe();je("data-v-b329ee4c");const $t={class:"resize-observer",tabindex:"-1"};Ve();const _t=vt((e,t,i,o,s,n)=>(B(),le("div",$t)));K.render=_t;K.__scopeId="data-v-b329ee4c";K.__file="src/components/ResizeObserver.vue";const Fe=(e="theme")=>({computed:{themeClass(){return pt(this[e])}}}),bt=U({name:"VPopperContent",components:{ResizeObserver:K},mixins:[Fe()],props:{popperId:String,theme:String,shown:Boolean,mounted:Boolean,skipTransition:Boolean,autoHide:Boolean,handleResize:Boolean,classes:Object,result:Object},emits:["hide","resize"],methods:{toPx(e){return e!=null&&!isNaN(e)?`${e}px`:null}}}),Tt=["id","aria-hidden","tabindex","data-popper-placement"],St={ref:"inner",class:"v-popper__inner"},xt=A("div",{class:"v-popper__arrow-outer"},null,-1),Ct=A("div",{class:"v-popper__arrow-inner"},null,-1),Pt=[xt,Ct];function Nt(e,t,i,o,s,n){const r=te("ResizeObserver");return B(),ie("div",{id:e.popperId,ref:"popover",class:ze(["v-popper__popper",[e.themeClass,e.classes.popperClass,{"v-popper__popper--shown":e.shown,"v-popper__popper--hidden":!e.shown,"v-popper__popper--show-from":e.classes.showFrom,"v-popper__popper--show-to":e.classes.showTo,"v-popper__popper--hide-from":e.classes.hideFrom,"v-popper__popper--hide-to":e.classes.hideTo,"v-popper__popper--skip-transition":e.skipTransition,"v-popper__popper--arrow-overflow":e.result&&e.result.arrow.overflow,"v-popper__popper--no-positioning":!e.result}]]),style:Z(e.result?{position:e.result.strategy,transform:`translate3d(${Math.round(e.result.x)}px,${Math.round(e.result.y)}px,0)`}:void 0),"aria-hidden":e.shown?"false":"true",tabindex:e.autoHide?0:void 0,"data-popper-placement":e.result?e.result.placement:void 0,onKeyup:t[2]||(t[2]=Ge(a=>e.autoHide&&e.$emit("hide"),["esc"]))},[A("div",{class:"v-popper__backdrop",onClick:t[0]||(t[0]=a=>e.autoHide&&e.$emit("hide"))}),A("div",{class:"v-popper__wrapper",style:Z(e.result?{transformOrigin:e.result.transformOrigin}:void 0)},[A("div",St,[e.mounted?(B(),ie(qe,{key:0},[A("div",null,[V(e.$slots,"default")]),e.handleResize?(B(),le(r,{key:0,onNotify:t[1]||(t[1]=a=>e.$emit("resize",a))})):ce("",!0)],64)):ce("",!0)],512),A("div",{ref:"arrow",class:"v-popper__arrow-container",style:Z(e.result?{left:e.toPx(e.result.arrow.x),top:e.toPx(e.result.arrow.y)}:void 0)},Pt,4)],4)],46,Tt)}const Ie=pe(bt,[["render",Nt]]),We={methods:{show(...e){return this.$refs.popper.show(...e)},hide(...e){return this.$refs.popper.hide(...e)},dispose(...e){return this.$refs.popper.dispose(...e)},onResize(...e){return this.$refs.popper.onResize(...e)}}};let ae=function(){};typeof window<"u"&&(ae=window.Element);const zt=U({name:"VPopperWrapper",components:{Popper:wt,PopperContent:Ie},mixins:[We,Fe("finalTheme")],props:{theme:{type:String,default:null},referenceNode:{type:Function,default:null},shown:{type:Boolean,default:!1},showGroup:{type:String,default:null},ariaId:{default:null},disabled:{type:Boolean,default:void 0},positioningDisabled:{type:Boolean,default:void 0},placement:{type:String,default:void 0},delay:{type:[String,Number,Object],default:void 0},distance:{type:[Number,String],default:void 0},skidding:{type:[Number,String],default:void 0},triggers:{type:Array,default:void 0},showTriggers:{type:[Array,Function],default:void 0},hideTriggers:{type:[Array,Function],default:void 0},popperTriggers:{type:Array,default:void 0},popperShowTriggers:{type:[Array,Function],default:void 0},popperHideTriggers:{type:[Array,Function],default:void 0},container:{type:[String,Object,ae,Boolean],default:void 0},boundary:{type:[String,ae],default:void 0},strategy:{type:String,default:void 0},autoHide:{type:[Boolean,Function],default:void 0},handleResize:{type:Boolean,default:void 0},instantMove:{type:Boolean,default:void 0},eagerMount:{type:Boolean,default:void 0},popperClass:{type:[String,Array,Object],default:void 0},computeTransformOrigin:{type:Boolean,default:void 0},autoMinSize:{type:Boolean,default:void 0},autoSize:{type:[Boolean,String],default:void 0},autoMaxSize:{type:Boolean,default:void 0},autoBoundaryMaxSize:{type:Boolean,default:void 0},preventOverflow:{type:Boolean,default:void 0},overflowPadding:{type:[Number,String],default:void 0},arrowPadding:{type:[Number,String],default:void 0},arrowOverflow:{type:Boolean,default:void 0},flip:{type:Boolean,default:void 0},shift:{type:Boolean,default:void 0},shiftCrossAxis:{type:Boolean,default:void 0},noAutoFocus:{type:Boolean,default:void 0},disposeTimeout:{type:Number,default:void 0}},emits:{show:()=>!0,hide:()=>!0,"update:shown":e=>!0,"apply-show":()=>!0,"apply-hide":()=>!0,"close-group":()=>!0,"close-directive":()=>!0,"auto-hide":()=>!0,resize:()=>!0},computed:{finalTheme(){return this.theme??this.$options.vPopperTheme}},methods:{getTargetNodes(){return Array.from(this.$el.children).filter(e=>e!==this.$refs.popperContent.$el)}}});function At(e,t,i,o,s,n){const r=te("PopperContent"),a=te("Popper");return B(),le(a,Ke({ref:"popper"},e.$props,{theme:e.finalTheme,"target-nodes":e.getTargetNodes,"popper-node":()=>e.$refs.popperContent.$el,class:[e.themeClass],onShow:t[0]||(t[0]=()=>e.$emit("show")),onHide:t[1]||(t[1]=()=>e.$emit("hide")),"onUpdate:shown":t[2]||(t[2]=l=>e.$emit("update:shown",l)),onApplyShow:t[3]||(t[3]=()=>e.$emit("apply-show")),onApplyHide:t[4]||(t[4]=()=>e.$emit("apply-hide")),onCloseGroup:t[5]||(t[5]=()=>e.$emit("close-group")),onCloseDirective:t[6]||(t[6]=()=>e.$emit("close-directive")),onAutoHide:t[7]||(t[7]=()=>e.$emit("auto-hide")),onResize:t[8]||(t[8]=()=>e.$emit("resize"))}),{default:fe(({popperId:l,isShown:d,shouldMountContent:c,skipTransition:h,autoHide:u,show:y,hide:v,handleResize:g,onResize:T,classes:f,result:$})=>[V(e.$slots,"default",{shown:d,show:y,hide:v}),Ye(r,{ref:"popperContent","popper-id":l,theme:e.finalTheme,shown:d,mounted:c,"skip-transition":h,"auto-hide":u,"handle-resize":g,classes:f,result:$,onHide:v,onResize:T},{default:fe(()=>[V(e.$slots,"popper",{shown:d,hide:v})]),_:2},1032,["popper-id","theme","shown","mounted","skip-transition","auto-hide","handle-resize","classes","result","onHide","onResize"])]),_:3},16,["theme","target-nodes","popper-node","class"])}const he=pe(zt,[["render",At]]),Ht={...he,name:"VDropdown",vPopperTheme:"dropdown"};({...he});({...he});U({name:"VTooltipDirective",components:{Popper:Ee(),PopperContent:Ie},mixins:[We],inheritAttrs:!1,props:{theme:{type:String,default:"tooltip"},html:{type:Boolean,default:e=>se(e.theme,"html")},content:{type:[String,Number,Function],default:null},loadingContent:{type:String,default:e=>se(e.theme,"loadingContent")},targetNodes:{type:Function,required:!0}},data(){return{asyncContent:null}},computed:{isContentAsync(){return typeof this.content=="function"},loading(){return this.isContentAsync&&this.asyncContent==null},finalContent(){return this.isContentAsync?this.loading?this.loadingContent:this.asyncContent:this.content}},watch:{content:{handler(){this.fetchContent(!0)},immediate:!0},async finalContent(){await this.$nextTick(),this.$refs.popper.onResize()}},created(){this.$_fetchId=0},methods:{fetchContent(e){if(typeof this.content=="function"&&this.$_isShown&&(e||!this.$_loading&&this.asyncContent==null)){this.asyncContent=null,this.$_loading=!0;const t=++this.$_fetchId,i=this.content(this);i.then?i.then(o=>this.onResult(t,o)):this.onResult(t,i)}},onResult(e,t){e===this.$_fetchId&&(this.$_loading=!1,this.asyncContent=t)},onShow(){this.$_isShown=!0,this.fetchContent()},onHide(){this.$_isShown=!1}}});const kt=Ht;export{kt as k}; diff --git a/assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js b/assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js similarity index 82% rename from assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js rename to assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js index 85b8fc4454855a0c9c9c6477b7adb090f3848ef2..6abe8865e3e3104899f9e9cf75190b40ee22e23f 100644 --- a/assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js +++ b/assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js @@ -1 +1 @@ -import{d as B,K as ee,c as b,o as g,f as $,x as O,e as a,n as G,F as H,g as q,r as u,v as z,I as J,i as T,b as s,t as k,j as R,y as D,at as te,l as oe,S as ae,s as le,h as C,H as se,A as re,w as M,C as A,D as E,au as ie}from"./index-BQKiy4UR.js";import{b as ne,a as ue}from"./FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as de,g as ve}from"./speech-Db_L6FBm.js";import{u as ce}from"./providers-kjOpfeNb.js";import{_ as pe,a as me}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as fe}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as ge,a as be}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";const he={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":""},xe=B({__name:"ProviderSettingsLayout2",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function}},setup(_){return(o,S)=>{const d=ee("motion");return g(),b(H,null,[$(o.$slots,"default"),O((g(),b("div",he,[a("div",{text:"60",class:G(_.providerIcon||_.providerIconColor)},null,2)])),[[d]])],64)}}}),_e={"w-full":"","rounded-xl":""},ye={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},ke={class:"inline-flex items-center gap-4"},Se={flex:"~ col gap-4"},Ue=["placeholder"],Ie=["placeholder"],we={flex:"~ col gap-6"},Ve={grid:"~ cols-2 gap-4"},Te={class:"flex items-center gap-1 text-sm font-medium"},$e={class:"text-xs text-neutral-500 dark:text-neutral-400"},Le=["value"],Re={flex:"~ row","gap-4":""},Pe=["disabled"],Ce={flex:"~ row","items-center":"","gap-2":""},Me={flex:"~ row","items-center":"","gap-2":""},Oe={key:2,class:"mt-2 text-sm text-red-500"},Ke={key:3,class:"mt-2 text-sm text-red-500"},ze={key:4,class:"mt-2 text-sm text-red-500"},Be=["src"],at=B({__name:"SpeechPlayground",props:{defaultText:null,availableVoices:null,generateSpeech:{type:Function},apiKeyConfigured:{type:Boolean}},setup(_,{expose:o}){const S=_,{t:d}=q(),m=u(S.defaultText||"Hello! This is a test of the voice synthesis."),U=u(!1),t=u(""),c=u(""),f=u(null),i=u(!1),h=u(""),p=u("");z(()=>S.availableVoices,n=>{var r;n.length>0&&!p.value&&(p.value=((r=n[0])==null?void 0:r.id)||"")},{immediate:!0});async function x(){if(!(!m.value.trim()&&!i.value||i.value&&!h.value.trim()||!p.value)){U.value=!0,c.value="";try{t.value&&w();const n=i.value?h.value:m.value,r=await S.generateSpeech(n,p.value,i.value);t.value=URL.createObjectURL(new Blob([r])),setTimeout(()=>{f.value&&f.value.play()},100)}catch(n){console.error("Error generating speech:",n),c.value=n instanceof Error?n.message:"An unknown error occurred"}finally{U.value=!1}}}function w(){f.value&&(f.value.pause(),f.value.currentTime=0),t.value&&(URL.revokeObjectURL(t.value),t.value="")}return J(()=>{t.value&&URL.revokeObjectURL(t.value)}),o({testText:m,ssmlText:h,useSSML:i,selectedVoice:p,isGenerating:U,audioUrl:t,errorMessage:c,audioPlayer:f,generateTestSpeech:x,stopTestAudio:w}),(n,r)=>(g(),b("div",_e,[a("h2",ye,[a("div",ke,[T(s(ne)),a("div",null,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),a("div",Se,[T(s(ue),{modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=v=>i.value=v),label:s(d)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.label"),description:s(d)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.description")},null,8,["modelValue","label","description"]),i.value?O((g(),b("textarea",{key:1,"onUpdate:modelValue":r[2]||(r[2]=v=>h.value=v),placeholder:s(d)("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,Ie)),[[D,h.value]]):O((g(),b("textarea",{key:0,"onUpdate:modelValue":r[1]||(r[1]=v=>m.value=v),placeholder:s(d)("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,Ue)),[[D,m.value]]),a("div",we,[a("label",Ve,[a("div",null,[a("div",Te,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.label")),1),a("div",$e,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.description")),1)]),O(a("select",{"onUpdate:modelValue":r[3]||(r[3]=v=>p.value=v),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":""},[(g(!0),b(H,null,oe(_.availableVoices,v=>(g(),b("option",{key:v.id,value:v.id},k(v.name),9,Le))),128))],512),[[te,p.value]])])]),a("div",Re,[a("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:U.value||!m.value.trim()&&!i.value||i.value&&!h.value.trim()||!p.value||!_.apiKeyConfigured,class:G({"opacity-50 cursor-not-allowed":U.value||!m.value.trim()&&!i.value||i.value&&!h.value.trim()||!p.value||!_.apiKeyConfigured}),bg:"neutral-700 dark:neutral-300",onClick:x},[a("div",Ce,[r[4]||(r[4]=a("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),a("span",null,k(U.value?s(d)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):s(d)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,Pe),t.value?(g(),b("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:w},[a("div",Me,[r[5]||(r[5]=a("div",{"i-solar:stop-circle-bold-duotone":""},null,-1)),a("span",null,k(s(d)("settings.pages.modules.speech.sections.section.playground.buttons.stop.label")),1)])])):R("",!0)]),_.apiKeyConfigured?R("",!0):(g(),b("div",Oe,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.validation.error-missing-api-key")),1)),p.value?R("",!0):(g(),b("div",Ke,k(s(d)("settings.pages.modules.speech.sections.section.playground.select-voice.required")),1)),c.value?(g(),b("div",ze,k(c.value),1)):R("",!0),t.value?(g(),b("audio",{key:5,ref_key:"audioPlayer",ref:f,src:t.value,controls:"",class:"mt-2 w-full"},null,8,Be)):R("",!0)]),$(n.$slots,"default")]))}}),je={flex:"~ col md:row gap-6"},Fe={flex:"~ col gap-6"},Ne={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},De={flex:"~ col gap-4"},Ae={flex:"~ col gap-6",class:"w-full md:w-[60%]"},Ee={"w-full":"","rounded-xl":""},lt=B({__name:"SpeechProviderSettings",props:{providerId:null,defaultModel:null,additionalSettings:null},setup(_){const o=_,{t:S}=q(),d=ae(),m=ce(),U=de(),{providers:t}=le(m),c=C(()=>m.getProviderMetadata(o.providerId)),f=C({get:()=>{var e;return((e=t.value[o.providerId])==null?void 0:e.apiKey)||""},set:e=>{t.value[o.providerId]||(t.value[o.providerId]={}),t.value[o.providerId].apiKey=e}}),i=C({get:()=>{var e,l,y;return((e=t.value[o.providerId])==null?void 0:e.baseUrl)||((y=(l=c.value)==null?void 0:l.defaultOptions)==null?void 0:y.baseUrl)||""},set:e=>{t.value[o.providerId]||(t.value[o.providerId]={}),t.value[o.providerId].baseUrl=e}}),h=u("Hello! This is a test of voice synthesis."),p=u(!1),x=u(""),w=u(""),n=u(null),r=u(!1),v=u(""),j=u(""),I=u({});function Q(){var e;(e=t.value[o.providerId])!=null&&e.voiceSettings?I.value={...t.value[o.providerId].voiceSettings}:I.value={pitch:0,speed:1,volume:0,...o.additionalSettings}}se(()=>{var e,l,y,V;m.initializeProvider(o.providerId),f.value=((e=t.value[o.providerId])==null?void 0:e.apiKey)||"",i.value=((l=t.value[o.providerId])==null?void 0:l.baseUrl)||((V=(y=c.value)==null?void 0:y.defaultOptions)==null?void 0:V.baseUrl)||"",Q(),m.configuredProviders[o.providerId]&&U.loadVoicesForProvider(o.providerId)});const K=ie(()=>{var e,l;t.value[o.providerId]={...t.value[o.providerId],apiKey:f.value,baseUrl:i.value||((l=(e=c.value)==null?void 0:e.defaultOptions)==null?void 0:l.baseUrl)||"",voiceSettings:{...I.value}}},1e3);z([f,i],K),z(I,K,{deep:!0});async function W(){if(!h.value.trim()&&!r.value||r.value&&!v.value.trim())return;const e=m.getProviderInstance(o.providerId);if(!e){console.error("Failed to initialize speech provider");return}if(!j.value){console.error("No active speech voice selected");return}p.value=!0,w.value="";try{x.value&&F();const l=o.defaultModel||"default",y=r.value?v.value:h.value,V=await ve({...e.speech(l,{voiceSettings:I.value}),input:y,voice:j.value});x.value=URL.createObjectURL(new Blob([V])),setTimeout(()=>{n.value&&n.value.play()},100)}catch(l){console.error("Error generating speech:",l),w.value=l instanceof Error?l.message:"An unknown error occurred"}finally{p.value=!1}}function F(){n.value&&(n.value.pause(),n.value.currentTime=0),x.value&&(URL.revokeObjectURL(x.value),x.value="")}J(()=>{x.value&&URL.revokeObjectURL(x.value)});function X(){var e,l;I.value={...((l=(e=c.value)==null?void 0:e.defaultOptions)==null?void 0:l.voiceSettings)||{}},K()}function Y(e,l){I.value[e]=l}const N=C(()=>({voiceSettings:I.value,updateVoiceSettings:Y,isGenerating:p.value,testText:h.value,useSSML:r.value,ssmlText:v.value,generateTestSpeech:W,stopTestAudio:F,audioUrl:x.value,audioPlayer:n.value,errorMessage:w.value}));return(e,l)=>{var y,V;return g(),re(xe,{"provider-name":(y=c.value)==null?void 0:y.localizedName,"provider-icon":(V=c.value)==null?void 0:V.icon,"on-back":()=>s(d).back()},{default:M(()=>[a("div",je,[T(s(ge),{class:"w-full md:w-[40%]"},{default:M(()=>[T(s(be),{title:s(S)("settings.pages.providers.common.section.basic.title"),description:s(S)("settings.pages.providers.common.section.basic.description"),"on-reset":X},{default:M(()=>{var L;return[T(s(fe),{modelValue:f.value,"onUpdate:modelValue":l[0]||(l[0]=P=>f.value=P),"provider-name":(L=c.value)==null?void 0:L.localizedName,placeholder:"sk-"},null,8,["modelValue","provider-name"]),$(e.$slots,"basic-settings")]}),_:3},8,["title","description"]),a("div",Fe,[a("h2",Ne,k(s(S)("settings.pages.providers.common.section.voice.title")),1),a("div",De,[$(e.$slots,"voice-settings",A(E(N.value)))])]),T(s(pe),{title:s(S)("settings.pages.providers.common.section.advanced.title")},{default:M(()=>{var L,P;return[T(s(me),{modelValue:i.value,"onUpdate:modelValue":l[1]||(l[1]=Z=>i.value=Z),placeholder:((P=(L=c.value)==null?void 0:L.defaultOptions)==null?void 0:P.baseUrl)||"",required:""},null,8,["modelValue","placeholder"]),$(e.$slots,"advanced-settings")]}),_:3},8,["title"])]),_:3}),a("div",Ae,[a("div",Ee,[$(e.$slots,"playground",A(E(N.value)))])])])]),_:3},8,["provider-name","provider-icon","on-back"])}}});export{at as _,lt as a}; +import{d as B,K as ee,c as b,o as g,f as $,x as O,e as a,n as G,F as H,g as q,r as u,v as z,I as J,i as T,b as s,t as k,j as R,y as D,av as te,l as oe,S as ae,s as le,h as C,H as se,A as re,w as M,C as A,D as E,aw as ie}from"./index-CQudhZin.js";import{b as ne,a as ue}from"./FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as de,g as ve}from"./speech-nVAae-rt.js";import{u as ce}from"./providers-Y3Mr8_DF.js";import{_ as pe,a as me}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as fe}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as ge,a as be}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";const he={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":""},xe=B({__name:"ProviderSettingsLayout2",props:{providerName:null,providerIcon:null,providerIconColor:null,onBack:{type:Function}},setup(_){return(o,S)=>{const d=ee("motion");return g(),b(H,null,[$(o.$slots,"default"),O((g(),b("div",he,[a("div",{text:"60",class:G(_.providerIcon||_.providerIconColor)},null,2)])),[[d]])],64)}}}),_e={"w-full":"","rounded-xl":""},ye={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},ke={class:"inline-flex items-center gap-4"},Se={flex:"~ col gap-4"},Ue=["placeholder"],we=["placeholder"],Ie={flex:"~ col gap-6"},Ve={grid:"~ cols-2 gap-4"},Te={class:"flex items-center gap-1 text-sm font-medium"},$e={class:"text-xs text-neutral-500 dark:text-neutral-400"},Le=["value"],Re={flex:"~ row","gap-4":""},Pe=["disabled"],Ce={flex:"~ row","items-center":"","gap-2":""},Me={flex:"~ row","items-center":"","gap-2":""},Oe={key:2,class:"mt-2 text-sm text-red-500"},Ke={key:3,class:"mt-2 text-sm text-red-500"},ze={key:4,class:"mt-2 text-sm text-red-500"},Be=["src"],at=B({__name:"SpeechPlayground",props:{defaultText:null,availableVoices:null,generateSpeech:{type:Function},apiKeyConfigured:{type:Boolean}},setup(_,{expose:o}){const S=_,{t:d}=q(),m=u(S.defaultText||"Hello! This is a test of the voice synthesis."),U=u(!1),t=u(""),c=u(""),f=u(null),i=u(!1),h=u(""),p=u("");z(()=>S.availableVoices,n=>{var r;n.length>0&&!p.value&&(p.value=((r=n[0])==null?void 0:r.id)||"")},{immediate:!0});async function x(){if(!(!m.value.trim()&&!i.value||i.value&&!h.value.trim()||!p.value)){U.value=!0,c.value="";try{t.value&&I();const n=i.value?h.value:m.value,r=await S.generateSpeech(n,p.value,i.value);t.value=URL.createObjectURL(new Blob([r])),setTimeout(()=>{f.value&&f.value.play()},100)}catch(n){console.error("Error generating speech:",n),c.value=n instanceof Error?n.message:"An unknown error occurred"}finally{U.value=!1}}}function I(){f.value&&(f.value.pause(),f.value.currentTime=0),t.value&&(URL.revokeObjectURL(t.value),t.value="")}return J(()=>{t.value&&URL.revokeObjectURL(t.value)}),o({testText:m,ssmlText:h,useSSML:i,selectedVoice:p,isGenerating:U,audioUrl:t,errorMessage:c,audioPlayer:f,generateTestSpeech:x,stopTestAudio:I}),(n,r)=>(g(),b("div",_e,[a("h2",ye,[a("div",ke,[T(s(ne)),a("div",null,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),a("div",Se,[T(s(ue),{modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=v=>i.value=v),label:s(d)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.label"),description:s(d)("settings.pages.modules.speech.sections.section.voice-settings.use-ssml.description")},null,8,["modelValue","label","description"]),i.value?O((g(),b("textarea",{key:1,"onUpdate:modelValue":r[2]||(r[2]=v=>h.value=v),placeholder:s(d)("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,we)),[[D,h.value]]):O((g(),b("textarea",{key:0,"onUpdate:modelValue":r[1]||(r[1]=v=>m.value=v),placeholder:s(d)("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,Ue)),[[D,m.value]]),a("div",Ie,[a("label",Ve,[a("div",null,[a("div",Te,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.label")),1),a("div",$e,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.fields.field.voice.description")),1)]),O(a("select",{"onUpdate:modelValue":r[3]||(r[3]=v=>p.value=v),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":""},[(g(!0),b(H,null,oe(_.availableVoices,v=>(g(),b("option",{key:v.id,value:v.id},k(v.name),9,Le))),128))],512),[[te,p.value]])])]),a("div",Re,[a("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:U.value||!m.value.trim()&&!i.value||i.value&&!h.value.trim()||!p.value||!_.apiKeyConfigured,class:G({"opacity-50 cursor-not-allowed":U.value||!m.value.trim()&&!i.value||i.value&&!h.value.trim()||!p.value||!_.apiKeyConfigured}),bg:"neutral-700 dark:neutral-300",onClick:x},[a("div",Ce,[r[4]||(r[4]=a("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),a("span",null,k(U.value?s(d)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):s(d)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,Pe),t.value?(g(),b("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:I},[a("div",Me,[r[5]||(r[5]=a("div",{"i-solar:stop-circle-bold-duotone":""},null,-1)),a("span",null,k(s(d)("settings.pages.modules.speech.sections.section.playground.buttons.stop.label")),1)])])):R("",!0)]),_.apiKeyConfigured?R("",!0):(g(),b("div",Oe,k(s(d)("settings.pages.providers.provider.elevenlabs.playground.validation.error-missing-api-key")),1)),p.value?R("",!0):(g(),b("div",Ke,k(s(d)("settings.pages.modules.speech.sections.section.playground.select-voice.required")),1)),c.value?(g(),b("div",ze,k(c.value),1)):R("",!0),t.value?(g(),b("audio",{key:5,ref_key:"audioPlayer",ref:f,src:t.value,controls:"",class:"mt-2 w-full"},null,8,Be)):R("",!0)]),$(n.$slots,"default")]))}}),je={flex:"~ col md:row gap-6"},Fe={flex:"~ col gap-6"},Ne={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},De={flex:"~ col gap-4"},Ae={flex:"~ col gap-6",class:"w-full md:w-[60%]"},Ee={"w-full":"","rounded-xl":""},lt=B({__name:"SpeechProviderSettings",props:{providerId:null,defaultModel:null,additionalSettings:null},setup(_){const o=_,{t:S}=q(),d=ae(),m=ce(),U=de(),{providers:t}=le(m),c=C(()=>m.getProviderMetadata(o.providerId)),f=C({get:()=>{var e;return((e=t.value[o.providerId])==null?void 0:e.apiKey)||""},set:e=>{t.value[o.providerId]||(t.value[o.providerId]={}),t.value[o.providerId].apiKey=e}}),i=C({get:()=>{var e,l,y;return((e=t.value[o.providerId])==null?void 0:e.baseUrl)||((y=(l=c.value)==null?void 0:l.defaultOptions)==null?void 0:y.baseUrl)||""},set:e=>{t.value[o.providerId]||(t.value[o.providerId]={}),t.value[o.providerId].baseUrl=e}}),h=u("Hello! This is a test of voice synthesis."),p=u(!1),x=u(""),I=u(""),n=u(null),r=u(!1),v=u(""),j=u(""),w=u({});function Q(){var e;(e=t.value[o.providerId])!=null&&e.voiceSettings?w.value={...t.value[o.providerId].voiceSettings}:w.value={pitch:0,speed:1,volume:0,...o.additionalSettings}}se(()=>{var e,l,y,V;m.initializeProvider(o.providerId),f.value=((e=t.value[o.providerId])==null?void 0:e.apiKey)||"",i.value=((l=t.value[o.providerId])==null?void 0:l.baseUrl)||((V=(y=c.value)==null?void 0:y.defaultOptions)==null?void 0:V.baseUrl)||"",Q(),m.configuredProviders[o.providerId]&&U.loadVoicesForProvider(o.providerId)});const K=ie(()=>{var e,l;t.value[o.providerId]={...t.value[o.providerId],apiKey:f.value,baseUrl:i.value||((l=(e=c.value)==null?void 0:e.defaultOptions)==null?void 0:l.baseUrl)||"",voiceSettings:{...w.value}}},1e3);z([f,i],K),z(w,K,{deep:!0});async function W(){if(!h.value.trim()&&!r.value||r.value&&!v.value.trim())return;const e=m.getProviderInstance(o.providerId);if(!e){console.error("Failed to initialize speech provider");return}if(!j.value){console.error("No active speech voice selected");return}p.value=!0,I.value="";try{x.value&&F();const l=o.defaultModel||"default",y=r.value?v.value:h.value,V=await ve({...e.speech(l,{voiceSettings:w.value}),input:y,voice:j.value});x.value=URL.createObjectURL(new Blob([V])),setTimeout(()=>{n.value&&n.value.play()},100)}catch(l){console.error("Error generating speech:",l),I.value=l instanceof Error?l.message:"An unknown error occurred"}finally{p.value=!1}}function F(){n.value&&(n.value.pause(),n.value.currentTime=0),x.value&&(URL.revokeObjectURL(x.value),x.value="")}J(()=>{x.value&&URL.revokeObjectURL(x.value)});function X(){var e,l;w.value={...((l=(e=c.value)==null?void 0:e.defaultOptions)==null?void 0:l.voiceSettings)||{}},K()}function Y(e,l){w.value[e]=l}const N=C(()=>({voiceSettings:w.value,updateVoiceSettings:Y,isGenerating:p.value,testText:h.value,useSSML:r.value,ssmlText:v.value,generateTestSpeech:W,stopTestAudio:F,audioUrl:x.value,audioPlayer:n.value,errorMessage:I.value}));return(e,l)=>{var y,V;return g(),re(xe,{"provider-name":(y=c.value)==null?void 0:y.localizedName,"provider-icon":(V=c.value)==null?void 0:V.icon,"on-back":()=>s(d).back()},{default:M(()=>[a("div",je,[T(s(ge),{class:"w-full md:w-[40%]"},{default:M(()=>[T(s(be),{title:s(S)("settings.pages.providers.common.section.basic.title"),description:s(S)("settings.pages.providers.common.section.basic.description"),"on-reset":X},{default:M(()=>{var L;return[T(s(fe),{modelValue:f.value,"onUpdate:modelValue":l[0]||(l[0]=P=>f.value=P),"provider-name":(L=c.value)==null?void 0:L.localizedName,placeholder:"sk-"},null,8,["modelValue","provider-name"]),$(e.$slots,"basic-settings")]}),_:3},8,["title","description"]),a("div",Fe,[a("h2",Ne,k(s(S)("settings.pages.providers.common.section.voice.title")),1),a("div",De,[$(e.$slots,"voice-settings",A(E(N.value)))])]),T(s(pe),{title:s(S)("settings.pages.providers.common.section.advanced.title")},{default:M(()=>{var L,P;return[T(s(me),{modelValue:i.value,"onUpdate:modelValue":l[1]||(l[1]=Z=>i.value=Z),placeholder:((P=(L=c.value)==null?void 0:L.defaultOptions)==null?void 0:P.baseUrl)||"",required:""},null,8,["modelValue","placeholder"]),$(e.$slots,"advanced-settings")]}),_:3},8,["title"])]),_:3}),a("div",Ae,[a("div",Ee,[$(e.$slots,"playground",A(E(N.value)))])])])]),_:3},8,["provider-name","provider-icon","on-back"])}}});export{at as _,lt as a}; diff --git a/assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js b/assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js similarity index 93% rename from assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js rename to assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js index a1543e8b9cb1d935e5e1f31b46ca0558dc03f135..7f1978169b87f5e3ab70e45122998d43ea8efd6f 100644 --- a/assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js +++ b/assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-node-S5EYlj5_.js","assets/index-BQKiy4UR.js","assets/index-C-ktGyiB.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 Ix=Object.defineProperty;var Ex=(r,t,e)=>t in r?Ix(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var G=(r,t,e)=>Ex(r,typeof t!="symbol"?t+"":t,e);import{cX as Nh,d2 as gi,cY as Cx,L as ln}from"./index-BQKiy4UR.js";/*! +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-node-DAs8YCRC.js","assets/index-CQudhZin.js","assets/index-C-ktGyiB.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 Ix=Object.defineProperty;var Ex=(r,t,e)=>t in r?Ix(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var $=(r,t,e)=>Ex(r,typeof t!="symbol"?t+"":t,e);import{cq as Nh,cx as gi,cr as Cx,L as ln}from"./index-CQudhZin.js";/*! * @pixi/constants - v6.5.10 * Compiled Thu, 06 Jul 2023 15:25:11 UTC * @@ -11,8 +11,8 @@ var Ix=Object.defineProperty;var Ex=(r,t,e)=>t in r?Ix(r,t,{enumerable:!0,config * * @pixi/settings is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license - */var Ax={createCanvas:function(r,t){var e=document.createElement("canvas");return e.width=r,e.height=t,e},getWebGLRenderingContext:function(){return WebGLRenderingContext},getNavigator:function(){return navigator},getBaseUrl:function(){var r;return(r=document.baseURI)!==null&&r!==void 0?r:window.location.href},fetch:function(r,t){return fetch(r,t)}},yu=/iPhone/i,td=/iPod/i,ed=/iPad/i,rd=/\biOS-universal(?:.+)Mac\b/i,gu=/\bAndroid(?:.+)Mobile\b/i,id=/Android/i,ps=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,va=/Silk/i,Fi=/Windows Phone/i,nd=/\bWindows(?:.+)ARM\b/i,sd=/BlackBerry/i,od=/BB10/i,ad=/Opera Mini/i,ld=/\b(CriOS|Chrome)(?:.+)Mobile/i,ud=/Mobile(?:.+)Firefox\b/i,cd=function(r){return typeof r<"u"&&r.platform==="MacIntel"&&typeof r.maxTouchPoints=="number"&&r.maxTouchPoints>1&&typeof MSStream>"u"};function Ox(r){return function(t){return t.test(r)}}function Fx(r){var t={userAgent:"",platform:"",maxTouchPoints:0};!r&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof r=="string"?t.userAgent=r:r&&r.userAgent&&(t={userAgent:r.userAgent,platform:r.platform,maxTouchPoints:r.maxTouchPoints||0});var e=t.userAgent,i=e.split("[FBAN");typeof i[1]<"u"&&(e=i[0]),i=e.split("Twitter"),typeof i[1]<"u"&&(e=i[0]);var n=Ox(e),s={apple:{phone:n(yu)&&!n(Fi),ipod:n(td),tablet:!n(yu)&&(n(ed)||cd(t))&&!n(Fi),universal:n(rd),device:(n(yu)||n(td)||n(ed)||n(rd)||cd(t))&&!n(Fi)},amazon:{phone:n(ps),tablet:!n(ps)&&n(va),device:n(ps)||n(va)},android:{phone:!n(Fi)&&n(ps)||!n(Fi)&&n(gu),tablet:!n(Fi)&&!n(ps)&&!n(gu)&&(n(va)||n(id)),device:!n(Fi)&&(n(ps)||n(va)||n(gu)||n(id))||n(/\bokhttp\b/i)},windows:{phone:n(Fi),tablet:n(nd),device:n(Fi)||n(nd)},other:{blackberry:n(sd),blackberry10:n(od),opera:n(ad),firefox:n(ud),chrome:n(ld),device:n(sd)||n(od)||n(ad)||n(ud)||n(ld)},any:!1,phone:!1,tablet:!1};return s.any=s.apple.device||s.android.device||s.windows.device||s.other.device,s.phone=s.apple.phone||s.android.phone||s.windows.phone,s.tablet=s.apple.tablet||s.android.tablet||s.windows.tablet,s}var Xn=Fx(globalThis.navigator);function Px(){return!Xn.apple.device}function Mx(r){var t=!0;if(Xn.tablet||Xn.phone){if(Xn.apple.device){var e=navigator.userAgent.match(/OS (\d+)_(\d+)?/);if(e){var i=parseInt(e[1],10);i<11&&(t=!1)}}if(Xn.android.device){var e=navigator.userAgent.match(/Android\s([0-9.]*)/);if(e){var i=parseInt(e[1],10);i<7&&(t=!1)}}}return t?r:4}var It={ADAPTER:Ax,MIPMAP_TEXTURES:wi.POW2,ANISOTROPIC_LEVEL:0,RESOLUTION:1,FILTER_RESOLUTION:1,FILTER_MULTISAMPLE:Be.NONE,SPRITE_MAX_TEXTURES:Mx(32),SPRITE_BATCH_SIZE:4096,RENDER_OPTIONS:{view:null,width:800,height:600,autoDensity:!1,backgroundColor:0,backgroundAlpha:1,useContextAlpha:!0,clearBeforeRender:!0,antialias:!1,preserveDrawingBuffer:!1},GC_MODE:tl.AUTO,GC_MAX_IDLE:60*60,GC_MAX_CHECK_COUNT:60*10,WRAP_MODE:Ja.CLAMP,SCALE_MODE:Tr.LINEAR,PRECISION_VERTEX:Ir.HIGH,PRECISION_FRAGMENT:Xn.apple.device?Ir.HIGH:Ir.MEDIUM,CAN_UPLOAD_SAME_BUFFER:Px(),CREATE_IMAGE_BITMAP:!1,ROUND_PIXELS:!1},vu={exports:{}},hd;function Dx(){return hd||(hd=1,function(r){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function n(l,u,c){this.fn=l,this.context=u,this.once=c||!1}function s(l,u,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new n(c,h||l,p),y=e?e+u:u;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],f]:l._events[y].push(f):(l._events[y]=f,l._eventsCount++),l}function o(l,u){--l._eventsCount===0?l._events=new i:delete l._events[u]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var u=[],c,h;if(this._eventsCount===0)return u;for(h in c=this._events)t.call(c,h)&&u.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(c)):u},a.prototype.listeners=function(u){var c=e?e+u:u,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,f=h.length,y=new Array(f);p80*D){$=J=M[0],et=yt=M[1];for(var gt=D;gtJ&&(J=vt),dt>yt&&(yt=dt);_t=Math.max(J-$,yt-et),_t=_t!==0?32767/_t:0}return i(C,A,D,$,et,_t,0),A}function t(M,O,D,U,k){var C,A;if(k===it(M,O,D,U)>0)for(C=O;C=O;C-=U)A=I(C,M[C],M[C+1],A);return A&&E(A,A.next)&&(Z(A),A=A.next),A}function e(M,O){if(!M)return M;O||(O=M);var D=M,U;do if(U=!1,!D.steiner&&(E(D,D.next)||S(D.prev,D,D.next)===0)){if(Z(D),D=O=D.prev,D===D.next)break;U=!0}else D=D.next;while(U||D!==O);return O}function i(M,O,D,U,k,C,A){if(M){!A&&C&&f(M,U,k,C);for(var $=M,et,J;M.prev!==M.next;){if(et=M.prev,J=M.next,C?s(M,U,k,C):n(M)){O.push(et.i/D|0),O.push(M.i/D|0),O.push(J.i/D|0),Z(M),M=J.next,$=J.next;continue}if(M=J,M===$){A?A===1?(M=o(e(M),O,D),i(M,O,D,U,k,C,2)):A===2&&a(M,O,D,U,k,C):i(e(M),O,D,U,k,C,1);break}}}}function n(M){var O=M.prev,D=M,U=M.next;if(S(O,D,U)>=0)return!1;for(var k=O.x,C=D.x,A=U.x,$=O.y,et=D.y,J=U.y,yt=kC?k>A?k:A:C>A?C:A,_t=$>et?$>J?$:J:et>J?et:J,gt=U.next;gt!==O;){if(gt.x>=yt&>.x<=dt&>.y>=vt&>.y<=_t&&m(k,$,C,et,A,J,gt.x,gt.y)&&S(gt.prev,gt,gt.next)>=0)return!1;gt=gt.next}return!0}function s(M,O,D,U){var k=M.prev,C=M,A=M.next;if(S(k,C,A)>=0)return!1;for(var $=k.x,et=C.x,J=A.x,yt=k.y,vt=C.y,dt=A.y,_t=$et?$>J?$:J:et>J?et:J,ee=yt>vt?yt>dt?yt:dt:vt>dt?vt:dt,he=g(_t,gt,O,D,U),v=g(Ct,ee,O,D,U),K=M.prevZ,q=M.nextZ;K&&K.z>=he&&q&&q.z<=v;){if(K.x>=_t&&K.x<=Ct&&K.y>=gt&&K.y<=ee&&K!==k&&K!==A&&m($,yt,et,vt,J,dt,K.x,K.y)&&S(K.prev,K,K.next)>=0||(K=K.prevZ,q.x>=_t&&q.x<=Ct&&q.y>=gt&&q.y<=ee&&q!==k&&q!==A&&m($,yt,et,vt,J,dt,q.x,q.y)&&S(q.prev,q,q.next)>=0))return!1;q=q.nextZ}for(;K&&K.z>=he;){if(K.x>=_t&&K.x<=Ct&&K.y>=gt&&K.y<=ee&&K!==k&&K!==A&&m($,yt,et,vt,J,dt,K.x,K.y)&&S(K.prev,K,K.next)>=0)return!1;K=K.prevZ}for(;q&&q.z<=v;){if(q.x>=_t&&q.x<=Ct&&q.y>=gt&&q.y<=ee&&q!==k&&q!==A&&m($,yt,et,vt,J,dt,q.x,q.y)&&S(q.prev,q,q.next)>=0)return!1;q=q.nextZ}return!0}function o(M,O,D){var U=M;do{var k=U.prev,C=U.next.next;!E(k,C)&&b(k,U,U.next,C)&&B(k,C)&&B(C,k)&&(O.push(k.i/D|0),O.push(U.i/D|0),O.push(C.i/D|0),Z(U),Z(U.next),U=M=C),U=U.next}while(U!==M);return e(U)}function a(M,O,D,U,k,C){var A=M;do{for(var $=A.next.next;$!==A.prev;){if(A.i!==$.i&&_(A,$)){var et=st(A,$);A=e(A,A.next),et=e(et,et.next),i(A,O,D,U,k,C,0),i(et,O,D,U,k,C,0);return}$=$.next}A=A.next}while(A!==M)}function l(M,O,D,U){var k=[],C,A,$,et,J;for(C=0,A=O.length;C=D.next.y&&D.next.y!==D.y){var $=D.x+(k-D.y)*(D.next.x-D.x)/(D.next.y-D.y);if($<=U&&$>C&&(C=$,A=D.x=D.x&&D.x>=J&&U!==D.x&&m(kA.x||D.x===A.x&&p(A,D)))&&(A=D,vt=dt)),D=D.next;while(D!==et);return A}function p(M,O){return S(M.prev,M,O.prev)<0&&S(O.next,M,M.next)<0}function f(M,O,D,U){var k=M;do k.z===0&&(k.z=g(k.x,k.y,O,D,U)),k.prevZ=k.prev,k.nextZ=k.next,k=k.next;while(k!==M);k.prevZ.nextZ=null,k.prevZ=null,y(k)}function y(M){var O,D,U,k,C,A,$,et,J=1;do{for(D=M,M=null,C=null,A=0;D;){for(A++,U=D,$=0,O=0;O0||et>0&&U;)$!==0&&(et===0||!U||D.z<=U.z)?(k=D,D=D.nextZ,$--):(k=U,U=U.nextZ,et--),C?C.nextZ=k:M=k,k.prevZ=C,C=k;D=U}C.nextZ=null,J*=2}while(A>1);return M}function g(M,O,D,U,k){return M=(M-D)*k|0,O=(O-U)*k|0,M=(M|M<<8)&16711935,M=(M|M<<4)&252645135,M=(M|M<<2)&858993459,M=(M|M<<1)&1431655765,O=(O|O<<8)&16711935,O=(O|O<<4)&252645135,O=(O|O<<2)&858993459,O=(O|O<<1)&1431655765,M|O<<1}function d(M){var O=M,D=M;do(O.x=(M-A)*(C-$)&&(M-A)*(U-$)>=(D-A)*(O-$)&&(D-A)*(C-$)>=(k-A)*(U-$)}function _(M,O){return M.next.i!==O.i&&M.prev.i!==O.i&&!z(M,O)&&(B(M,O)&&B(O,M)&&tt(M,O)&&(S(M.prev,M,O.prev)||S(M,O.prev,O))||E(M,O)&&S(M.prev,M,M.next)>0&&S(O.prev,O,O.next)>0)}function S(M,O,D){return(O.y-M.y)*(D.x-O.x)-(O.x-M.x)*(D.y-O.y)}function E(M,O){return M.x===O.x&&M.y===O.y}function b(M,O,D,U){var k=x(S(M,O,D)),C=x(S(M,O,U)),A=x(S(D,U,M)),$=x(S(D,U,O));return!!(k!==C&&A!==$||k===0&&F(M,D,O)||C===0&&F(M,U,O)||A===0&&F(D,M,U)||$===0&&F(D,O,U))}function F(M,O,D){return O.x<=Math.max(M.x,D.x)&&O.x>=Math.min(M.x,D.x)&&O.y<=Math.max(M.y,D.y)&&O.y>=Math.min(M.y,D.y)}function x(M){return M>0?1:M<0?-1:0}function z(M,O){var D=M;do{if(D.i!==M.i&&D.next.i!==M.i&&D.i!==O.i&&D.next.i!==O.i&&b(D,D.next,M,O))return!0;D=D.next}while(D!==M);return!1}function B(M,O){return S(M.prev,M,M.next)<0?S(M,O,M.next)>=0&&S(M,M.prev,O)>=0:S(M,O,M.prev)<0||S(M,M.next,O)<0}function tt(M,O){var D=M,U=!1,k=(M.x+O.x)/2,C=(M.y+O.y)/2;do D.y>C!=D.next.y>C&&D.next.y!==D.y&&k<(D.next.x-D.x)*(C-D.y)/(D.next.y-D.y)+D.x&&(U=!U),D=D.next;while(D!==M);return U}function st(M,O){var D=new w(M.i,M.x,M.y),U=new w(O.i,O.x,O.y),k=M.next,C=O.prev;return M.next=O,O.prev=M,D.next=k,k.prev=D,U.next=D,D.prev=U,C.next=U,U.prev=C,U}function I(M,O,D,U){var k=new w(M,O,D);return U?(k.next=U.next,k.prev=U,U.next.prev=k,U.next=k):(k.prev=k,k.next=k),k}function Z(M){M.next.prev=M.prev,M.prev.next=M.next,M.prevZ&&(M.prevZ.nextZ=M.nextZ),M.nextZ&&(M.nextZ.prevZ=M.prevZ)}function w(M,O,D){this.i=M,this.x=O,this.y=D,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}r.deviation=function(M,O,D,U){var k=O&&O.length,C=k?O[0]*D:M.length,A=Math.abs(it(M,0,C,D));if(k)for(var $=0,et=O.length;$0&&(U+=M[k-1].length,D.holes.push(U))}return D},_a.exports}Nx();var Cn={},_o={exports:{}};/*! https://mths.be/punycode v1.4.1 by @mathias */var Lx=_o.exports,dd;function Bx(){return dd||(dd=1,function(r,t){(function(e){var i=t&&!t.nodeType&&t,n=r&&!r.nodeType&&r,s=typeof gi=="object"&&gi;(s.global===s||s.window===s||s.self===s)&&(e=s);var o,a=2147483647,l=36,u=1,c=26,h=38,p=700,f=72,y=128,g="-",d=/^xn--/,m=/[^\x20-\x7E]/,_=/[\x2E\u3002\uFF0E\uFF61]/g,S={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},E=l-u,b=Math.floor,F=String.fromCharCode,x;function z(k){throw new RangeError(S[k])}function B(k,C){for(var A=k.length,$=[];A--;)$[A]=C(k[A]);return $}function tt(k,C){var A=k.split("@"),$="";A.length>1&&($=A[0]+"@",k=A[1]),k=k.replace(_,".");var et=k.split("."),J=B(et,C).join(".");return $+J}function st(k){for(var C=[],A=0,$=k.length,et,J;A<$;)et=k.charCodeAt(A++),et>=55296&&et<=56319&&A<$?(J=k.charCodeAt(A++),(J&64512)==56320?C.push(((et&1023)<<10)+(J&1023)+65536):(C.push(et),A--)):C.push(et);return C}function I(k){return B(k,function(C){var A="";return C>65535&&(C-=65536,A+=F(C>>>10&1023|55296),C=56320|C&1023),A+=F(C),A}).join("")}function Z(k){return k-48<10?k-22:k-65<26?k-65:k-97<26?k-97:l}function w(k,C){return k+22+75*(k<26)-((C!=0)<<5)}function it(k,C,A){var $=0;for(k=A?b(k/p):k>>1,k+=b(k/C);k>E*c>>1;$+=l)k=b(k/E);return b($+(E+1)*k/(k+h))}function M(k){var C=[],A=k.length,$,et=0,J=y,yt=f,vt,dt,_t,gt,Ct,ee,he,v,K;for(vt=k.lastIndexOf(g),vt<0&&(vt=0),dt=0;dt=128&&z("not-basic"),C.push(k.charCodeAt(dt));for(_t=vt>0?vt+1:0;_t=A&&z("invalid-input"),he=Z(k.charCodeAt(_t++)),(he>=l||he>b((a-et)/Ct))&&z("overflow"),et+=he*Ct,v=ee<=yt?u:ee>=yt+c?c:ee-yt,!(heb(a/K)&&z("overflow"),Ct*=K;$=C.length+1,yt=it(et-gt,$,gt==0),b(et/$)>a-J&&z("overflow"),J+=b(et/$),et%=$,C.splice(et++,0,J)}return I(C)}function O(k){var C,A,$,et,J,yt,vt,dt,_t,gt,Ct,ee=[],he,v,K,q;for(k=st(k),he=k.length,C=y,A=0,J=f,yt=0;yt=C&&Ctb((a-A)/v)&&z("overflow"),A+=(vt-C)*v,C=vt,yt=0;yta&&z("overflow"),Ct==C){for(dt=A,_t=l;gt=_t<=J?u:_t>=J+c?c:_t-J,!(dt{if(u&&(typeof u=="object"||typeof u=="function")){if(i)return i.get(u)}else if(n)return n.get(u)},o=(u,c)=>{u&&(typeof u=="object"||typeof u=="function")?(i||(i=new WeakMap),i.set(u,c)):(n||(n=new Map),n.set(u,c))},a=u=>{if(u&&(typeof u=="object"||typeof u=="function")){if(i)return i.has(u)}else if(n)return n.has(u);return!1};return{get:s,set:o,has:a,assert:u=>{if(!a(u))throw new TypeError("Side channel does not contain the given key")}}}t.default=e,(typeof t.default=="object"&&t.default!==null||typeof t.default=="function")&&(Object.assign(t.default,t),r.exports=t.default)}(ba,ba.exports)),ba.exports}var _u,md;function Lh(){if(md)return _u;md=1;var r=String.prototype.replace,t=/%20/g,e={RFC1738:"RFC1738",RFC3986:"RFC3986"};return _u={default:e.RFC3986,formatters:{RFC1738:function(i){return r.call(i,t,"+")},RFC3986:function(i){return String(i)}},RFC1738:e.RFC1738,RFC3986:e.RFC3986},_u}var bu,yd;function Rg(){if(yd)return bu;yd=1;var r=Lh(),t=Object.prototype.hasOwnProperty,e=Array.isArray,i=function(){for(var d=[],m=0;m<256;++m)d.push("%"+((m<16?"0":"")+m.toString(16)).toUpperCase());return d}(),n=function(m){for(;m.length>1;){var _=m.pop(),S=_.obj[_.prop];if(e(S)){for(var E=[],b=0;b=u?F.slice(z,z+u):F,tt=[],st=0;st=48&&I<=57||I>=65&&I<=90||I>=97&&I<=122||b===r.RFC1738&&(I===40||I===41)){tt[tt.length]=B.charAt(st);continue}if(I<128){tt[tt.length]=i[I];continue}if(I<2048){tt[tt.length]=i[192|I>>6]+i[128|I&63];continue}if(I<55296||I>=57344){tt[tt.length]=i[224|I>>12]+i[128|I>>6&63]+i[128|I&63];continue}st+=1,I=65536+((I&1023)<<10|B.charCodeAt(st)&1023),tt[tt.length]=i[240|I>>18]+i[128|I>>12&63]+i[128|I>>6&63]+i[128|I&63]}x+=tt.join("")}return x},h=function(m){for(var _=[{obj:{o:m},prop:"o"}],S=[],E=0;E<_.length;++E)for(var b=_[E],F=b.obj[b.prop],x=Object.keys(F),z=0;z"u"&&(k=0)}if(typeof B=="function"?D=B(m,D):D instanceof Date?D=I(D):_==="comma"&&s(D)&&(D=t.maybeMap(D,function(K){return K instanceof Date?I(K):K})),D===null){if(b)return z&&!it?z(m,c.encoder,M,"key",Z):m;D=""}if(h(D)||t.isBuffer(D)){if(z){var $=it?m:z(m,c.encoder,M,"key",Z);return[w($)+"="+w(z(D,c.encoder,M,"value",Z))]}return[w(m)+"="+w(String(D))]}var et=[];if(typeof D>"u")return et;var J;if(_==="comma"&&s(D))it&&z&&(D=t.maybeMap(D,z)),J=[{value:D.length>0?D.join(",")||null:void 0}];else if(s(B))J=B;else{var yt=Object.keys(D);J=tt?yt.sort(tt):yt}var vt=x?String(m).replace(/\./g,"%2E"):String(m),dt=S&&s(D)&&D.length===1?vt+"[]":vt;if(E&&s(D)&&D.length===0)return dt+"[]";for(var _t=0;_t"u"?d.encodeDotInKeys===!0?!0:c.allowDots:!!d.allowDots;return{addQueryPrefix:typeof d.addQueryPrefix=="boolean"?d.addQueryPrefix:c.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof d.allowEmptyArrays=="boolean"?!!d.allowEmptyArrays:c.allowEmptyArrays,arrayFormat:b,charset:m,charsetSentinel:typeof d.charsetSentinel=="boolean"?d.charsetSentinel:c.charsetSentinel,commaRoundTrip:!!d.commaRoundTrip,delimiter:typeof d.delimiter>"u"?c.delimiter:d.delimiter,encode:typeof d.encode=="boolean"?d.encode:c.encode,encodeDotInKeys:typeof d.encodeDotInKeys=="boolean"?d.encodeDotInKeys:c.encodeDotInKeys,encoder:typeof d.encoder=="function"?d.encoder:c.encoder,encodeValuesOnly:typeof d.encodeValuesOnly=="boolean"?d.encodeValuesOnly:c.encodeValuesOnly,filter:E,format:_,formatter:S,serializeDate:typeof d.serializeDate=="function"?d.serializeDate:c.serializeDate,skipNulls:typeof d.skipNulls=="boolean"?d.skipNulls:c.skipNulls,sort:typeof d.sort=="function"?d.sort:null,strictNullHandling:typeof d.strictNullHandling=="boolean"?d.strictNullHandling:c.strictNullHandling}};return wu=function(g,d){var m=g,_=y(d),S,E;typeof _.filter=="function"?(E=_.filter,m=E("",m)):s(_.filter)&&(E=_.filter,S=E);var b=[];if(typeof m!="object"||m===null)return"";var F=n[_.arrayFormat],x=F==="comma"&&_.commaRoundTrip;S||(S=Object.keys(m)),_.sort&&S.sort(_.sort);for(var z=r(),B=0;B0?Z+I:""},wu}var xu,vd;function zx(){if(vd)return xu;vd=1;var r=Rg(),t=Object.prototype.hasOwnProperty,e=Array.isArray,i={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:r.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},n=function(p){return p.replace(/&#(\d+);/g,function(f,y){return String.fromCharCode(parseInt(y,10))})},s=function(p,f,y){if(p&&typeof p=="string"&&f.comma&&p.indexOf(",")>-1)return p.split(",");if(f.throwOnLimitExceeded&&y>=f.arrayLimit)throw new RangeError("Array limit exceeded. Only "+f.arrayLimit+" element"+(f.arrayLimit===1?"":"s")+" allowed in an array.");return p},o="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(f,y){var g={__proto__:null},d=y.ignoreQueryPrefix?f.replace(/^\?/,""):f;d=d.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var m=y.parameterLimit===1/0?void 0:y.parameterLimit,_=d.split(y.delimiter,y.throwOnLimitExceeded?m+1:m);if(y.throwOnLimitExceeded&&_.length>m)throw new RangeError("Parameter limit exceeded. Only "+m+" parameter"+(m===1?"":"s")+" allowed.");var S=-1,E,b=y.charset;if(y.charsetSentinel)for(E=0;E<_.length;++E)_[E].indexOf("utf8=")===0&&(_[E]===a?b="utf-8":_[E]===o&&(b="iso-8859-1"),S=E,E=_.length);for(E=0;E<_.length;++E)if(E!==S){var F=_[E],x=F.indexOf("]="),z=x===-1?F.indexOf("="):x+1,B,tt;z===-1?(B=y.decoder(F,i.decoder,b,"key"),tt=y.strictNullHandling?null:""):(B=y.decoder(F.slice(0,z),i.decoder,b,"key"),tt=r.maybeMap(s(F.slice(z+1),y,e(g[B])?g[B].length:0),function(I){return y.decoder(I,i.decoder,b,"value")})),tt&&y.interpretNumericEntities&&b==="iso-8859-1"&&(tt=n(String(tt))),F.indexOf("[]=")>-1&&(tt=e(tt)?[tt]:tt);var st=t.call(g,B);st&&y.duplicates==="combine"?g[B]=r.combine(g[B],tt):(!st||y.duplicates==="last")&&(g[B]=tt)}return g},u=function(p,f,y,g){var d=0;if(p.length>0&&p[p.length-1]==="[]"){var m=p.slice(0,-1).join("");d=Array.isArray(f)&&f[m]?f[m].length:0}for(var _=g?f:s(f,y,d),S=p.length-1;S>=0;--S){var E,b=p[S];if(b==="[]"&&y.parseArrays)E=y.allowEmptyArrays&&(_===""||y.strictNullHandling&&_===null)?[]:r.combine([],_);else{E=y.plainObjects?{__proto__:null}:{};var F=b.charAt(0)==="["&&b.charAt(b.length-1)==="]"?b.slice(1,-1):b,x=y.decodeDotInKeys?F.replace(/%2E/g,"."):F,z=parseInt(x,10);!y.parseArrays&&x===""?E={0:_}:!isNaN(z)&&b!==x&&String(z)===x&&z>=0&&y.parseArrays&&z<=y.arrayLimit?(E=[],E[z]=_):x!=="__proto__"&&(E[x]=_)}_=E}return _},c=function(f,y,g,d){if(f){var m=g.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f,_=/(\[[^[\]]*])/,S=/(\[[^[\]]*])/g,E=g.depth>0&&_.exec(m),b=E?m.slice(0,E.index):m,F=[];if(b){if(!g.plainObjects&&t.call(Object.prototype,b)&&!g.allowPrototypes)return;F.push(b)}for(var x=0;g.depth>0&&(E=S.exec(m))!==null&&x"u"?i.charset:f.charset,g=typeof f.duplicates>"u"?i.duplicates:f.duplicates;if(g!=="combine"&&g!=="first"&&g!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var d=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:i.allowDots:!!f.allowDots;return{allowDots:d,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:i.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:i.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:i.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:i.arrayLimit,charset:y,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:i.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:i.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:i.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:i.decoder,delimiter:typeof f.delimiter=="string"||r.isRegExp(f.delimiter)?f.delimiter:i.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:i.depth,duplicates:g,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:i.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:i.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:i.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:i.strictDepth,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:i.strictNullHandling,throwOnLimitExceeded:typeof f.throwOnLimitExceeded=="boolean"?f.throwOnLimitExceeded:!1}};return xu=function(p,f){var y=h(f);if(p===""||p===null||typeof p>"u")return y.plainObjects?{__proto__:null}:{};for(var g=typeof p=="string"?l(p,y):p,d=y.plainObjects?{__proto__:null}:{},m=Object.keys(g),_=0;_",'"',"`"," ","\r",` -`," "],o=["{","}","|","\\","^","`"].concat(s),a=["'"].concat(o),l=["%","/","?",";","#"].concat(a),u=["/","?","#"],c=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,f={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},d=jx();function m(b,F,x){if(b&&typeof b=="object"&&b instanceof t)return b;var z=new t;return z.parse(b,F,x),z}t.prototype.parse=function(b,F,x){if(typeof b!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof b);var z=b.indexOf("?"),B=z!==-1&&z127?yt+="x":yt+=J[vt];if(!yt.match(h)){var _t=$.slice(0,D),gt=$.slice(D+1),Ct=J.match(p);Ct&&(_t.push(Ct[1]),gt.unshift(Ct[2])),gt.length&&(I="/"+gt.join(".")+I),this.hostname=_t.join(".");break}}}this.hostname.length>c?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=r.toASCII(this.hostname));var ee=this.port?":"+this.port:"",he=this.hostname||"";this.host=he+ee,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),I[0]!=="/"&&(I="/"+I))}if(!f[it])for(var D=0,et=a.length;D0?x.host.split("@"):!1;yt&&(x.auth=yt.shift(),x.hostname=yt.shift(),x.host=x.hostname)}return x.search=b.search,x.query=b.query,(x.pathname!==null||x.search!==null)&&(x.path=(x.pathname?x.pathname:"")+(x.search?x.search:"")),x.href=x.format(),x}if(!$.length)return x.pathname=null,x.search?x.path="/"+x.search:x.path=null,x.href=x.format(),x;for(var vt=$.slice(-1)[0],dt=(x.host||b.host||$.length>1)&&(vt==="."||vt==="..")||vt==="",_t=0,gt=$.length;gt>=0;gt--)vt=$[gt],vt==="."?$.splice(gt,1):vt===".."?($.splice(gt,1),_t++):_t&&($.splice(gt,1),_t--);if(!C&&!A)for(;_t--;_t)$.unshift("..");C&&$[0]!==""&&(!$[0]||$[0].charAt(0)!=="/")&&$.unshift(""),dt&&$.join("/").substr(-1)!=="/"&&$.push("");var Ct=$[0]===""||$[0]&&$[0].charAt(0)==="/";if(J){x.hostname=Ct?"":$.length?$.shift():"",x.host=x.hostname;var yt=x.host&&x.host.indexOf("@")>0?x.host.split("@"):!1;yt&&(x.auth=yt.shift(),x.hostname=yt.shift(),x.host=x.hostname)}return C=C||x.host&&$.length,C&&!Ct&&$.unshift(""),$.length>0?x.pathname=$.join("/"):(x.pathname=null,x.path=null),(x.pathname!==null||x.search!==null)&&(x.path=(x.pathname?x.pathname:"")+(x.search?x.search:"")),x.auth=b.auth||x.auth,x.slashes=x.slashes||b.slashes,x.href=x.format(),x},t.prototype.parseHost=function(){var b=this.host,F=i.exec(b);F&&(F=F[0],F!==":"&&(this.port=F.substr(1)),b=b.substr(0,b.length-F.length)),b&&(this.hostname=b)},Cn.parse=m,Cn.resolve=S,Cn.resolveObject=E,Cn.format=_,Cn.Url=t,Cn}var Tu=$x();/*! + */var Ax={createCanvas:function(r,t){var e=document.createElement("canvas");return e.width=r,e.height=t,e},getWebGLRenderingContext:function(){return WebGLRenderingContext},getNavigator:function(){return navigator},getBaseUrl:function(){var r;return(r=document.baseURI)!==null&&r!==void 0?r:window.location.href},fetch:function(r,t){return fetch(r,t)}},yu=/iPhone/i,td=/iPod/i,ed=/iPad/i,rd=/\biOS-universal(?:.+)Mac\b/i,gu=/\bAndroid(?:.+)Mobile\b/i,id=/Android/i,ps=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,va=/Silk/i,Fi=/Windows Phone/i,nd=/\bWindows(?:.+)ARM\b/i,sd=/BlackBerry/i,od=/BB10/i,ad=/Opera Mini/i,ld=/\b(CriOS|Chrome)(?:.+)Mobile/i,ud=/Mobile(?:.+)Firefox\b/i,cd=function(r){return typeof r<"u"&&r.platform==="MacIntel"&&typeof r.maxTouchPoints=="number"&&r.maxTouchPoints>1&&typeof MSStream>"u"};function Ox(r){return function(t){return t.test(r)}}function Fx(r){var t={userAgent:"",platform:"",maxTouchPoints:0};!r&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof r=="string"?t.userAgent=r:r&&r.userAgent&&(t={userAgent:r.userAgent,platform:r.platform,maxTouchPoints:r.maxTouchPoints||0});var e=t.userAgent,i=e.split("[FBAN");typeof i[1]<"u"&&(e=i[0]),i=e.split("Twitter"),typeof i[1]<"u"&&(e=i[0]);var n=Ox(e),s={apple:{phone:n(yu)&&!n(Fi),ipod:n(td),tablet:!n(yu)&&(n(ed)||cd(t))&&!n(Fi),universal:n(rd),device:(n(yu)||n(td)||n(ed)||n(rd)||cd(t))&&!n(Fi)},amazon:{phone:n(ps),tablet:!n(ps)&&n(va),device:n(ps)||n(va)},android:{phone:!n(Fi)&&n(ps)||!n(Fi)&&n(gu),tablet:!n(Fi)&&!n(ps)&&!n(gu)&&(n(va)||n(id)),device:!n(Fi)&&(n(ps)||n(va)||n(gu)||n(id))||n(/\bokhttp\b/i)},windows:{phone:n(Fi),tablet:n(nd),device:n(Fi)||n(nd)},other:{blackberry:n(sd),blackberry10:n(od),opera:n(ad),firefox:n(ud),chrome:n(ld),device:n(sd)||n(od)||n(ad)||n(ud)||n(ld)},any:!1,phone:!1,tablet:!1};return s.any=s.apple.device||s.android.device||s.windows.device||s.other.device,s.phone=s.apple.phone||s.android.phone||s.windows.phone,s.tablet=s.apple.tablet||s.android.tablet||s.windows.tablet,s}var Xn=Fx(globalThis.navigator);function Px(){return!Xn.apple.device}function Mx(r){var t=!0;if(Xn.tablet||Xn.phone){if(Xn.apple.device){var e=navigator.userAgent.match(/OS (\d+)_(\d+)?/);if(e){var i=parseInt(e[1],10);i<11&&(t=!1)}}if(Xn.android.device){var e=navigator.userAgent.match(/Android\s([0-9.]*)/);if(e){var i=parseInt(e[1],10);i<7&&(t=!1)}}}return t?r:4}var It={ADAPTER:Ax,MIPMAP_TEXTURES:wi.POW2,ANISOTROPIC_LEVEL:0,RESOLUTION:1,FILTER_RESOLUTION:1,FILTER_MULTISAMPLE:Be.NONE,SPRITE_MAX_TEXTURES:Mx(32),SPRITE_BATCH_SIZE:4096,RENDER_OPTIONS:{view:null,width:800,height:600,autoDensity:!1,backgroundColor:0,backgroundAlpha:1,useContextAlpha:!0,clearBeforeRender:!0,antialias:!1,preserveDrawingBuffer:!1},GC_MODE:tl.AUTO,GC_MAX_IDLE:60*60,GC_MAX_CHECK_COUNT:60*10,WRAP_MODE:Ja.CLAMP,SCALE_MODE:Tr.LINEAR,PRECISION_VERTEX:Ir.HIGH,PRECISION_FRAGMENT:Xn.apple.device?Ir.HIGH:Ir.MEDIUM,CAN_UPLOAD_SAME_BUFFER:Px(),CREATE_IMAGE_BITMAP:!1,ROUND_PIXELS:!1},vu={exports:{}},hd;function Dx(){return hd||(hd=1,function(r){var t=Object.prototype.hasOwnProperty,e="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(e=!1));function n(l,u,c){this.fn=l,this.context=u,this.once=c||!1}function s(l,u,c,h,p){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new n(c,h||l,p),y=e?e+u:u;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],f]:l._events[y].push(f):(l._events[y]=f,l._eventsCount++),l}function o(l,u){--l._eventsCount===0?l._events=new i:delete l._events[u]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var u=[],c,h;if(this._eventsCount===0)return u;for(h in c=this._events)t.call(c,h)&&u.push(e?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(c)):u},a.prototype.listeners=function(u){var c=e?e+u:u,h=this._events[c];if(!h)return[];if(h.fn)return[h.fn];for(var p=0,f=h.length,y=new Array(f);p80*D){V=J=M[0],et=yt=M[1];for(var gt=D;gtJ&&(J=vt),dt>yt&&(yt=dt);_t=Math.max(J-V,yt-et),_t=_t!==0?32767/_t:0}return i(C,A,D,V,et,_t,0),A}function t(M,O,D,U,k){var C,A;if(k===it(M,O,D,U)>0)for(C=O;C=O;C-=U)A=I(C,M[C],M[C+1],A);return A&&E(A,A.next)&&(Z(A),A=A.next),A}function e(M,O){if(!M)return M;O||(O=M);var D=M,U;do if(U=!1,!D.steiner&&(E(D,D.next)||S(D.prev,D,D.next)===0)){if(Z(D),D=O=D.prev,D===D.next)break;U=!0}else D=D.next;while(U||D!==O);return O}function i(M,O,D,U,k,C,A){if(M){!A&&C&&f(M,U,k,C);for(var V=M,et,J;M.prev!==M.next;){if(et=M.prev,J=M.next,C?s(M,U,k,C):n(M)){O.push(et.i/D|0),O.push(M.i/D|0),O.push(J.i/D|0),Z(M),M=J.next,V=J.next;continue}if(M=J,M===V){A?A===1?(M=o(e(M),O,D),i(M,O,D,U,k,C,2)):A===2&&a(M,O,D,U,k,C):i(e(M),O,D,U,k,C,1);break}}}}function n(M){var O=M.prev,D=M,U=M.next;if(S(O,D,U)>=0)return!1;for(var k=O.x,C=D.x,A=U.x,V=O.y,et=D.y,J=U.y,yt=kC?k>A?k:A:C>A?C:A,_t=V>et?V>J?V:J:et>J?et:J,gt=U.next;gt!==O;){if(gt.x>=yt&>.x<=dt&>.y>=vt&>.y<=_t&&m(k,V,C,et,A,J,gt.x,gt.y)&&S(gt.prev,gt,gt.next)>=0)return!1;gt=gt.next}return!0}function s(M,O,D,U){var k=M.prev,C=M,A=M.next;if(S(k,C,A)>=0)return!1;for(var V=k.x,et=C.x,J=A.x,yt=k.y,vt=C.y,dt=A.y,_t=Vet?V>J?V:J:et>J?et:J,ee=yt>vt?yt>dt?yt:dt:vt>dt?vt:dt,he=g(_t,gt,O,D,U),v=g(Ct,ee,O,D,U),K=M.prevZ,q=M.nextZ;K&&K.z>=he&&q&&q.z<=v;){if(K.x>=_t&&K.x<=Ct&&K.y>=gt&&K.y<=ee&&K!==k&&K!==A&&m(V,yt,et,vt,J,dt,K.x,K.y)&&S(K.prev,K,K.next)>=0||(K=K.prevZ,q.x>=_t&&q.x<=Ct&&q.y>=gt&&q.y<=ee&&q!==k&&q!==A&&m(V,yt,et,vt,J,dt,q.x,q.y)&&S(q.prev,q,q.next)>=0))return!1;q=q.nextZ}for(;K&&K.z>=he;){if(K.x>=_t&&K.x<=Ct&&K.y>=gt&&K.y<=ee&&K!==k&&K!==A&&m(V,yt,et,vt,J,dt,K.x,K.y)&&S(K.prev,K,K.next)>=0)return!1;K=K.prevZ}for(;q&&q.z<=v;){if(q.x>=_t&&q.x<=Ct&&q.y>=gt&&q.y<=ee&&q!==k&&q!==A&&m(V,yt,et,vt,J,dt,q.x,q.y)&&S(q.prev,q,q.next)>=0)return!1;q=q.nextZ}return!0}function o(M,O,D){var U=M;do{var k=U.prev,C=U.next.next;!E(k,C)&&b(k,U,U.next,C)&&B(k,C)&&B(C,k)&&(O.push(k.i/D|0),O.push(U.i/D|0),O.push(C.i/D|0),Z(U),Z(U.next),U=M=C),U=U.next}while(U!==M);return e(U)}function a(M,O,D,U,k,C){var A=M;do{for(var V=A.next.next;V!==A.prev;){if(A.i!==V.i&&_(A,V)){var et=st(A,V);A=e(A,A.next),et=e(et,et.next),i(A,O,D,U,k,C,0),i(et,O,D,U,k,C,0);return}V=V.next}A=A.next}while(A!==M)}function l(M,O,D,U){var k=[],C,A,V,et,J;for(C=0,A=O.length;C=D.next.y&&D.next.y!==D.y){var V=D.x+(k-D.y)*(D.next.x-D.x)/(D.next.y-D.y);if(V<=U&&V>C&&(C=V,A=D.x=D.x&&D.x>=J&&U!==D.x&&m(kA.x||D.x===A.x&&p(A,D)))&&(A=D,vt=dt)),D=D.next;while(D!==et);return A}function p(M,O){return S(M.prev,M,O.prev)<0&&S(O.next,M,M.next)<0}function f(M,O,D,U){var k=M;do k.z===0&&(k.z=g(k.x,k.y,O,D,U)),k.prevZ=k.prev,k.nextZ=k.next,k=k.next;while(k!==M);k.prevZ.nextZ=null,k.prevZ=null,y(k)}function y(M){var O,D,U,k,C,A,V,et,J=1;do{for(D=M,M=null,C=null,A=0;D;){for(A++,U=D,V=0,O=0;O0||et>0&&U;)V!==0&&(et===0||!U||D.z<=U.z)?(k=D,D=D.nextZ,V--):(k=U,U=U.nextZ,et--),C?C.nextZ=k:M=k,k.prevZ=C,C=k;D=U}C.nextZ=null,J*=2}while(A>1);return M}function g(M,O,D,U,k){return M=(M-D)*k|0,O=(O-U)*k|0,M=(M|M<<8)&16711935,M=(M|M<<4)&252645135,M=(M|M<<2)&858993459,M=(M|M<<1)&1431655765,O=(O|O<<8)&16711935,O=(O|O<<4)&252645135,O=(O|O<<2)&858993459,O=(O|O<<1)&1431655765,M|O<<1}function d(M){var O=M,D=M;do(O.x=(M-A)*(C-V)&&(M-A)*(U-V)>=(D-A)*(O-V)&&(D-A)*(C-V)>=(k-A)*(U-V)}function _(M,O){return M.next.i!==O.i&&M.prev.i!==O.i&&!z(M,O)&&(B(M,O)&&B(O,M)&&tt(M,O)&&(S(M.prev,M,O.prev)||S(M,O.prev,O))||E(M,O)&&S(M.prev,M,M.next)>0&&S(O.prev,O,O.next)>0)}function S(M,O,D){return(O.y-M.y)*(D.x-O.x)-(O.x-M.x)*(D.y-O.y)}function E(M,O){return M.x===O.x&&M.y===O.y}function b(M,O,D,U){var k=x(S(M,O,D)),C=x(S(M,O,U)),A=x(S(D,U,M)),V=x(S(D,U,O));return!!(k!==C&&A!==V||k===0&&F(M,D,O)||C===0&&F(M,U,O)||A===0&&F(D,M,U)||V===0&&F(D,O,U))}function F(M,O,D){return O.x<=Math.max(M.x,D.x)&&O.x>=Math.min(M.x,D.x)&&O.y<=Math.max(M.y,D.y)&&O.y>=Math.min(M.y,D.y)}function x(M){return M>0?1:M<0?-1:0}function z(M,O){var D=M;do{if(D.i!==M.i&&D.next.i!==M.i&&D.i!==O.i&&D.next.i!==O.i&&b(D,D.next,M,O))return!0;D=D.next}while(D!==M);return!1}function B(M,O){return S(M.prev,M,M.next)<0?S(M,O,M.next)>=0&&S(M,M.prev,O)>=0:S(M,O,M.prev)<0||S(M,M.next,O)<0}function tt(M,O){var D=M,U=!1,k=(M.x+O.x)/2,C=(M.y+O.y)/2;do D.y>C!=D.next.y>C&&D.next.y!==D.y&&k<(D.next.x-D.x)*(C-D.y)/(D.next.y-D.y)+D.x&&(U=!U),D=D.next;while(D!==M);return U}function st(M,O){var D=new w(M.i,M.x,M.y),U=new w(O.i,O.x,O.y),k=M.next,C=O.prev;return M.next=O,O.prev=M,D.next=k,k.prev=D,U.next=D,D.prev=U,C.next=U,U.prev=C,U}function I(M,O,D,U){var k=new w(M,O,D);return U?(k.next=U.next,k.prev=U,U.next.prev=k,U.next=k):(k.prev=k,k.next=k),k}function Z(M){M.next.prev=M.prev,M.prev.next=M.next,M.prevZ&&(M.prevZ.nextZ=M.nextZ),M.nextZ&&(M.nextZ.prevZ=M.prevZ)}function w(M,O,D){this.i=M,this.x=O,this.y=D,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}r.deviation=function(M,O,D,U){var k=O&&O.length,C=k?O[0]*D:M.length,A=Math.abs(it(M,0,C,D));if(k)for(var V=0,et=O.length;V0&&(U+=M[k-1].length,D.holes.push(U))}return D},_a.exports}Nx();var Cn={},_o={exports:{}};/*! https://mths.be/punycode v1.4.1 by @mathias */var Lx=_o.exports,dd;function Bx(){return dd||(dd=1,function(r,t){(function(e){var i=t&&!t.nodeType&&t,n=r&&!r.nodeType&&r,s=typeof gi=="object"&&gi;(s.global===s||s.window===s||s.self===s)&&(e=s);var o,a=2147483647,l=36,u=1,c=26,h=38,p=700,f=72,y=128,g="-",d=/^xn--/,m=/[^\x20-\x7E]/,_=/[\x2E\u3002\uFF0E\uFF61]/g,S={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},E=l-u,b=Math.floor,F=String.fromCharCode,x;function z(k){throw new RangeError(S[k])}function B(k,C){for(var A=k.length,V=[];A--;)V[A]=C(k[A]);return V}function tt(k,C){var A=k.split("@"),V="";A.length>1&&(V=A[0]+"@",k=A[1]),k=k.replace(_,".");var et=k.split("."),J=B(et,C).join(".");return V+J}function st(k){for(var C=[],A=0,V=k.length,et,J;A=55296&&et<=56319&&A65535&&(C-=65536,A+=F(C>>>10&1023|55296),C=56320|C&1023),A+=F(C),A}).join("")}function Z(k){return k-48<10?k-22:k-65<26?k-65:k-97<26?k-97:l}function w(k,C){return k+22+75*(k<26)-((C!=0)<<5)}function it(k,C,A){var V=0;for(k=A?b(k/p):k>>1,k+=b(k/C);k>E*c>>1;V+=l)k=b(k/E);return b(V+(E+1)*k/(k+h))}function M(k){var C=[],A=k.length,V,et=0,J=y,yt=f,vt,dt,_t,gt,Ct,ee,he,v,K;for(vt=k.lastIndexOf(g),vt<0&&(vt=0),dt=0;dt=128&&z("not-basic"),C.push(k.charCodeAt(dt));for(_t=vt>0?vt+1:0;_t=A&&z("invalid-input"),he=Z(k.charCodeAt(_t++)),(he>=l||he>b((a-et)/Ct))&&z("overflow"),et+=he*Ct,v=ee<=yt?u:ee>=yt+c?c:ee-yt,!(heb(a/K)&&z("overflow"),Ct*=K;V=C.length+1,yt=it(et-gt,V,gt==0),b(et/V)>a-J&&z("overflow"),J+=b(et/V),et%=V,C.splice(et++,0,J)}return I(C)}function O(k){var C,A,V,et,J,yt,vt,dt,_t,gt,Ct,ee=[],he,v,K,q;for(k=st(k),he=k.length,C=y,A=0,J=f,yt=0;yt=C&&Ctb((a-A)/v)&&z("overflow"),A+=(vt-C)*v,C=vt,yt=0;yta&&z("overflow"),Ct==C){for(dt=A,_t=l;gt=_t<=J?u:_t>=J+c?c:_t-J,!(dt{if(u&&(typeof u=="object"||typeof u=="function")){if(i)return i.get(u)}else if(n)return n.get(u)},o=(u,c)=>{u&&(typeof u=="object"||typeof u=="function")?(i||(i=new WeakMap),i.set(u,c)):(n||(n=new Map),n.set(u,c))},a=u=>{if(u&&(typeof u=="object"||typeof u=="function")){if(i)return i.has(u)}else if(n)return n.has(u);return!1};return{get:s,set:o,has:a,assert:u=>{if(!a(u))throw new TypeError("Side channel does not contain the given key")}}}t.default=e,(typeof t.default=="object"&&t.default!==null||typeof t.default=="function")&&(Object.assign(t.default,t),r.exports=t.default)}(ba,ba.exports)),ba.exports}var _u,md;function Lh(){if(md)return _u;md=1;var r=String.prototype.replace,t=/%20/g,e={RFC1738:"RFC1738",RFC3986:"RFC3986"};return _u={default:e.RFC3986,formatters:{RFC1738:function(i){return r.call(i,t,"+")},RFC3986:function(i){return String(i)}},RFC1738:e.RFC1738,RFC3986:e.RFC3986},_u}var bu,yd;function Rg(){if(yd)return bu;yd=1;var r=Lh(),t=Object.prototype.hasOwnProperty,e=Array.isArray,i=function(){for(var d=[],m=0;m<256;++m)d.push("%"+((m<16?"0":"")+m.toString(16)).toUpperCase());return d}(),n=function(m){for(;m.length>1;){var _=m.pop(),S=_.obj[_.prop];if(e(S)){for(var E=[],b=0;b=u?F.slice(z,z+u):F,tt=[],st=0;st=48&&I<=57||I>=65&&I<=90||I>=97&&I<=122||b===r.RFC1738&&(I===40||I===41)){tt[tt.length]=B.charAt(st);continue}if(I<128){tt[tt.length]=i[I];continue}if(I<2048){tt[tt.length]=i[192|I>>6]+i[128|I&63];continue}if(I<55296||I>=57344){tt[tt.length]=i[224|I>>12]+i[128|I>>6&63]+i[128|I&63];continue}st+=1,I=65536+((I&1023)<<10|B.charCodeAt(st)&1023),tt[tt.length]=i[240|I>>18]+i[128|I>>12&63]+i[128|I>>6&63]+i[128|I&63]}x+=tt.join("")}return x},h=function(m){for(var _=[{obj:{o:m},prop:"o"}],S=[],E=0;E<_.length;++E)for(var b=_[E],F=b.obj[b.prop],x=Object.keys(F),z=0;z"u"&&(k=0)}if(typeof B=="function"?D=B(m,D):D instanceof Date?D=I(D):_==="comma"&&s(D)&&(D=t.maybeMap(D,function(K){return K instanceof Date?I(K):K})),D===null){if(b)return z&&!it?z(m,c.encoder,M,"key",Z):m;D=""}if(h(D)||t.isBuffer(D)){if(z){var V=it?m:z(m,c.encoder,M,"key",Z);return[w(V)+"="+w(z(D,c.encoder,M,"value",Z))]}return[w(m)+"="+w(String(D))]}var et=[];if(typeof D>"u")return et;var J;if(_==="comma"&&s(D))it&&z&&(D=t.maybeMap(D,z)),J=[{value:D.length>0?D.join(",")||null:void 0}];else if(s(B))J=B;else{var yt=Object.keys(D);J=tt?yt.sort(tt):yt}var vt=x?String(m).replace(/\./g,"%2E"):String(m),dt=S&&s(D)&&D.length===1?vt+"[]":vt;if(E&&s(D)&&D.length===0)return dt+"[]";for(var _t=0;_t"u"?d.encodeDotInKeys===!0?!0:c.allowDots:!!d.allowDots;return{addQueryPrefix:typeof d.addQueryPrefix=="boolean"?d.addQueryPrefix:c.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof d.allowEmptyArrays=="boolean"?!!d.allowEmptyArrays:c.allowEmptyArrays,arrayFormat:b,charset:m,charsetSentinel:typeof d.charsetSentinel=="boolean"?d.charsetSentinel:c.charsetSentinel,commaRoundTrip:!!d.commaRoundTrip,delimiter:typeof d.delimiter>"u"?c.delimiter:d.delimiter,encode:typeof d.encode=="boolean"?d.encode:c.encode,encodeDotInKeys:typeof d.encodeDotInKeys=="boolean"?d.encodeDotInKeys:c.encodeDotInKeys,encoder:typeof d.encoder=="function"?d.encoder:c.encoder,encodeValuesOnly:typeof d.encodeValuesOnly=="boolean"?d.encodeValuesOnly:c.encodeValuesOnly,filter:E,format:_,formatter:S,serializeDate:typeof d.serializeDate=="function"?d.serializeDate:c.serializeDate,skipNulls:typeof d.skipNulls=="boolean"?d.skipNulls:c.skipNulls,sort:typeof d.sort=="function"?d.sort:null,strictNullHandling:typeof d.strictNullHandling=="boolean"?d.strictNullHandling:c.strictNullHandling}};return wu=function(g,d){var m=g,_=y(d),S,E;typeof _.filter=="function"?(E=_.filter,m=E("",m)):s(_.filter)&&(E=_.filter,S=E);var b=[];if(typeof m!="object"||m===null)return"";var F=n[_.arrayFormat],x=F==="comma"&&_.commaRoundTrip;S||(S=Object.keys(m)),_.sort&&S.sort(_.sort);for(var z=r(),B=0;B0?Z+I:""},wu}var xu,vd;function zx(){if(vd)return xu;vd=1;var r=Rg(),t=Object.prototype.hasOwnProperty,e=Array.isArray,i={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:r.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},n=function(p){return p.replace(/&#(\d+);/g,function(f,y){return String.fromCharCode(parseInt(y,10))})},s=function(p,f,y){if(p&&typeof p=="string"&&f.comma&&p.indexOf(",")>-1)return p.split(",");if(f.throwOnLimitExceeded&&y>=f.arrayLimit)throw new RangeError("Array limit exceeded. Only "+f.arrayLimit+" element"+(f.arrayLimit===1?"":"s")+" allowed in an array.");return p},o="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",l=function(f,y){var g={__proto__:null},d=y.ignoreQueryPrefix?f.replace(/^\?/,""):f;d=d.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var m=y.parameterLimit===1/0?void 0:y.parameterLimit,_=d.split(y.delimiter,y.throwOnLimitExceeded?m+1:m);if(y.throwOnLimitExceeded&&_.length>m)throw new RangeError("Parameter limit exceeded. Only "+m+" parameter"+(m===1?"":"s")+" allowed.");var S=-1,E,b=y.charset;if(y.charsetSentinel)for(E=0;E<_.length;++E)_[E].indexOf("utf8=")===0&&(_[E]===a?b="utf-8":_[E]===o&&(b="iso-8859-1"),S=E,E=_.length);for(E=0;E<_.length;++E)if(E!==S){var F=_[E],x=F.indexOf("]="),z=x===-1?F.indexOf("="):x+1,B,tt;z===-1?(B=y.decoder(F,i.decoder,b,"key"),tt=y.strictNullHandling?null:""):(B=y.decoder(F.slice(0,z),i.decoder,b,"key"),tt=r.maybeMap(s(F.slice(z+1),y,e(g[B])?g[B].length:0),function(I){return y.decoder(I,i.decoder,b,"value")})),tt&&y.interpretNumericEntities&&b==="iso-8859-1"&&(tt=n(String(tt))),F.indexOf("[]=")>-1&&(tt=e(tt)?[tt]:tt);var st=t.call(g,B);st&&y.duplicates==="combine"?g[B]=r.combine(g[B],tt):(!st||y.duplicates==="last")&&(g[B]=tt)}return g},u=function(p,f,y,g){var d=0;if(p.length>0&&p[p.length-1]==="[]"){var m=p.slice(0,-1).join("");d=Array.isArray(f)&&f[m]?f[m].length:0}for(var _=g?f:s(f,y,d),S=p.length-1;S>=0;--S){var E,b=p[S];if(b==="[]"&&y.parseArrays)E=y.allowEmptyArrays&&(_===""||y.strictNullHandling&&_===null)?[]:r.combine([],_);else{E=y.plainObjects?{__proto__:null}:{};var F=b.charAt(0)==="["&&b.charAt(b.length-1)==="]"?b.slice(1,-1):b,x=y.decodeDotInKeys?F.replace(/%2E/g,"."):F,z=parseInt(x,10);!y.parseArrays&&x===""?E={0:_}:!isNaN(z)&&b!==x&&String(z)===x&&z>=0&&y.parseArrays&&z<=y.arrayLimit?(E=[],E[z]=_):x!=="__proto__"&&(E[x]=_)}_=E}return _},c=function(f,y,g,d){if(f){var m=g.allowDots?f.replace(/\.([^.[]+)/g,"[$1]"):f,_=/(\[[^[\]]*])/,S=/(\[[^[\]]*])/g,E=g.depth>0&&_.exec(m),b=E?m.slice(0,E.index):m,F=[];if(b){if(!g.plainObjects&&t.call(Object.prototype,b)&&!g.allowPrototypes)return;F.push(b)}for(var x=0;g.depth>0&&(E=S.exec(m))!==null&&x"u"?i.charset:f.charset,g=typeof f.duplicates>"u"?i.duplicates:f.duplicates;if(g!=="combine"&&g!=="first"&&g!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var d=typeof f.allowDots>"u"?f.decodeDotInKeys===!0?!0:i.allowDots:!!f.allowDots;return{allowDots:d,allowEmptyArrays:typeof f.allowEmptyArrays=="boolean"?!!f.allowEmptyArrays:i.allowEmptyArrays,allowPrototypes:typeof f.allowPrototypes=="boolean"?f.allowPrototypes:i.allowPrototypes,allowSparse:typeof f.allowSparse=="boolean"?f.allowSparse:i.allowSparse,arrayLimit:typeof f.arrayLimit=="number"?f.arrayLimit:i.arrayLimit,charset:y,charsetSentinel:typeof f.charsetSentinel=="boolean"?f.charsetSentinel:i.charsetSentinel,comma:typeof f.comma=="boolean"?f.comma:i.comma,decodeDotInKeys:typeof f.decodeDotInKeys=="boolean"?f.decodeDotInKeys:i.decodeDotInKeys,decoder:typeof f.decoder=="function"?f.decoder:i.decoder,delimiter:typeof f.delimiter=="string"||r.isRegExp(f.delimiter)?f.delimiter:i.delimiter,depth:typeof f.depth=="number"||f.depth===!1?+f.depth:i.depth,duplicates:g,ignoreQueryPrefix:f.ignoreQueryPrefix===!0,interpretNumericEntities:typeof f.interpretNumericEntities=="boolean"?f.interpretNumericEntities:i.interpretNumericEntities,parameterLimit:typeof f.parameterLimit=="number"?f.parameterLimit:i.parameterLimit,parseArrays:f.parseArrays!==!1,plainObjects:typeof f.plainObjects=="boolean"?f.plainObjects:i.plainObjects,strictDepth:typeof f.strictDepth=="boolean"?!!f.strictDepth:i.strictDepth,strictNullHandling:typeof f.strictNullHandling=="boolean"?f.strictNullHandling:i.strictNullHandling,throwOnLimitExceeded:typeof f.throwOnLimitExceeded=="boolean"?f.throwOnLimitExceeded:!1}};return xu=function(p,f){var y=h(f);if(p===""||p===null||typeof p>"u")return y.plainObjects?{__proto__:null}:{};for(var g=typeof p=="string"?l(p,y):p,d=y.plainObjects?{__proto__:null}:{},m=Object.keys(g),_=0;_",'"',"`"," ","\r",` +`," "],o=["{","}","|","\\","^","`"].concat(s),a=["'"].concat(o),l=["%","/","?",";","#"].concat(a),u=["/","?","#"],c=255,h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,f={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},d=jx();function m(b,F,x){if(b&&typeof b=="object"&&b instanceof t)return b;var z=new t;return z.parse(b,F,x),z}t.prototype.parse=function(b,F,x){if(typeof b!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof b);var z=b.indexOf("?"),B=z!==-1&&z127?yt+="x":yt+=J[vt];if(!yt.match(h)){var _t=V.slice(0,D),gt=V.slice(D+1),Ct=J.match(p);Ct&&(_t.push(Ct[1]),gt.unshift(Ct[2])),gt.length&&(I="/"+gt.join(".")+I),this.hostname=_t.join(".");break}}}this.hostname.length>c?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=r.toASCII(this.hostname));var ee=this.port?":"+this.port:"",he=this.hostname||"";this.host=he+ee,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),I[0]!=="/"&&(I="/"+I))}if(!f[it])for(var D=0,et=a.length;D0?x.host.split("@"):!1;yt&&(x.auth=yt.shift(),x.hostname=yt.shift(),x.host=x.hostname)}return x.search=b.search,x.query=b.query,(x.pathname!==null||x.search!==null)&&(x.path=(x.pathname?x.pathname:"")+(x.search?x.search:"")),x.href=x.format(),x}if(!V.length)return x.pathname=null,x.search?x.path="/"+x.search:x.path=null,x.href=x.format(),x;for(var vt=V.slice(-1)[0],dt=(x.host||b.host||V.length>1)&&(vt==="."||vt==="..")||vt==="",_t=0,gt=V.length;gt>=0;gt--)vt=V[gt],vt==="."?V.splice(gt,1):vt===".."?(V.splice(gt,1),_t++):_t&&(V.splice(gt,1),_t--);if(!C&&!A)for(;_t--;_t)V.unshift("..");C&&V[0]!==""&&(!V[0]||V[0].charAt(0)!=="/")&&V.unshift(""),dt&&V.join("/").substr(-1)!=="/"&&V.push("");var Ct=V[0]===""||V[0]&&V[0].charAt(0)==="/";if(J){x.hostname=Ct?"":V.length?V.shift():"",x.host=x.hostname;var yt=x.host&&x.host.indexOf("@")>0?x.host.split("@"):!1;yt&&(x.auth=yt.shift(),x.hostname=yt.shift(),x.host=x.hostname)}return C=C||x.host&&V.length,C&&!Ct&&V.unshift(""),V.length>0?x.pathname=V.join("/"):(x.pathname=null,x.path=null),(x.pathname!==null||x.search!==null)&&(x.path=(x.pathname?x.pathname:"")+(x.search?x.search:"")),x.auth=b.auth||x.auth,x.slashes=x.slashes||b.slashes,x.href=x.format(),x},t.prototype.parseHost=function(){var b=this.host,F=i.exec(b);F&&(F=F[0],F!==":"&&(this.port=F.substr(1)),b=b.substr(0,b.length-F.length)),b&&(this.hostname=b)},Cn.parse=m,Cn.resolve=S,Cn.resolveObject=E,Cn.format=_,Cn.Url=t,Cn}var Tu=$x();/*! * @pixi/utils - 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 ap;function fI(){return ap||(ap=1,function(r,t){(function(e){r.exports=e()})(function(){return function e(i,n,s){function o(u,c){if(!n[u]){if(!i[u]){var h=typeof un=="function"&&un;if(!c&&h)return h(u,!0);if(a)return a(u,!0);var p=new Error("Cannot find module '"+u+"'");throw p.code="MODULE_NOT_FOUND",p}var f=n[u]={exports:{}};i[u][0].call(f.exports,function(y){var g=i[u][1][y];return o(g||y)},f,f.exports,e,i,n,s)}return n[u].exports}for(var a=typeof un=="function"&&un,l=0;l"u"&&e(3);var h=Promise;function p(T,j){j&&T.then(function(P){j(null,P)},function(P){j(P)})}function f(T,j,P){typeof j=="function"&&T.then(j),typeof P=="function"&&T.catch(P)}function y(T){return typeof T!="string"&&(console.warn(T+" used as a key, but it is not a string."),T=String(T)),T}function g(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var d="local-forage-detect-blob-support",m=void 0,_={},S=Object.prototype.toString,E="readonly",b="readwrite";function F(T){for(var j=T.length,P=new ArrayBuffer(j),H=new Uint8Array(P),Q=0;Q=43)}}).catch(function(){return!1})}function z(T){return typeof m=="boolean"?h.resolve(m):x(T).then(function(j){return m=j,m})}function B(T){var j=_[T.name],P={};P.promise=new h(function(H,Q){P.resolve=H,P.reject=Q}),j.deferredOperations.push(P),j.dbReady?j.dbReady=j.dbReady.then(function(){return P.promise}):j.dbReady=P.promise}function tt(T){var j=_[T.name],P=j.deferredOperations.pop();if(P)return P.resolve(),P.promise}function st(T,j){var P=_[T.name],H=P.deferredOperations.pop();if(H)return H.reject(j),H.promise}function I(T,j){return new h(function(P,H){if(_[T.name]=_[T.name]||A(),T.db)if(j)B(T),T.db.close();else return P(T.db);var Q=[T.name];j&&Q.push(T.version);var V=l.open.apply(l,Q);j&&(V.onupgradeneeded=function(nt){var ut=V.result;try{ut.createObjectStore(T.storeName),nt.oldVersion<=1&&ut.createObjectStore(d)}catch(ct){if(ct.name==="ConstraintError")console.warn('The database "'+T.name+'" has been upgraded from version '+nt.oldVersion+" to version "+nt.newVersion+', but the storage "'+T.storeName+'" already exists.');else throw ct}}),V.onerror=function(nt){nt.preventDefault(),H(V.error)},V.onsuccess=function(){var nt=V.result;nt.onversionchange=function(ut){ut.target.close()},P(nt),tt(T)}})}function Z(T){return I(T,!1)}function w(T){return I(T,!0)}function it(T,j){if(!T.db)return!0;var P=!T.db.objectStoreNames.contains(T.storeName),H=T.versionT.db.version;if(H&&(T.version!==j&&console.warn('The database "'+T.name+`" can't be downgraded from version `+T.db.version+" to version "+T.version+"."),T.version=T.db.version),Q||P){if(P){var V=T.db.version+1;V>T.version&&(T.version=V)}return!0}return!1}function M(T){return new h(function(j,P){var H=new FileReader;H.onerror=P,H.onloadend=function(Q){var V=btoa(Q.target.result||"");j({__local_forage_encoded_blob:!0,data:V,type:T.type})},H.readAsBinaryString(T)})}function O(T){var j=F(atob(T.data));return c([j],{type:T.type})}function D(T){return T&&T.__local_forage_encoded_blob}function U(T){var j=this,P=j._initReady().then(function(){var H=_[j._dbInfo.name];if(H&&H.dbReady)return H.dbReady});return f(P,T,T),P}function k(T){B(T);for(var j=_[T.name],P=j.forages,H=0;H0&&(!T.db||V.name==="InvalidStateError"||V.name==="NotFoundError"))return h.resolve().then(function(){if(!T.db||V.name==="NotFoundError"&&!T.db.objectStoreNames.contains(T.storeName)&&T.version<=T.db.version)return T.db&&(T.version=T.db.version+1),w(T)}).then(function(){return k(T).then(function(){C(T,j,P,H-1)})}).catch(P);P(V)}}function A(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function $(T){var j=this,P={db:null};if(T)for(var H in T)P[H]=T[H];var Q=_[P.name];Q||(Q=A(),_[P.name]=Q),Q.forages.push(j),j._initReady||(j._initReady=j.ready,j.ready=U);var V=[];function nt(){return h.resolve()}for(var ut=0;ut>4,mt[Q++]=(nt&15)<<4|ut>>2,mt[Q++]=(ut&3)<<6|ct&63;return ft}function Ji(T){var j=new Uint8Array(T),P="",H;for(H=0;H>2],P+=K[(j[H]&3)<<4|j[H+1]>>4],P+=K[(j[H+1]&15)<<2|j[H+2]>>6],P+=K[j[H+2]&63];return j.length%3===2?P=P.substring(0,P.length-1)+"=":j.length%3===1&&(P=P.substring(0,P.length-2)+"=="),P}function ao(T,j){var P="";if(T&&(P=Zi.call(T)),T&&(P==="[object ArrayBuffer]"||T.buffer&&Zi.call(T.buffer)==="[object ArrayBuffer]")){var H,Q=R;T instanceof ArrayBuffer?(H=T,Q+=ot):(H=T.buffer,P==="[object Int8Array]"?Q+=rt:P==="[object Uint8Array]"?Q+=ht:P==="[object Uint8ClampedArray]"?Q+=bt:P==="[object Int16Array]"?Q+=pt:P==="[object Uint16Array]"?Q+=ye:P==="[object Int32Array]"?Q+=Ot:P==="[object Uint32Array]"?Q+=oe:P==="[object Float32Array]"?Q+=ir:P==="[object Float64Array]"?Q+=Ki:j(new Error("Failed to get type for BinaryArray"))),j(Q+Ji(H))}else if(P==="[object Blob]"){var V=new FileReader;V.onload=function(){var nt=q+T.type+"~"+Ji(this.result);j(R+at+nt)},V.readAsArrayBuffer(T)}else try{j(JSON.stringify(T))}catch(nt){console.error("Couldn't convert value into a JSON string: ",T),j(null,nt)}}function Qr(T){if(T.substring(0,Y)!==R)return JSON.parse(T);var j=T.substring(vr),P=T.substring(Y,vr),H;if(P===at&&N.test(j)){var Q=j.match(N);H=Q[1],j=j.substring(Q[0].length)}var V=Ae(j);switch(P){case ot:return V;case at:return c([V],{type:H});case rt:return new Int8Array(V);case ht:return new Uint8Array(V);case bt:return new Uint8ClampedArray(V);case pt:return new Int16Array(V);case ye:return new Uint16Array(V);case Ot:return new Int32Array(V);case oe:return new Uint32Array(V);case ir:return new Float32Array(V);case Ki:return new Float64Array(V);default:throw new Error("Unkown type: "+P)}}var fs={serialize:ao,deserialize:Qr,stringToBuffer:Ae,bufferToString:Ji};function ma(T,j,P,H){T.executeSql("CREATE TABLE IF NOT EXISTS "+j.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],P,H)}function hu(T){var j=this,P={db:null};if(T)for(var H in T)P[H]=typeof T[H]!="string"?T[H].toString():T[H];var Q=new h(function(V,nt){try{P.db=openDatabase(P.name,String(P.version),P.description,P.size)}catch(ut){return nt(ut)}P.db.transaction(function(ut){ma(ut,P,function(){j._dbInfo=P,V()},function(ct,ft){nt(ft)})},nt)});return P.serializer=fs,Q}function si(T,j,P,H,Q,V){T.executeSql(P,H,Q,function(nt,ut){ut.code===ut.SYNTAX_ERR?nt.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[j.storeName],function(ct,ft){ft.rows.length?V(ct,ut):ma(ct,j,function(){ct.executeSql(P,H,Q,V)},V)},V):V(nt,ut)},V)}function ya(T,j){var P=this;T=y(T);var H=new h(function(Q,V){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"SELECT * FROM "+nt.storeName+" WHERE key = ? LIMIT 1",[T],function(ct,ft){var mt=ft.rows.length?ft.rows.item(0).value:null;mt&&(mt=nt.serializer.deserialize(mt)),Q(mt)},function(ct,ft){V(ft)})})}).catch(V)});return p(H,j),H}function In(T,j){var P=this,H=new h(function(Q,V){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"SELECT * FROM "+nt.storeName,[],function(ct,ft){for(var mt=ft.rows,St=mt.length,ne=0;ne0){nt(En.apply(Q,[T,ct,P,H-1]));return}ut(ne)}})})}).catch(ut)});return p(V,P),V}function Hw(T,j,P){return En.apply(this,[T,j,P,1])}function Xw(T,j){var P=this;T=y(T);var H=new h(function(Q,V){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"DELETE FROM "+nt.storeName+" WHERE key = ?",[T],function(){Q()},function(ct,ft){V(ft)})})}).catch(V)});return p(H,j),H}function Yw(T){var j=this,P=new h(function(H,Q){j.ready().then(function(){var V=j._dbInfo;V.db.transaction(function(nt){si(nt,V,"DELETE FROM "+V.storeName,[],function(){H()},function(ut,ct){Q(ct)})})}).catch(Q)});return p(P,T),P}function qw(T){var j=this,P=new h(function(H,Q){j.ready().then(function(){var V=j._dbInfo;V.db.transaction(function(nt){si(nt,V,"SELECT COUNT(key) as c FROM "+V.storeName,[],function(ut,ct){var ft=ct.rows.item(0).c;H(ft)},function(ut,ct){Q(ct)})})}).catch(Q)});return p(P,T),P}function Qw(T,j){var P=this,H=new h(function(Q,V){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"SELECT key FROM "+nt.storeName+" WHERE id = ? LIMIT 1",[T+1],function(ct,ft){var mt=ft.rows.length?ft.rows.item(0).key:null;Q(mt)},function(ct,ft){V(ft)})})}).catch(V)});return p(H,j),H}function Kw(T){var j=this,P=new h(function(H,Q){j.ready().then(function(){var V=j._dbInfo;V.db.transaction(function(nt){si(nt,V,"SELECT key FROM "+V.storeName,[],function(ut,ct){for(var ft=[],mt=0;mt '__WebKitDatabaseInfoTable__'",[],function(Q,V){for(var nt=[],ut=0;ut0}function nx(T){var j=this,P={};if(T)for(var H in T)P[H]=T[H];return P.keyPrefix=qf(T,j._defaultConfig),ix()?(j._dbInfo=P,P.serializer=fs,h.resolve()):h.reject()}function sx(T){var j=this,P=j.ready().then(function(){for(var H=j._dbInfo.keyPrefix,Q=localStorage.length-1;Q>=0;Q--){var V=localStorage.key(Q);V.indexOf(H)===0&&localStorage.removeItem(V)}});return p(P,T),P}function ox(T,j){var P=this;T=y(T);var H=P.ready().then(function(){var Q=P._dbInfo,V=localStorage.getItem(Q.keyPrefix+T);return V&&(V=Q.serializer.deserialize(V)),V});return p(H,j),H}function ax(T,j){var P=this,H=P.ready().then(function(){for(var Q=P._dbInfo,V=Q.keyPrefix,nt=V.length,ut=localStorage.length,ct=1,ft=0;ft=0;nt--){var ut=localStorage.key(nt);ut.indexOf(V)===0&&localStorage.removeItem(ut)}}):Q=h.reject("Invalid arguments"),p(Q,j),Q}var px={_driver:"localStorageWrapper",_initStorage:nx,_support:ex(),iterate:ax,getItem:ox,setItem:fx,removeItem:hx,clear:sx,length:cx,key:lx,keys:ux,dropInstance:dx},mx=function(j,P){return j===P||typeof j=="number"&&typeof P=="number"&&isNaN(j)&&isNaN(P)},yx=function(j,P){for(var H=j.length,Q=0;Q"u"?"undefined":s(P))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var H in P){if(H==="storeName"&&(P[H]=P[H].replace(/\W/g,"_")),H==="version"&&typeof P[H]!="number")return new Error("Database version must be a number.");this._config[H]=P[H]}return"driver"in P&&P.driver?this.setDriver(this._config.driver):!0}else return typeof P=="string"?this._config[P]:this._config},T.prototype.defineDriver=function(P,H,Q){var V=new h(function(nt,ut){try{var ct=P._driver,ft=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!P._driver){ut(ft);return}for(var mt=fu.concat("_initStorage"),St=0,ne=mt.length;St"u"&&e(3);var h=Promise;function p(T,j){j&&T.then(function(P){j(null,P)},function(P){j(P)})}function f(T,j,P){typeof j=="function"&&T.then(j),typeof P=="function"&&T.catch(P)}function y(T){return typeof T!="string"&&(console.warn(T+" used as a key, but it is not a string."),T=String(T)),T}function g(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var d="local-forage-detect-blob-support",m=void 0,_={},S=Object.prototype.toString,E="readonly",b="readwrite";function F(T){for(var j=T.length,P=new ArrayBuffer(j),X=new Uint8Array(P),Q=0;Q=43)}}).catch(function(){return!1})}function z(T){return typeof m=="boolean"?h.resolve(m):x(T).then(function(j){return m=j,m})}function B(T){var j=_[T.name],P={};P.promise=new h(function(X,Q){P.resolve=X,P.reject=Q}),j.deferredOperations.push(P),j.dbReady?j.dbReady=j.dbReady.then(function(){return P.promise}):j.dbReady=P.promise}function tt(T){var j=_[T.name],P=j.deferredOperations.pop();if(P)return P.resolve(),P.promise}function st(T,j){var P=_[T.name],X=P.deferredOperations.pop();if(X)return X.reject(j),X.promise}function I(T,j){return new h(function(P,X){if(_[T.name]=_[T.name]||A(),T.db)if(j)B(T),T.db.close();else return P(T.db);var Q=[T.name];j&&Q.push(T.version);var G=l.open.apply(l,Q);j&&(G.onupgradeneeded=function(nt){var ut=G.result;try{ut.createObjectStore(T.storeName),nt.oldVersion<=1&&ut.createObjectStore(d)}catch(ct){if(ct.name==="ConstraintError")console.warn('The database "'+T.name+'" has been upgraded from version '+nt.oldVersion+" to version "+nt.newVersion+', but the storage "'+T.storeName+'" already exists.');else throw ct}}),G.onerror=function(nt){nt.preventDefault(),X(G.error)},G.onsuccess=function(){var nt=G.result;nt.onversionchange=function(ut){ut.target.close()},P(nt),tt(T)}})}function Z(T){return I(T,!1)}function w(T){return I(T,!0)}function it(T,j){if(!T.db)return!0;var P=!T.db.objectStoreNames.contains(T.storeName),X=T.versionT.db.version;if(X&&(T.version!==j&&console.warn('The database "'+T.name+`" can't be downgraded from version `+T.db.version+" to version "+T.version+"."),T.version=T.db.version),Q||P){if(P){var G=T.db.version+1;G>T.version&&(T.version=G)}return!0}return!1}function M(T){return new h(function(j,P){var X=new FileReader;X.onerror=P,X.onloadend=function(Q){var G=btoa(Q.target.result||"");j({__local_forage_encoded_blob:!0,data:G,type:T.type})},X.readAsBinaryString(T)})}function O(T){var j=F(atob(T.data));return c([j],{type:T.type})}function D(T){return T&&T.__local_forage_encoded_blob}function U(T){var j=this,P=j._initReady().then(function(){var X=_[j._dbInfo.name];if(X&&X.dbReady)return X.dbReady});return f(P,T,T),P}function k(T){B(T);for(var j=_[T.name],P=j.forages,X=0;X0&&(!T.db||G.name==="InvalidStateError"||G.name==="NotFoundError"))return h.resolve().then(function(){if(!T.db||G.name==="NotFoundError"&&!T.db.objectStoreNames.contains(T.storeName)&&T.version<=T.db.version)return T.db&&(T.version=T.db.version+1),w(T)}).then(function(){return k(T).then(function(){C(T,j,P,X-1)})}).catch(P);P(G)}}function A(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function V(T){var j=this,P={db:null};if(T)for(var X in T)P[X]=T[X];var Q=_[P.name];Q||(Q=A(),_[P.name]=Q),Q.forages.push(j),j._initReady||(j._initReady=j.ready,j.ready=U);var G=[];function nt(){return h.resolve()}for(var ut=0;ut>4,mt[Q++]=(nt&15)<<4|ut>>2,mt[Q++]=(ut&3)<<6|ct&63;return ft}function Ji(T){var j=new Uint8Array(T),P="",X;for(X=0;X>2],P+=K[(j[X]&3)<<4|j[X+1]>>4],P+=K[(j[X+1]&15)<<2|j[X+2]>>6],P+=K[j[X+2]&63];return j.length%3===2?P=P.substring(0,P.length-1)+"=":j.length%3===1&&(P=P.substring(0,P.length-2)+"=="),P}function ao(T,j){var P="";if(T&&(P=Zi.call(T)),T&&(P==="[object ArrayBuffer]"||T.buffer&&Zi.call(T.buffer)==="[object ArrayBuffer]")){var X,Q=R;T instanceof ArrayBuffer?(X=T,Q+=ot):(X=T.buffer,P==="[object Int8Array]"?Q+=rt:P==="[object Uint8Array]"?Q+=ht:P==="[object Uint8ClampedArray]"?Q+=bt:P==="[object Int16Array]"?Q+=pt:P==="[object Uint16Array]"?Q+=ye:P==="[object Int32Array]"?Q+=Ot:P==="[object Uint32Array]"?Q+=oe:P==="[object Float32Array]"?Q+=ir:P==="[object Float64Array]"?Q+=Ki:j(new Error("Failed to get type for BinaryArray"))),j(Q+Ji(X))}else if(P==="[object Blob]"){var G=new FileReader;G.onload=function(){var nt=q+T.type+"~"+Ji(this.result);j(R+at+nt)},G.readAsArrayBuffer(T)}else try{j(JSON.stringify(T))}catch(nt){console.error("Couldn't convert value into a JSON string: ",T),j(null,nt)}}function Qr(T){if(T.substring(0,Y)!==R)return JSON.parse(T);var j=T.substring(vr),P=T.substring(Y,vr),X;if(P===at&&N.test(j)){var Q=j.match(N);X=Q[1],j=j.substring(Q[0].length)}var G=Ae(j);switch(P){case ot:return G;case at:return c([G],{type:X});case rt:return new Int8Array(G);case ht:return new Uint8Array(G);case bt:return new Uint8ClampedArray(G);case pt:return new Int16Array(G);case ye:return new Uint16Array(G);case Ot:return new Int32Array(G);case oe:return new Uint32Array(G);case ir:return new Float32Array(G);case Ki:return new Float64Array(G);default:throw new Error("Unkown type: "+P)}}var fs={serialize:ao,deserialize:Qr,stringToBuffer:Ae,bufferToString:Ji};function ma(T,j,P,X){T.executeSql("CREATE TABLE IF NOT EXISTS "+j.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],P,X)}function hu(T){var j=this,P={db:null};if(T)for(var X in T)P[X]=typeof T[X]!="string"?T[X].toString():T[X];var Q=new h(function(G,nt){try{P.db=openDatabase(P.name,String(P.version),P.description,P.size)}catch(ut){return nt(ut)}P.db.transaction(function(ut){ma(ut,P,function(){j._dbInfo=P,G()},function(ct,ft){nt(ft)})},nt)});return P.serializer=fs,Q}function si(T,j,P,X,Q,G){T.executeSql(P,X,Q,function(nt,ut){ut.code===ut.SYNTAX_ERR?nt.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[j.storeName],function(ct,ft){ft.rows.length?G(ct,ut):ma(ct,j,function(){ct.executeSql(P,X,Q,G)},G)},G):G(nt,ut)},G)}function ya(T,j){var P=this;T=y(T);var X=new h(function(Q,G){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"SELECT * FROM "+nt.storeName+" WHERE key = ? LIMIT 1",[T],function(ct,ft){var mt=ft.rows.length?ft.rows.item(0).value:null;mt&&(mt=nt.serializer.deserialize(mt)),Q(mt)},function(ct,ft){G(ft)})})}).catch(G)});return p(X,j),X}function In(T,j){var P=this,X=new h(function(Q,G){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"SELECT * FROM "+nt.storeName,[],function(ct,ft){for(var mt=ft.rows,St=mt.length,ne=0;ne0){nt(En.apply(Q,[T,ct,P,X-1]));return}ut(ne)}})})}).catch(ut)});return p(G,P),G}function Hw(T,j,P){return En.apply(this,[T,j,P,1])}function Xw(T,j){var P=this;T=y(T);var X=new h(function(Q,G){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"DELETE FROM "+nt.storeName+" WHERE key = ?",[T],function(){Q()},function(ct,ft){G(ft)})})}).catch(G)});return p(X,j),X}function Yw(T){var j=this,P=new h(function(X,Q){j.ready().then(function(){var G=j._dbInfo;G.db.transaction(function(nt){si(nt,G,"DELETE FROM "+G.storeName,[],function(){X()},function(ut,ct){Q(ct)})})}).catch(Q)});return p(P,T),P}function qw(T){var j=this,P=new h(function(X,Q){j.ready().then(function(){var G=j._dbInfo;G.db.transaction(function(nt){si(nt,G,"SELECT COUNT(key) as c FROM "+G.storeName,[],function(ut,ct){var ft=ct.rows.item(0).c;X(ft)},function(ut,ct){Q(ct)})})}).catch(Q)});return p(P,T),P}function Qw(T,j){var P=this,X=new h(function(Q,G){P.ready().then(function(){var nt=P._dbInfo;nt.db.transaction(function(ut){si(ut,nt,"SELECT key FROM "+nt.storeName+" WHERE id = ? LIMIT 1",[T+1],function(ct,ft){var mt=ft.rows.length?ft.rows.item(0).key:null;Q(mt)},function(ct,ft){G(ft)})})}).catch(G)});return p(X,j),X}function Kw(T){var j=this,P=new h(function(X,Q){j.ready().then(function(){var G=j._dbInfo;G.db.transaction(function(nt){si(nt,G,"SELECT key FROM "+G.storeName,[],function(ut,ct){for(var ft=[],mt=0;mt '__WebKitDatabaseInfoTable__'",[],function(Q,G){for(var nt=[],ut=0;ut0}function nx(T){var j=this,P={};if(T)for(var X in T)P[X]=T[X];return P.keyPrefix=qf(T,j._defaultConfig),ix()?(j._dbInfo=P,P.serializer=fs,h.resolve()):h.reject()}function sx(T){var j=this,P=j.ready().then(function(){for(var X=j._dbInfo.keyPrefix,Q=localStorage.length-1;Q>=0;Q--){var G=localStorage.key(Q);G.indexOf(X)===0&&localStorage.removeItem(G)}});return p(P,T),P}function ox(T,j){var P=this;T=y(T);var X=P.ready().then(function(){var Q=P._dbInfo,G=localStorage.getItem(Q.keyPrefix+T);return G&&(G=Q.serializer.deserialize(G)),G});return p(X,j),X}function ax(T,j){var P=this,X=P.ready().then(function(){for(var Q=P._dbInfo,G=Q.keyPrefix,nt=G.length,ut=localStorage.length,ct=1,ft=0;ft=0;nt--){var ut=localStorage.key(nt);ut.indexOf(G)===0&&localStorage.removeItem(ut)}}):Q=h.reject("Invalid arguments"),p(Q,j),Q}var px={_driver:"localStorageWrapper",_initStorage:nx,_support:ex(),iterate:ax,getItem:ox,setItem:fx,removeItem:hx,clear:sx,length:cx,key:lx,keys:ux,dropInstance:dx},mx=function(j,P){return j===P||typeof j=="number"&&typeof P=="number"&&isNaN(j)&&isNaN(P)},yx=function(j,P){for(var X=j.length,Q=0;Q"u"?"undefined":s(P))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var X in P){if(X==="storeName"&&(P[X]=P[X].replace(/\W/g,"_")),X==="version"&&typeof P[X]!="number")return new Error("Database version must be a number.");this._config[X]=P[X]}return"driver"in P&&P.driver?this.setDriver(this._config.driver):!0}else return typeof P=="string"?this._config[P]:this._config},T.prototype.defineDriver=function(P,X,Q){var G=new h(function(nt,ut){try{var ct=P._driver,ft=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!P._driver){ut(ft);return}for(var mt=fu.concat("_initStorage"),St=0,ne=mt.length;St>2,f=(3&u)<<4|c>>4,y=1>6:64,g=2>4,c=(15&p)<<4|(f=a.indexOf(l.charAt(g++)))>>2,h=(3&f)<<6|(y=a.indexOf(l.charAt(g++))),_[d++]=u,f!==64&&(_[d++]=c),y!==64&&(_[d++]=h);return _}},{"./support":30,"./utils":32}],2:[function(e,i,n){var s=e("./external"),o=e("./stream/DataWorker"),a=e("./stream/Crc32Probe"),l=e("./stream/DataLengthProbe");function u(c,h,p,f,y){this.compressedSize=c,this.uncompressedSize=h,this.crc32=p,this.compression=f,this.compressedContent=y}u.prototype={getContentWorker:function(){var c=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),h=this;return c.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),c},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},u.createWorkerFrom=function(c,h,p){return c.pipe(new a).pipe(new l("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new l("compressedSize")).withStreamInfo("compression",h)},i.exports=u},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,i,n){var s=e("./stream/GenericWorker");n.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},n.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,i,n){var s=e("./utils"),o=function(){for(var a,l=[],u=0;u<256;u++){a=u;for(var c=0;c<8;c++)a=1&a?3988292384^a>>>1:a>>>1;l[u]=a}return l}();i.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(u,c,h,p){var f=o,y=p+h;u^=-1;for(var g=p;g>>8^f[255&(u^c[g])];return-1^u}(0|l,a,a.length,0):function(u,c,h,p){var f=o,y=p+h;u^=-1;for(var g=p;g>>8^f[255&(u^c.charCodeAt(g))];return-1^u}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(e,i,n){n.base64=!1,n.binary=!1,n.dir=!1,n.createFolders=!0,n.date=null,n.compression=null,n.compressionOptions=null,n.comment=null,n.unixPermissions=null,n.dosPermissions=null},{}],6:[function(e,i,n){var s=null;s=typeof Promise<"u"?Promise:e("lie"),i.exports={Promise:s}},{lie:37}],7:[function(e,i,n){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=e("pako"),a=e("./utils"),l=e("./stream/GenericWorker"),u=s?"uint8array":"array";function c(h,p){l.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}n.magic="\b\0",a.inherits(c,l),c.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(u,h.data),!1)},c.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},n.compressWorker=function(h){return new c("Deflate",h)},n.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,i,n){function s(f,y){var g,d="";for(g=0;g>>=8;return d}function o(f,y,g,d,m,_){var S,E,b=f.file,F=f.compression,x=_!==u.utf8encode,z=a.transformTo("string",_(b.name)),B=a.transformTo("string",u.utf8encode(b.name)),tt=b.comment,st=a.transformTo("string",_(tt)),I=a.transformTo("string",u.utf8encode(tt)),Z=B.length!==b.name.length,w=I.length!==tt.length,it="",M="",O="",D=b.dir,U=b.date,k={crc32:0,compressedSize:0,uncompressedSize:0};y&&!g||(k.crc32=f.crc32,k.compressedSize=f.compressedSize,k.uncompressedSize=f.uncompressedSize);var C=0;y&&(C|=8),x||!Z&&!w||(C|=2048);var A=0,$=0;D&&(A|=16),m==="UNIX"?($=798,A|=function(J,yt){var vt=J;return J||(vt=yt?16893:33204),(65535&vt)<<16}(b.unixPermissions,D)):($=20,A|=function(J){return 63&(J||0)}(b.dosPermissions)),S=U.getUTCHours(),S<<=6,S|=U.getUTCMinutes(),S<<=5,S|=U.getUTCSeconds()/2,E=U.getUTCFullYear()-1980,E<<=4,E|=U.getUTCMonth()+1,E<<=5,E|=U.getUTCDate(),Z&&(M=s(1,1)+s(c(z),4)+B,it+="up"+s(M.length,2)+M),w&&(O=s(1,1)+s(c(st),4)+I,it+="uc"+s(O.length,2)+O);var et="";return et+=` -\0`,et+=s(C,2),et+=F.magic,et+=s(S,2),et+=s(E,2),et+=s(k.crc32,4),et+=s(k.compressedSize,4),et+=s(k.uncompressedSize,4),et+=s(z.length,2),et+=s(it.length,2),{fileRecord:h.LOCAL_FILE_HEADER+et+z+it,dirRecord:h.CENTRAL_FILE_HEADER+s($,2)+et+s(st.length,2)+"\0\0\0\0"+s(A,4)+s(d,4)+z+it+st}}var a=e("../utils"),l=e("../stream/GenericWorker"),u=e("../utf8"),c=e("../crc32"),h=e("../signature");function p(f,y,g,d){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=g,this.encodeFileName=d,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(p,l),p.prototype.push=function(f){var y=f.meta.percent||0,g=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,l.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:g?(y+100*(g-d-1))/g:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var y=this.streamFiles&&!f.file.dir;if(y){var g=o(f,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var y=this.streamFiles&&!f.file.dir,g=o(f,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),y)this.push({data:function(d){return h.DATA_DESCRIPTOR+s(d.crc32,4)+s(d.compressedSize,4)+s(d.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,y=0;y=this.index;l--)u=(u<<8)+this.byteAt(l);return this.index+=a,u},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},i.exports=o},{"../utils":32}],19:[function(e,i,n){var s=e("./Uint8ArrayReader");function o(a){s.call(this,a)}e("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,i,n){var s=e("./DataReader");function o(a){s.call(this,a)}e("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./DataReader":18}],21:[function(e,i,n){var s=e("./ArrayReader");function o(a){s.call(this,a)}e("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(e,i,n){var s=e("../utils"),o=e("../support"),a=e("./ArrayReader"),l=e("./StringReader"),u=e("./NodeBufferReader"),c=e("./Uint8ArrayReader");i.exports=function(h){var p=s.getTypeOf(h);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new u(h):o.uint8array?new c(s.transformTo("uint8array",h)):new a(s.transformTo("array",h)):new l(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,i,n){n.LOCAL_FILE_HEADER="PK",n.CENTRAL_FILE_HEADER="PK",n.CENTRAL_DIRECTORY_END="PK",n.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",n.ZIP64_CENTRAL_DIRECTORY_END="PK",n.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(e,i,n){var s=e("./GenericWorker"),o=e("../utils");function a(l){s.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,s),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},i.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(e,i,n){var s=e("./GenericWorker"),o=e("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(a,s),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},i.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,i,n){var s=e("../utils"),o=e("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}s.inherits(a,o),a.prototype.processChunk=function(l){if(l){var u=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=u+l.data.length}o.prototype.processChunk.call(this,l)},i.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(e,i,n){var s=e("../utils"),o=e("./GenericWorker");function a(l){o.call(this,"DataWorker");var u=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(c){u.dataIsReady=!0,u.data=c,u.max=c&&c.length||0,u.type=s.getTypeOf(c),u.isPaused||u._tickAndRepeat()},function(c){u.error(c)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,u=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,u);break;case"uint8array":l=this.data.subarray(this.index,u);break;case"array":case"nodebuffer":l=this.data.slice(this.index,u)}return this.index=u,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(e,i,n){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},i.exports=s},{}],29:[function(e,i,n){var s=e("../utils"),o=e("./ConvertWorker"),a=e("./GenericWorker"),l=e("../base64"),u=e("../support"),c=e("../external"),h=null;if(u.nodestream)try{h=e("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(y,g){return new c.Promise(function(d,m){var _=[],S=y._internalType,E=y._outputType,b=y._mimeType;y.on("data",function(F,x){_.push(F),g&&g(x)}).on("error",function(F){_=[],m(F)}).on("end",function(){try{var F=function(x,z,B){switch(x){case"blob":return s.newBlob(s.transformTo("arraybuffer",z),B);case"base64":return l.encode(z);default:return s.transformTo(x,z)}}(E,function(x,z){var B,tt=0,st=null,I=0;for(B=0;B"u")n.blob=!1;else{var s=new ArrayBuffer(0);try{n.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),n.blob=o.getBlob("application/zip").size===0}catch{n.blob=!1}}}try{n.nodestream=!!e("readable-stream").Readable}catch{n.nodestream=!1}},{"readable-stream":16}],31:[function(e,i,n){for(var s=e("./utils"),o=e("./support"),a=e("./nodejsUtils"),l=e("./stream/GenericWorker"),u=new Array(256),c=0;c<256;c++)u[c]=252<=c?6:248<=c?5:240<=c?4:224<=c?3:192<=c?2:1;u[254]=u[254]=1;function h(){l.call(this,"utf-8 decode"),this.leftOver=null}function p(){l.call(this,"utf-8 encode")}n.utf8encode=function(f){return o.nodebuffer?a.newBufferFrom(f,"utf-8"):function(y){var g,d,m,_,S,E=y.length,b=0;for(_=0;_>>6:(d<65536?g[S++]=224|d>>>12:(g[S++]=240|d>>>18,g[S++]=128|d>>>12&63),g[S++]=128|d>>>6&63),g[S++]=128|63&d);return g}(f)},n.utf8decode=function(f){return o.nodebuffer?s.transformTo("nodebuffer",f).toString("utf-8"):function(y){var g,d,m,_,S=y.length,E=new Array(2*S);for(g=d=0;g>10&1023,E[d++]=56320|1023&m)}return E.length!==d&&(E.subarray?E=E.subarray(0,d):E.length=d),s.applyFromCharCode(E)}(f=s.transformTo(o.uint8array?"uint8array":"array",f))},s.inherits(h,l),h.prototype.processChunk=function(f){var y=s.transformTo(o.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var g=y;(y=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),y.set(g,this.leftOver.length)}else y=this.leftOver.concat(y);this.leftOver=null}var d=function(_,S){var E;for((S=S||_.length)>_.length&&(S=_.length),E=S-1;0<=E&&(192&_[E])==128;)E--;return E<0||E===0?S:E+u[_[E]]>S?E:S}(y),m=y;d!==y.length&&(o.uint8array?(m=y.subarray(0,d),this.leftOver=y.subarray(d,y.length)):(m=y.slice(0,d),this.leftOver=y.slice(d,y.length))),this.push({data:n.utf8decode(m),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:n.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},n.Utf8DecodeWorker=h,s.inherits(p,l),p.prototype.processChunk=function(f){this.push({data:n.utf8encode(f.data),meta:f.meta})},n.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,i,n){var s=e("./support"),o=e("./base64"),a=e("./nodejsUtils"),l=e("./external");function u(g){return g}function c(g,d){for(var m=0;m>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var y,g,d,m=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?p[d++]=224|f>>>12:(p[d++]=240|f>>>18,p[d++]=128|f>>>12&63),p[d++]=128|f>>>6&63),p[d++]=128|63&f);return p},n.buf2binstring=function(h){return c(h,h.length)},n.binstring2buf=function(h){for(var p=new s.Buf8(h.length),f=0,y=p.length;f>10&1023,_[y++]=56320|1023&g)}return c(_,y)},n.utf8border=function(h,p){var f;for((p=p||h.length)>h.length&&(p=h.length),f=p-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?p:f+l[h[f]]>p?f:p}},{"./common":41}],43:[function(e,i,n){i.exports=function(s,o,a,l){for(var u=65535&s|0,c=s>>>16&65535|0,h=0;a!==0;){for(a-=h=2e3>>1:o>>>1;a[l]=o}return a}();i.exports=function(o,a,l,u){var c=s,h=u+l;o^=-1;for(var p=u;p>>8^c[255&(o^a[p])];return-1^o}},{}],46:[function(e,i,n){var s,o=e("../utils/common"),a=e("./trees"),l=e("./adler32"),u=e("./crc32"),c=e("./messages"),h=0,p=4,f=0,y=-2,g=-1,d=4,m=2,_=8,S=9,E=286,b=30,F=19,x=2*E+1,z=15,B=3,tt=258,st=tt+B+1,I=42,Z=113,w=1,it=2,M=3,O=4;function D(v,K){return v.msg=c[K],K}function U(v){return(v<<1)-(4v.avail_out&&(q=v.avail_out),q!==0&&(o.arraySet(v.output,K.pending_buf,K.pending_out,q,v.next_out),v.next_out+=q,K.pending_out+=q,v.total_out+=q,v.avail_out-=q,K.pending-=q,K.pending===0&&(K.pending_out=0))}function A(v,K){a._tr_flush_block(v,0<=v.block_start?v.block_start:-1,v.strstart-v.block_start,K),v.block_start=v.strstart,C(v.strm)}function $(v,K){v.pending_buf[v.pending++]=K}function et(v,K){v.pending_buf[v.pending++]=K>>>8&255,v.pending_buf[v.pending++]=255&K}function J(v,K){var q,N,R=v.max_chain_length,Y=v.strstart,ot=v.prev_length,at=v.nice_match,rt=v.strstart>v.w_size-st?v.strstart-(v.w_size-st):0,ht=v.window,bt=v.w_mask,pt=v.prev,Ot=v.strstart+tt,ye=ht[Y+ot-1],oe=ht[Y+ot];v.prev_length>=v.good_match&&(R>>=2),at>v.lookahead&&(at=v.lookahead);do if(ht[(q=K)+ot]===oe&&ht[q+ot-1]===ye&&ht[q]===ht[Y]&&ht[++q]===ht[Y+1]){Y+=2,q++;do;while(ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&Yrt&&--R!=0);return ot<=v.lookahead?ot:v.lookahead}function yt(v){var K,q,N,R,Y,ot,at,rt,ht,bt,pt=v.w_size;do{if(R=v.window_size-v.lookahead-v.strstart,v.strstart>=pt+(pt-st)){for(o.arraySet(v.window,v.window,pt,pt,0),v.match_start-=pt,v.strstart-=pt,v.block_start-=pt,K=q=v.hash_size;N=v.head[--K],v.head[K]=pt<=N?N-pt:0,--q;);for(K=q=pt;N=v.prev[--K],v.prev[K]=pt<=N?N-pt:0,--q;);R+=pt}if(v.strm.avail_in===0)break;if(ot=v.strm,at=v.window,rt=v.strstart+v.lookahead,ht=R,bt=void 0,bt=ot.avail_in,ht=B)for(Y=v.strstart-v.insert,v.ins_h=v.window[Y],v.ins_h=(v.ins_h<=B&&(v.ins_h=(v.ins_h<=B)if(N=a._tr_tally(v,v.strstart-v.match_start,v.match_length-B),v.lookahead-=v.match_length,v.match_length<=v.max_lazy_match&&v.lookahead>=B){for(v.match_length--;v.strstart++,v.ins_h=(v.ins_h<=B&&(v.ins_h=(v.ins_h<=B&&v.match_length<=v.prev_length){for(R=v.strstart+v.lookahead-B,N=a._tr_tally(v,v.strstart-1-v.prev_match,v.prev_length-B),v.lookahead-=v.prev_length-1,v.prev_length-=2;++v.strstart<=R&&(v.ins_h=(v.ins_h<v.pending_buf_size-5&&(q=v.pending_buf_size-5);;){if(v.lookahead<=1){if(yt(v),v.lookahead===0&&K===h)return w;if(v.lookahead===0)break}v.strstart+=v.lookahead,v.lookahead=0;var N=v.block_start+q;if((v.strstart===0||v.strstart>=N)&&(v.lookahead=v.strstart-N,v.strstart=N,A(v,!1),v.strm.avail_out===0)||v.strstart-v.block_start>=v.w_size-st&&(A(v,!1),v.strm.avail_out===0))return w}return v.insert=0,K===p?(A(v,!0),v.strm.avail_out===0?M:O):(v.strstart>v.block_start&&(A(v,!1),v.strm.avail_out),w)}),new _t(4,4,8,4,vt),new _t(4,5,16,8,vt),new _t(4,6,32,32,vt),new _t(4,4,16,16,dt),new _t(8,16,32,32,dt),new _t(8,16,128,128,dt),new _t(8,32,128,256,dt),new _t(32,128,258,1024,dt),new _t(32,258,258,4096,dt)],n.deflateInit=function(v,K){return he(v,K,_,15,8,0)},n.deflateInit2=he,n.deflateReset=ee,n.deflateResetKeep=Ct,n.deflateSetHeader=function(v,K){return v&&v.state?v.state.wrap!==2?y:(v.state.gzhead=K,f):y},n.deflate=function(v,K){var q,N,R,Y;if(!v||!v.state||5>8&255),$(N,N.gzhead.time>>16&255),$(N,N.gzhead.time>>24&255),$(N,N.level===9?2:2<=N.strategy||N.level<2?4:0),$(N,255&N.gzhead.os),N.gzhead.extra&&N.gzhead.extra.length&&($(N,255&N.gzhead.extra.length),$(N,N.gzhead.extra.length>>8&255)),N.gzhead.hcrc&&(v.adler=u(v.adler,N.pending_buf,N.pending,0)),N.gzindex=0,N.status=69):($(N,0),$(N,0),$(N,0),$(N,0),$(N,0),$(N,N.level===9?2:2<=N.strategy||N.level<2?4:0),$(N,3),N.status=Z);else{var ot=_+(N.w_bits-8<<4)<<8;ot|=(2<=N.strategy||N.level<2?0:N.level<6?1:N.level===6?2:3)<<6,N.strstart!==0&&(ot|=32),ot+=31-ot%31,N.status=Z,et(N,ot),N.strstart!==0&&(et(N,v.adler>>>16),et(N,65535&v.adler)),v.adler=1}if(N.status===69)if(N.gzhead.extra){for(R=N.pending;N.gzindex<(65535&N.gzhead.extra.length)&&(N.pending!==N.pending_buf_size||(N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),C(v),R=N.pending,N.pending!==N.pending_buf_size));)$(N,255&N.gzhead.extra[N.gzindex]),N.gzindex++;N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),N.gzindex===N.gzhead.extra.length&&(N.gzindex=0,N.status=73)}else N.status=73;if(N.status===73)if(N.gzhead.name){R=N.pending;do{if(N.pending===N.pending_buf_size&&(N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),C(v),R=N.pending,N.pending===N.pending_buf_size)){Y=1;break}Y=N.gzindexR&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),Y===0&&(N.gzindex=0,N.status=91)}else N.status=91;if(N.status===91)if(N.gzhead.comment){R=N.pending;do{if(N.pending===N.pending_buf_size&&(N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),C(v),R=N.pending,N.pending===N.pending_buf_size)){Y=1;break}Y=N.gzindexR&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),Y===0&&(N.status=103)}else N.status=103;if(N.status===103&&(N.gzhead.hcrc?(N.pending+2>N.pending_buf_size&&C(v),N.pending+2<=N.pending_buf_size&&($(N,255&v.adler),$(N,v.adler>>8&255),v.adler=0,N.status=Z)):N.status=Z),N.pending!==0){if(C(v),v.avail_out===0)return N.last_flush=-1,f}else if(v.avail_in===0&&U(K)<=U(q)&&K!==p)return D(v,-5);if(N.status===666&&v.avail_in!==0)return D(v,-5);if(v.avail_in!==0||N.lookahead!==0||K!==h&&N.status!==666){var at=N.strategy===2?function(rt,ht){for(var bt;;){if(rt.lookahead===0&&(yt(rt),rt.lookahead===0)){if(ht===h)return w;break}if(rt.match_length=0,bt=a._tr_tally(rt,0,rt.window[rt.strstart]),rt.lookahead--,rt.strstart++,bt&&(A(rt,!1),rt.strm.avail_out===0))return w}return rt.insert=0,ht===p?(A(rt,!0),rt.strm.avail_out===0?M:O):rt.last_lit&&(A(rt,!1),rt.strm.avail_out===0)?w:it}(N,K):N.strategy===3?function(rt,ht){for(var bt,pt,Ot,ye,oe=rt.window;;){if(rt.lookahead<=tt){if(yt(rt),rt.lookahead<=tt&&ht===h)return w;if(rt.lookahead===0)break}if(rt.match_length=0,rt.lookahead>=B&&0rt.lookahead&&(rt.match_length=rt.lookahead)}if(rt.match_length>=B?(bt=a._tr_tally(rt,1,rt.match_length-B),rt.lookahead-=rt.match_length,rt.strstart+=rt.match_length,rt.match_length=0):(bt=a._tr_tally(rt,0,rt.window[rt.strstart]),rt.lookahead--,rt.strstart++),bt&&(A(rt,!1),rt.strm.avail_out===0))return w}return rt.insert=0,ht===p?(A(rt,!0),rt.strm.avail_out===0?M:O):rt.last_lit&&(A(rt,!1),rt.strm.avail_out===0)?w:it}(N,K):s[N.level].func(N,K);if(at!==M&&at!==O||(N.status=666),at===w||at===M)return v.avail_out===0&&(N.last_flush=-1),f;if(at===it&&(K===1?a._tr_align(N):K!==5&&(a._tr_stored_block(N,0,0,!1),K===3&&(k(N.head),N.lookahead===0&&(N.strstart=0,N.block_start=0,N.insert=0))),C(v),v.avail_out===0))return N.last_flush=-1,f}return K!==p?f:N.wrap<=0?1:(N.wrap===2?($(N,255&v.adler),$(N,v.adler>>8&255),$(N,v.adler>>16&255),$(N,v.adler>>24&255),$(N,255&v.total_in),$(N,v.total_in>>8&255),$(N,v.total_in>>16&255),$(N,v.total_in>>24&255)):(et(N,v.adler>>>16),et(N,65535&v.adler)),C(v),0=q.w_size&&(Y===0&&(k(q.head),q.strstart=0,q.block_start=0,q.insert=0),ht=new o.Buf8(q.w_size),o.arraySet(ht,K,bt-q.w_size,q.w_size,0),K=ht,bt=q.w_size),ot=v.avail_in,at=v.next_in,rt=v.input,v.avail_in=bt,v.next_in=0,v.input=K,yt(q);q.lookahead>=B;){for(N=q.strstart,R=q.lookahead-(B-1);q.ins_h=(q.ins_h<>>=B=z>>>24,S-=B,(B=z>>>16&255)===0)it[c++]=65535&z;else{if(!(16&B)){if((64&B)==0){z=E[(65535&z)+(_&(1<>>=B,S-=B),S<15&&(_+=w[l++]<>>=B=z>>>24,S-=B,!(16&(B=z>>>16&255))){if((64&B)==0){z=b[(65535&z)+(_&(1<>>=B,S-=B,(B=c-h)>3,_&=(1<<(S-=tt<<3))-1,s.next_in=l,s.next_out=c,s.avail_in=l>>24&255)+(I>>>8&65280)+((65280&I)<<8)+((255&I)<<24)}function _(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function S(I){var Z;return I&&I.state?(Z=I.state,I.total_in=I.total_out=Z.total=0,I.msg="",Z.wrap&&(I.adler=1&Z.wrap),Z.mode=y,Z.last=0,Z.havedict=0,Z.dmax=32768,Z.head=null,Z.hold=0,Z.bits=0,Z.lencode=Z.lendyn=new s.Buf32(g),Z.distcode=Z.distdyn=new s.Buf32(d),Z.sane=1,Z.back=-1,p):f}function E(I){var Z;return I&&I.state?((Z=I.state).wsize=0,Z.whave=0,Z.wnext=0,S(I)):f}function b(I,Z){var w,it;return I&&I.state?(it=I.state,Z<0?(w=0,Z=-Z):(w=1+(Z>>4),Z<48&&(Z&=15)),Z&&(Z<8||15=O.wsize?(s.arraySet(O.window,Z,w-O.wsize,O.wsize,0),O.wnext=0,O.whave=O.wsize):(it<(M=O.wsize-O.wnext)&&(M=it),s.arraySet(O.window,Z,w-it,M,O.wnext),(it-=M)?(s.arraySet(O.window,Z,w-it,it,0),O.wnext=it,O.whave=O.wsize):(O.wnext+=M,O.wnext===O.wsize&&(O.wnext=0),O.whave>>8&255,w.check=a(w.check,Y,2,0),A=C=0,w.mode=2;break}if(w.flags=0,w.head&&(w.head.done=!1),!(1&w.wrap)||(((255&C)<<8)+(C>>8))%31){I.msg="incorrect header check",w.mode=30;break}if((15&C)!=8){I.msg="unknown compression method",w.mode=30;break}if(A-=4,v=8+(15&(C>>>=4)),w.wbits===0)w.wbits=v;else if(v>w.wbits){I.msg="invalid window size",w.mode=30;break}w.dmax=1<>8&1),512&w.flags&&(Y[0]=255&C,Y[1]=C>>>8&255,w.check=a(w.check,Y,2,0)),A=C=0,w.mode=3;case 3:for(;A<32;){if(U===0)break t;U--,C+=it[O++]<>>8&255,Y[2]=C>>>16&255,Y[3]=C>>>24&255,w.check=a(w.check,Y,4,0)),A=C=0,w.mode=4;case 4:for(;A<16;){if(U===0)break t;U--,C+=it[O++]<>8),512&w.flags&&(Y[0]=255&C,Y[1]=C>>>8&255,w.check=a(w.check,Y,2,0)),A=C=0,w.mode=5;case 5:if(1024&w.flags){for(;A<16;){if(U===0)break t;U--,C+=it[O++]<>>8&255,w.check=a(w.check,Y,2,0)),A=C=0}else w.head&&(w.head.extra=null);w.mode=6;case 6:if(1024&w.flags&&(U<(J=w.length)&&(J=U),J&&(w.head&&(v=w.head.extra_len-w.length,w.head.extra||(w.head.extra=new Array(w.head.extra_len)),s.arraySet(w.head.extra,it,O,J,v)),512&w.flags&&(w.check=a(w.check,it,J,O)),U-=J,O+=J,w.length-=J),w.length))break t;w.length=0,w.mode=7;case 7:if(2048&w.flags){if(U===0)break t;for(J=0;v=it[O+J++],w.head&&v&&w.length<65536&&(w.head.name+=String.fromCharCode(v)),v&&J>9&1,w.head.done=!0),I.adler=w.check=0,w.mode=12;break;case 10:for(;A<32;){if(U===0)break t;U--,C+=it[O++]<>>=7&A,A-=7&A,w.mode=27;break}for(;A<3;){if(U===0)break t;U--,C+=it[O++]<>>=1)){case 0:w.mode=14;break;case 1:if(tt(w),w.mode=20,Z!==6)break;C>>>=2,A-=2;break t;case 2:w.mode=17;break;case 3:I.msg="invalid block type",w.mode=30}C>>>=2,A-=2;break;case 14:for(C>>>=7&A,A-=7&A;A<32;){if(U===0)break t;U--,C+=it[O++]<>>16^65535)){I.msg="invalid stored block lengths",w.mode=30;break}if(w.length=65535&C,A=C=0,w.mode=15,Z===6)break t;case 15:w.mode=16;case 16:if(J=w.length){if(U>>=5,A-=5,w.ndist=1+(31&C),C>>>=5,A-=5,w.ncode=4+(15&C),C>>>=4,A-=4,286>>=3,A-=3}for(;w.have<19;)w.lens[ot[w.have++]]=0;if(w.lencode=w.lendyn,w.lenbits=7,q={bits:w.lenbits},K=u(0,w.lens,0,19,w.lencode,0,w.work,q),w.lenbits=q.bits,K){I.msg="invalid code lengths set",w.mode=30;break}w.have=0,w.mode=19;case 19:for(;w.have>>16&255,gt=65535&R,!((dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>>=dt,A-=dt,w.lens[w.have++]=gt;else{if(gt===16){for(N=dt+2;A>>=dt,A-=dt,w.have===0){I.msg="invalid bit length repeat",w.mode=30;break}v=w.lens[w.have-1],J=3+(3&C),C>>>=2,A-=2}else if(gt===17){for(N=dt+3;A>>=dt)),C>>>=3,A-=3}else{for(N=dt+7;A>>=dt)),C>>>=7,A-=7}if(w.have+J>w.nlen+w.ndist){I.msg="invalid bit length repeat",w.mode=30;break}for(;J--;)w.lens[w.have++]=v}}if(w.mode===30)break;if(w.lens[256]===0){I.msg="invalid code -- missing end-of-block",w.mode=30;break}if(w.lenbits=9,q={bits:w.lenbits},K=u(c,w.lens,0,w.nlen,w.lencode,0,w.work,q),w.lenbits=q.bits,K){I.msg="invalid literal/lengths set",w.mode=30;break}if(w.distbits=6,w.distcode=w.distdyn,q={bits:w.distbits},K=u(h,w.lens,w.nlen,w.ndist,w.distcode,0,w.work,q),w.distbits=q.bits,K){I.msg="invalid distances set",w.mode=30;break}if(w.mode=20,Z===6)break t;case 20:w.mode=21;case 21:if(6<=U&&258<=k){I.next_out=D,I.avail_out=k,I.next_in=O,I.avail_in=U,w.hold=C,w.bits=A,l(I,et),D=I.next_out,M=I.output,k=I.avail_out,O=I.next_in,it=I.input,U=I.avail_in,C=w.hold,A=w.bits,w.mode===12&&(w.back=-1);break}for(w.back=0;_t=(R=w.lencode[C&(1<>>16&255,gt=65535&R,!((dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>Ct)])>>>16&255,gt=65535&R,!(Ct+(dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>>=Ct,A-=Ct,w.back+=Ct}if(C>>>=dt,A-=dt,w.back+=dt,w.length=gt,_t===0){w.mode=26;break}if(32&_t){w.back=-1,w.mode=12;break}if(64&_t){I.msg="invalid literal/length code",w.mode=30;break}w.extra=15&_t,w.mode=22;case 22:if(w.extra){for(N=w.extra;A>>=w.extra,A-=w.extra,w.back+=w.extra}w.was=w.length,w.mode=23;case 23:for(;_t=(R=w.distcode[C&(1<>>16&255,gt=65535&R,!((dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>Ct)])>>>16&255,gt=65535&R,!(Ct+(dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>>=Ct,A-=Ct,w.back+=Ct}if(C>>>=dt,A-=dt,w.back+=dt,64&_t){I.msg="invalid distance code",w.mode=30;break}w.offset=gt,w.extra=15&_t,w.mode=24;case 24:if(w.extra){for(N=w.extra;A>>=w.extra,A-=w.extra,w.back+=w.extra}if(w.offset>w.dmax){I.msg="invalid distance too far back",w.mode=30;break}w.mode=25;case 25:if(k===0)break t;if(J=et-k,w.offset>J){if((J=w.offset-J)>w.whave&&w.sane){I.msg="invalid distance too far back",w.mode=30;break}yt=J>w.wnext?(J-=w.wnext,w.wsize-J):w.wnext-J,J>w.length&&(J=w.length),vt=w.window}else vt=M,yt=D-w.offset,J=w.length;for(kx?(B=yt[vt+d[Z]],A[$+d[Z]]):(B=96,0),_=1<>D)+(S-=_)]=z<<24|B<<16|tt|0,S!==0;);for(_=1<>=1;if(_!==0?(C&=_-1,C+=_):C=0,Z++,--et[I]==0){if(I===it)break;I=h[p+d[Z]]}if(M>>7)]}function $(R,Y){R.pending_buf[R.pending++]=255&Y,R.pending_buf[R.pending++]=Y>>>8&255}function et(R,Y,ot){R.bi_valid>m-ot?(R.bi_buf|=Y<>m-R.bi_valid,R.bi_valid+=ot-m):(R.bi_buf|=Y<>>=1,ot<<=1,0<--Y;);return ot>>>1}function vt(R,Y,ot){var at,rt,ht=new Array(d+1),bt=0;for(at=1;at<=d;at++)ht[at]=bt=bt+ot[at-1]<<1;for(rt=0;rt<=Y;rt++){var pt=R[2*rt+1];pt!==0&&(R[2*rt]=yt(ht[pt]++,pt))}}function dt(R){var Y;for(Y=0;Y>1;1<=ot;ot--)Ct(R,ht,ot);for(rt=Ot;ot=R.heap[1],R.heap[1]=R.heap[R.heap_len--],Ct(R,ht,1),at=R.heap[1],R.heap[--R.heap_max]=ot,R.heap[--R.heap_max]=at,ht[2*rt]=ht[2*ot]+ht[2*at],R.depth[rt]=(R.depth[ot]>=R.depth[at]?R.depth[ot]:R.depth[at])+1,ht[2*ot+1]=ht[2*at+1]=rt,R.heap[1]=rt++,Ct(R,ht,1),2<=R.heap_len;);R.heap[--R.heap_max]=R.heap[1],function(oe,ir){var Ki,vr,Zi,Ae,Ji,ao,Qr=ir.dyn_tree,fs=ir.max_code,ma=ir.stat_desc.static_tree,hu=ir.stat_desc.has_stree,si=ir.stat_desc.extra_bits,ya=ir.stat_desc.extra_base,In=ir.stat_desc.max_length,En=0;for(Ae=0;Ae<=d;Ae++)oe.bl_count[Ae]=0;for(Qr[2*oe.heap[oe.heap_max]+1]=0,Ki=oe.heap_max+1;Ki>=7;rt>>=1)if(1&ye&&pt.dyn_ltree[2*Ot]!==0)return o;if(pt.dyn_ltree[18]!==0||pt.dyn_ltree[20]!==0||pt.dyn_ltree[26]!==0)return a;for(Ot=32;Ot>>3,(ht=R.static_len+3+7>>>3)<=rt&&(rt=ht)):rt=ht=ot+5,ot+4<=rt&&Y!==-1?N(R,Y,ot,at):R.strategy===4||ht===rt?(et(R,2+(at?1:0),3),ee(R,st,I)):(et(R,4+(at?1:0),3),function(pt,Ot,ye,oe){var ir;for(et(pt,Ot-257,5),et(pt,ye-1,5),et(pt,oe-4,4),ir=0;ir>>8&255,R.pending_buf[R.d_buf+2*R.last_lit+1]=255&Y,R.pending_buf[R.l_buf+R.last_lit]=255&ot,R.last_lit++,Y===0?R.dyn_ltree[2*ot]++:(R.matches++,Y--,R.dyn_ltree[2*(w[ot]+h+1)]++,R.dyn_dtree[2*A(Y)]++),R.last_lit===R.lit_bufsize-1},n._tr_align=function(R){et(R,2,3),J(R,S,st),function(Y){Y.bi_valid===16?($(Y,Y.bi_buf),Y.bi_buf=0,Y.bi_valid=0):8<=Y.bi_valid&&(Y.pending_buf[Y.pending++]=255&Y.bi_buf,Y.bi_buf>>=8,Y.bi_valid-=8)}(R)}},{"../utils/common":41}],53:[function(e,i,n){i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,i,n){(function(s){(function(o,a){if(!o.setImmediate){var l,u,c,h,p=1,f={},y=!1,g=o.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(o);d=d&&d.setTimeout?d:o,l={}.toString.call(o.process)==="[object process]"?function(E){process.nextTick(function(){_(E)})}:function(){if(o.postMessage&&!o.importScripts){var E=!0,b=o.onmessage;return o.onmessage=function(){E=!1},o.postMessage("","*"),o.onmessage=b,E}}()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",S,!1):o.attachEvent("onmessage",S),function(E){o.postMessage(h+E,"*")}):o.MessageChannel?((c=new MessageChannel).port1.onmessage=function(E){_(E.data)},function(E){c.port2.postMessage(E)}):g&&"onreadystatechange"in g.createElement("script")?(u=g.documentElement,function(E){var b=g.createElement("script");b.onreadystatechange=function(){_(E),b.onreadystatechange=null,u.removeChild(b),b=null},u.appendChild(b)}):function(E){setTimeout(_,0,E)},d.setImmediate=function(E){typeof E!="function"&&(E=new Function(""+E));for(var b=new Array(arguments.length-1),F=0;F"u"?s===void 0?this:s:self)}).call(this,typeof gi<"u"?gi:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})}(Gu)),Gu.exports}var dC=fC();const pC=Nh(dC);Ai.zipReader=(r,t)=>pC.loadAsync(r);const mC=Ai.createSettings;Ai.createSettings=async r=>{const t=Object.keys(r.files);return t.find(e=>yC(e))?mC(r):_C(t)};function yC(r){return r.endsWith("model3.json")}function gC(r){return r.endsWith(".moc3")}function vC(r){return r.split(/[\\/]/).pop()}function _C(r){const t=r.filter(u=>gC(u));if(t.length!==1){const u=t.length?`(${t.map(c=>`"${c}"`).join(",")})`:"";throw new Error(`Expected exactly one moc file, got ${t.length} ${u}`)}const e=t[0],i=vC(e).replace(/\.moc3?/,""),n=r.filter(u=>u.endsWith(".png"));if(!n.length)throw new Error("Textures not found");const s=r.filter(u=>u.endsWith(".mtn")||u.endsWith(".motion3.json")),o=r.find(u=>u.includes("physics")),a=r.find(u=>u.includes("pose")),l=new Jn({url:`${i}.model3.json`,Version:3,FileReferences:{Moc:e,Textures:n,Physics:o,Pose:a,Motions:s.length?{"":s.map(u=>({File:u}))}:void 0}});return l.name=i,l._objectURL=`example://${l.url}`,l}Ai.readText=(r,t)=>{const e=r.file(t);if(!e)throw new Error(`Cannot find file: ${t}`);return e.async("text")};Ai.getFilePaths=r=>{const t=[];return r.forEach(e=>t.push(e)),Promise.resolve(t)};Ai.getFiles=(r,t)=>Promise.all(t.map(async e=>{const i=e.slice(e.lastIndexOf("/")+1),n=await r.file(e).async("blob");return new File([n],i)}));function Zt(r,t,e,i){function n(s){return s instanceof e?s:new e(function(o){o(s)})}return new(e||(e=Promise))(function(s,o){function a(c){try{u(i.next(c))}catch(h){o(h)}}function l(c){try{u(i.throw(c))}catch(h){o(h)}}function u(c){c.done?s(c.value):n(c.value).then(a,l)}u((i=i.apply(r,t||[])).next())})}function up(r){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&r[t],i=0;if(e)return e.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Pt(r){return this instanceof Pt?(this.v=r,this):new Pt(r)}function dr(r,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=e.apply(r,t||[]),n,s=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(f){return function(y){return Promise.resolve(y).then(f,h)}}function a(f,y){i[f]&&(n[f]=function(g){return new Promise(function(d,m){s.push([f,g,d,m])>1||l(f,g)})},y&&(n[f]=y(n[f])))}function l(f,y){try{u(i[f](y))}catch(g){p(s[0][3],g)}}function u(f){f.value instanceof Pt?Promise.resolve(f.value.v).then(c,h):p(s[0][2],f)}function c(f){l("next",f)}function h(f){l("throw",f)}function p(f,y){f(y),s.shift(),s.length&&l(s[0][0],s[0][1])}}function ts(r){var t,e;return t={},i("next"),i("throw",function(n){throw n}),i("return"),t[Symbol.iterator]=function(){return this},t;function i(n,s){t[n]=r[n]?function(o){return(e=!e)?{value:Pt(r[n](o)),done:!1}:s?s(o):o}:s}}function bi(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 up=="function"?up(r):r[Symbol.iterator](),e={},i("next"),i("throw"),i("return"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=r[s]&&function(o){return new Promise(function(a,l){o=r[s](o),n(a,l,o.done,o.value)})}}function n(s,o,a,l){Promise.resolve(l).then(function(u){s({value:u,done:a})},o)}}const bC=new TextDecoder("utf-8"),eh=r=>bC.decode(r),wC=new TextEncoder,ef=r=>wC.encode(r),xC=r=>typeof r=="number",_v=r=>typeof r=="boolean",Ge=r=>typeof r=="function",pr=r=>r!=null&&Object(r)===r,rs=r=>pr(r)&&Ge(r.then),oa=r=>pr(r)&&Ge(r[Symbol.iterator]),no=r=>pr(r)&&Ge(r[Symbol.asyncIterator]),rh=r=>pr(r)&&pr(r.schema),bv=r=>pr(r)&&"done"in r&&"value"in r,wv=r=>pr(r)&&Ge(r.stat)&&xC(r.fd),xv=r=>pr(r)&&rf(r.body),tu=r=>"_getDOMStream"in r&&"_getNodeStream"in r,SC=r=>pr(r)&&Ge(r.abort)&&Ge(r.getWriter)&&!tu(r),rf=r=>pr(r)&&Ge(r.cancel)&&Ge(r.getReader)&&!tu(r),TC=r=>pr(r)&&Ge(r.end)&&Ge(r.write)&&_v(r.writable)&&!tu(r),Sv=r=>pr(r)&&Ge(r.read)&&Ge(r.pipe)&&_v(r.readable)&&!tu(r),IC=r=>pr(r)&&Ge(r.clear)&&Ge(r.bytes)&&Ge(r.position)&&Ge(r.setPosition)&&Ge(r.capacity)&&Ge(r.getBufferIdentifier)&&Ge(r.createLong),nf=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function EC(r){const t=r[0]?[r[0]]:[];let e,i,n,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let n,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,i);for(const c=e.length;++l_e(Int32Array,r),hp=r=>_e(BigInt64Array,r),ae=r=>_e(Uint8Array,r),ih=r=>(r.next(),r);function*CC(r,t){const e=function*(n){yield n},i=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof nf?e(t):oa(t)?t:e(t);return yield*ih(function*(n){let s=null;do s=n.next(yield _e(r,s));while(!s.done)}(i[Symbol.iterator]())),new r}const AC=r=>CC(Uint8Array,r);function Tv(r,t){return dr(this,arguments,function*(){if(rs(t))return yield Pt(yield Pt(yield*ts(bi(Tv(r,yield Pt(t))))));const i=function(o){return dr(this,arguments,function*(){yield yield Pt(yield Pt(o))})},n=function(o){return dr(this,arguments,function*(){yield Pt(yield*ts(bi(ih(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 nf?i(t):oa(t)?n(t):no(t)?t:i(t);return yield Pt(yield*ts(bi(ih(function(o){return dr(this,arguments,function*(){let a=null;do a=yield Pt(o.next(yield yield Pt(_e(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Pt(new r)})}const OC=r=>Tv(Uint8Array,r);function Iv(r,t,e){if(r!==0){e=e.slice(0,t);for(let i=-1,n=e.length;++i0)do if(r[e]!==t[e])return!1;while(++e(r.next(),r);function*PC(r){let t,e=!1,i=[],n,s,o,a=0;function l(){return s==="peek"?xi(i,o)[0]:([n,i,a]=xi(i,o),n)}({cmd:s,size:o}=(yield null)||{cmd:"read",size:0});const u=AC(r)[Symbol.iterator]();try{do if({done:t,value:n}=Number.isNaN(o-a)?u.next():u.next(o-a),!t&&n.byteLength>0&&(i.push(n),a+=n.byteLength),t||o<=a)do({cmd:s,size:o}=yield l());while(o0&&(n.push(s),l+=s.byteLength),e||a<=l)do({cmd:o,size:a}=yield yield Pt(u()));while(a0&&(n.push(ae(s)),l+=s.byteLength),e||a<=l)do({cmd:o,size:a}=yield yield Pt(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 Zt(this,void 0,void 0,function*(){const{reader:e,source:i}=this;e&&(yield e.cancel(t).catch(()=>{})),i&&i.locked&&this.releaseLock()})}read(t){return Zt(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=ae(e)),e})}}const Wu=(r,t)=>{const e=n=>i([t,n]);let i;return[t,e,new Promise(n=>(i=n)&&r.once(t,e))]};function NC(r){return dr(this,arguments,function*(){const e=[];let i="error",n=!1,s=null,o,a,l=0,u=[],c;function h(){return o==="peek"?xi(u,a)[0]:([c,u,l]=xi(u,a),c)}if({cmd:o,size:a}=(yield yield Pt(null))||{cmd:"read",size:0},r.isTTY)return yield yield Pt(new Uint8Array(0)),yield Pt(null);try{e[0]=Wu(r,"end"),e[1]=Wu(r,"error");do{if(e[2]=Wu(r,"readable"),[i,s]=yield Pt(Promise.race(e.map(f=>f[2]))),i==="error")break;if((n=i==="end")||(Number.isFinite(a-l)?(c=ae(r.read(a-l)),c.byteLength0&&(u.push(c),l+=c.byteLength)),n||a<=l)do({cmd:o,size:a}=yield yield Pt(h()));while(a{for(const[m,_]of f)r.off(m,_);try{const m=r.destroy;m&&m.call(r,y),y=void 0}catch(m){y=m||y}finally{y!=null?d(y):g()}})}})}var ke;(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"})(ke||(ke={}));var er;(function(r){r[r.Sparse=0]="Sparse",r[r.Dense=1]="Dense"})(er||(er={}));var tr;(function(r){r[r.HALF=0]="HALF",r[r.SINGLE=1]="SINGLE",r[r.DOUBLE=2]="DOUBLE"})(tr||(tr={}));var Hr;(function(r){r[r.DAY=0]="DAY",r[r.MILLISECOND=1]="MILLISECOND"})(Hr||(Hr={}));var zt;(function(r){r[r.SECOND=0]="SECOND",r[r.MILLISECOND=1]="MILLISECOND",r[r.MICROSECOND=2]="MICROSECOND",r[r.NANOSECOND=3]="NANOSECOND"})(zt||(zt={}));var Si;(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"})(Si||(Si={}));const Hu=2,pi=4,ji=4,me=4,on=new Int32Array(2),fp=new Float32Array(on.buffer),dp=new Float64Array(on.buffer),Na=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var nh;(function(r){r[r.UTF8_BYTES=1]="UTF8_BYTES",r[r.UTF16_STRING=2]="UTF16_STRING"})(nh||(nh={}));let Qs=class Ev{constructor(t){this.bytes_=t,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new Ev(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){fp[0]=e,this.writeInt32(t,on[0])}writeFloat64(t,e){dp[0]=e,this.writeInt32(t,on[Na?0:1]),this.writeInt32(t+4,on[Na?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=t);const i=~(this.bb.capacity()-this.space+e)+1&t-1;for(;this.space=0&&this.vtable[e]==0;e--);const i=e+1;for(;e>=0;e--)this.addInt16(this.vtable[e]!=0?t-this.vtable[e]:0);const n=2;this.addInt16(t-this.object_start);const s=(i+n)*Hu;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,pi+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const i=this.bb.capacity()-t,n=i-this.bb.readInt32(i);if(!(e=0;i--)t.addInt32(e[i]);return t.endVector()}static startTypeIdsVector(t,e){t.startVector(4,e,4)}static endUnion(t){return t.endObject()}static createUnion(t,e,i){return hr.startUnion(t),hr.addMode(t,e),hr.addTypeIds(t,i),hr.endUnion(t)}}let bp=class Fo{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 Fo).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUtf8(t,e){return t.setPosition(t.position()+me),(e||new Fo).__init(t.readInt32(t.position())+t.position(),t)}static startUtf8(t){t.startObject(0)}static endUtf8(t){return t.endObject()}static createUtf8(t){return Fo.startUtf8(t),Fo.endUtf8(t)}};var xe;(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"})(xe||(xe={}));let Nr=class Ga{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 Ga).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsField(t,e){return t.setPosition(t.position()+me),(e||new Ga).__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):xe.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 $i).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}children(t,e){const i=this.bb.__offset(this.bb_pos,14);return i?(e||new Ga).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,16);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,xe.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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endField(t){return t.endObject()}},ui=class Mi{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 Mi).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSchema(t,e){return t.setPosition(t.position()+me),(e||new Mi).__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):Ks.Little}fields(t,e){const i=this.bb.__offset(this.bb_pos,6);return i?(e||new Nr).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,8);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,Ks.Little)}static addFields(t,e){t.addFieldOffset(1,e,0)}static createFieldsVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 i=e.length-1;i>=0;i--)t.addInt64(e[i]);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,i,n,s){return Mi.startSchema(t),Mi.addEndianness(t,e),Mi.addFields(t,i),Mi.addCustomMetadata(t,n),Mi.addFeatures(t,s),Mi.endSchema(t)}};var fe;(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"})(fe||(fe={}));var L;(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"})(L||(L={}));var ki;(function(r){r[r.OFFSET=0]="OFFSET",r[r.DATA=1]="DATA",r[r.VALIDITY=2]="VALIDITY",r[r.TYPE=3]="TYPE"})(ki||(ki={}));const LC=void 0;function Xo(r){if(r===null)return"null";if(r===LC)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=>Xo(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}function we(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 Pv(r,t){return we(r/t)+we(r%t)/we(t)}const BC=Symbol.for("isArrowBigNum");function ri(r,...t){return t.length===0?Object.setPrototypeOf(_e(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}ri.prototype[BC]=!0;ri.prototype.toJSON=function(){return`"${qo(this)}"`};ri.prototype.valueOf=function(r){return Mv(this,r)};ri.prototype.toString=function(){return qo(this)};ri.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Mv(this);case"string":return qo(this);case"default":return zC(this)}return qo(this)};function zs(...r){return ri.apply(this,r)}function js(...r){return ri.apply(this,r)}function Yo(...r){return ri.apply(this,r)}Object.setPrototypeOf(zs.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(js.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Yo.prototype,Object.create(Uint32Array.prototype));Object.assign(zs.prototype,ri.prototype,{constructor:zs,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(js.prototype,ri.prototype,{constructor:js,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Yo.prototype,ri.prototype,{constructor:Yo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const kC=BigInt(4294967296)*BigInt(4294967296),UC=kC-BigInt(1);function Mv(r,t){const{buffer:e,byteOffset:i,byteLength:n,signed:s}=r,o=new BigUint64Array(e,i,n/8),a=s&&o.at(-1)&BigInt(1)<=0)return Xu(r);t=t.slice();let i=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(At.prototype);let pn=class extends At{constructor(){super(L.Null)}toString(){return"Null"}};Nv=Symbol.toStringTag;pn[Nv]=(r=>r[Symbol.toStringTag]="Null")(pn.prototype);let is=class extends At{constructor(t,e){super(L.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}`}};Lv=Symbol.toStringTag;is[Lv]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))(is.prototype);class Qo extends is{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(Qo.prototype,"ArrayType",{value:Int32Array});let cl=class extends At{constructor(t){super(L.Float),this.precision=t}get ArrayType(){switch(this.precision){case tr.HALF:return Uint16Array;case tr.SINGLE:return Float32Array;case tr.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}};Bv=Symbol.toStringTag;cl[Bv]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(cl.prototype);let hl=class extends At{constructor(){super(L.Binary)}toString(){return"Binary"}};kv=Symbol.toStringTag;hl[kv]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(hl.prototype);let fl=class extends At{constructor(){super(L.LargeBinary)}toString(){return"LargeBinary"}};Uv=Symbol.toStringTag;fl[Uv]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(fl.prototype);let dl=class extends At{constructor(){super(L.Utf8)}toString(){return"Utf8"}};zv=Symbol.toStringTag;dl[zv]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(dl.prototype);let pl=class extends At{constructor(){super(L.LargeUtf8)}toString(){return"LargeUtf8"}};jv=Symbol.toStringTag;pl[jv]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(pl.prototype);let ml=class extends At{constructor(){super(L.Bool)}toString(){return"Bool"}};$v=Symbol.toStringTag;ml[$v]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(ml.prototype);let yl=class extends At{constructor(t,e,i=128){super(L.Decimal),this.scale=t,this.precision=e,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}};Vv=Symbol.toStringTag;yl[Vv]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(yl.prototype);let gl=class extends At{constructor(t){super(L.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${Hr[this.unit]}>`}get ArrayType(){return this.unit===Hr.DAY?Int32Array:BigInt64Array}};Gv=Symbol.toStringTag;gl[Gv]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(gl.prototype);let vl=class extends At{constructor(t,e){super(L.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${zt[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}};Wv=Symbol.toStringTag;vl[Wv]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(vl.prototype);let _l=class extends At{constructor(t,e){super(L.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${zt[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}};Hv=Symbol.toStringTag;_l[Hv]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(_l.prototype);let bl=class extends At{constructor(t){super(L.Interval),this.unit=t}toString(){return`Interval<${Si[this.unit]}>`}};Xv=Symbol.toStringTag;bl[Xv]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(bl.prototype);let wl=class extends At{constructor(t){super(L.Duration),this.unit=t}toString(){return`Duration<${zt[this.unit]}>`}};Yv=Symbol.toStringTag;wl[Yv]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(wl.prototype);let xl=class extends At{constructor(t){super(L.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}};qv=Symbol.toStringTag;xl[qv]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(xl.prototype);let sr=class extends At{constructor(t){super(L.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}};Qv=Symbol.toStringTag;sr[Qv]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(sr.prototype);let Sl=class extends At{constructor(t,e,i){super(L.Union),this.mode=t,this.children=i,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((n,s,o)=>(n[s]=o)&&n||n,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}};Kv=Symbol.toStringTag;Sl[Kv]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))(Sl.prototype);let Tl=class extends At{constructor(t){super(L.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}};Zv=Symbol.toStringTag;Tl[Zv]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(Tl.prototype);let Il=class extends At{constructor(t,e){super(L.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}>`}};Jv=Symbol.toStringTag;Il[Jv]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(Il.prototype);let El=class extends At{constructor(t,e=!1){var i,n,s;if(super(L.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((i=t==null?void 0:t.type)===null||i===void 0)&&i.children)){const o=(n=t==null?void 0:t.type)===null||n===void 0?void 0:n.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(", ")}}>`}};t_=Symbol.toStringTag;El[t_]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(El.prototype);const $C=(r=>()=>++r)(-1);let Zs=class extends At{constructor(t,e,i,n){super(L.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=n||!1,this.id=i==null?$C():we(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}};e_=Symbol.toStringTag;Zs[e_]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(Zs.prototype);function Ui(r){const t=r;switch(r.typeId){case L.Decimal:return r.bitWidth/32;case L.Interval:return 1+t.unit;case L.FixedSizeList:return t.listSize;case L.FixedSizeBinary:return t.byteWidth;default:return 1}}let ie=class{visitMany(t,...e){return t.map((i,n)=>this.visit(i,...e.map(s=>s[n])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return VC(this,t,e)}getVisitFnByTypeId(t,e=!0){return As(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 VC(r,t,e=!0){return typeof t=="number"?As(r,t,e):typeof t=="string"&&t in L?As(r,L[t],e):t&&t instanceof At?As(r,wp(t),e):t!=null&&t.type&&t.type instanceof At?As(r,wp(t.type),e):As(r,L.NONE,e)}function As(r,t,e=!0){let i=null;switch(t){case L.Null:i=r.visitNull;break;case L.Bool:i=r.visitBool;break;case L.Int:i=r.visitInt;break;case L.Int8:i=r.visitInt8||r.visitInt;break;case L.Int16:i=r.visitInt16||r.visitInt;break;case L.Int32:i=r.visitInt32||r.visitInt;break;case L.Int64:i=r.visitInt64||r.visitInt;break;case L.Uint8:i=r.visitUint8||r.visitInt;break;case L.Uint16:i=r.visitUint16||r.visitInt;break;case L.Uint32:i=r.visitUint32||r.visitInt;break;case L.Uint64:i=r.visitUint64||r.visitInt;break;case L.Float:i=r.visitFloat;break;case L.Float16:i=r.visitFloat16||r.visitFloat;break;case L.Float32:i=r.visitFloat32||r.visitFloat;break;case L.Float64:i=r.visitFloat64||r.visitFloat;break;case L.Utf8:i=r.visitUtf8;break;case L.LargeUtf8:i=r.visitLargeUtf8;break;case L.Binary:i=r.visitBinary;break;case L.LargeBinary:i=r.visitLargeBinary;break;case L.FixedSizeBinary:i=r.visitFixedSizeBinary;break;case L.Date:i=r.visitDate;break;case L.DateDay:i=r.visitDateDay||r.visitDate;break;case L.DateMillisecond:i=r.visitDateMillisecond||r.visitDate;break;case L.Timestamp:i=r.visitTimestamp;break;case L.TimestampSecond:i=r.visitTimestampSecond||r.visitTimestamp;break;case L.TimestampMillisecond:i=r.visitTimestampMillisecond||r.visitTimestamp;break;case L.TimestampMicrosecond:i=r.visitTimestampMicrosecond||r.visitTimestamp;break;case L.TimestampNanosecond:i=r.visitTimestampNanosecond||r.visitTimestamp;break;case L.Time:i=r.visitTime;break;case L.TimeSecond:i=r.visitTimeSecond||r.visitTime;break;case L.TimeMillisecond:i=r.visitTimeMillisecond||r.visitTime;break;case L.TimeMicrosecond:i=r.visitTimeMicrosecond||r.visitTime;break;case L.TimeNanosecond:i=r.visitTimeNanosecond||r.visitTime;break;case L.Decimal:i=r.visitDecimal;break;case L.List:i=r.visitList;break;case L.Struct:i=r.visitStruct;break;case L.Union:i=r.visitUnion;break;case L.DenseUnion:i=r.visitDenseUnion||r.visitUnion;break;case L.SparseUnion:i=r.visitSparseUnion||r.visitUnion;break;case L.Dictionary:i=r.visitDictionary;break;case L.Interval:i=r.visitInterval;break;case L.IntervalDayTime:i=r.visitIntervalDayTime||r.visitInterval;break;case L.IntervalYearMonth:i=r.visitIntervalYearMonth||r.visitInterval;break;case L.Duration:i=r.visitDuration;break;case L.DurationSecond:i=r.visitDurationSecond||r.visitDuration;break;case L.DurationMillisecond:i=r.visitDurationMillisecond||r.visitDuration;break;case L.DurationMicrosecond:i=r.visitDurationMicrosecond||r.visitDuration;break;case L.DurationNanosecond:i=r.visitDurationNanosecond||r.visitDuration;break;case L.FixedSizeList:i=r.visitFixedSizeList;break;case L.Map:i=r.visitMap;break}if(typeof i=="function")return i;if(!e)return()=>null;throw new Error(`Unrecognized type '${L[t]}'`)}function wp(r){switch(r.typeId){case L.Null:return L.Null;case L.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?L.Int8:L.Uint8;case 16:return e?L.Int16:L.Uint16;case 32:return e?L.Int32:L.Uint32;case 64:return e?L.Int64:L.Uint64}return L.Int}case L.Float:switch(r.precision){case tr.HALF:return L.Float16;case tr.SINGLE:return L.Float32;case tr.DOUBLE:return L.Float64}return L.Float;case L.Binary:return L.Binary;case L.LargeBinary:return L.LargeBinary;case L.Utf8:return L.Utf8;case L.LargeUtf8:return L.LargeUtf8;case L.Bool:return L.Bool;case L.Decimal:return L.Decimal;case L.Time:switch(r.unit){case zt.SECOND:return L.TimeSecond;case zt.MILLISECOND:return L.TimeMillisecond;case zt.MICROSECOND:return L.TimeMicrosecond;case zt.NANOSECOND:return L.TimeNanosecond}return L.Time;case L.Timestamp:switch(r.unit){case zt.SECOND:return L.TimestampSecond;case zt.MILLISECOND:return L.TimestampMillisecond;case zt.MICROSECOND:return L.TimestampMicrosecond;case zt.NANOSECOND:return L.TimestampNanosecond}return L.Timestamp;case L.Date:switch(r.unit){case Hr.DAY:return L.DateDay;case Hr.MILLISECOND:return L.DateMillisecond}return L.Date;case L.Interval:switch(r.unit){case Si.DAY_TIME:return L.IntervalDayTime;case Si.YEAR_MONTH:return L.IntervalYearMonth}return L.Interval;case L.Duration:switch(r.unit){case zt.SECOND:return L.DurationSecond;case zt.MILLISECOND:return L.DurationMillisecond;case zt.MICROSECOND:return L.DurationMicrosecond;case zt.NANOSECOND:return L.DurationNanosecond}return L.Duration;case L.Map:return L.Map;case L.List:return L.List;case L.Struct:return L.Struct;case L.Union:switch(r.mode){case er.Dense:return L.DenseUnion;case er.Sparse:return L.SparseUnion}return L.Union;case L.FixedSizeBinary:return L.FixedSizeBinary;case L.FixedSizeList:return L.FixedSizeList;case L.Dictionary:return L.Dictionary}throw new Error(`Unrecognized type '${L[r.typeId]}'`)}ie.prototype.visitInt8=null;ie.prototype.visitInt16=null;ie.prototype.visitInt32=null;ie.prototype.visitInt64=null;ie.prototype.visitUint8=null;ie.prototype.visitUint16=null;ie.prototype.visitUint32=null;ie.prototype.visitUint64=null;ie.prototype.visitFloat16=null;ie.prototype.visitFloat32=null;ie.prototype.visitFloat64=null;ie.prototype.visitDateDay=null;ie.prototype.visitDateMillisecond=null;ie.prototype.visitTimestampSecond=null;ie.prototype.visitTimestampMillisecond=null;ie.prototype.visitTimestampMicrosecond=null;ie.prototype.visitTimestampNanosecond=null;ie.prototype.visitTimeSecond=null;ie.prototype.visitTimeMillisecond=null;ie.prototype.visitTimeMicrosecond=null;ie.prototype.visitTimeNanosecond=null;ie.prototype.visitDenseUnion=null;ie.prototype.visitSparseUnion=null;ie.prototype.visitIntervalDayTime=null;ie.prototype.visitIntervalYearMonth=null;ie.prototype.visitDuration=null;ie.prototype.visitDurationSecond=null;ie.prototype.visitDurationMillisecond=null;ie.prototype.visitDurationMicrosecond=null;ie.prototype.visitDurationNanosecond=null;const r_=new Float64Array(1),gs=new Uint32Array(r_.buffer);function i_(r){const t=(r&31744)>>10,e=(r&1023)/1024,i=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return i*(e?Number.NaN:1/0);case 0:return i*(e?6103515625e-14*e:0)}return i*Math.pow(2,t-15)*(1+e)}function GC(r){if(r!==r)return 32256;r_[0]=r;const t=(gs[1]&2147483648)>>16&65535;let e=gs[1]&2146435072,i=0;return e>=1089470464?gs[0]>0?e=31744:(e=(e&2080374784)>>16,i=(gs[1]&1048575)>>10):e<=1056964608?(i=1048576+(gs[1]&1048575),i=1048576+(i<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,i=(gs[1]&1048575)+512>>10),t|e|i&65535}let jt=class extends ie{};function Xt(r){return(t,e,i)=>{if(t.setValid(e,i!=null))return r(t,e,i)}}const WC=(r,t,e)=>{r[t]=Math.floor(e/864e5)},n_=(r,t,e,i)=>{if(e+1{const n=r+e;i?t[n>>3]|=1<>3]&=~(1<{r[t]=e},sf=({values:r},t,e)=>{r[t]=e},s_=({values:r},t,e)=>{r[t]=GC(e)},XC=(r,t,e)=>{switch(r.type.precision){case tr.HALF:return s_(r,t,e);case tr.SINGLE:case tr.DOUBLE:return sf(r,t,e)}},o_=({values:r},t,e)=>{WC(r,t,e.valueOf())},a_=({values:r},t,e)=>{r[t]=BigInt(e)},YC=({stride:r,values:t},e,i)=>{t.set(i.subarray(0,r),r*e)},l_=({values:r,valueOffsets:t},e,i)=>n_(r,t,e,i),u_=({values:r,valueOffsets:t},e,i)=>n_(r,t,e,ef(i)),qC=(r,t,e)=>{r.type.unit===Hr.DAY?o_(r,t,e):a_(r,t,e)},c_=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},h_=({values:r},t,e)=>{r[t]=BigInt(e)},f_=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},d_=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},QC=(r,t,e)=>{switch(r.type.unit){case zt.SECOND:return c_(r,t,e);case zt.MILLISECOND:return h_(r,t,e);case zt.MICROSECOND:return f_(r,t,e);case zt.NANOSECOND:return d_(r,t,e)}},p_=({values:r},t,e)=>{r[t]=e},m_=({values:r},t,e)=>{r[t]=e},y_=({values:r},t,e)=>{r[t]=e},g_=({values:r},t,e)=>{r[t]=e},KC=(r,t,e)=>{switch(r.type.unit){case zt.SECOND:return p_(r,t,e);case zt.MILLISECOND:return m_(r,t,e);case zt.MICROSECOND:return y_(r,t,e);case zt.NANOSECOND:return g_(r,t,e)}},ZC=({values:r,stride:t},e,i)=>{r.set(i.subarray(0,t),t*e)},JC=(r,t,e)=>{const i=r.children[0],n=r.valueOffsets,s=Xr.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=n[t],l=n[t+1];a{const i=r.children[0],{valueOffsets:n}=r,s=Xr.getVisitFn(i);let{[t]:o,[t+1]:a}=n;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(i,o,u),++o>=a)break},eA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[s]),rA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(s)),iA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(n.name)),nA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[n.name]),sA=(r,t,e)=>{const i=r.type.children.map(s=>Xr.getVisitFn(s.type)),n=e instanceof Map?iA(t,e):e instanceof Me?rA(t,e):Array.isArray(e)?eA(t,e):nA(t,e);r.type.children.forEach((s,o)=>n(i[o],r.children[o],s,o))},oA=(r,t,e)=>{r.type.mode===er.Dense?v_(r,t,e):__(r,t,e)},v_=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Xr.visit(n,r.valueOffsets[t],e)},__=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Xr.visit(n,t,e)},aA=(r,t,e)=>{var i;(i=r.dictionary)===null||i===void 0||i.set(r.values[t],e)},lA=(r,t,e)=>{r.type.unit===Si.DAY_TIME?b_(r,t,e):w_(r,t,e)},b_=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},w_=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},x_=({values:r},t,e)=>{r[t]=e},S_=({values:r},t,e)=>{r[t]=e},T_=({values:r},t,e)=>{r[t]=e},I_=({values:r},t,e)=>{r[t]=e},uA=(r,t,e)=>{switch(r.type.unit){case zt.SECOND:return x_(r,t,e);case zt.MILLISECOND:return S_(r,t,e);case zt.MICROSECOND:return T_(r,t,e);case zt.NANOSECOND:return I_(r,t,e)}},cA=(r,t,e)=>{const{stride:i}=r,n=r.children[0],s=Xr.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=t*i;++o`${Xo(t)}: ${Xo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new hA(this[Kr],this[$s])}},hA=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[Kr].type.children.findIndex(i=>i.name===e)!==-1}getOwnPropertyDescriptor(t,e){if(t[Kr].type.children.findIndex(i=>i.name===e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Kr].type.children.findIndex(n=>n.name===e);if(i!==-1){const n=mr.visit(t[Kr].children[i],t[$s]);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Kr].type.children.findIndex(s=>s.name===e);return n!==-1?(Xr.visit(t[Kr].children[n],t[$s],i),Reflect.set(t,e,i)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,i):!1}},Mt=class extends ie{};function $t(r){return(t,e)=>t.getValid(e)?r(t,e):null}const dA=(r,t)=>864e5*r[t],pA=(r,t)=>null,E_=(r,t,e)=>{if(e+1>=t.length)return null;const i=we(t[e]),n=we(t[e+1]);return r.subarray(i,n)},mA=({offset:r,values:t},e)=>{const i=r+e;return(t[i>>3]&1<dA(r,t),A_=({values:r},t)=>we(r[t]),wn=({stride:r,values:t},e)=>t[r*e],yA=({stride:r,values:t},e)=>i_(t[r*e]),O_=({values:r},t)=>r[t],gA=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),F_=({values:r,valueOffsets:t},e)=>E_(r,t,e),P_=({values:r,valueOffsets:t},e)=>{const i=E_(r,t,e);return i!==null?eh(i):null},vA=({values:r},t)=>r[t],_A=({type:r,values:t},e)=>r.precision!==tr.HALF?t[e]:i_(t[e]),bA=(r,t)=>r.type.unit===Hr.DAY?C_(r,t):A_(r,t),M_=({values:r},t)=>1e3*we(r[t]),D_=({values:r},t)=>we(r[t]),R_=({values:r},t)=>Pv(r[t],BigInt(1e3)),N_=({values:r},t)=>Pv(r[t],BigInt(1e6)),wA=(r,t)=>{switch(r.type.unit){case zt.SECOND:return M_(r,t);case zt.MILLISECOND:return D_(r,t);case zt.MICROSECOND:return R_(r,t);case zt.NANOSECOND:return N_(r,t)}},L_=({values:r},t)=>r[t],B_=({values:r},t)=>r[t],k_=({values:r},t)=>r[t],U_=({values:r},t)=>r[t],xA=(r,t)=>{switch(r.type.unit){case zt.SECOND:return L_(r,t);case zt.MILLISECOND:return B_(r,t);case zt.MICROSECOND:return k_(r,t);case zt.NANOSECOND:return U_(r,t)}},SA=({values:r,stride:t},e)=>jC.decimal(r.subarray(t*e,t*(e+1))),TA=(r,t)=>{const{valueOffsets:e,stride:i,children:n}=r,{[t*i]:s,[t*i+1]:o}=e,l=n[0].slice(s,o-s);return new Me([l])},IA=(r,t)=>{const{valueOffsets:e,children:i}=r,{[t]:n,[t+1]:s}=e,o=i[0];return new af(o.slice(n,s-n))},EA=(r,t)=>new of(r,t),CA=(r,t)=>r.type.mode===er.Dense?z_(r,t):j_(r,t),z_=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return mr.visit(i,r.valueOffsets[t])},j_=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return mr.visit(i,t)},AA=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},OA=(r,t)=>r.type.unit===Si.DAY_TIME?$_(r,t):V_(r,t),$_=({values:r},t)=>r.subarray(2*t,2*(t+1)),V_=({values:r},t)=>{const e=r[t],i=new Int32Array(2);return i[0]=Math.trunc(e/12),i[1]=Math.trunc(e%12),i},G_=({values:r},t)=>r[t],W_=({values:r},t)=>r[t],H_=({values:r},t)=>r[t],X_=({values:r},t)=>r[t],FA=(r,t)=>{switch(r.type.unit){case zt.SECOND:return G_(r,t);case zt.MILLISECOND:return W_(r,t);case zt.MICROSECOND:return H_(r,t);case zt.NANOSECOND:return X_(r,t)}},PA=(r,t)=>{const{stride:e,children:i}=r,s=i[0].slice(t*e,e);return new Me([s])};Mt.prototype.visitNull=$t(pA);Mt.prototype.visitBool=$t(mA);Mt.prototype.visitInt=$t(vA);Mt.prototype.visitInt8=$t(wn);Mt.prototype.visitInt16=$t(wn);Mt.prototype.visitInt32=$t(wn);Mt.prototype.visitInt64=$t(O_);Mt.prototype.visitUint8=$t(wn);Mt.prototype.visitUint16=$t(wn);Mt.prototype.visitUint32=$t(wn);Mt.prototype.visitUint64=$t(O_);Mt.prototype.visitFloat=$t(_A);Mt.prototype.visitFloat16=$t(yA);Mt.prototype.visitFloat32=$t(wn);Mt.prototype.visitFloat64=$t(wn);Mt.prototype.visitUtf8=$t(P_);Mt.prototype.visitLargeUtf8=$t(P_);Mt.prototype.visitBinary=$t(F_);Mt.prototype.visitLargeBinary=$t(F_);Mt.prototype.visitFixedSizeBinary=$t(gA);Mt.prototype.visitDate=$t(bA);Mt.prototype.visitDateDay=$t(C_);Mt.prototype.visitDateMillisecond=$t(A_);Mt.prototype.visitTimestamp=$t(wA);Mt.prototype.visitTimestampSecond=$t(M_);Mt.prototype.visitTimestampMillisecond=$t(D_);Mt.prototype.visitTimestampMicrosecond=$t(R_);Mt.prototype.visitTimestampNanosecond=$t(N_);Mt.prototype.visitTime=$t(xA);Mt.prototype.visitTimeSecond=$t(L_);Mt.prototype.visitTimeMillisecond=$t(B_);Mt.prototype.visitTimeMicrosecond=$t(k_);Mt.prototype.visitTimeNanosecond=$t(U_);Mt.prototype.visitDecimal=$t(SA);Mt.prototype.visitList=$t(TA);Mt.prototype.visitStruct=$t(EA);Mt.prototype.visitUnion=$t(CA);Mt.prototype.visitDenseUnion=$t(z_);Mt.prototype.visitSparseUnion=$t(j_);Mt.prototype.visitDictionary=$t(AA);Mt.prototype.visitInterval=$t(OA);Mt.prototype.visitIntervalDayTime=$t($_);Mt.prototype.visitIntervalYearMonth=$t(V_);Mt.prototype.visitDuration=$t(FA);Mt.prototype.visitDurationSecond=$t(G_);Mt.prototype.visitDurationMillisecond=$t(W_);Mt.prototype.visitDurationMicrosecond=$t(H_);Mt.prototype.visitDurationNanosecond=$t(X_);Mt.prototype.visitFixedSizeList=$t(PA);Mt.prototype.visitMap=$t(IA);const mr=new Mt,Os=Symbol.for("keys"),Vs=Symbol.for("vals"),Fs=Symbol.for("kKeysAsStrings"),lh=Symbol.for("_kKeysAsStrings");let af=class{constructor(t){return this[Os]=new Me([t.children[0]]).memoize(),this[Vs]=t.children[1],new Proxy(this,new DA)}get[Fs](){return this[lh]||(this[lh]=Array.from(this[Os].toArray(),String))}[Symbol.iterator](){return new MA(this[Os],this[Vs])}get size(){return this[Os].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[Os],e=this[Vs],i={};for(let n=-1,s=t.length;++n`${Xo(t)}: ${Xo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}},MA=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),mr.visit(this.vals,t)]})}},DA=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[Fs]}has(t,e){return t[Fs].includes(e)}getOwnPropertyDescriptor(t,e){if(t[Fs].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Fs].indexOf(e);if(i!==-1){const n=mr.visit(Reflect.get(t,Vs),i);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Fs].indexOf(e);return n!==-1?(Xr.visit(Reflect.get(t,Vs),n,i),Reflect.set(t,e,i)):Reflect.has(t,e)?Reflect.set(t,e,i):!1}};Object.defineProperties(af.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[Os]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Vs]:{writable:!0,enumerable:!1,configurable:!1,value:null},[lh]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let xp;function Y_(r,t,e,i){const{length:n=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?n:e;return s<0&&(s=(s%n+n)%n),o<0&&(o=(o%n+n)%n),on&&(o=n),i?i(r,s,o):[s,o]}const lf=(r,t)=>r<0?t+r:r,Sp=r=>r!==r;function so(r){if(typeof r!=="object"||r===null)return Sp(r)?Sp:e=>e===r;if(r instanceof Date){const e=r.valueOf();return i=>i instanceof Date?i.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?FC(r,e):!1:r instanceof Map?NA(r):Array.isArray(r)?RA(r):r instanceof Me?LA(r):BA(r,!0)}function RA(r){const t=[];for(let e=-1,i=r.length;++e!1;const i=[];for(let n=-1,s=e.length;++n{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return kA(r,e);case Map:return Tp(r,e,e.keys());case af:case of:case Object:case void 0:return Tp(r,e,t||Object.keys(e))}return e instanceof Me?UA(r,e):!1}}function kA(r,t){const e=r.length;if(t.length!==e)return!1;for(let i=-1;++i>i}function Cl(r,t,e){const i=e.byteLength+7&-8;if(r>0||e.byteLength>3):Al(new uf(e,r,t,null,q_)).subarray(0,i)),n}return e}function Al(r){const t=[];let e=0,i=0,n=0;for(const o of r)o&&(n|=1<0)&&(t[e++]=n);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}let uf=class{constructor(t,e,i,n,s){this.bytes=t,this.length=i,this.context=n,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,n=t+(t%8===0?0:8-t%8);return uh(r,t,n)+uh(r,i,e)+jA(r,n>>3,i-n>>3)}function jA(r,t,e){let i=0,n=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:n+e;for(;o-n>=4;)i+=Yu(s.getUint32(n)),n+=4;for(;o-n>=2;)i+=Yu(s.getUint16(n)),n+=2;for(;o-n>=1;)i+=Yu(s.getUint8(n)),n+=1;return i}function Yu(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 $A=-1;let Se=class ch{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 At.isSparseUnion(t)?this.children.some(e=>e.nullable):At.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:i,nullBitmap:n,typeIds:s}=this;return e&&(t+=e.byteLength),i&&(t+=i.byteLength),n&&(t+=n.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(At.isUnion(this.type))return this.children.reduce((i,n)=>i+n.nullCount,0);let t=this._nullCount,e;return t<=$A&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-uh(e,this.offset,this.offset+this.length)),t}constructor(t,e,i,n,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(i||0,0)),this._nullCount=Math.floor(Math.max(n||0,-1));let l;s instanceof ch?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=Ui(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(At.isUnion(e)){const i=e,n=this.children[i.typeIdToChildIndex[this.typeIds[t]]],s=i.mode===er.Dense?this.valueOffsets[t]:t;return n.getValid(s)}if(this.nullable&&this.nullCount>0){const i=this.offset+t;return(this.nullBitmap[i>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(Cl(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];i=(h&u)!==0,s[c]=e?h|u:h&~u}return i!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,i=this.length,n=this._nullCount,s=this,o=this.children){return new ch(t,e,i,n,s,o,this.dictionary)}slice(t,e){const{stride:i,typeId:n,children:s}=this,o=+(this._nullCount===0)-1,a=n===16?i:1,l=this._sliceBuffers(t,e,i,n);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===L.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:i}=this,n=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);n[e>>3]=(1<0&&n.set(Cl(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[ki.VALIDITY]=n,this.clone(this.type,0,t,i+(t-e),s)}_sliceBuffers(t,e,i,n){let s;const{buffers:o}=this;return(s=o[ki.TYPE])&&(o[ki.TYPE]=s.subarray(t,t+e)),(s=o[ki.OFFSET])&&(o[ki.OFFSET]=s.subarray(t,t+e+1))||(s=o[ki.DATA])&&(o[ki.DATA]=n===6?s:s.subarray(i*t,i*(t+e))),o}_sliceChildren(t,e,i){return t.map(n=>n.slice(e,i))}};Se.prototype.children=Object.freeze([]);class Ro extends ie{visit(t){return this.getVisitFn(t.type).call(this,t)}visitNull(t){const{["type"]:e,["offset"]:i=0,["length"]:n=0}=t;return new Se(e,i,n,n)}visitBool(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length>>3,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitInt(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitFloat(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitUtf8(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitLargeUtf8(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=hp(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitBinary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitLargeBinary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=hp(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitFixedSizeBinary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitDate(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitTimestamp(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitTime(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitDecimal(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitList(t){const{["type"]:e,["offset"]:i=0,["child"]:n}=t,s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,void 0,s],[n])}visitStruct(t){const{["type"]:e,["offset"]:i=0,["children"]:n=[]}=t,s=ae(t.nullBitmap),{length:o=n.reduce((l,{length:u})=>Math.max(l,u),0),nullCount:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,void 0,s],n)}visitUnion(t){const{["type"]:e,["offset"]:i=0,["children"]:n=[]}=t,s=_e(e.ArrayType,t.typeIds),{["length"]:o=s.length,["nullCount"]:a=-1}=t;if(At.isSparseUnion(e))return new Se(e,i,o,a,[void 0,void 0,void 0,s],n);const l=yo(t.valueOffsets);return new Se(e,i,o,a,[l,void 0,void 0,s],n)}visitDictionary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.indices.ArrayType,t.data),{["dictionary"]:o=new Me([new Ro().visit({type:e.dictionary})])}=t,{["length"]:a=s.length,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[void 0,s,n],[],o)}visitInterval(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitDuration(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitFixedSizeList(t){const{["type"]:e,["offset"]:i=0,["child"]:n=new Ro().visit({type:e.valueType})}=t,s=ae(t.nullBitmap),{["length"]:o=n.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,void 0,s],[n])}visitMap(t){const{["type"]:e,["offset"]:i=0,["child"]:n=new Ro().visit({type:e.childType})}=t,s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,void 0,s],[n])}}const VA=new Ro;function se(r){return VA.visit(r)}let Ip=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 Q_(r){return r.reduce((t,e)=>t+e.nullCount,0)}function K_(r){return r.reduce((t,e,i)=>(t[i+1]=t[i]+e.length,t),new Uint32Array(r.length+1))}function Z_(r,t,e,i){const n=[];for(let s=-1,o=r.length;++s=i)break;if(e>=l+u)continue;if(l>=e&&l+u<=i){n.push(a);continue}const c=Math.max(0,e-l),h=Math.min(i-l,u);n.push(a.slice(c,h-c))}return n.length===0&&n.push(r[0].slice(0,0)),n}function cf(r,t,e,i){let n=0,s=0,o=t.length-1;do{if(n>=o-1)return e0?0:-1}function HA(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let i=0;for(const n of new uf(e,r.offset+(t||0),r.length,e,q_)){if(!n)return i;++i}return-1}function Qt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case L.Union:break;case L.Dictionary:break;default:return HA(r,e)}const i=mr.getVisitFn(r),n=so(t);for(let s=(e||0)-1,o=r.length;++s{const n=r.data[i];return n.values.subarray(0,n.length)[Symbol.iterator]()});let e=0;return new Ip(r.data.length,i=>{const s=r.data[i].length,o=r.slice(e,e+s);return e+=s,new XA(o)})}let XA=class{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof Se)))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}=i0[o.typeId],c=s[0];this.isValid=h=>hf(c,h),this.get=h=>a(c,h),this.set=(h,p)=>l(c,h,p),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,n0[o.typeId]),this._offsets=K_(s);break}this.data=s,this.type=o,this.stride=Ui(o),this.numChildren=(n=(i=o.children)===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return GA(this.data)}get nullCount(){return Q_(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${L[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(lf(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return ff.visit(this)}concat(...t){return new zn(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new zn(Y_(this,t,e,({data:i,_offsets:n},s,o)=>Z_(i,n,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:i,stride:n,ArrayType:s}=this;switch(t.typeId){case L.Int:case L.Float:case L.Decimal:case L.Time:case L.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,i*n);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*n),o.offset),o.offset+=l*n,o),{array:new s(i*n),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(i=>i.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return At.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(At.isDictionary(this.type)){const t=new Ep(this.data[0].dictionary),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new zn(e)}return new Ep(this)}unmemoize(){if(At.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new zn(e)}return this}};r0=Symbol.toStringTag;Me[r0]=(r=>{r.type=At.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(L).map(e=>L[e]).filter(e=>typeof e=="number"&&e!==L.NONE);for(const e of t){const i=mr.getVisitFnByTypeId(e),n=Xr.getVisitFnByTypeId(e),s=Fl.getVisitFnByTypeId(e);i0[e]={get:i,set:n,indexOf:s},n0[e]=Object.create(r,{isValid:{value:Ol(hf)},get:{value:Ol(mr.getVisitFnByTypeId(e))},set:{value:J_(Xr.getVisitFnByTypeId(e))},indexOf:{value:t0(Fl.getVisitFnByTypeId(e))}})}return"Vector"})(Me.prototype);let Ep=class s0 extends Me{constructor(t){super(t.data);const e=this.get,i=this.set,n=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){i.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new s0(n.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Me(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}};class hh{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,i,n){return t.prep(8,24),t.writeInt64(BigInt(n??0)),t.pad(4),t.writeInt32(i),t.writeInt64(BigInt(e??0)),t.offset()}}class _r{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 _r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFooter(t,e){return t.setPosition(t.position()+me),(e||new _r).__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):ke.V1}schema(t){const e=this.bb.__offset(this.bb_pos,6);return e?(t||new ui).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dictionaries(t,e){const i=this.bb.__offset(this.bb_pos,8);return i?(e||new hh).__init(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,10);return i?(e||new hh).__init(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,12);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,ke.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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 Pe=class jn{constructor(t=[],e,i,n=ke.V5){this.fields=t||[],this.metadata=e||new Map,i||(i=fh(this.fields)),this.dictionaries=i,this.metadataVersion=n}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),i=this.fields.filter(n=>e.has(n.name));return new jn(i,this.metadata)}selectAt(t){const e=t.map(i=>this.fields[i]).filter(Boolean);return new jn(e,this.metadata)}assign(...t){const e=t[0]instanceof jn?t[0]:Array.isArray(t[0])?new jn(t[0]):new jn(t),i=[...this.fields],n=La(La(new Map,this.metadata),e.metadata),s=e.fields.filter(a=>{const l=i.findIndex(u=>u.name===a.name);return~l?(i[l]=a.clone({metadata:La(La(new Map,i[l].metadata),a.metadata)}))&&!1:!0}),o=fh(s,new Map);return new jn([...i,...s],n,new Map([...this.dictionaries,...o]))}};Pe.prototype.fields=null;Pe.prototype.metadata=null;Pe.prototype.dictionaries=null;class Ce{static new(...t){let[e,i,n,s]=t;return t[0]&&typeof t[0]=="object"&&({name:e}=t[0],i===void 0&&(i=t[0].type),n===void 0&&(n=t[0].nullable),s===void 0&&(s=t[0].metadata)),new Ce(`${e}`,i,n,s)}constructor(t,e,i=!1,n){this.name=t,this.type=e,this.nullable=i,this.metadata=n||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...t){let[e,i,n,s]=t;return!t[0]||typeof t[0]!="object"?[e=this.name,i=this.type,n=this.nullable,s=this.metadata]=t:{name:e=this.name,type:i=this.type,nullable:n=this.nullable,metadata:s=this.metadata}=t[0],Ce.new(e,i,n,s)}}Ce.prototype.type=null;Ce.prototype.name=null;Ce.prototype.nullable=null;Ce.prototype.metadata=null;function La(r,t){return new Map([...r||new Map,...t||new Map])}function fh(r,t=new Map){for(let e=-1,i=r.length;++e0&&fh(s.children,t)}return t}var YA=Cv,qA=Qs;class Ko{static decode(t){t=new qA(ae(t));const e=_r.getRootAsFooter(t),i=Pe.decode(e.schema(),new Map,e.version());return new QA(i,e)}static encode(t){const e=new YA,i=Pe.encode(e,t.schema);_r.startRecordBatchesVector(e,t.numRecordBatches);for(const o of[...t.recordBatches()].slice().reverse())mn.encode(e,o);const n=e.endVector();_r.startDictionariesVector(e,t.numDictionaries);for(const o of[...t.dictionaryBatches()].slice().reverse())mn.encode(e,o);const s=e.endVector();return _r.startFooter(e),_r.addSchema(e,i),_r.addVersion(e,ke.V5),_r.addRecordBatches(e,n),_r.addDictionaries(e,s),_r.finishFooterBuffer(e,_r.endFooter(e)),e.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(t,e=ke.V5,i,n){this.schema=t,this.version=e,i&&(this._recordBatches=i),n&&(this._dictionaryBatches=n)}*recordBatches(){for(let t,e=-1,i=this.numRecordBatches;++e=0&&t=0&&t=0&&t=0&&tthis._closedPromiseResolve=t)}get closed(){return this._closedPromise}cancel(t){return Zt(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(De);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(t){return kr.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,t)}toNodeStream(t){return kr.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,t)}throw(t){return Zt(this,void 0,void 0,function*(){return yield this.abort(t),De})}return(t){return Zt(this,void 0,void 0,function*(){return yield this.close(),De})}read(t){return Zt(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return Zt(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,i)=>{this.resolvers.push({resolve:e,reject:i})}):Promise.resolve(De)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class Wa extends KA{write(t){if((t=ae(t)).byteLength>0)return super.write(t)}toString(t=!1){return t?eh(this.toUint8Array(!0)):this.toUint8Array(!1).then(eh)}toUint8Array(t=!1){return t?xi(this._values)[0]:Zt(this,void 0,void 0,function*(){var e,i,n,s;const o=[];let a=0;try{for(var l=!0,u=bi(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){i={error:h}}finally{try{!l&&!e&&(n=u.return)&&(yield n.call(u))}finally{if(i)throw i.error}}return xi(o,a)[0]})}}class Pl{constructor(t){t&&(this.source=new ZA(kr.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 Js{constructor(t){t instanceof Js?this.source=t.source:t instanceof Wa?this.source=new Mn(kr.fromAsyncIterable(t)):Sv(t)?this.source=new Mn(kr.fromNodeStream(t)):rf(t)?this.source=new Mn(kr.fromDOMStream(t)):xv(t)?this.source=new Mn(kr.fromDOMStream(t.body)):oa(t)?this.source=new Mn(kr.fromIterable(t)):rs(t)?this.source=new Mn(kr.fromAsyncIterable(t)):no(t)&&(this.source=new Mn(kr.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 ZA{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)||De)}return(t){return Object.create(this.source.return&&this.source.return(t)||De)}}class Mn{constructor(t){this.source=t,this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}cancel(t){return Zt(this,void 0,void 0,function*(){yield this.return(t)})}get closed(){return this._closedPromise}read(t){return Zt(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return Zt(this,void 0,void 0,function*(){return(yield this.next(t,"peek")).value})}next(t){return Zt(this,arguments,void 0,function*(e,i="read"){return yield this.source.next({cmd:i,size:e})})}throw(t){return Zt(this,void 0,void 0,function*(){const e=this.source.throw&&(yield this.source.throw(t))||De;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}return(t){return Zt(this,void 0,void 0,function*(){const e=this.source.return&&(yield this.source.return(t))||De;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}}class Ap extends Pl{constructor(t,e){super(),this.position=0,this.buffer=ae(t),this.size=e===void 0?this.buffer.byteLength:e}readInt32(t){const{buffer:e,byteOffset:i}=this.readAt(t,4);return new DataView(e,i).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]),i=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let n=e[3]*i[3];this.buffer[0]=n&65535;let s=n>>>16;return n=e[2]*i[3],s+=n,n=e[3]*i[2]>>>0,s+=n,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*i[3]+e[2]*i[2]+e[3]*i[1],this.buffer[1]+=e[0]*i[3]+e[1]*i[2]+e[2]*i[1]+e[3]*i[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`${Ns(this.buffer[3])} ${Ns(this.buffer[2])} ${Ns(this.buffer[1])} ${Ns(this.buffer[0])}`}static multiply(t,e){return new Ni(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new Ni(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return Ni.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return Ni.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const i=t.startsWith("-"),n=t.length,s=new Ni(e);for(let o=i?1:0;o0&&this.readData(t,i)||new Uint8Array(0)}readOffsets(t,e){return this.readData(t,e)}readTypeIds(t,e){return this.readData(t,e)}readData(t,{length:e,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+e)}readDictionary(t){return this.dictionaries.get(t.id)}}class eO extends a0{constructor(t,e,i,n,s){super(new Uint8Array(0),e,i,n,s),this.sources=t}readNullBitmap(t,e,{offset:i}=this.nextBufferRange()){return e<=0?new Uint8Array(0):Al(this.sources[i])}readOffsets(t,{offset:e}=this.nextBufferRange()){return _e(Uint8Array,_e(t.OffsetArrayType,this.sources[e]))}readTypeIds(t,{offset:e}=this.nextBufferRange()){return _e(Uint8Array,_e(t.ArrayType,this.sources[e]))}readData(t,{offset:e}=this.nextBufferRange()){const{sources:i}=this;return At.isTimestamp(t)||(At.isInt(t)||At.isTime(t))&&t.bitWidth===64||At.isDuration(t)||At.isDate(t)&&t.unit===Hr.MILLISECOND?_e(Uint8Array,No.convertArray(i[e])):At.isDecimal(t)?_e(Uint8Array,tO.convertArray(i[e])):At.isBinary(t)||At.isLargeBinary(t)||At.isFixedSizeBinary(t)?rO(i[e]):At.isBool(t)?Al(i[e]):At.isUtf8(t)||At.isLargeUtf8(t)?ef(i[e].join("")):_e(Uint8Array,_e(t.ArrayType,i[e].map(n=>+n)))}}function rO(r){const t=r.join(""),e=new Uint8Array(t.length/2);for(let i=0;i>1]=Number.parseInt(t.slice(i,i+2),16);return e}let Nt=class extends ie{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((i,n)=>this.compareFields(i,e[n]))}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 lr(r,t){return t instanceof r.constructor}function us(r,t){return r===t||lr(r,t)}function Xi(r,t){return r===t||lr(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function ru(r,t){return r===t||lr(r,t)&&r.precision===t.precision}function iO(r,t){return r===t||lr(r,t)&&r.byteWidth===t.byteWidth}function mf(r,t){return r===t||lr(r,t)&&r.unit===t.unit}function aa(r,t){return r===t||lr(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function la(r,t){return r===t||lr(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function nO(r,t){return r===t||lr(r,t)&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}function sO(r,t){return r===t||lr(r,t)&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}function yf(r,t){return r===t||lr(r,t)&&r.mode===t.mode&&r.typeIds.every((e,i)=>e===t.typeIds[i])&&yn.compareManyFields(r.children,t.children)}function oO(r,t){return r===t||lr(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&yn.visit(r.indices,t.indices)&&yn.visit(r.dictionary,t.dictionary)}function gf(r,t){return r===t||lr(r,t)&&r.unit===t.unit}function ua(r,t){return r===t||lr(r,t)&&r.unit===t.unit}function aO(r,t){return r===t||lr(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}function lO(r,t){return r===t||lr(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}Nt.prototype.visitNull=us;Nt.prototype.visitBool=us;Nt.prototype.visitInt=Xi;Nt.prototype.visitInt8=Xi;Nt.prototype.visitInt16=Xi;Nt.prototype.visitInt32=Xi;Nt.prototype.visitInt64=Xi;Nt.prototype.visitUint8=Xi;Nt.prototype.visitUint16=Xi;Nt.prototype.visitUint32=Xi;Nt.prototype.visitUint64=Xi;Nt.prototype.visitFloat=ru;Nt.prototype.visitFloat16=ru;Nt.prototype.visitFloat32=ru;Nt.prototype.visitFloat64=ru;Nt.prototype.visitUtf8=us;Nt.prototype.visitLargeUtf8=us;Nt.prototype.visitBinary=us;Nt.prototype.visitLargeBinary=us;Nt.prototype.visitFixedSizeBinary=iO;Nt.prototype.visitDate=mf;Nt.prototype.visitDateDay=mf;Nt.prototype.visitDateMillisecond=mf;Nt.prototype.visitTimestamp=aa;Nt.prototype.visitTimestampSecond=aa;Nt.prototype.visitTimestampMillisecond=aa;Nt.prototype.visitTimestampMicrosecond=aa;Nt.prototype.visitTimestampNanosecond=aa;Nt.prototype.visitTime=la;Nt.prototype.visitTimeSecond=la;Nt.prototype.visitTimeMillisecond=la;Nt.prototype.visitTimeMicrosecond=la;Nt.prototype.visitTimeNanosecond=la;Nt.prototype.visitDecimal=us;Nt.prototype.visitList=nO;Nt.prototype.visitStruct=sO;Nt.prototype.visitUnion=yf;Nt.prototype.visitDenseUnion=yf;Nt.prototype.visitSparseUnion=yf;Nt.prototype.visitDictionary=oO;Nt.prototype.visitInterval=gf;Nt.prototype.visitIntervalDayTime=gf;Nt.prototype.visitIntervalYearMonth=gf;Nt.prototype.visitDuration=ua;Nt.prototype.visitDurationSecond=ua;Nt.prototype.visitDurationMillisecond=ua;Nt.prototype.visitDurationMicrosecond=ua;Nt.prototype.visitDurationNanosecond=ua;Nt.prototype.visitFixedSizeList=aO;Nt.prototype.visitMap=lO;const yn=new Nt;function dh(r,t){return yn.compareSchemas(r,t)}function qu(r,t){return uO(r,t.map(e=>e.data.concat()))}function uO(r,t){const e=[...r.fields],i=[],n={numBatches:t.reduce((h,p)=>Math.max(h,p.length),0)};let s=0,o=0,a=-1;const l=t.length;let u,c=[];for(;n.numBatches-- >0;){for(o=Number.POSITIVE_INFINITY,a=-1;++a0&&(i[s++]=se({type:new sr(e),length:o,nullCount:0,children:c.slice()})))}return[r=r.assign(e),i.map(h=>new fr(r,h))]}function cO(r,t,e,i,n){var s;const o=(t+63&-64)>>3;for(let a=-1,l=i.length;++a=t)c===t?e[a]=u:(e[a]=u.slice(0,t),n.numBatches=Math.max(n.numBatches,i[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:se({type:h.type,length:t,nullCount:t,nullBitmap:new Uint8Array(o)})}}return e}var l0;let gn=class $n{constructor(...t){var e,i;if(t.length===0)return this.batches=[],this.schema=new Pe([]),this._offsets=[0],this;let n,s;t[0]instanceof Pe&&(n=t.shift()),t.at(-1)instanceof Uint32Array&&(s=t.pop());const o=l=>{if(l){if(l instanceof fr)return[l];if(l instanceof $n)return l.batches;if(l instanceof Se){if(l.type instanceof sr)return[new fr(new Pe(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(f=>new Me([l[f]])),h=n??new Pe(u.map((f,y)=>new Ce(String(f),c[y].type,c[y].nullable))),[,p]=qu(h,c);return p.length===0?[new fr(l)]:p}}}return[]},a=t.flatMap(l=>o(l));if(n=(i=n??((e=a[0])===null||e===void 0?void 0:e.schema))!==null&&i!==void 0?i:new Pe([]),!(n instanceof Pe))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const l of a){if(!(l instanceof fr))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!dh(n,l.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=n,this.batches=a,this._offsets=s??K_(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=Q_(this.data)),this._nullCount}isValid(t){return!1}get(t){return null}at(t){return this.get(lf(t,this.numRows))}set(t,e){}indexOf(t,e){return-1}[Symbol.iterator](){return this.batches.length>0?ff.visit(new Me(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ +*/var lp;function fC(){return lp||(lp=1,function(r,t){(function(e){r.exports=e()})(function(){return function e(i,n,s){function o(u,c){if(!n[u]){if(!i[u]){var h=typeof un=="function"&&un;if(!c&&h)return h(u,!0);if(a)return a(u,!0);var p=new Error("Cannot find module '"+u+"'");throw p.code="MODULE_NOT_FOUND",p}var f=n[u]={exports:{}};i[u][0].call(f.exports,function(y){var g=i[u][1][y];return o(g||y)},f,f.exports,e,i,n,s)}return n[u].exports}for(var a=typeof un=="function"&&un,l=0;l>2,f=(3&u)<<4|c>>4,y=1>6:64,g=2>4,c=(15&p)<<4|(f=a.indexOf(l.charAt(g++)))>>2,h=(3&f)<<6|(y=a.indexOf(l.charAt(g++))),_[d++]=u,f!==64&&(_[d++]=c),y!==64&&(_[d++]=h);return _}},{"./support":30,"./utils":32}],2:[function(e,i,n){var s=e("./external"),o=e("./stream/DataWorker"),a=e("./stream/Crc32Probe"),l=e("./stream/DataLengthProbe");function u(c,h,p,f,y){this.compressedSize=c,this.uncompressedSize=h,this.crc32=p,this.compression=f,this.compressedContent=y}u.prototype={getContentWorker:function(){var c=new o(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new l("data_length")),h=this;return c.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),c},getCompressedWorker:function(){return new o(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},u.createWorkerFrom=function(c,h,p){return c.pipe(new a).pipe(new l("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new l("compressedSize")).withStreamInfo("compression",h)},i.exports=u},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,i,n){var s=e("./stream/GenericWorker");n.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},n.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,i,n){var s=e("./utils"),o=function(){for(var a,l=[],u=0;u<256;u++){a=u;for(var c=0;c<8;c++)a=1&a?3988292384^a>>>1:a>>>1;l[u]=a}return l}();i.exports=function(a,l){return a!==void 0&&a.length?s.getTypeOf(a)!=="string"?function(u,c,h,p){var f=o,y=p+h;u^=-1;for(var g=p;g>>8^f[255&(u^c[g])];return-1^u}(0|l,a,a.length,0):function(u,c,h,p){var f=o,y=p+h;u^=-1;for(var g=p;g>>8^f[255&(u^c.charCodeAt(g))];return-1^u}(0|l,a,a.length,0):0}},{"./utils":32}],5:[function(e,i,n){n.base64=!1,n.binary=!1,n.dir=!1,n.createFolders=!0,n.date=null,n.compression=null,n.compressionOptions=null,n.comment=null,n.unixPermissions=null,n.dosPermissions=null},{}],6:[function(e,i,n){var s=null;s=typeof Promise<"u"?Promise:e("lie"),i.exports={Promise:s}},{lie:37}],7:[function(e,i,n){var s=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",o=e("pako"),a=e("./utils"),l=e("./stream/GenericWorker"),u=s?"uint8array":"array";function c(h,p){l.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}n.magic="\b\0",a.inherits(c,l),c.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(a.transformTo(u,h.data),!1)},c.prototype.flush=function(){l.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},c.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this._pako=null},c.prototype._createPako=function(){this._pako=new o[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},n.compressWorker=function(h){return new c("Deflate",h)},n.uncompressWorker=function(){return new c("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,i,n){function s(f,y){var g,d="";for(g=0;g>>=8;return d}function o(f,y,g,d,m,_){var S,E,b=f.file,F=f.compression,x=_!==u.utf8encode,z=a.transformTo("string",_(b.name)),B=a.transformTo("string",u.utf8encode(b.name)),tt=b.comment,st=a.transformTo("string",_(tt)),I=a.transformTo("string",u.utf8encode(tt)),Z=B.length!==b.name.length,w=I.length!==tt.length,it="",M="",O="",D=b.dir,U=b.date,k={crc32:0,compressedSize:0,uncompressedSize:0};y&&!g||(k.crc32=f.crc32,k.compressedSize=f.compressedSize,k.uncompressedSize=f.uncompressedSize);var C=0;y&&(C|=8),x||!Z&&!w||(C|=2048);var A=0,V=0;D&&(A|=16),m==="UNIX"?(V=798,A|=function(J,yt){var vt=J;return J||(vt=yt?16893:33204),(65535&vt)<<16}(b.unixPermissions,D)):(V=20,A|=function(J){return 63&(J||0)}(b.dosPermissions)),S=U.getUTCHours(),S<<=6,S|=U.getUTCMinutes(),S<<=5,S|=U.getUTCSeconds()/2,E=U.getUTCFullYear()-1980,E<<=4,E|=U.getUTCMonth()+1,E<<=5,E|=U.getUTCDate(),Z&&(M=s(1,1)+s(c(z),4)+B,it+="up"+s(M.length,2)+M),w&&(O=s(1,1)+s(c(st),4)+I,it+="uc"+s(O.length,2)+O);var et="";return et+=` +\0`,et+=s(C,2),et+=F.magic,et+=s(S,2),et+=s(E,2),et+=s(k.crc32,4),et+=s(k.compressedSize,4),et+=s(k.uncompressedSize,4),et+=s(z.length,2),et+=s(it.length,2),{fileRecord:h.LOCAL_FILE_HEADER+et+z+it,dirRecord:h.CENTRAL_FILE_HEADER+s(V,2)+et+s(st.length,2)+"\0\0\0\0"+s(A,4)+s(d,4)+z+it+st}}var a=e("../utils"),l=e("../stream/GenericWorker"),u=e("../utf8"),c=e("../crc32"),h=e("../signature");function p(f,y,g,d){l.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=g,this.encodeFileName=d,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(p,l),p.prototype.push=function(f){var y=f.meta.percent||0,g=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,l.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:g?(y+100*(g-d-1))/g:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var y=this.streamFiles&&!f.file.dir;if(y){var g=o(f,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var y=this.streamFiles&&!f.file.dir,g=o(f,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),y)this.push({data:function(d){return h.DATA_DESCRIPTOR+s(d.crc32,4)+s(d.compressedSize,4)+s(d.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,y=0;y=this.index;l--)u=(u<<8)+this.byteAt(l);return this.index+=a,u},readString:function(a){return s.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date(Date.UTC(1980+(a>>25&127),(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1))}},i.exports=o},{"../utils":32}],19:[function(e,i,n){var s=e("./Uint8ArrayReader");function o(a){s.call(this,a)}e("../utils").inherits(o,s),o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,i,n){var s=e("./DataReader");function o(a){s.call(this,a)}e("../utils").inherits(o,s),o.prototype.byteAt=function(a){return this.data.charCodeAt(this.zero+a)},o.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)-this.zero},o.prototype.readAndCheckSignature=function(a){return a===this.readData(4)},o.prototype.readData=function(a){this.checkOffset(a);var l=this.data.slice(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./DataReader":18}],21:[function(e,i,n){var s=e("./ArrayReader");function o(a){s.call(this,a)}e("../utils").inherits(o,s),o.prototype.readData=function(a){if(this.checkOffset(a),a===0)return new Uint8Array(0);var l=this.data.subarray(this.zero+this.index,this.zero+this.index+a);return this.index+=a,l},i.exports=o},{"../utils":32,"./ArrayReader":17}],22:[function(e,i,n){var s=e("../utils"),o=e("../support"),a=e("./ArrayReader"),l=e("./StringReader"),u=e("./NodeBufferReader"),c=e("./Uint8ArrayReader");i.exports=function(h){var p=s.getTypeOf(h);return s.checkSupport(p),p!=="string"||o.uint8array?p==="nodebuffer"?new u(h):o.uint8array?new c(s.transformTo("uint8array",h)):new a(s.transformTo("array",h)):new l(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,i,n){n.LOCAL_FILE_HEADER="PK",n.CENTRAL_FILE_HEADER="PK",n.CENTRAL_DIRECTORY_END="PK",n.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",n.ZIP64_CENTRAL_DIRECTORY_END="PK",n.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(e,i,n){var s=e("./GenericWorker"),o=e("../utils");function a(l){s.call(this,"ConvertWorker to "+l),this.destType=l}o.inherits(a,s),a.prototype.processChunk=function(l){this.push({data:o.transformTo(this.destType,l.data),meta:l.meta})},i.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(e,i,n){var s=e("./GenericWorker"),o=e("../crc32");function a(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(a,s),a.prototype.processChunk=function(l){this.streamInfo.crc32=o(l.data,this.streamInfo.crc32||0),this.push(l)},i.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,i,n){var s=e("../utils"),o=e("./GenericWorker");function a(l){o.call(this,"DataLengthProbe for "+l),this.propName=l,this.withStreamInfo(l,0)}s.inherits(a,o),a.prototype.processChunk=function(l){if(l){var u=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=u+l.data.length}o.prototype.processChunk.call(this,l)},i.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(e,i,n){var s=e("../utils"),o=e("./GenericWorker");function a(l){o.call(this,"DataWorker");var u=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,l.then(function(c){u.dataIsReady=!0,u.data=c,u.max=c&&c.length||0,u.type=s.getTypeOf(c),u.isPaused||u._tickAndRepeat()},function(c){u.error(c)})}s.inherits(a,o),a.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var l=null,u=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":l=this.data.substring(this.index,u);break;case"uint8array":l=this.data.subarray(this.index,u);break;case"array":case"nodebuffer":l=this.data.slice(this.index,u)}return this.index=u,this.push({data:l,meta:{percent:this.max?this.index/this.max*100:0}})},i.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(e,i,n){function s(o){this.name=o||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(o){this.emit("data",o)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(o){this.emit("error",o)}return!0},error:function(o){return!this.isFinished&&(this.isPaused?this.generatedError=o:(this.isFinished=!0,this.emit("error",o),this.previous&&this.previous.error(o),this.cleanUp()),!0)},on:function(o,a){return this._listeners[o].push(a),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(o,a){if(this._listeners[o])for(var l=0;l "+o:o}},i.exports=s},{}],29:[function(e,i,n){var s=e("../utils"),o=e("./ConvertWorker"),a=e("./GenericWorker"),l=e("../base64"),u=e("../support"),c=e("../external"),h=null;if(u.nodestream)try{h=e("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(y,g){return new c.Promise(function(d,m){var _=[],S=y._internalType,E=y._outputType,b=y._mimeType;y.on("data",function(F,x){_.push(F),g&&g(x)}).on("error",function(F){_=[],m(F)}).on("end",function(){try{var F=function(x,z,B){switch(x){case"blob":return s.newBlob(s.transformTo("arraybuffer",z),B);case"base64":return l.encode(z);default:return s.transformTo(x,z)}}(E,function(x,z){var B,tt=0,st=null,I=0;for(B=0;B"u")n.blob=!1;else{var s=new ArrayBuffer(0);try{n.blob=new Blob([s],{type:"application/zip"}).size===0}catch{try{var o=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);o.append(s),n.blob=o.getBlob("application/zip").size===0}catch{n.blob=!1}}}try{n.nodestream=!!e("readable-stream").Readable}catch{n.nodestream=!1}},{"readable-stream":16}],31:[function(e,i,n){for(var s=e("./utils"),o=e("./support"),a=e("./nodejsUtils"),l=e("./stream/GenericWorker"),u=new Array(256),c=0;c<256;c++)u[c]=252<=c?6:248<=c?5:240<=c?4:224<=c?3:192<=c?2:1;u[254]=u[254]=1;function h(){l.call(this,"utf-8 decode"),this.leftOver=null}function p(){l.call(this,"utf-8 encode")}n.utf8encode=function(f){return o.nodebuffer?a.newBufferFrom(f,"utf-8"):function(y){var g,d,m,_,S,E=y.length,b=0;for(_=0;_>>6:(d<65536?g[S++]=224|d>>>12:(g[S++]=240|d>>>18,g[S++]=128|d>>>12&63),g[S++]=128|d>>>6&63),g[S++]=128|63&d);return g}(f)},n.utf8decode=function(f){return o.nodebuffer?s.transformTo("nodebuffer",f).toString("utf-8"):function(y){var g,d,m,_,S=y.length,E=new Array(2*S);for(g=d=0;g>10&1023,E[d++]=56320|1023&m)}return E.length!==d&&(E.subarray?E=E.subarray(0,d):E.length=d),s.applyFromCharCode(E)}(f=s.transformTo(o.uint8array?"uint8array":"array",f))},s.inherits(h,l),h.prototype.processChunk=function(f){var y=s.transformTo(o.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(o.uint8array){var g=y;(y=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),y.set(g,this.leftOver.length)}else y=this.leftOver.concat(y);this.leftOver=null}var d=function(_,S){var E;for((S=S||_.length)>_.length&&(S=_.length),E=S-1;0<=E&&(192&_[E])==128;)E--;return E<0||E===0?S:E+u[_[E]]>S?E:S}(y),m=y;d!==y.length&&(o.uint8array?(m=y.subarray(0,d),this.leftOver=y.subarray(d,y.length)):(m=y.slice(0,d),this.leftOver=y.slice(d,y.length))),this.push({data:n.utf8decode(m),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:n.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},n.Utf8DecodeWorker=h,s.inherits(p,l),p.prototype.processChunk=function(f){this.push({data:n.utf8encode(f.data),meta:f.meta})},n.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,i,n){var s=e("./support"),o=e("./base64"),a=e("./nodejsUtils"),l=e("./external");function u(g){return g}function c(g,d){for(var m=0;m>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=s(this.extraFields[1].value);this.uncompressedSize===o.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===o.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===o.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===o.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var y,g,d,m=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?p[d++]=224|f>>>12:(p[d++]=240|f>>>18,p[d++]=128|f>>>12&63),p[d++]=128|f>>>6&63),p[d++]=128|63&f);return p},n.buf2binstring=function(h){return c(h,h.length)},n.binstring2buf=function(h){for(var p=new s.Buf8(h.length),f=0,y=p.length;f>10&1023,_[y++]=56320|1023&g)}return c(_,y)},n.utf8border=function(h,p){var f;for((p=p||h.length)>h.length&&(p=h.length),f=p-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?p:f+l[h[f]]>p?f:p}},{"./common":41}],43:[function(e,i,n){i.exports=function(s,o,a,l){for(var u=65535&s|0,c=s>>>16&65535|0,h=0;a!==0;){for(a-=h=2e3>>1:o>>>1;a[l]=o}return a}();i.exports=function(o,a,l,u){var c=s,h=u+l;o^=-1;for(var p=u;p>>8^c[255&(o^a[p])];return-1^o}},{}],46:[function(e,i,n){var s,o=e("../utils/common"),a=e("./trees"),l=e("./adler32"),u=e("./crc32"),c=e("./messages"),h=0,p=4,f=0,y=-2,g=-1,d=4,m=2,_=8,S=9,E=286,b=30,F=19,x=2*E+1,z=15,B=3,tt=258,st=tt+B+1,I=42,Z=113,w=1,it=2,M=3,O=4;function D(v,K){return v.msg=c[K],K}function U(v){return(v<<1)-(4v.avail_out&&(q=v.avail_out),q!==0&&(o.arraySet(v.output,K.pending_buf,K.pending_out,q,v.next_out),v.next_out+=q,K.pending_out+=q,v.total_out+=q,v.avail_out-=q,K.pending-=q,K.pending===0&&(K.pending_out=0))}function A(v,K){a._tr_flush_block(v,0<=v.block_start?v.block_start:-1,v.strstart-v.block_start,K),v.block_start=v.strstart,C(v.strm)}function V(v,K){v.pending_buf[v.pending++]=K}function et(v,K){v.pending_buf[v.pending++]=K>>>8&255,v.pending_buf[v.pending++]=255&K}function J(v,K){var q,N,R=v.max_chain_length,Y=v.strstart,ot=v.prev_length,at=v.nice_match,rt=v.strstart>v.w_size-st?v.strstart-(v.w_size-st):0,ht=v.window,bt=v.w_mask,pt=v.prev,Ot=v.strstart+tt,ye=ht[Y+ot-1],oe=ht[Y+ot];v.prev_length>=v.good_match&&(R>>=2),at>v.lookahead&&(at=v.lookahead);do if(ht[(q=K)+ot]===oe&&ht[q+ot-1]===ye&&ht[q]===ht[Y]&&ht[++q]===ht[Y+1]){Y+=2,q++;do;while(ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&ht[++Y]===ht[++q]&&Yrt&&--R!=0);return ot<=v.lookahead?ot:v.lookahead}function yt(v){var K,q,N,R,Y,ot,at,rt,ht,bt,pt=v.w_size;do{if(R=v.window_size-v.lookahead-v.strstart,v.strstart>=pt+(pt-st)){for(o.arraySet(v.window,v.window,pt,pt,0),v.match_start-=pt,v.strstart-=pt,v.block_start-=pt,K=q=v.hash_size;N=v.head[--K],v.head[K]=pt<=N?N-pt:0,--q;);for(K=q=pt;N=v.prev[--K],v.prev[K]=pt<=N?N-pt:0,--q;);R+=pt}if(v.strm.avail_in===0)break;if(ot=v.strm,at=v.window,rt=v.strstart+v.lookahead,ht=R,bt=void 0,bt=ot.avail_in,ht=B)for(Y=v.strstart-v.insert,v.ins_h=v.window[Y],v.ins_h=(v.ins_h<=B&&(v.ins_h=(v.ins_h<=B)if(N=a._tr_tally(v,v.strstart-v.match_start,v.match_length-B),v.lookahead-=v.match_length,v.match_length<=v.max_lazy_match&&v.lookahead>=B){for(v.match_length--;v.strstart++,v.ins_h=(v.ins_h<=B&&(v.ins_h=(v.ins_h<=B&&v.match_length<=v.prev_length){for(R=v.strstart+v.lookahead-B,N=a._tr_tally(v,v.strstart-1-v.prev_match,v.prev_length-B),v.lookahead-=v.prev_length-1,v.prev_length-=2;++v.strstart<=R&&(v.ins_h=(v.ins_h<v.pending_buf_size-5&&(q=v.pending_buf_size-5);;){if(v.lookahead<=1){if(yt(v),v.lookahead===0&&K===h)return w;if(v.lookahead===0)break}v.strstart+=v.lookahead,v.lookahead=0;var N=v.block_start+q;if((v.strstart===0||v.strstart>=N)&&(v.lookahead=v.strstart-N,v.strstart=N,A(v,!1),v.strm.avail_out===0)||v.strstart-v.block_start>=v.w_size-st&&(A(v,!1),v.strm.avail_out===0))return w}return v.insert=0,K===p?(A(v,!0),v.strm.avail_out===0?M:O):(v.strstart>v.block_start&&(A(v,!1),v.strm.avail_out),w)}),new _t(4,4,8,4,vt),new _t(4,5,16,8,vt),new _t(4,6,32,32,vt),new _t(4,4,16,16,dt),new _t(8,16,32,32,dt),new _t(8,16,128,128,dt),new _t(8,32,128,256,dt),new _t(32,128,258,1024,dt),new _t(32,258,258,4096,dt)],n.deflateInit=function(v,K){return he(v,K,_,15,8,0)},n.deflateInit2=he,n.deflateReset=ee,n.deflateResetKeep=Ct,n.deflateSetHeader=function(v,K){return v&&v.state?v.state.wrap!==2?y:(v.state.gzhead=K,f):y},n.deflate=function(v,K){var q,N,R,Y;if(!v||!v.state||5>8&255),V(N,N.gzhead.time>>16&255),V(N,N.gzhead.time>>24&255),V(N,N.level===9?2:2<=N.strategy||N.level<2?4:0),V(N,255&N.gzhead.os),N.gzhead.extra&&N.gzhead.extra.length&&(V(N,255&N.gzhead.extra.length),V(N,N.gzhead.extra.length>>8&255)),N.gzhead.hcrc&&(v.adler=u(v.adler,N.pending_buf,N.pending,0)),N.gzindex=0,N.status=69):(V(N,0),V(N,0),V(N,0),V(N,0),V(N,0),V(N,N.level===9?2:2<=N.strategy||N.level<2?4:0),V(N,3),N.status=Z);else{var ot=_+(N.w_bits-8<<4)<<8;ot|=(2<=N.strategy||N.level<2?0:N.level<6?1:N.level===6?2:3)<<6,N.strstart!==0&&(ot|=32),ot+=31-ot%31,N.status=Z,et(N,ot),N.strstart!==0&&(et(N,v.adler>>>16),et(N,65535&v.adler)),v.adler=1}if(N.status===69)if(N.gzhead.extra){for(R=N.pending;N.gzindex<(65535&N.gzhead.extra.length)&&(N.pending!==N.pending_buf_size||(N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),C(v),R=N.pending,N.pending!==N.pending_buf_size));)V(N,255&N.gzhead.extra[N.gzindex]),N.gzindex++;N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),N.gzindex===N.gzhead.extra.length&&(N.gzindex=0,N.status=73)}else N.status=73;if(N.status===73)if(N.gzhead.name){R=N.pending;do{if(N.pending===N.pending_buf_size&&(N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),C(v),R=N.pending,N.pending===N.pending_buf_size)){Y=1;break}Y=N.gzindexR&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),Y===0&&(N.gzindex=0,N.status=91)}else N.status=91;if(N.status===91)if(N.gzhead.comment){R=N.pending;do{if(N.pending===N.pending_buf_size&&(N.gzhead.hcrc&&N.pending>R&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),C(v),R=N.pending,N.pending===N.pending_buf_size)){Y=1;break}Y=N.gzindexR&&(v.adler=u(v.adler,N.pending_buf,N.pending-R,R)),Y===0&&(N.status=103)}else N.status=103;if(N.status===103&&(N.gzhead.hcrc?(N.pending+2>N.pending_buf_size&&C(v),N.pending+2<=N.pending_buf_size&&(V(N,255&v.adler),V(N,v.adler>>8&255),v.adler=0,N.status=Z)):N.status=Z),N.pending!==0){if(C(v),v.avail_out===0)return N.last_flush=-1,f}else if(v.avail_in===0&&U(K)<=U(q)&&K!==p)return D(v,-5);if(N.status===666&&v.avail_in!==0)return D(v,-5);if(v.avail_in!==0||N.lookahead!==0||K!==h&&N.status!==666){var at=N.strategy===2?function(rt,ht){for(var bt;;){if(rt.lookahead===0&&(yt(rt),rt.lookahead===0)){if(ht===h)return w;break}if(rt.match_length=0,bt=a._tr_tally(rt,0,rt.window[rt.strstart]),rt.lookahead--,rt.strstart++,bt&&(A(rt,!1),rt.strm.avail_out===0))return w}return rt.insert=0,ht===p?(A(rt,!0),rt.strm.avail_out===0?M:O):rt.last_lit&&(A(rt,!1),rt.strm.avail_out===0)?w:it}(N,K):N.strategy===3?function(rt,ht){for(var bt,pt,Ot,ye,oe=rt.window;;){if(rt.lookahead<=tt){if(yt(rt),rt.lookahead<=tt&&ht===h)return w;if(rt.lookahead===0)break}if(rt.match_length=0,rt.lookahead>=B&&0rt.lookahead&&(rt.match_length=rt.lookahead)}if(rt.match_length>=B?(bt=a._tr_tally(rt,1,rt.match_length-B),rt.lookahead-=rt.match_length,rt.strstart+=rt.match_length,rt.match_length=0):(bt=a._tr_tally(rt,0,rt.window[rt.strstart]),rt.lookahead--,rt.strstart++),bt&&(A(rt,!1),rt.strm.avail_out===0))return w}return rt.insert=0,ht===p?(A(rt,!0),rt.strm.avail_out===0?M:O):rt.last_lit&&(A(rt,!1),rt.strm.avail_out===0)?w:it}(N,K):s[N.level].func(N,K);if(at!==M&&at!==O||(N.status=666),at===w||at===M)return v.avail_out===0&&(N.last_flush=-1),f;if(at===it&&(K===1?a._tr_align(N):K!==5&&(a._tr_stored_block(N,0,0,!1),K===3&&(k(N.head),N.lookahead===0&&(N.strstart=0,N.block_start=0,N.insert=0))),C(v),v.avail_out===0))return N.last_flush=-1,f}return K!==p?f:N.wrap<=0?1:(N.wrap===2?(V(N,255&v.adler),V(N,v.adler>>8&255),V(N,v.adler>>16&255),V(N,v.adler>>24&255),V(N,255&v.total_in),V(N,v.total_in>>8&255),V(N,v.total_in>>16&255),V(N,v.total_in>>24&255)):(et(N,v.adler>>>16),et(N,65535&v.adler)),C(v),0=q.w_size&&(Y===0&&(k(q.head),q.strstart=0,q.block_start=0,q.insert=0),ht=new o.Buf8(q.w_size),o.arraySet(ht,K,bt-q.w_size,q.w_size,0),K=ht,bt=q.w_size),ot=v.avail_in,at=v.next_in,rt=v.input,v.avail_in=bt,v.next_in=0,v.input=K,yt(q);q.lookahead>=B;){for(N=q.strstart,R=q.lookahead-(B-1);q.ins_h=(q.ins_h<>>=B=z>>>24,S-=B,(B=z>>>16&255)===0)it[c++]=65535&z;else{if(!(16&B)){if((64&B)==0){z=E[(65535&z)+(_&(1<>>=B,S-=B),S<15&&(_+=w[l++]<>>=B=z>>>24,S-=B,!(16&(B=z>>>16&255))){if((64&B)==0){z=b[(65535&z)+(_&(1<>>=B,S-=B,(B=c-h)>3,_&=(1<<(S-=tt<<3))-1,s.next_in=l,s.next_out=c,s.avail_in=l>>24&255)+(I>>>8&65280)+((65280&I)<<8)+((255&I)<<24)}function _(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function S(I){var Z;return I&&I.state?(Z=I.state,I.total_in=I.total_out=Z.total=0,I.msg="",Z.wrap&&(I.adler=1&Z.wrap),Z.mode=y,Z.last=0,Z.havedict=0,Z.dmax=32768,Z.head=null,Z.hold=0,Z.bits=0,Z.lencode=Z.lendyn=new s.Buf32(g),Z.distcode=Z.distdyn=new s.Buf32(d),Z.sane=1,Z.back=-1,p):f}function E(I){var Z;return I&&I.state?((Z=I.state).wsize=0,Z.whave=0,Z.wnext=0,S(I)):f}function b(I,Z){var w,it;return I&&I.state?(it=I.state,Z<0?(w=0,Z=-Z):(w=1+(Z>>4),Z<48&&(Z&=15)),Z&&(Z<8||15=O.wsize?(s.arraySet(O.window,Z,w-O.wsize,O.wsize,0),O.wnext=0,O.whave=O.wsize):(it<(M=O.wsize-O.wnext)&&(M=it),s.arraySet(O.window,Z,w-it,M,O.wnext),(it-=M)?(s.arraySet(O.window,Z,w-it,it,0),O.wnext=it,O.whave=O.wsize):(O.wnext+=M,O.wnext===O.wsize&&(O.wnext=0),O.whave>>8&255,w.check=a(w.check,Y,2,0),A=C=0,w.mode=2;break}if(w.flags=0,w.head&&(w.head.done=!1),!(1&w.wrap)||(((255&C)<<8)+(C>>8))%31){I.msg="incorrect header check",w.mode=30;break}if((15&C)!=8){I.msg="unknown compression method",w.mode=30;break}if(A-=4,v=8+(15&(C>>>=4)),w.wbits===0)w.wbits=v;else if(v>w.wbits){I.msg="invalid window size",w.mode=30;break}w.dmax=1<>8&1),512&w.flags&&(Y[0]=255&C,Y[1]=C>>>8&255,w.check=a(w.check,Y,2,0)),A=C=0,w.mode=3;case 3:for(;A<32;){if(U===0)break t;U--,C+=it[O++]<>>8&255,Y[2]=C>>>16&255,Y[3]=C>>>24&255,w.check=a(w.check,Y,4,0)),A=C=0,w.mode=4;case 4:for(;A<16;){if(U===0)break t;U--,C+=it[O++]<>8),512&w.flags&&(Y[0]=255&C,Y[1]=C>>>8&255,w.check=a(w.check,Y,2,0)),A=C=0,w.mode=5;case 5:if(1024&w.flags){for(;A<16;){if(U===0)break t;U--,C+=it[O++]<>>8&255,w.check=a(w.check,Y,2,0)),A=C=0}else w.head&&(w.head.extra=null);w.mode=6;case 6:if(1024&w.flags&&(U<(J=w.length)&&(J=U),J&&(w.head&&(v=w.head.extra_len-w.length,w.head.extra||(w.head.extra=new Array(w.head.extra_len)),s.arraySet(w.head.extra,it,O,J,v)),512&w.flags&&(w.check=a(w.check,it,J,O)),U-=J,O+=J,w.length-=J),w.length))break t;w.length=0,w.mode=7;case 7:if(2048&w.flags){if(U===0)break t;for(J=0;v=it[O+J++],w.head&&v&&w.length<65536&&(w.head.name+=String.fromCharCode(v)),v&&J>9&1,w.head.done=!0),I.adler=w.check=0,w.mode=12;break;case 10:for(;A<32;){if(U===0)break t;U--,C+=it[O++]<>>=7&A,A-=7&A,w.mode=27;break}for(;A<3;){if(U===0)break t;U--,C+=it[O++]<>>=1)){case 0:w.mode=14;break;case 1:if(tt(w),w.mode=20,Z!==6)break;C>>>=2,A-=2;break t;case 2:w.mode=17;break;case 3:I.msg="invalid block type",w.mode=30}C>>>=2,A-=2;break;case 14:for(C>>>=7&A,A-=7&A;A<32;){if(U===0)break t;U--,C+=it[O++]<>>16^65535)){I.msg="invalid stored block lengths",w.mode=30;break}if(w.length=65535&C,A=C=0,w.mode=15,Z===6)break t;case 15:w.mode=16;case 16:if(J=w.length){if(U>>=5,A-=5,w.ndist=1+(31&C),C>>>=5,A-=5,w.ncode=4+(15&C),C>>>=4,A-=4,286>>=3,A-=3}for(;w.have<19;)w.lens[ot[w.have++]]=0;if(w.lencode=w.lendyn,w.lenbits=7,q={bits:w.lenbits},K=u(0,w.lens,0,19,w.lencode,0,w.work,q),w.lenbits=q.bits,K){I.msg="invalid code lengths set",w.mode=30;break}w.have=0,w.mode=19;case 19:for(;w.have>>16&255,gt=65535&R,!((dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>>=dt,A-=dt,w.lens[w.have++]=gt;else{if(gt===16){for(N=dt+2;A>>=dt,A-=dt,w.have===0){I.msg="invalid bit length repeat",w.mode=30;break}v=w.lens[w.have-1],J=3+(3&C),C>>>=2,A-=2}else if(gt===17){for(N=dt+3;A>>=dt)),C>>>=3,A-=3}else{for(N=dt+7;A>>=dt)),C>>>=7,A-=7}if(w.have+J>w.nlen+w.ndist){I.msg="invalid bit length repeat",w.mode=30;break}for(;J--;)w.lens[w.have++]=v}}if(w.mode===30)break;if(w.lens[256]===0){I.msg="invalid code -- missing end-of-block",w.mode=30;break}if(w.lenbits=9,q={bits:w.lenbits},K=u(c,w.lens,0,w.nlen,w.lencode,0,w.work,q),w.lenbits=q.bits,K){I.msg="invalid literal/lengths set",w.mode=30;break}if(w.distbits=6,w.distcode=w.distdyn,q={bits:w.distbits},K=u(h,w.lens,w.nlen,w.ndist,w.distcode,0,w.work,q),w.distbits=q.bits,K){I.msg="invalid distances set",w.mode=30;break}if(w.mode=20,Z===6)break t;case 20:w.mode=21;case 21:if(6<=U&&258<=k){I.next_out=D,I.avail_out=k,I.next_in=O,I.avail_in=U,w.hold=C,w.bits=A,l(I,et),D=I.next_out,M=I.output,k=I.avail_out,O=I.next_in,it=I.input,U=I.avail_in,C=w.hold,A=w.bits,w.mode===12&&(w.back=-1);break}for(w.back=0;_t=(R=w.lencode[C&(1<>>16&255,gt=65535&R,!((dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>Ct)])>>>16&255,gt=65535&R,!(Ct+(dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>>=Ct,A-=Ct,w.back+=Ct}if(C>>>=dt,A-=dt,w.back+=dt,w.length=gt,_t===0){w.mode=26;break}if(32&_t){w.back=-1,w.mode=12;break}if(64&_t){I.msg="invalid literal/length code",w.mode=30;break}w.extra=15&_t,w.mode=22;case 22:if(w.extra){for(N=w.extra;A>>=w.extra,A-=w.extra,w.back+=w.extra}w.was=w.length,w.mode=23;case 23:for(;_t=(R=w.distcode[C&(1<>>16&255,gt=65535&R,!((dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>Ct)])>>>16&255,gt=65535&R,!(Ct+(dt=R>>>24)<=A);){if(U===0)break t;U--,C+=it[O++]<>>=Ct,A-=Ct,w.back+=Ct}if(C>>>=dt,A-=dt,w.back+=dt,64&_t){I.msg="invalid distance code",w.mode=30;break}w.offset=gt,w.extra=15&_t,w.mode=24;case 24:if(w.extra){for(N=w.extra;A>>=w.extra,A-=w.extra,w.back+=w.extra}if(w.offset>w.dmax){I.msg="invalid distance too far back",w.mode=30;break}w.mode=25;case 25:if(k===0)break t;if(J=et-k,w.offset>J){if((J=w.offset-J)>w.whave&&w.sane){I.msg="invalid distance too far back",w.mode=30;break}yt=J>w.wnext?(J-=w.wnext,w.wsize-J):w.wnext-J,J>w.length&&(J=w.length),vt=w.window}else vt=M,yt=D-w.offset,J=w.length;for(kx?(B=yt[vt+d[Z]],A[V+d[Z]]):(B=96,0),_=1<>D)+(S-=_)]=z<<24|B<<16|tt|0,S!==0;);for(_=1<>=1;if(_!==0?(C&=_-1,C+=_):C=0,Z++,--et[I]==0){if(I===it)break;I=h[p+d[Z]]}if(M>>7)]}function V(R,Y){R.pending_buf[R.pending++]=255&Y,R.pending_buf[R.pending++]=Y>>>8&255}function et(R,Y,ot){R.bi_valid>m-ot?(R.bi_buf|=Y<>m-R.bi_valid,R.bi_valid+=ot-m):(R.bi_buf|=Y<>>=1,ot<<=1,0<--Y;);return ot>>>1}function vt(R,Y,ot){var at,rt,ht=new Array(d+1),bt=0;for(at=1;at<=d;at++)ht[at]=bt=bt+ot[at-1]<<1;for(rt=0;rt<=Y;rt++){var pt=R[2*rt+1];pt!==0&&(R[2*rt]=yt(ht[pt]++,pt))}}function dt(R){var Y;for(Y=0;Y>1;1<=ot;ot--)Ct(R,ht,ot);for(rt=Ot;ot=R.heap[1],R.heap[1]=R.heap[R.heap_len--],Ct(R,ht,1),at=R.heap[1],R.heap[--R.heap_max]=ot,R.heap[--R.heap_max]=at,ht[2*rt]=ht[2*ot]+ht[2*at],R.depth[rt]=(R.depth[ot]>=R.depth[at]?R.depth[ot]:R.depth[at])+1,ht[2*ot+1]=ht[2*at+1]=rt,R.heap[1]=rt++,Ct(R,ht,1),2<=R.heap_len;);R.heap[--R.heap_max]=R.heap[1],function(oe,ir){var Ki,vr,Zi,Ae,Ji,ao,Qr=ir.dyn_tree,fs=ir.max_code,ma=ir.stat_desc.static_tree,hu=ir.stat_desc.has_stree,si=ir.stat_desc.extra_bits,ya=ir.stat_desc.extra_base,In=ir.stat_desc.max_length,En=0;for(Ae=0;Ae<=d;Ae++)oe.bl_count[Ae]=0;for(Qr[2*oe.heap[oe.heap_max]+1]=0,Ki=oe.heap_max+1;Ki>=7;rt>>=1)if(1&ye&&pt.dyn_ltree[2*Ot]!==0)return o;if(pt.dyn_ltree[18]!==0||pt.dyn_ltree[20]!==0||pt.dyn_ltree[26]!==0)return a;for(Ot=32;Ot>>3,(ht=R.static_len+3+7>>>3)<=rt&&(rt=ht)):rt=ht=ot+5,ot+4<=rt&&Y!==-1?N(R,Y,ot,at):R.strategy===4||ht===rt?(et(R,2+(at?1:0),3),ee(R,st,I)):(et(R,4+(at?1:0),3),function(pt,Ot,ye,oe){var ir;for(et(pt,Ot-257,5),et(pt,ye-1,5),et(pt,oe-4,4),ir=0;ir>>8&255,R.pending_buf[R.d_buf+2*R.last_lit+1]=255&Y,R.pending_buf[R.l_buf+R.last_lit]=255&ot,R.last_lit++,Y===0?R.dyn_ltree[2*ot]++:(R.matches++,Y--,R.dyn_ltree[2*(w[ot]+h+1)]++,R.dyn_dtree[2*A(Y)]++),R.last_lit===R.lit_bufsize-1},n._tr_align=function(R){et(R,2,3),J(R,S,st),function(Y){Y.bi_valid===16?(V(Y,Y.bi_buf),Y.bi_buf=0,Y.bi_valid=0):8<=Y.bi_valid&&(Y.pending_buf[Y.pending++]=255&Y.bi_buf,Y.bi_buf>>=8,Y.bi_valid-=8)}(R)}},{"../utils/common":41}],53:[function(e,i,n){i.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,i,n){(function(s){(function(o,a){if(!o.setImmediate){var l,u,c,h,p=1,f={},y=!1,g=o.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(o);d=d&&d.setTimeout?d:o,l={}.toString.call(o.process)==="[object process]"?function(E){process.nextTick(function(){_(E)})}:function(){if(o.postMessage&&!o.importScripts){var E=!0,b=o.onmessage;return o.onmessage=function(){E=!1},o.postMessage("","*"),o.onmessage=b,E}}()?(h="setImmediate$"+Math.random()+"$",o.addEventListener?o.addEventListener("message",S,!1):o.attachEvent("onmessage",S),function(E){o.postMessage(h+E,"*")}):o.MessageChannel?((c=new MessageChannel).port1.onmessage=function(E){_(E.data)},function(E){c.port2.postMessage(E)}):g&&"onreadystatechange"in g.createElement("script")?(u=g.documentElement,function(E){var b=g.createElement("script");b.onreadystatechange=function(){_(E),b.onreadystatechange=null,u.removeChild(b),b=null},u.appendChild(b)}):function(E){setTimeout(_,0,E)},d.setImmediate=function(E){typeof E!="function"&&(E=new Function(""+E));for(var b=new Array(arguments.length-1),F=0;F"u"?s===void 0?this:s:self)}).call(this,typeof gi<"u"?gi:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})}(Gu)),Gu.exports}var dC=fC();const pC=Nh(dC);Ai.zipReader=(r,t)=>pC.loadAsync(r);const mC=Ai.createSettings;Ai.createSettings=async r=>{const t=Object.keys(r.files);return t.find(e=>yC(e))?mC(r):_C(t)};function yC(r){return r.endsWith("model3.json")}function gC(r){return r.endsWith(".moc3")}function vC(r){return r.split(/[\\/]/).pop()}function _C(r){const t=r.filter(u=>gC(u));if(t.length!==1){const u=t.length?`(${t.map(c=>`"${c}"`).join(",")})`:"";throw new Error(`Expected exactly one moc file, got ${t.length} ${u}`)}const e=t[0],i=vC(e).replace(/\.moc3?/,""),n=r.filter(u=>u.endsWith(".png"));if(!n.length)throw new Error("Textures not found");const s=r.filter(u=>u.endsWith(".mtn")||u.endsWith(".motion3.json")),o=r.find(u=>u.includes("physics")),a=r.find(u=>u.includes("pose")),l=new Jn({url:`${i}.model3.json`,Version:3,FileReferences:{Moc:e,Textures:n,Physics:o,Pose:a,Motions:s.length?{"":s.map(u=>({File:u}))}:void 0}});return l.name=i,l._objectURL=`example://${l.url}`,l}Ai.readText=(r,t)=>{const e=r.file(t);if(!e)throw new Error(`Cannot find file: ${t}`);return e.async("text")};Ai.getFilePaths=r=>{const t=[];return r.forEach(e=>t.push(e)),Promise.resolve(t)};Ai.getFiles=(r,t)=>Promise.all(t.map(async e=>{const i=e.slice(e.lastIndexOf("/")+1),n=await r.file(e).async("blob");return new File([n],i)}));function Zt(r,t,e,i){function n(s){return s instanceof e?s:new e(function(o){o(s)})}return new(e||(e=Promise))(function(s,o){function a(c){try{u(i.next(c))}catch(h){o(h)}}function l(c){try{u(i.throw(c))}catch(h){o(h)}}function u(c){c.done?s(c.value):n(c.value).then(a,l)}u((i=i.apply(r,t||[])).next())})}function up(r){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&r[t],i=0;if(e)return e.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&i>=r.length&&(r=void 0),{value:r&&r[i++],done:!r}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Pt(r){return this instanceof Pt?(this.v=r,this):new Pt(r)}function dr(r,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=e.apply(r,t||[]),n,s=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(f){return function(y){return Promise.resolve(y).then(f,h)}}function a(f,y){i[f]&&(n[f]=function(g){return new Promise(function(d,m){s.push([f,g,d,m])>1||l(f,g)})},y&&(n[f]=y(n[f])))}function l(f,y){try{u(i[f](y))}catch(g){p(s[0][3],g)}}function u(f){f.value instanceof Pt?Promise.resolve(f.value.v).then(c,h):p(s[0][2],f)}function c(f){l("next",f)}function h(f){l("throw",f)}function p(f,y){f(y),s.shift(),s.length&&l(s[0][0],s[0][1])}}function ts(r){var t,e;return t={},i("next"),i("throw",function(n){throw n}),i("return"),t[Symbol.iterator]=function(){return this},t;function i(n,s){t[n]=r[n]?function(o){return(e=!e)?{value:Pt(r[n](o)),done:!1}:s?s(o):o}:s}}function bi(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 up=="function"?up(r):r[Symbol.iterator](),e={},i("next"),i("throw"),i("return"),e[Symbol.asyncIterator]=function(){return this},e);function i(s){e[s]=r[s]&&function(o){return new Promise(function(a,l){o=r[s](o),n(a,l,o.done,o.value)})}}function n(s,o,a,l){Promise.resolve(l).then(function(u){s({value:u,done:a})},o)}}const bC=new TextDecoder("utf-8"),eh=r=>bC.decode(r),wC=new TextEncoder,ef=r=>wC.encode(r),xC=r=>typeof r=="number",_v=r=>typeof r=="boolean",Ge=r=>typeof r=="function",pr=r=>r!=null&&Object(r)===r,rs=r=>pr(r)&&Ge(r.then),oa=r=>pr(r)&&Ge(r[Symbol.iterator]),no=r=>pr(r)&&Ge(r[Symbol.asyncIterator]),rh=r=>pr(r)&&pr(r.schema),bv=r=>pr(r)&&"done"in r&&"value"in r,wv=r=>pr(r)&&Ge(r.stat)&&xC(r.fd),xv=r=>pr(r)&&rf(r.body),tu=r=>"_getDOMStream"in r&&"_getNodeStream"in r,SC=r=>pr(r)&&Ge(r.abort)&&Ge(r.getWriter)&&!tu(r),rf=r=>pr(r)&&Ge(r.cancel)&&Ge(r.getReader)&&!tu(r),TC=r=>pr(r)&&Ge(r.end)&&Ge(r.write)&&_v(r.writable)&&!tu(r),Sv=r=>pr(r)&&Ge(r.read)&&Ge(r.pipe)&&_v(r.readable)&&!tu(r),IC=r=>pr(r)&&Ge(r.clear)&&Ge(r.bytes)&&Ge(r.position)&&Ge(r.setPosition)&&Ge(r.capacity)&&Ge(r.getBufferIdentifier)&&Ge(r.createLong),nf=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function EC(r){const t=r[0]?[r[0]]:[];let e,i,n,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let n,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,i);for(const c=e.length;++l_e(Int32Array,r),hp=r=>_e(BigInt64Array,r),ae=r=>_e(Uint8Array,r),ih=r=>(r.next(),r);function*CC(r,t){const e=function*(n){yield n},i=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof nf?e(t):oa(t)?t:e(t);return yield*ih(function*(n){let s=null;do s=n.next(yield _e(r,s));while(!s.done)}(i[Symbol.iterator]())),new r}const AC=r=>CC(Uint8Array,r);function Tv(r,t){return dr(this,arguments,function*(){if(rs(t))return yield Pt(yield Pt(yield*ts(bi(Tv(r,yield Pt(t))))));const i=function(o){return dr(this,arguments,function*(){yield yield Pt(yield Pt(o))})},n=function(o){return dr(this,arguments,function*(){yield Pt(yield*ts(bi(ih(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 nf?i(t):oa(t)?n(t):no(t)?t:i(t);return yield Pt(yield*ts(bi(ih(function(o){return dr(this,arguments,function*(){let a=null;do a=yield Pt(o.next(yield yield Pt(_e(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Pt(new r)})}const OC=r=>Tv(Uint8Array,r);function Iv(r,t,e){if(r!==0){e=e.slice(0,t);for(let i=-1,n=e.length;++i0)do if(r[e]!==t[e])return!1;while(++e(r.next(),r);function*PC(r){let t,e=!1,i=[],n,s,o,a=0;function l(){return s==="peek"?xi(i,o)[0]:([n,i,a]=xi(i,o),n)}({cmd:s,size:o}=(yield null)||{cmd:"read",size:0});const u=AC(r)[Symbol.iterator]();try{do if({done:t,value:n}=Number.isNaN(o-a)?u.next():u.next(o-a),!t&&n.byteLength>0&&(i.push(n),a+=n.byteLength),t||o<=a)do({cmd:s,size:o}=yield l());while(o0&&(n.push(s),l+=s.byteLength),e||a<=l)do({cmd:o,size:a}=yield yield Pt(u()));while(a0&&(n.push(ae(s)),l+=s.byteLength),e||a<=l)do({cmd:o,size:a}=yield yield Pt(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 Zt(this,void 0,void 0,function*(){const{reader:e,source:i}=this;e&&(yield e.cancel(t).catch(()=>{})),i&&i.locked&&this.releaseLock()})}read(t){return Zt(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=ae(e)),e})}}const Wu=(r,t)=>{const e=n=>i([t,n]);let i;return[t,e,new Promise(n=>(i=n)&&r.once(t,e))]};function NC(r){return dr(this,arguments,function*(){const e=[];let i="error",n=!1,s=null,o,a,l=0,u=[],c;function h(){return o==="peek"?xi(u,a)[0]:([c,u,l]=xi(u,a),c)}if({cmd:o,size:a}=(yield yield Pt(null))||{cmd:"read",size:0},r.isTTY)return yield yield Pt(new Uint8Array(0)),yield Pt(null);try{e[0]=Wu(r,"end"),e[1]=Wu(r,"error");do{if(e[2]=Wu(r,"readable"),[i,s]=yield Pt(Promise.race(e.map(f=>f[2]))),i==="error")break;if((n=i==="end")||(Number.isFinite(a-l)?(c=ae(r.read(a-l)),c.byteLength0&&(u.push(c),l+=c.byteLength)),n||a<=l)do({cmd:o,size:a}=yield yield Pt(h()));while(a{for(const[m,_]of f)r.off(m,_);try{const m=r.destroy;m&&m.call(r,y),y=void 0}catch(m){y=m||y}finally{y!=null?d(y):g()}})}})}var ke;(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"})(ke||(ke={}));var er;(function(r){r[r.Sparse=0]="Sparse",r[r.Dense=1]="Dense"})(er||(er={}));var tr;(function(r){r[r.HALF=0]="HALF",r[r.SINGLE=1]="SINGLE",r[r.DOUBLE=2]="DOUBLE"})(tr||(tr={}));var Hr;(function(r){r[r.DAY=0]="DAY",r[r.MILLISECOND=1]="MILLISECOND"})(Hr||(Hr={}));var zt;(function(r){r[r.SECOND=0]="SECOND",r[r.MILLISECOND=1]="MILLISECOND",r[r.MICROSECOND=2]="MICROSECOND",r[r.NANOSECOND=3]="NANOSECOND"})(zt||(zt={}));var Si;(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"})(Si||(Si={}));const Hu=2,pi=4,ji=4,me=4,on=new Int32Array(2),fp=new Float32Array(on.buffer),dp=new Float64Array(on.buffer),Na=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var nh;(function(r){r[r.UTF8_BYTES=1]="UTF8_BYTES",r[r.UTF16_STRING=2]="UTF16_STRING"})(nh||(nh={}));let Qs=class Ev{constructor(t){this.bytes_=t,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(t){return new Ev(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){fp[0]=e,this.writeInt32(t,on[0])}writeFloat64(t,e){dp[0]=e,this.writeInt32(t,on[Na?0:1]),this.writeInt32(t+4,on[Na?1:0])}getBufferIdentifier(){if(this.bytes_.lengththis.minalign&&(this.minalign=t);const i=~(this.bb.capacity()-this.space+e)+1&t-1;for(;this.space=0&&this.vtable[e]==0;e--);const i=e+1;for(;e>=0;e--)this.addInt16(this.vtable[e]!=0?t-this.vtable[e]:0);const n=2;this.addInt16(t-this.object_start);const s=(i+n)*Hu;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,pi+n),this.addOffset(t),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(t,e){this.finish(t,e,!0)}requiredField(t,e){const i=this.bb.capacity()-t,n=i-this.bb.readInt32(i);if(!(e=0;i--)t.addInt32(e[i]);return t.endVector()}static startTypeIdsVector(t,e){t.startVector(4,e,4)}static endUnion(t){return t.endObject()}static createUnion(t,e,i){return hr.startUnion(t),hr.addMode(t,e),hr.addTypeIds(t,i),hr.endUnion(t)}}let bp=class Fo{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 Fo).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsUtf8(t,e){return t.setPosition(t.position()+me),(e||new Fo).__init(t.readInt32(t.position())+t.position(),t)}static startUtf8(t){t.startObject(0)}static endUtf8(t){return t.endObject()}static createUtf8(t){return Fo.startUtf8(t),Fo.endUtf8(t)}};var xe;(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"})(xe||(xe={}));let Nr=class Ga{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 Ga).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsField(t,e){return t.setPosition(t.position()+me),(e||new Ga).__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):xe.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 $i).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}children(t,e){const i=this.bb.__offset(this.bb_pos,14);return i?(e||new Ga).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,16);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,xe.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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);return t.endVector()}static startCustomMetadataVector(t,e){t.startVector(4,e,4)}static endField(t){return t.endObject()}},ui=class Mi{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 Mi).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSchema(t,e){return t.setPosition(t.position()+me),(e||new Mi).__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):Ks.Little}fields(t,e){const i=this.bb.__offset(this.bb_pos,6);return i?(e||new Nr).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,8);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,Ks.Little)}static addFields(t,e){t.addFieldOffset(1,e,0)}static createFieldsVector(t,e){t.startVector(4,e.length,4);for(let i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 i=e.length-1;i>=0;i--)t.addInt64(e[i]);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,i,n,s){return Mi.startSchema(t),Mi.addEndianness(t,e),Mi.addFields(t,i),Mi.addCustomMetadata(t,n),Mi.addFeatures(t,s),Mi.endSchema(t)}};var fe;(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"})(fe||(fe={}));var L;(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"})(L||(L={}));var ki;(function(r){r[r.OFFSET=0]="OFFSET",r[r.DATA=1]="DATA",r[r.VALIDITY=2]="VALIDITY",r[r.TYPE=3]="TYPE"})(ki||(ki={}));const LC=void 0;function Xo(r){if(r===null)return"null";if(r===LC)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=>Xo(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}function we(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 Pv(r,t){return we(r/t)+we(r%t)/we(t)}const BC=Symbol.for("isArrowBigNum");function ri(r,...t){return t.length===0?Object.setPrototypeOf(_e(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}ri.prototype[BC]=!0;ri.prototype.toJSON=function(){return`"${qo(this)}"`};ri.prototype.valueOf=function(r){return Mv(this,r)};ri.prototype.toString=function(){return qo(this)};ri.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Mv(this);case"string":return qo(this);case"default":return zC(this)}return qo(this)};function zs(...r){return ri.apply(this,r)}function js(...r){return ri.apply(this,r)}function Yo(...r){return ri.apply(this,r)}Object.setPrototypeOf(zs.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(js.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Yo.prototype,Object.create(Uint32Array.prototype));Object.assign(zs.prototype,ri.prototype,{constructor:zs,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(js.prototype,ri.prototype,{constructor:js,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Yo.prototype,ri.prototype,{constructor:Yo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const kC=BigInt(4294967296)*BigInt(4294967296),UC=kC-BigInt(1);function Mv(r,t){const{buffer:e,byteOffset:i,byteLength:n,signed:s}=r,o=new BigUint64Array(e,i,n/8),a=s&&o.at(-1)&BigInt(1)<=0)return Xu(r);t=t.slice();let i=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(At.prototype);let pn=class extends At{constructor(){super(L.Null)}toString(){return"Null"}};Nv=Symbol.toStringTag;pn[Nv]=(r=>r[Symbol.toStringTag]="Null")(pn.prototype);let is=class extends At{constructor(t,e){super(L.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}`}};Lv=Symbol.toStringTag;is[Lv]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))(is.prototype);class Qo extends is{constructor(){super(!0,32)}get ArrayType(){return Int32Array}}Object.defineProperty(Qo.prototype,"ArrayType",{value:Int32Array});let cl=class extends At{constructor(t){super(L.Float),this.precision=t}get ArrayType(){switch(this.precision){case tr.HALF:return Uint16Array;case tr.SINGLE:return Float32Array;case tr.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}};Bv=Symbol.toStringTag;cl[Bv]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(cl.prototype);let hl=class extends At{constructor(){super(L.Binary)}toString(){return"Binary"}};kv=Symbol.toStringTag;hl[kv]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(hl.prototype);let fl=class extends At{constructor(){super(L.LargeBinary)}toString(){return"LargeBinary"}};Uv=Symbol.toStringTag;fl[Uv]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(fl.prototype);let dl=class extends At{constructor(){super(L.Utf8)}toString(){return"Utf8"}};zv=Symbol.toStringTag;dl[zv]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(dl.prototype);let pl=class extends At{constructor(){super(L.LargeUtf8)}toString(){return"LargeUtf8"}};jv=Symbol.toStringTag;pl[jv]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(pl.prototype);let ml=class extends At{constructor(){super(L.Bool)}toString(){return"Bool"}};$v=Symbol.toStringTag;ml[$v]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(ml.prototype);let yl=class extends At{constructor(t,e,i=128){super(L.Decimal),this.scale=t,this.precision=e,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}};Vv=Symbol.toStringTag;yl[Vv]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(yl.prototype);let gl=class extends At{constructor(t){super(L.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${Hr[this.unit]}>`}get ArrayType(){return this.unit===Hr.DAY?Int32Array:BigInt64Array}};Gv=Symbol.toStringTag;gl[Gv]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(gl.prototype);let vl=class extends At{constructor(t,e){super(L.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${zt[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}};Wv=Symbol.toStringTag;vl[Wv]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(vl.prototype);let _l=class extends At{constructor(t,e){super(L.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${zt[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}};Hv=Symbol.toStringTag;_l[Hv]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(_l.prototype);let bl=class extends At{constructor(t){super(L.Interval),this.unit=t}toString(){return`Interval<${Si[this.unit]}>`}};Xv=Symbol.toStringTag;bl[Xv]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(bl.prototype);let wl=class extends At{constructor(t){super(L.Duration),this.unit=t}toString(){return`Duration<${zt[this.unit]}>`}};Yv=Symbol.toStringTag;wl[Yv]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(wl.prototype);let xl=class extends At{constructor(t){super(L.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}};qv=Symbol.toStringTag;xl[qv]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(xl.prototype);let sr=class extends At{constructor(t){super(L.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}};Qv=Symbol.toStringTag;sr[Qv]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(sr.prototype);let Sl=class extends At{constructor(t,e,i){super(L.Union),this.mode=t,this.children=i,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((n,s,o)=>(n[s]=o)&&n||n,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}};Kv=Symbol.toStringTag;Sl[Kv]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))(Sl.prototype);let Tl=class extends At{constructor(t){super(L.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}};Zv=Symbol.toStringTag;Tl[Zv]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(Tl.prototype);let Il=class extends At{constructor(t,e){super(L.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}>`}};Jv=Symbol.toStringTag;Il[Jv]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(Il.prototype);let El=class extends At{constructor(t,e=!1){var i,n,s;if(super(L.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((i=t==null?void 0:t.type)===null||i===void 0)&&i.children)){const o=(n=t==null?void 0:t.type)===null||n===void 0?void 0:n.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(", ")}}>`}};t_=Symbol.toStringTag;El[t_]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(El.prototype);const $C=(r=>()=>++r)(-1);let Zs=class extends At{constructor(t,e,i,n){super(L.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=n||!1,this.id=i==null?$C():we(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}};e_=Symbol.toStringTag;Zs[e_]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(Zs.prototype);function Ui(r){const t=r;switch(r.typeId){case L.Decimal:return r.bitWidth/32;case L.Interval:return 1+t.unit;case L.FixedSizeList:return t.listSize;case L.FixedSizeBinary:return t.byteWidth;default:return 1}}let ie=class{visitMany(t,...e){return t.map((i,n)=>this.visit(i,...e.map(s=>s[n])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return VC(this,t,e)}getVisitFnByTypeId(t,e=!0){return As(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 VC(r,t,e=!0){return typeof t=="number"?As(r,t,e):typeof t=="string"&&t in L?As(r,L[t],e):t&&t instanceof At?As(r,wp(t),e):t!=null&&t.type&&t.type instanceof At?As(r,wp(t.type),e):As(r,L.NONE,e)}function As(r,t,e=!0){let i=null;switch(t){case L.Null:i=r.visitNull;break;case L.Bool:i=r.visitBool;break;case L.Int:i=r.visitInt;break;case L.Int8:i=r.visitInt8||r.visitInt;break;case L.Int16:i=r.visitInt16||r.visitInt;break;case L.Int32:i=r.visitInt32||r.visitInt;break;case L.Int64:i=r.visitInt64||r.visitInt;break;case L.Uint8:i=r.visitUint8||r.visitInt;break;case L.Uint16:i=r.visitUint16||r.visitInt;break;case L.Uint32:i=r.visitUint32||r.visitInt;break;case L.Uint64:i=r.visitUint64||r.visitInt;break;case L.Float:i=r.visitFloat;break;case L.Float16:i=r.visitFloat16||r.visitFloat;break;case L.Float32:i=r.visitFloat32||r.visitFloat;break;case L.Float64:i=r.visitFloat64||r.visitFloat;break;case L.Utf8:i=r.visitUtf8;break;case L.LargeUtf8:i=r.visitLargeUtf8;break;case L.Binary:i=r.visitBinary;break;case L.LargeBinary:i=r.visitLargeBinary;break;case L.FixedSizeBinary:i=r.visitFixedSizeBinary;break;case L.Date:i=r.visitDate;break;case L.DateDay:i=r.visitDateDay||r.visitDate;break;case L.DateMillisecond:i=r.visitDateMillisecond||r.visitDate;break;case L.Timestamp:i=r.visitTimestamp;break;case L.TimestampSecond:i=r.visitTimestampSecond||r.visitTimestamp;break;case L.TimestampMillisecond:i=r.visitTimestampMillisecond||r.visitTimestamp;break;case L.TimestampMicrosecond:i=r.visitTimestampMicrosecond||r.visitTimestamp;break;case L.TimestampNanosecond:i=r.visitTimestampNanosecond||r.visitTimestamp;break;case L.Time:i=r.visitTime;break;case L.TimeSecond:i=r.visitTimeSecond||r.visitTime;break;case L.TimeMillisecond:i=r.visitTimeMillisecond||r.visitTime;break;case L.TimeMicrosecond:i=r.visitTimeMicrosecond||r.visitTime;break;case L.TimeNanosecond:i=r.visitTimeNanosecond||r.visitTime;break;case L.Decimal:i=r.visitDecimal;break;case L.List:i=r.visitList;break;case L.Struct:i=r.visitStruct;break;case L.Union:i=r.visitUnion;break;case L.DenseUnion:i=r.visitDenseUnion||r.visitUnion;break;case L.SparseUnion:i=r.visitSparseUnion||r.visitUnion;break;case L.Dictionary:i=r.visitDictionary;break;case L.Interval:i=r.visitInterval;break;case L.IntervalDayTime:i=r.visitIntervalDayTime||r.visitInterval;break;case L.IntervalYearMonth:i=r.visitIntervalYearMonth||r.visitInterval;break;case L.Duration:i=r.visitDuration;break;case L.DurationSecond:i=r.visitDurationSecond||r.visitDuration;break;case L.DurationMillisecond:i=r.visitDurationMillisecond||r.visitDuration;break;case L.DurationMicrosecond:i=r.visitDurationMicrosecond||r.visitDuration;break;case L.DurationNanosecond:i=r.visitDurationNanosecond||r.visitDuration;break;case L.FixedSizeList:i=r.visitFixedSizeList;break;case L.Map:i=r.visitMap;break}if(typeof i=="function")return i;if(!e)return()=>null;throw new Error(`Unrecognized type '${L[t]}'`)}function wp(r){switch(r.typeId){case L.Null:return L.Null;case L.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?L.Int8:L.Uint8;case 16:return e?L.Int16:L.Uint16;case 32:return e?L.Int32:L.Uint32;case 64:return e?L.Int64:L.Uint64}return L.Int}case L.Float:switch(r.precision){case tr.HALF:return L.Float16;case tr.SINGLE:return L.Float32;case tr.DOUBLE:return L.Float64}return L.Float;case L.Binary:return L.Binary;case L.LargeBinary:return L.LargeBinary;case L.Utf8:return L.Utf8;case L.LargeUtf8:return L.LargeUtf8;case L.Bool:return L.Bool;case L.Decimal:return L.Decimal;case L.Time:switch(r.unit){case zt.SECOND:return L.TimeSecond;case zt.MILLISECOND:return L.TimeMillisecond;case zt.MICROSECOND:return L.TimeMicrosecond;case zt.NANOSECOND:return L.TimeNanosecond}return L.Time;case L.Timestamp:switch(r.unit){case zt.SECOND:return L.TimestampSecond;case zt.MILLISECOND:return L.TimestampMillisecond;case zt.MICROSECOND:return L.TimestampMicrosecond;case zt.NANOSECOND:return L.TimestampNanosecond}return L.Timestamp;case L.Date:switch(r.unit){case Hr.DAY:return L.DateDay;case Hr.MILLISECOND:return L.DateMillisecond}return L.Date;case L.Interval:switch(r.unit){case Si.DAY_TIME:return L.IntervalDayTime;case Si.YEAR_MONTH:return L.IntervalYearMonth}return L.Interval;case L.Duration:switch(r.unit){case zt.SECOND:return L.DurationSecond;case zt.MILLISECOND:return L.DurationMillisecond;case zt.MICROSECOND:return L.DurationMicrosecond;case zt.NANOSECOND:return L.DurationNanosecond}return L.Duration;case L.Map:return L.Map;case L.List:return L.List;case L.Struct:return L.Struct;case L.Union:switch(r.mode){case er.Dense:return L.DenseUnion;case er.Sparse:return L.SparseUnion}return L.Union;case L.FixedSizeBinary:return L.FixedSizeBinary;case L.FixedSizeList:return L.FixedSizeList;case L.Dictionary:return L.Dictionary}throw new Error(`Unrecognized type '${L[r.typeId]}'`)}ie.prototype.visitInt8=null;ie.prototype.visitInt16=null;ie.prototype.visitInt32=null;ie.prototype.visitInt64=null;ie.prototype.visitUint8=null;ie.prototype.visitUint16=null;ie.prototype.visitUint32=null;ie.prototype.visitUint64=null;ie.prototype.visitFloat16=null;ie.prototype.visitFloat32=null;ie.prototype.visitFloat64=null;ie.prototype.visitDateDay=null;ie.prototype.visitDateMillisecond=null;ie.prototype.visitTimestampSecond=null;ie.prototype.visitTimestampMillisecond=null;ie.prototype.visitTimestampMicrosecond=null;ie.prototype.visitTimestampNanosecond=null;ie.prototype.visitTimeSecond=null;ie.prototype.visitTimeMillisecond=null;ie.prototype.visitTimeMicrosecond=null;ie.prototype.visitTimeNanosecond=null;ie.prototype.visitDenseUnion=null;ie.prototype.visitSparseUnion=null;ie.prototype.visitIntervalDayTime=null;ie.prototype.visitIntervalYearMonth=null;ie.prototype.visitDuration=null;ie.prototype.visitDurationSecond=null;ie.prototype.visitDurationMillisecond=null;ie.prototype.visitDurationMicrosecond=null;ie.prototype.visitDurationNanosecond=null;const r_=new Float64Array(1),gs=new Uint32Array(r_.buffer);function i_(r){const t=(r&31744)>>10,e=(r&1023)/1024,i=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return i*(e?Number.NaN:1/0);case 0:return i*(e?6103515625e-14*e:0)}return i*Math.pow(2,t-15)*(1+e)}function GC(r){if(r!==r)return 32256;r_[0]=r;const t=(gs[1]&2147483648)>>16&65535;let e=gs[1]&2146435072,i=0;return e>=1089470464?gs[0]>0?e=31744:(e=(e&2080374784)>>16,i=(gs[1]&1048575)>>10):e<=1056964608?(i=1048576+(gs[1]&1048575),i=1048576+(i<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,i=(gs[1]&1048575)+512>>10),t|e|i&65535}let jt=class extends ie{};function Xt(r){return(t,e,i)=>{if(t.setValid(e,i!=null))return r(t,e,i)}}const WC=(r,t,e)=>{r[t]=Math.floor(e/864e5)},n_=(r,t,e,i)=>{if(e+1{const n=r+e;i?t[n>>3]|=1<>3]&=~(1<{r[t]=e},sf=({values:r},t,e)=>{r[t]=e},s_=({values:r},t,e)=>{r[t]=GC(e)},XC=(r,t,e)=>{switch(r.type.precision){case tr.HALF:return s_(r,t,e);case tr.SINGLE:case tr.DOUBLE:return sf(r,t,e)}},o_=({values:r},t,e)=>{WC(r,t,e.valueOf())},a_=({values:r},t,e)=>{r[t]=BigInt(e)},YC=({stride:r,values:t},e,i)=>{t.set(i.subarray(0,r),r*e)},l_=({values:r,valueOffsets:t},e,i)=>n_(r,t,e,i),u_=({values:r,valueOffsets:t},e,i)=>n_(r,t,e,ef(i)),qC=(r,t,e)=>{r.type.unit===Hr.DAY?o_(r,t,e):a_(r,t,e)},c_=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},h_=({values:r},t,e)=>{r[t]=BigInt(e)},f_=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},d_=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},QC=(r,t,e)=>{switch(r.type.unit){case zt.SECOND:return c_(r,t,e);case zt.MILLISECOND:return h_(r,t,e);case zt.MICROSECOND:return f_(r,t,e);case zt.NANOSECOND:return d_(r,t,e)}},p_=({values:r},t,e)=>{r[t]=e},m_=({values:r},t,e)=>{r[t]=e},y_=({values:r},t,e)=>{r[t]=e},g_=({values:r},t,e)=>{r[t]=e},KC=(r,t,e)=>{switch(r.type.unit){case zt.SECOND:return p_(r,t,e);case zt.MILLISECOND:return m_(r,t,e);case zt.MICROSECOND:return y_(r,t,e);case zt.NANOSECOND:return g_(r,t,e)}},ZC=({values:r,stride:t},e,i)=>{r.set(i.subarray(0,t),t*e)},JC=(r,t,e)=>{const i=r.children[0],n=r.valueOffsets,s=Xr.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=n[t],l=n[t+1];a{const i=r.children[0],{valueOffsets:n}=r,s=Xr.getVisitFn(i);let{[t]:o,[t+1]:a}=n;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(i,o,u),++o>=a)break},eA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[s]),rA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(s)),iA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(n.name)),nA=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[n.name]),sA=(r,t,e)=>{const i=r.type.children.map(s=>Xr.getVisitFn(s.type)),n=e instanceof Map?iA(t,e):e instanceof Me?rA(t,e):Array.isArray(e)?eA(t,e):nA(t,e);r.type.children.forEach((s,o)=>n(i[o],r.children[o],s,o))},oA=(r,t,e)=>{r.type.mode===er.Dense?v_(r,t,e):__(r,t,e)},v_=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Xr.visit(n,r.valueOffsets[t],e)},__=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Xr.visit(n,t,e)},aA=(r,t,e)=>{var i;(i=r.dictionary)===null||i===void 0||i.set(r.values[t],e)},lA=(r,t,e)=>{r.type.unit===Si.DAY_TIME?b_(r,t,e):w_(r,t,e)},b_=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},w_=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},x_=({values:r},t,e)=>{r[t]=e},S_=({values:r},t,e)=>{r[t]=e},T_=({values:r},t,e)=>{r[t]=e},I_=({values:r},t,e)=>{r[t]=e},uA=(r,t,e)=>{switch(r.type.unit){case zt.SECOND:return x_(r,t,e);case zt.MILLISECOND:return S_(r,t,e);case zt.MICROSECOND:return T_(r,t,e);case zt.NANOSECOND:return I_(r,t,e)}},cA=(r,t,e)=>{const{stride:i}=r,n=r.children[0],s=Xr.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=t*i;++o`${Xo(t)}: ${Xo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new hA(this[Kr],this[$s])}},hA=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[Kr].type.children.findIndex(i=>i.name===e)!==-1}getOwnPropertyDescriptor(t,e){if(t[Kr].type.children.findIndex(i=>i.name===e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Kr].type.children.findIndex(n=>n.name===e);if(i!==-1){const n=mr.visit(t[Kr].children[i],t[$s]);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Kr].type.children.findIndex(s=>s.name===e);return n!==-1?(Xr.visit(t[Kr].children[n],t[$s],i),Reflect.set(t,e,i)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,i):!1}},Mt=class extends ie{};function $t(r){return(t,e)=>t.getValid(e)?r(t,e):null}const dA=(r,t)=>864e5*r[t],pA=(r,t)=>null,E_=(r,t,e)=>{if(e+1>=t.length)return null;const i=we(t[e]),n=we(t[e+1]);return r.subarray(i,n)},mA=({offset:r,values:t},e)=>{const i=r+e;return(t[i>>3]&1<dA(r,t),A_=({values:r},t)=>we(r[t]),wn=({stride:r,values:t},e)=>t[r*e],yA=({stride:r,values:t},e)=>i_(t[r*e]),O_=({values:r},t)=>r[t],gA=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),F_=({values:r,valueOffsets:t},e)=>E_(r,t,e),P_=({values:r,valueOffsets:t},e)=>{const i=E_(r,t,e);return i!==null?eh(i):null},vA=({values:r},t)=>r[t],_A=({type:r,values:t},e)=>r.precision!==tr.HALF?t[e]:i_(t[e]),bA=(r,t)=>r.type.unit===Hr.DAY?C_(r,t):A_(r,t),M_=({values:r},t)=>1e3*we(r[t]),D_=({values:r},t)=>we(r[t]),R_=({values:r},t)=>Pv(r[t],BigInt(1e3)),N_=({values:r},t)=>Pv(r[t],BigInt(1e6)),wA=(r,t)=>{switch(r.type.unit){case zt.SECOND:return M_(r,t);case zt.MILLISECOND:return D_(r,t);case zt.MICROSECOND:return R_(r,t);case zt.NANOSECOND:return N_(r,t)}},L_=({values:r},t)=>r[t],B_=({values:r},t)=>r[t],k_=({values:r},t)=>r[t],U_=({values:r},t)=>r[t],xA=(r,t)=>{switch(r.type.unit){case zt.SECOND:return L_(r,t);case zt.MILLISECOND:return B_(r,t);case zt.MICROSECOND:return k_(r,t);case zt.NANOSECOND:return U_(r,t)}},SA=({values:r,stride:t},e)=>jC.decimal(r.subarray(t*e,t*(e+1))),TA=(r,t)=>{const{valueOffsets:e,stride:i,children:n}=r,{[t*i]:s,[t*i+1]:o}=e,l=n[0].slice(s,o-s);return new Me([l])},IA=(r,t)=>{const{valueOffsets:e,children:i}=r,{[t]:n,[t+1]:s}=e,o=i[0];return new af(o.slice(n,s-n))},EA=(r,t)=>new of(r,t),CA=(r,t)=>r.type.mode===er.Dense?z_(r,t):j_(r,t),z_=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return mr.visit(i,r.valueOffsets[t])},j_=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return mr.visit(i,t)},AA=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},OA=(r,t)=>r.type.unit===Si.DAY_TIME?$_(r,t):V_(r,t),$_=({values:r},t)=>r.subarray(2*t,2*(t+1)),V_=({values:r},t)=>{const e=r[t],i=new Int32Array(2);return i[0]=Math.trunc(e/12),i[1]=Math.trunc(e%12),i},G_=({values:r},t)=>r[t],W_=({values:r},t)=>r[t],H_=({values:r},t)=>r[t],X_=({values:r},t)=>r[t],FA=(r,t)=>{switch(r.type.unit){case zt.SECOND:return G_(r,t);case zt.MILLISECOND:return W_(r,t);case zt.MICROSECOND:return H_(r,t);case zt.NANOSECOND:return X_(r,t)}},PA=(r,t)=>{const{stride:e,children:i}=r,s=i[0].slice(t*e,e);return new Me([s])};Mt.prototype.visitNull=$t(pA);Mt.prototype.visitBool=$t(mA);Mt.prototype.visitInt=$t(vA);Mt.prototype.visitInt8=$t(wn);Mt.prototype.visitInt16=$t(wn);Mt.prototype.visitInt32=$t(wn);Mt.prototype.visitInt64=$t(O_);Mt.prototype.visitUint8=$t(wn);Mt.prototype.visitUint16=$t(wn);Mt.prototype.visitUint32=$t(wn);Mt.prototype.visitUint64=$t(O_);Mt.prototype.visitFloat=$t(_A);Mt.prototype.visitFloat16=$t(yA);Mt.prototype.visitFloat32=$t(wn);Mt.prototype.visitFloat64=$t(wn);Mt.prototype.visitUtf8=$t(P_);Mt.prototype.visitLargeUtf8=$t(P_);Mt.prototype.visitBinary=$t(F_);Mt.prototype.visitLargeBinary=$t(F_);Mt.prototype.visitFixedSizeBinary=$t(gA);Mt.prototype.visitDate=$t(bA);Mt.prototype.visitDateDay=$t(C_);Mt.prototype.visitDateMillisecond=$t(A_);Mt.prototype.visitTimestamp=$t(wA);Mt.prototype.visitTimestampSecond=$t(M_);Mt.prototype.visitTimestampMillisecond=$t(D_);Mt.prototype.visitTimestampMicrosecond=$t(R_);Mt.prototype.visitTimestampNanosecond=$t(N_);Mt.prototype.visitTime=$t(xA);Mt.prototype.visitTimeSecond=$t(L_);Mt.prototype.visitTimeMillisecond=$t(B_);Mt.prototype.visitTimeMicrosecond=$t(k_);Mt.prototype.visitTimeNanosecond=$t(U_);Mt.prototype.visitDecimal=$t(SA);Mt.prototype.visitList=$t(TA);Mt.prototype.visitStruct=$t(EA);Mt.prototype.visitUnion=$t(CA);Mt.prototype.visitDenseUnion=$t(z_);Mt.prototype.visitSparseUnion=$t(j_);Mt.prototype.visitDictionary=$t(AA);Mt.prototype.visitInterval=$t(OA);Mt.prototype.visitIntervalDayTime=$t($_);Mt.prototype.visitIntervalYearMonth=$t(V_);Mt.prototype.visitDuration=$t(FA);Mt.prototype.visitDurationSecond=$t(G_);Mt.prototype.visitDurationMillisecond=$t(W_);Mt.prototype.visitDurationMicrosecond=$t(H_);Mt.prototype.visitDurationNanosecond=$t(X_);Mt.prototype.visitFixedSizeList=$t(PA);Mt.prototype.visitMap=$t(IA);const mr=new Mt,Os=Symbol.for("keys"),Vs=Symbol.for("vals"),Fs=Symbol.for("kKeysAsStrings"),lh=Symbol.for("_kKeysAsStrings");let af=class{constructor(t){return this[Os]=new Me([t.children[0]]).memoize(),this[Vs]=t.children[1],new Proxy(this,new DA)}get[Fs](){return this[lh]||(this[lh]=Array.from(this[Os].toArray(),String))}[Symbol.iterator](){return new MA(this[Os],this[Vs])}get size(){return this[Os].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[Os],e=this[Vs],i={};for(let n=-1,s=t.length;++n`${Xo(t)}: ${Xo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}},MA=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),mr.visit(this.vals,t)]})}},DA=class{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[Fs]}has(t,e){return t[Fs].includes(e)}getOwnPropertyDescriptor(t,e){if(t[Fs].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Fs].indexOf(e);if(i!==-1){const n=mr.visit(Reflect.get(t,Vs),i);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Fs].indexOf(e);return n!==-1?(Xr.visit(Reflect.get(t,Vs),n,i),Reflect.set(t,e,i)):Reflect.has(t,e)?Reflect.set(t,e,i):!1}};Object.defineProperties(af.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[Os]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Vs]:{writable:!0,enumerable:!1,configurable:!1,value:null},[lh]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let xp;function Y_(r,t,e,i){const{length:n=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?n:e;return s<0&&(s=(s%n+n)%n),o<0&&(o=(o%n+n)%n),on&&(o=n),i?i(r,s,o):[s,o]}const lf=(r,t)=>r<0?t+r:r,Sp=r=>r!==r;function so(r){if(typeof r!=="object"||r===null)return Sp(r)?Sp:e=>e===r;if(r instanceof Date){const e=r.valueOf();return i=>i instanceof Date?i.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?FC(r,e):!1:r instanceof Map?NA(r):Array.isArray(r)?RA(r):r instanceof Me?LA(r):BA(r,!0)}function RA(r){const t=[];for(let e=-1,i=r.length;++e!1;const i=[];for(let n=-1,s=e.length;++n{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return kA(r,e);case Map:return Tp(r,e,e.keys());case af:case of:case Object:case void 0:return Tp(r,e,t||Object.keys(e))}return e instanceof Me?UA(r,e):!1}}function kA(r,t){const e=r.length;if(t.length!==e)return!1;for(let i=-1;++i>i}function Cl(r,t,e){const i=e.byteLength+7&-8;if(r>0||e.byteLength>3):Al(new uf(e,r,t,null,q_)).subarray(0,i)),n}return e}function Al(r){const t=[];let e=0,i=0,n=0;for(const o of r)o&&(n|=1<0)&&(t[e++]=n);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}let uf=class{constructor(t,e,i,n,s){this.bytes=t,this.length=i,this.context=n,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,n=t+(t%8===0?0:8-t%8);return uh(r,t,n)+uh(r,i,e)+jA(r,n>>3,i-n>>3)}function jA(r,t,e){let i=0,n=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:n+e;for(;o-n>=4;)i+=Yu(s.getUint32(n)),n+=4;for(;o-n>=2;)i+=Yu(s.getUint16(n)),n+=2;for(;o-n>=1;)i+=Yu(s.getUint8(n)),n+=1;return i}function Yu(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 $A=-1;let Se=class ch{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 At.isSparseUnion(t)?this.children.some(e=>e.nullable):At.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:i,nullBitmap:n,typeIds:s}=this;return e&&(t+=e.byteLength),i&&(t+=i.byteLength),n&&(t+=n.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(At.isUnion(this.type))return this.children.reduce((i,n)=>i+n.nullCount,0);let t=this._nullCount,e;return t<=$A&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-uh(e,this.offset,this.offset+this.length)),t}constructor(t,e,i,n,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(i||0,0)),this._nullCount=Math.floor(Math.max(n||0,-1));let l;s instanceof ch?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=Ui(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(At.isUnion(e)){const i=e,n=this.children[i.typeIdToChildIndex[this.typeIds[t]]],s=i.mode===er.Dense?this.valueOffsets[t]:t;return n.getValid(s)}if(this.nullable&&this.nullCount>0){const i=this.offset+t;return(this.nullBitmap[i>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(Cl(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];i=(h&u)!==0,s[c]=e?h|u:h&~u}return i!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,i=this.length,n=this._nullCount,s=this,o=this.children){return new ch(t,e,i,n,s,o,this.dictionary)}slice(t,e){const{stride:i,typeId:n,children:s}=this,o=+(this._nullCount===0)-1,a=n===16?i:1,l=this._sliceBuffers(t,e,i,n);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===L.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:i}=this,n=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);n[e>>3]=(1<0&&n.set(Cl(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[ki.VALIDITY]=n,this.clone(this.type,0,t,i+(t-e),s)}_sliceBuffers(t,e,i,n){let s;const{buffers:o}=this;return(s=o[ki.TYPE])&&(o[ki.TYPE]=s.subarray(t,t+e)),(s=o[ki.OFFSET])&&(o[ki.OFFSET]=s.subarray(t,t+e+1))||(s=o[ki.DATA])&&(o[ki.DATA]=n===6?s:s.subarray(i*t,i*(t+e))),o}_sliceChildren(t,e,i){return t.map(n=>n.slice(e,i))}};Se.prototype.children=Object.freeze([]);class Ro extends ie{visit(t){return this.getVisitFn(t.type).call(this,t)}visitNull(t){const{["type"]:e,["offset"]:i=0,["length"]:n=0}=t;return new Se(e,i,n,n)}visitBool(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length>>3,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitInt(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitFloat(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitUtf8(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitLargeUtf8(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=hp(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitBinary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitLargeBinary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.data),s=ae(t.nullBitmap),o=hp(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,n,s])}visitFixedSizeBinary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitDate(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitTimestamp(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitTime(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitDecimal(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitList(t){const{["type"]:e,["offset"]:i=0,["child"]:n}=t,s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,void 0,s],[n])}visitStruct(t){const{["type"]:e,["offset"]:i=0,["children"]:n=[]}=t,s=ae(t.nullBitmap),{length:o=n.reduce((l,{length:u})=>Math.max(l,u),0),nullCount:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,void 0,s],n)}visitUnion(t){const{["type"]:e,["offset"]:i=0,["children"]:n=[]}=t,s=_e(e.ArrayType,t.typeIds),{["length"]:o=s.length,["nullCount"]:a=-1}=t;if(At.isSparseUnion(e))return new Se(e,i,o,a,[void 0,void 0,void 0,s],n);const l=yo(t.valueOffsets);return new Se(e,i,o,a,[l,void 0,void 0,s],n)}visitDictionary(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.indices.ArrayType,t.data),{["dictionary"]:o=new Me([new Ro().visit({type:e.dictionary})])}=t,{["length"]:a=s.length,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[void 0,s,n],[],o)}visitInterval(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitDuration(t){const{["type"]:e,["offset"]:i=0}=t,n=ae(t.nullBitmap),s=_e(e.ArrayType,t.data),{["length"]:o=s.length,["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,s,n])}visitFixedSizeList(t){const{["type"]:e,["offset"]:i=0,["child"]:n=new Ro().visit({type:e.valueType})}=t,s=ae(t.nullBitmap),{["length"]:o=n.length/Ui(e),["nullCount"]:a=t.nullBitmap?-1:0}=t;return new Se(e,i,o,a,[void 0,void 0,s],[n])}visitMap(t){const{["type"]:e,["offset"]:i=0,["child"]:n=new Ro().visit({type:e.childType})}=t,s=ae(t.nullBitmap),o=yo(t.valueOffsets),{["length"]:a=o.length-1,["nullCount"]:l=t.nullBitmap?-1:0}=t;return new Se(e,i,a,l,[o,void 0,s],[n])}}const VA=new Ro;function se(r){return VA.visit(r)}let Ip=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 Q_(r){return r.reduce((t,e)=>t+e.nullCount,0)}function K_(r){return r.reduce((t,e,i)=>(t[i+1]=t[i]+e.length,t),new Uint32Array(r.length+1))}function Z_(r,t,e,i){const n=[];for(let s=-1,o=r.length;++s=i)break;if(e>=l+u)continue;if(l>=e&&l+u<=i){n.push(a);continue}const c=Math.max(0,e-l),h=Math.min(i-l,u);n.push(a.slice(c,h-c))}return n.length===0&&n.push(r[0].slice(0,0)),n}function cf(r,t,e,i){let n=0,s=0,o=t.length-1;do{if(n>=o-1)return e0?0:-1}function HA(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let i=0;for(const n of new uf(e,r.offset+(t||0),r.length,e,q_)){if(!n)return i;++i}return-1}function Qt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case L.Union:break;case L.Dictionary:break;default:return HA(r,e)}const i=mr.getVisitFn(r),n=so(t);for(let s=(e||0)-1,o=r.length;++s{const n=r.data[i];return n.values.subarray(0,n.length)[Symbol.iterator]()});let e=0;return new Ip(r.data.length,i=>{const s=r.data[i].length,o=r.slice(e,e+s);return e+=s,new XA(o)})}let XA=class{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof Se)))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}=i0[o.typeId],c=s[0];this.isValid=h=>hf(c,h),this.get=h=>a(c,h),this.set=(h,p)=>l(c,h,p),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,n0[o.typeId]),this._offsets=K_(s);break}this.data=s,this.type=o,this.stride=Ui(o),this.numChildren=(n=(i=o.children)===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return GA(this.data)}get nullCount(){return Q_(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${L[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(lf(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return ff.visit(this)}concat(...t){return new zn(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new zn(Y_(this,t,e,({data:i,_offsets:n},s,o)=>Z_(i,n,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:i,stride:n,ArrayType:s}=this;switch(t.typeId){case L.Int:case L.Float:case L.Decimal:case L.Time:case L.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,i*n);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*n),o.offset),o.offset+=l*n,o),{array:new s(i*n),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(i=>i.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return At.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(At.isDictionary(this.type)){const t=new Ep(this.data[0].dictionary),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new zn(e)}return new Ep(this)}unmemoize(){if(At.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new zn(e)}return this}};r0=Symbol.toStringTag;Me[r0]=(r=>{r.type=At.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(L).map(e=>L[e]).filter(e=>typeof e=="number"&&e!==L.NONE);for(const e of t){const i=mr.getVisitFnByTypeId(e),n=Xr.getVisitFnByTypeId(e),s=Fl.getVisitFnByTypeId(e);i0[e]={get:i,set:n,indexOf:s},n0[e]=Object.create(r,{isValid:{value:Ol(hf)},get:{value:Ol(mr.getVisitFnByTypeId(e))},set:{value:J_(Xr.getVisitFnByTypeId(e))},indexOf:{value:t0(Fl.getVisitFnByTypeId(e))}})}return"Vector"})(Me.prototype);let Ep=class s0 extends Me{constructor(t){super(t.data);const e=this.get,i=this.set,n=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){i.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new s0(n.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Me(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}};class hh{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,i,n){return t.prep(8,24),t.writeInt64(BigInt(n??0)),t.pad(4),t.writeInt32(i),t.writeInt64(BigInt(e??0)),t.offset()}}class _r{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 _r).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsFooter(t,e){return t.setPosition(t.position()+me),(e||new _r).__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):ke.V1}schema(t){const e=this.bb.__offset(this.bb_pos,6);return e?(t||new ui).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dictionaries(t,e){const i=this.bb.__offset(this.bb_pos,8);return i?(e||new hh).__init(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,10);return i?(e||new hh).__init(this.bb.__vector(this.bb_pos+i)+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 i=this.bb.__offset(this.bb_pos,12);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,ke.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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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 Pe=class jn{constructor(t=[],e,i,n=ke.V5){this.fields=t||[],this.metadata=e||new Map,i||(i=fh(this.fields)),this.dictionaries=i,this.metadataVersion=n}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),i=this.fields.filter(n=>e.has(n.name));return new jn(i,this.metadata)}selectAt(t){const e=t.map(i=>this.fields[i]).filter(Boolean);return new jn(e,this.metadata)}assign(...t){const e=t[0]instanceof jn?t[0]:Array.isArray(t[0])?new jn(t[0]):new jn(t),i=[...this.fields],n=La(La(new Map,this.metadata),e.metadata),s=e.fields.filter(a=>{const l=i.findIndex(u=>u.name===a.name);return~l?(i[l]=a.clone({metadata:La(La(new Map,i[l].metadata),a.metadata)}))&&!1:!0}),o=fh(s,new Map);return new jn([...i,...s],n,new Map([...this.dictionaries,...o]))}};Pe.prototype.fields=null;Pe.prototype.metadata=null;Pe.prototype.dictionaries=null;class Ce{static new(...t){let[e,i,n,s]=t;return t[0]&&typeof t[0]=="object"&&({name:e}=t[0],i===void 0&&(i=t[0].type),n===void 0&&(n=t[0].nullable),s===void 0&&(s=t[0].metadata)),new Ce(`${e}`,i,n,s)}constructor(t,e,i=!1,n){this.name=t,this.type=e,this.nullable=i,this.metadata=n||new Map}get typeId(){return this.type.typeId}get[Symbol.toStringTag](){return"Field"}toString(){return`${this.name}: ${this.type}`}clone(...t){let[e,i,n,s]=t;return!t[0]||typeof t[0]!="object"?[e=this.name,i=this.type,n=this.nullable,s=this.metadata]=t:{name:e=this.name,type:i=this.type,nullable:n=this.nullable,metadata:s=this.metadata}=t[0],Ce.new(e,i,n,s)}}Ce.prototype.type=null;Ce.prototype.name=null;Ce.prototype.nullable=null;Ce.prototype.metadata=null;function La(r,t){return new Map([...r||new Map,...t||new Map])}function fh(r,t=new Map){for(let e=-1,i=r.length;++e0&&fh(s.children,t)}return t}var YA=Cv,qA=Qs;class Ko{static decode(t){t=new qA(ae(t));const e=_r.getRootAsFooter(t),i=Pe.decode(e.schema(),new Map,e.version());return new QA(i,e)}static encode(t){const e=new YA,i=Pe.encode(e,t.schema);_r.startRecordBatchesVector(e,t.numRecordBatches);for(const o of[...t.recordBatches()].slice().reverse())mn.encode(e,o);const n=e.endVector();_r.startDictionariesVector(e,t.numDictionaries);for(const o of[...t.dictionaryBatches()].slice().reverse())mn.encode(e,o);const s=e.endVector();return _r.startFooter(e),_r.addSchema(e,i),_r.addVersion(e,ke.V5),_r.addRecordBatches(e,n),_r.addDictionaries(e,s),_r.finishFooterBuffer(e,_r.endFooter(e)),e.asUint8Array()}get numRecordBatches(){return this._recordBatches.length}get numDictionaries(){return this._dictionaryBatches.length}constructor(t,e=ke.V5,i,n){this.schema=t,this.version=e,i&&(this._recordBatches=i),n&&(this._dictionaryBatches=n)}*recordBatches(){for(let t,e=-1,i=this.numRecordBatches;++e=0&&t=0&&t=0&&t=0&&tthis._closedPromiseResolve=t)}get closed(){return this._closedPromise}cancel(t){return Zt(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(De);this._closedPromiseResolve(),this._closedPromiseResolve=void 0}}[Symbol.asyncIterator](){return this}toDOMStream(t){return kr.toDOMStream(this._closedPromiseResolve||this._error?this:this._values,t)}toNodeStream(t){return kr.toNodeStream(this._closedPromiseResolve||this._error?this:this._values,t)}throw(t){return Zt(this,void 0,void 0,function*(){return yield this.abort(t),De})}return(t){return Zt(this,void 0,void 0,function*(){return yield this.close(),De})}read(t){return Zt(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return Zt(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,i)=>{this.resolvers.push({resolve:e,reject:i})}):Promise.resolve(De)}_ensureOpen(){if(this._closedPromiseResolve)return!0;throw new Error("AsyncQueue is closed")}}class Wa extends KA{write(t){if((t=ae(t)).byteLength>0)return super.write(t)}toString(t=!1){return t?eh(this.toUint8Array(!0)):this.toUint8Array(!1).then(eh)}toUint8Array(t=!1){return t?xi(this._values)[0]:Zt(this,void 0,void 0,function*(){var e,i,n,s;const o=[];let a=0;try{for(var l=!0,u=bi(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){i={error:h}}finally{try{!l&&!e&&(n=u.return)&&(yield n.call(u))}finally{if(i)throw i.error}}return xi(o,a)[0]})}}class Pl{constructor(t){t&&(this.source=new ZA(kr.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 Js{constructor(t){t instanceof Js?this.source=t.source:t instanceof Wa?this.source=new Mn(kr.fromAsyncIterable(t)):Sv(t)?this.source=new Mn(kr.fromNodeStream(t)):rf(t)?this.source=new Mn(kr.fromDOMStream(t)):xv(t)?this.source=new Mn(kr.fromDOMStream(t.body)):oa(t)?this.source=new Mn(kr.fromIterable(t)):rs(t)?this.source=new Mn(kr.fromAsyncIterable(t)):no(t)&&(this.source=new Mn(kr.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 ZA{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)||De)}return(t){return Object.create(this.source.return&&this.source.return(t)||De)}}class Mn{constructor(t){this.source=t,this._closedPromise=new Promise(e=>this._closedPromiseResolve=e)}cancel(t){return Zt(this,void 0,void 0,function*(){yield this.return(t)})}get closed(){return this._closedPromise}read(t){return Zt(this,void 0,void 0,function*(){return(yield this.next(t,"read")).value})}peek(t){return Zt(this,void 0,void 0,function*(){return(yield this.next(t,"peek")).value})}next(t){return Zt(this,arguments,void 0,function*(e,i="read"){return yield this.source.next({cmd:i,size:e})})}throw(t){return Zt(this,void 0,void 0,function*(){const e=this.source.throw&&(yield this.source.throw(t))||De;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}return(t){return Zt(this,void 0,void 0,function*(){const e=this.source.return&&(yield this.source.return(t))||De;return this._closedPromiseResolve&&this._closedPromiseResolve(),this._closedPromiseResolve=void 0,Object.create(e)})}}class Ap extends Pl{constructor(t,e){super(),this.position=0,this.buffer=ae(t),this.size=e===void 0?this.buffer.byteLength:e}readInt32(t){const{buffer:e,byteOffset:i}=this.readAt(t,4);return new DataView(e,i).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]),i=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let n=e[3]*i[3];this.buffer[0]=n&65535;let s=n>>>16;return n=e[2]*i[3],s+=n,n=e[3]*i[2]>>>0,s+=n,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*i[3]+e[2]*i[2]+e[3]*i[1],this.buffer[1]+=e[0]*i[3]+e[1]*i[2]+e[2]*i[1]+e[3]*i[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`${Ns(this.buffer[3])} ${Ns(this.buffer[2])} ${Ns(this.buffer[1])} ${Ns(this.buffer[0])}`}static multiply(t,e){return new Ni(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new Ni(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return Ni.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return Ni.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const i=t.startsWith("-"),n=t.length,s=new Ni(e);for(let o=i?1:0;o0&&this.readData(t,i)||new Uint8Array(0)}readOffsets(t,e){return this.readData(t,e)}readTypeIds(t,e){return this.readData(t,e)}readData(t,{length:e,offset:i}=this.nextBufferRange()){return this.bytes.subarray(i,i+e)}readDictionary(t){return this.dictionaries.get(t.id)}}class eO extends a0{constructor(t,e,i,n,s){super(new Uint8Array(0),e,i,n,s),this.sources=t}readNullBitmap(t,e,{offset:i}=this.nextBufferRange()){return e<=0?new Uint8Array(0):Al(this.sources[i])}readOffsets(t,{offset:e}=this.nextBufferRange()){return _e(Uint8Array,_e(t.OffsetArrayType,this.sources[e]))}readTypeIds(t,{offset:e}=this.nextBufferRange()){return _e(Uint8Array,_e(t.ArrayType,this.sources[e]))}readData(t,{offset:e}=this.nextBufferRange()){const{sources:i}=this;return At.isTimestamp(t)||(At.isInt(t)||At.isTime(t))&&t.bitWidth===64||At.isDuration(t)||At.isDate(t)&&t.unit===Hr.MILLISECOND?_e(Uint8Array,No.convertArray(i[e])):At.isDecimal(t)?_e(Uint8Array,tO.convertArray(i[e])):At.isBinary(t)||At.isLargeBinary(t)||At.isFixedSizeBinary(t)?rO(i[e]):At.isBool(t)?Al(i[e]):At.isUtf8(t)||At.isLargeUtf8(t)?ef(i[e].join("")):_e(Uint8Array,_e(t.ArrayType,i[e].map(n=>+n)))}}function rO(r){const t=r.join(""),e=new Uint8Array(t.length/2);for(let i=0;i>1]=Number.parseInt(t.slice(i,i+2),16);return e}let Nt=class extends ie{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((i,n)=>this.compareFields(i,e[n]))}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 lr(r,t){return t instanceof r.constructor}function us(r,t){return r===t||lr(r,t)}function Xi(r,t){return r===t||lr(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function ru(r,t){return r===t||lr(r,t)&&r.precision===t.precision}function iO(r,t){return r===t||lr(r,t)&&r.byteWidth===t.byteWidth}function mf(r,t){return r===t||lr(r,t)&&r.unit===t.unit}function aa(r,t){return r===t||lr(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function la(r,t){return r===t||lr(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function nO(r,t){return r===t||lr(r,t)&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}function sO(r,t){return r===t||lr(r,t)&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}function yf(r,t){return r===t||lr(r,t)&&r.mode===t.mode&&r.typeIds.every((e,i)=>e===t.typeIds[i])&&yn.compareManyFields(r.children,t.children)}function oO(r,t){return r===t||lr(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&yn.visit(r.indices,t.indices)&&yn.visit(r.dictionary,t.dictionary)}function gf(r,t){return r===t||lr(r,t)&&r.unit===t.unit}function ua(r,t){return r===t||lr(r,t)&&r.unit===t.unit}function aO(r,t){return r===t||lr(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}function lO(r,t){return r===t||lr(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&yn.compareManyFields(r.children,t.children)}Nt.prototype.visitNull=us;Nt.prototype.visitBool=us;Nt.prototype.visitInt=Xi;Nt.prototype.visitInt8=Xi;Nt.prototype.visitInt16=Xi;Nt.prototype.visitInt32=Xi;Nt.prototype.visitInt64=Xi;Nt.prototype.visitUint8=Xi;Nt.prototype.visitUint16=Xi;Nt.prototype.visitUint32=Xi;Nt.prototype.visitUint64=Xi;Nt.prototype.visitFloat=ru;Nt.prototype.visitFloat16=ru;Nt.prototype.visitFloat32=ru;Nt.prototype.visitFloat64=ru;Nt.prototype.visitUtf8=us;Nt.prototype.visitLargeUtf8=us;Nt.prototype.visitBinary=us;Nt.prototype.visitLargeBinary=us;Nt.prototype.visitFixedSizeBinary=iO;Nt.prototype.visitDate=mf;Nt.prototype.visitDateDay=mf;Nt.prototype.visitDateMillisecond=mf;Nt.prototype.visitTimestamp=aa;Nt.prototype.visitTimestampSecond=aa;Nt.prototype.visitTimestampMillisecond=aa;Nt.prototype.visitTimestampMicrosecond=aa;Nt.prototype.visitTimestampNanosecond=aa;Nt.prototype.visitTime=la;Nt.prototype.visitTimeSecond=la;Nt.prototype.visitTimeMillisecond=la;Nt.prototype.visitTimeMicrosecond=la;Nt.prototype.visitTimeNanosecond=la;Nt.prototype.visitDecimal=us;Nt.prototype.visitList=nO;Nt.prototype.visitStruct=sO;Nt.prototype.visitUnion=yf;Nt.prototype.visitDenseUnion=yf;Nt.prototype.visitSparseUnion=yf;Nt.prototype.visitDictionary=oO;Nt.prototype.visitInterval=gf;Nt.prototype.visitIntervalDayTime=gf;Nt.prototype.visitIntervalYearMonth=gf;Nt.prototype.visitDuration=ua;Nt.prototype.visitDurationSecond=ua;Nt.prototype.visitDurationMillisecond=ua;Nt.prototype.visitDurationMicrosecond=ua;Nt.prototype.visitDurationNanosecond=ua;Nt.prototype.visitFixedSizeList=aO;Nt.prototype.visitMap=lO;const yn=new Nt;function dh(r,t){return yn.compareSchemas(r,t)}function qu(r,t){return uO(r,t.map(e=>e.data.concat()))}function uO(r,t){const e=[...r.fields],i=[],n={numBatches:t.reduce((h,p)=>Math.max(h,p.length),0)};let s=0,o=0,a=-1;const l=t.length;let u,c=[];for(;n.numBatches-- >0;){for(o=Number.POSITIVE_INFINITY,a=-1;++a0&&(i[s++]=se({type:new sr(e),length:o,nullCount:0,children:c.slice()})))}return[r=r.assign(e),i.map(h=>new fr(r,h))]}function cO(r,t,e,i,n){var s;const o=(t+63&-64)>>3;for(let a=-1,l=i.length;++a=t)c===t?e[a]=u:(e[a]=u.slice(0,t),n.numBatches=Math.max(n.numBatches,i[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:se({type:h.type,length:t,nullCount:t,nullBitmap:new Uint8Array(o)})}}return e}var l0;let gn=class $n{constructor(...t){var e,i;if(t.length===0)return this.batches=[],this.schema=new Pe([]),this._offsets=[0],this;let n,s;t[0]instanceof Pe&&(n=t.shift()),t.at(-1)instanceof Uint32Array&&(s=t.pop());const o=l=>{if(l){if(l instanceof fr)return[l];if(l instanceof $n)return l.batches;if(l instanceof Se){if(l.type instanceof sr)return[new fr(new Pe(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(f=>new Me([l[f]])),h=n??new Pe(u.map((f,y)=>new Ce(String(f),c[y].type,c[y].nullable))),[,p]=qu(h,c);return p.length===0?[new fr(l)]:p}}}return[]},a=t.flatMap(l=>o(l));if(n=(i=n??((e=a[0])===null||e===void 0?void 0:e.schema))!==null&&i!==void 0?i:new Pe([]),!(n instanceof Pe))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");for(const l of a){if(!(l instanceof fr))throw new TypeError("Table constructor expects a [Schema, RecordBatch[]] pair.");if(!dh(n,l.schema))throw new TypeError("Table and inner RecordBatch schemas must be equivalent.")}this.schema=n,this.batches=a,this._offsets=s??K_(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=Q_(this.data)),this._nullCount}isValid(t){return!1}get(t){return null}at(t){return this.get(lf(t,this.numRows))}set(t,e){}indexOf(t,e){return-1}[Symbol.iterator](){return this.batches.length>0?ff.visit(new Me(this.data)):new Array(0)[Symbol.iterator]()}toArray(){return[...this]}toString(){return`[ ${this.toArray().join(`, `)} -]`}concat(...t){const e=this.schema,i=this.data.concat(t.flatMap(({data:n})=>n));return new $n(e,i.map(n=>new fr(e,n)))}slice(t,e){const i=this.schema;[t,e]=Y_({length:this.numRows},t,e);const n=Z_(this.data,this._offsets,t,e);return new $n(i,n.map(s=>new fr(i,s)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&ti.children[t]);if(e.length===0){const{type:i}=this.schema.fields[t],n=se({type:i,length:0,nullCount:0});e.push(n._changeLengthAndBackfillNullBitmap(this.numRows))}return new Me(e)}return null}setChild(t,e){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(n=>n.name===t),e)}setChildAt(t,e){let i=this.schema,n=[...this.batches];if(t>-1&&tthis.getChildAt(u));[s[t],a[t]]=[o,e],[i,n]=qu(i,a)}return new $n(i,n)}select(t){const e=this.schema.fields.reduce((i,n,s)=>i.set(n.name,s),new Map);return this.selectAt(t.map(i=>e.get(i)).filter(i=>i>-1))}selectAt(t){const e=this.schema.selectAt(t),i=this.batches.map(n=>n.selectAt(t));return new $n(e,i)}assign(t){const e=this.schema.fields,[i,n]=t.schema.fields.reduce((a,l,u)=>{const[c,h]=a,p=e.findIndex(f=>f.name===l.name);return~p?h[p]=u:c.push(u),a},[[],[]]),s=this.schema.assign(t.schema),o=[...e.map((a,l)=>[l,n[l]]).map(([a,l])=>l===void 0?this.getChildAt(a):t.getChildAt(l)),...i.map(a=>t.getChildAt(a))].filter(Boolean);return new $n(...qu(s,o))}};l0=Symbol.toStringTag;gn[l0]=(r=>(r.schema=null,r.batches=[],r._offsets=new Uint32Array([0]),r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,r.isValid=Ol(hf),r.get=Ol(mr.getVisitFn(L.Struct)),r.set=J_(Xr.getVisitFn(L.Struct)),r.indexOf=t0(Fl.getVisitFn(L.Struct)),"Table"))(gn.prototype);var u0;let fr=class Po{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof Pe))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=se({nullCount:0,type:new sr(this.schema.fields),children:this.schema.fields.map(e=>se({type:e.type,nullCount:0}))})]=t,!(this.data instanceof Se))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Op(this.schema,this.data.children);break}case 1:{const[e]=t,{fields:i,children:n,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]=Ce.new({name:u,type:e[u].type,nullable:!0}),l),{length:0,fields:new Array,children:new Array}),o=new Pe(i),a=se({type:new sr(i),length:s,children:n,nullCount:0});[this.schema,this.data]=Op(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=c0(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 mr.visit(this.data,t)}at(t){return this.get(lf(t,this.numRows))}set(t,e){return Xr.visit(this.data,t,e)}indexOf(t,e){return Fl.visit(this.data,t,e)}[Symbol.iterator](){return ff.visit(new Me([this.data]))}toArray(){return[...this]}concat(...t){return new gn(this.schema,[this,...t])}slice(t,e){const[i]=new Me([this.data]).slice(t,e).data;return new Po(this.schema,i)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(i=>i.name===t))}getChildAt(t){return t>-1&&tn.name===t),e)}setChildAt(t,e){let i=this.schema,n=this.data;if(t>-1&&ta.name===s);~o&&(n[o]=this.data.children[o])}return new Po(e,se({type:i,length:this.numRows,children:n}))}selectAt(t){const e=this.schema.selectAt(t),i=t.map(s=>this.data.children[s]).filter(Boolean),n=se({type:new sr(e.fields),length:this.numRows,children:i});return new Po(e,n)}};u0=Symbol.toStringTag;fr[u0]=(r=>(r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(fr.prototype);function Op(r,t,e=t.reduce((i,n)=>Math.max(i,n.length),0)){var i;const n=[...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)&&(n[a]=l.clone({nullable:!0}),s[a]=(i=u==null?void 0:u._changeLengthAndBackfillNullBitmap(e))!==null&&i!==void 0?i:se({type:l.type,length:e,nullCount:e,nullBitmap:new Uint8Array(o)}))}return[r.assign(n),se({type:new sr(n),length:e,children:s})]}function c0(r,t,e=new Map){var i,n;if(((i=r==null?void 0:r.length)!==null&&i!==void 0?i:0)>0&&(r==null?void 0:r.length)===(t==null?void 0:t.length))for(let s=-1,o=r.length;++sse({type:n.type})),i=se({type:new sr(t.fields),nullCount:0,children:e});super(t,i)}}let en=class ai{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 ai).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+me),(e||new ai).__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):ke.V1}headerType(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):fe.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 i=this.bb.__offset(this.bb_pos,12);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,ke.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,fe.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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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,i,n,s,o){return ai.startMessage(t),ai.addVersion(t,e),ai.addHeaderType(t,i),ai.addHeader(t,n),ai.addBodyLength(t,s),ai.addCustomMetadata(t,o),ai.endMessage(t)}};class hO extends ie{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return _p.startNull(e),_p.endNull(e)}visitInt(t,e){return xr.startInt(e),xr.addBitWidth(e,t.bitWidth),xr.addIsSigned(e,t.isSigned),xr.endInt(e)}visitFloat(t,e){return mi.startFloatingPoint(e),mi.addPrecision(e,t.precision),mi.endFloatingPoint(e)}visitBinary(t,e){return pp.startBinary(e),pp.endBinary(e)}visitLargeBinary(t,e){return yp.startLargeBinary(e),yp.endLargeBinary(e)}visitBool(t,e){return mp.startBool(e),mp.endBool(e)}visitUtf8(t,e){return bp.startUtf8(e),bp.endUtf8(e)}visitLargeUtf8(t,e){return gp.startLargeUtf8(e),gp.endLargeUtf8(e)}visitDecimal(t,e){return Ss.startDecimal(e),Ss.addScale(e,t.scale),Ss.addPrecision(e,t.precision),Ss.addBitWidth(e,t.bitWidth),Ss.endDecimal(e)}visitDate(t,e){return Ua.startDate(e),Ua.addUnit(e,t.unit),Ua.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 i=t.timezone&&e.createString(t.timezone)||void 0;return jr.startTimestamp(e),jr.addUnit(e,t.unit),i!==void 0&&jr.addTimezone(e,i),jr.endTimestamp(e)}visitInterval(t,e){return yi.startInterval(e),yi.addUnit(e,t.unit),yi.endInterval(e)}visitDuration(t,e){return za.startDuration(e),za.addUnit(e,t.unit),za.endDuration(e)}visitList(t,e){return vp.startList(e),vp.endList(e)}visitStruct(t,e){return Yn.startStruct_(e),Yn.endStruct_(e)}visitUnion(t,e){hr.startTypeIdsVector(e,t.typeIds.length);const i=hr.createTypeIdsVector(e,t.typeIds);return hr.startUnion(e),hr.addMode(e,t.mode),hr.addTypeIds(e,i),hr.endUnion(e)}visitDictionary(t,e){const i=this.visit(t.indices,e);return $i.startDictionaryEncoding(e),$i.addId(e,BigInt(t.id)),$i.addIsOrdered(e,t.isOrdered),i!==void 0&&$i.addIndexType(e,i),$i.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return ja.startFixedSizeBinary(e),ja.addByteWidth(e,t.byteWidth),ja.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return $a.startFixedSizeList(e),$a.addListSize(e,t.listSize),$a.endFixedSizeList(e)}visitMap(t,e){return Va.startMap(e),Va.addKeysSorted(e,t.keysSorted),Va.endMap(e)}}const Qu=new hO;function fO(r,t=new Map){return new Pe(pO(r,t),Ha(r.metadata),t)}function h0(r){return new Fr(r.count,f0(r.columns),d0(r.columns))}function dO(r){return new Ti(h0(r.data),r.id,r.isDelta)}function pO(r,t){return(r.fields||[]).filter(Boolean).map(e=>Ce.fromJSON(e,t))}function Fp(r,t){return(r.children||[]).filter(Boolean).map(e=>Ce.fromJSON(e,t))}function f0(r){return(r||[]).reduce((t,e)=>[...t,new vn(e.count,mO(e.VALIDITY)),...f0(e.children)],[])}function d0(r,t=[]){for(let e=-1,i=(r||[]).length;++et+ +(e===0),0)}function yO(r,t){let e,i,n,s,o,a;return!t||!(s=r.dictionary)?(o=Mp(r,Fp(r,t)),n=new Ce(r.name,o,r.nullable,Ha(r.metadata))):t.has(e=s.id)?(i=(i=s.indexType)?Pp(i):new Qo,a=new Zs(t.get(e),i,e,s.isOrdered),n=new Ce(r.name,a,r.nullable,Ha(r.metadata))):(i=(i=s.indexType)?Pp(i):new Qo,t.set(e,o=Mp(r,Fp(r,t))),a=new Zs(o,i,e,s.isOrdered),n=new Ce(r.name,a,r.nullable,Ha(r.metadata))),n||null}function Ha(r=[]){return new Map(r.map(({key:t,value:e})=>[t,e]))}function Pp(r){return new is(r.isSigned,r.bitWidth)}function Mp(r,t){const e=r.type.name;switch(e){case"NONE":return new pn;case"null":return new pn;case"binary":return new hl;case"largebinary":return new fl;case"utf8":return new dl;case"largeutf8":return new pl;case"bool":return new ml;case"list":return new xl((t||[])[0]);case"struct":return new sr(t||[]);case"struct_":return new sr(t||[])}switch(e){case"int":{const i=r.type;return new is(i.isSigned,i.bitWidth)}case"floatingpoint":{const i=r.type;return new cl(tr[i.precision])}case"decimal":{const i=r.type;return new yl(i.scale,i.precision,i.bitWidth)}case"date":{const i=r.type;return new gl(Hr[i.unit])}case"time":{const i=r.type;return new vl(zt[i.unit],i.bitWidth)}case"timestamp":{const i=r.type;return new _l(zt[i.unit],i.timezone)}case"interval":{const i=r.type;return new bl(Si[i.unit])}case"duration":{const i=r.type;return new wl(zt[i.unit])}case"union":{const i=r.type,[n,...s]=(i.mode+"").toLowerCase(),o=n.toUpperCase()+s.join("");return new Sl(er[o],i.typeIds||[],t||[])}case"fixedsizebinary":{const i=r.type;return new Tl(i.byteWidth)}case"fixedsizelist":{const i=r.type;return new Il(i.listSize,(t||[])[0])}case"map":{const i=r.type;return new El((t||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var gO=Cv,vO=Qs;class or{static fromJSON(t,e){const i=new or(0,ke.V5,e);return i._createHeader=_O(t,e),i}static decode(t){t=new vO(ae(t));const e=en.getRootAsMessage(t),i=e.bodyLength(),n=e.version(),s=e.headerType(),o=new or(i,n,s);return o._createHeader=bO(e,s),o}static encode(t){const e=new gO;let i=-1;return t.isSchema()?i=Pe.encode(e,t.header()):t.isRecordBatch()?i=Fr.encode(e,t.header()):t.isDictionaryBatch()&&(i=Ti.encode(e,t.header())),en.startMessage(e),en.addVersion(e,ke.V5),en.addHeader(e,i),en.addHeaderType(e,t.headerType),en.addBodyLength(e,BigInt(t.bodyLength)),en.finishMessageBuffer(e,en.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof Pe)return new or(0,ke.V5,fe.Schema,t);if(t instanceof Fr)return new or(e,ke.V5,fe.RecordBatch,t);if(t instanceof Ti)return new or(e,ke.V5,fe.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===fe.Schema}isRecordBatch(){return this.headerType===fe.RecordBatch}isDictionaryBatch(){return this.headerType===fe.DictionaryBatch}constructor(t,e,i,n){this._version=e,this._headerType=i,this.body=new Uint8Array(0),n&&(this._createHeader=()=>n),this._bodyLength=we(t)}}class Fr{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,i){this._nodes=e,this._buffers=i,this._length=we(t)}}class Ti{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,i=!1){this._data=t,this._isDelta=i,this._id=we(e)}}class vi{constructor(t,e){this.offset=we(t),this.length=we(e)}}class vn{constructor(t,e){this.length=we(t),this.nullCount=we(e)}}function _O(r,t){return()=>{switch(t){case fe.Schema:return Pe.fromJSON(r);case fe.RecordBatch:return Fr.fromJSON(r);case fe.DictionaryBatch:return Ti.fromJSON(r)}throw new Error(`Unrecognized Message type: { name: ${fe[t]}, type: ${t} }`)}}function bO(r,t){return()=>{switch(t){case fe.Schema:return Pe.decode(r.header(new ui),new Map,r.version());case fe.RecordBatch:return Fr.decode(r.header(new Bi),r.version());case fe.DictionaryBatch:return Ti.decode(r.header(new ws),r.version())}throw new Error(`Unrecognized Message type: { name: ${fe[t]}, type: ${t} }`)}}Ce.encode=PO;Ce.decode=OO;Ce.fromJSON=yO;Pe.encode=FO;Pe.decode=wO;Pe.fromJSON=fO;Fr.encode=MO;Fr.decode=xO;Fr.fromJSON=h0;Ti.encode=DO;Ti.decode=SO;Ti.fromJSON=dO;vn.encode=RO;vn.decode=IO;vi.encode=NO;vi.decode=TO;function wO(r,t=new Map,e=ke.V5){const i=AO(r,t);return new Pe(i,Xa(r),t,e)}function xO(r,t=ke.V5){if(r.compression()!==null)throw new Error("Record batch compression not implemented");return new Fr(r.length(),EO(r),CO(r,t))}function SO(r,t=ke.V5){return new Ti(Fr.decode(r.data(),t),r.id(),r.isDelta())}function TO(r){return new vi(r.offset(),r.length())}function IO(r){return new vn(r.length(),r.nullCount())}function EO(r){const t=[];for(let e,i=-1,n=-1,s=r.nodesLength();++iCe.encode(r,s));ui.startFieldsVector(r,e.length);const i=ui.createFieldsVector(r,e),n=t.metadata&&t.metadata.size>0?ui.createCustomMetadataVector(r,[...t.metadata].map(([s,o])=>{const a=r.createString(`${s}`),l=r.createString(`${o}`);return We.startKeyValue(r),We.addKey(r,a),We.addValue(r,l),We.endKeyValue(r)})):-1;return ui.startSchema(r),ui.addFields(r,i),ui.addEndianness(r,LO?Ks.Little:Ks.Big),n!==-1&&ui.addCustomMetadata(r,n),ui.endSchema(r)}function PO(r,t){let e=-1,i=-1,n=-1;const s=t.type;let o=t.typeId;At.isDictionary(s)?(o=s.dictionary.typeId,n=Qu.visit(s,r),i=Qu.visit(s.dictionary,r)):i=Qu.visit(s,r);const a=(s.children||[]).map(c=>Ce.encode(r,c)),l=Nr.createChildrenVector(r,a),u=t.metadata&&t.metadata.size>0?Nr.createCustomMetadataVector(r,[...t.metadata].map(([c,h])=>{const p=r.createString(`${c}`),f=r.createString(`${h}`);return We.startKeyValue(r),We.addKey(r,p),We.addValue(r,f),We.endKeyValue(r)})):-1;return t.name&&(e=r.createString(t.name)),Nr.startField(r),Nr.addType(r,i),Nr.addTypeType(r,o),Nr.addChildren(r,l),Nr.addNullable(r,!!t.nullable),e!==-1&&Nr.addName(r,e),n!==-1&&Nr.addDictionary(r,n),u!==-1&&Nr.addCustomMetadata(r,u),Nr.endField(r)}function MO(r,t){const e=t.nodes||[],i=t.buffers||[];Bi.startNodesVector(r,e.length);for(const o of e.slice().reverse())vn.encode(r,o);const n=r.endVector();Bi.startBuffersVector(r,i.length);for(const o of i.slice().reverse())vi.encode(r,o);const s=r.endVector();return Bi.startRecordBatch(r),Bi.addLength(r,BigInt(t.length)),Bi.addNodes(r,n),Bi.addBuffers(r,s),Bi.endRecordBatch(r)}function DO(r,t){const e=Fr.encode(r,t.data);return ws.startDictionaryBatch(r),ws.addId(r,BigInt(t.id)),ws.addIsDelta(r,t.isDelta),ws.addData(r,e),ws.endDictionaryBatch(r)}function RO(r,t){return Fv.createFieldNode(r,BigInt(t.length),BigInt(t.nullCount))}function NO(r,t){return Ov.createBuffer(r,BigInt(t.offset),BigInt(t.length))}const LO=(()=>{const r=new ArrayBuffer(2);return new DataView(r).setInt16(0,256,!0),new Int16Array(r)[0]===256})(),_f=r=>`Expected ${fe[r]} Message in stream, but was null or length 0.`,bf=r=>`Header pointer of flatbuffer-encoded ${fe[r]} Message is null or length 0.`,p0=(r,t)=>`Expected to read ${r} metadata bytes, but only read ${t}.`,m0=(r,t)=>`Expected to read ${r} bytes for message body, but only read ${t}.`;class y0{constructor(t){this.source=t instanceof Pl?t:new Pl(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?De: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(_f(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);const e=ae(this.source.read(t));if(e.byteLength[...n,...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(_f(t));return e.value}readSchema(){const t=fe.Schema,e=this.readMessage(t),i=e==null?void 0:e.header();if(!e||!i)throw new Error(bf(t));return i}}const iu=4,ph="ARROW1",Zo=new Uint8Array(ph.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 kr.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return kr.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 Vr?t:rh(t)?VO(t):wv(t)?HO(t):rs(t)?Zt(this,void 0,void 0,function*(){return yield Vr.from(yield t)}):xv(t)||rf(t)||Sv(t)||no(t)?WO(new Js(t)):GO(new Pl(t))}static readAll(t){return t instanceof Vr?t.isSync()?Lp(t):Bp(t):rh(t)||ArrayBuffer.isView(t)||oa(t)||bv(t)?Lp(t):Bp(t)}}class Dl extends Vr{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return dr(this,arguments,function*(){yield Pt(yield*ts(bi(this[Symbol.iterator]())))})}}class Rl extends Vr{constructor(t){super(t),this._impl=t}readAll(){return Zt(this,void 0,void 0,function*(){var t,e,i,n;const s=new Array;try{for(var o=!0,a=bi(this),l;l=yield a.next(),t=l.done,!t;o=!0){n=l.value,o=!1;const u=n;s.push(u)}}catch(u){e={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.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 v0 extends Dl{constructor(t){super(t),this._impl=t}}class zO extends Rl{constructor(t){super(t),this._impl=t}}class _0{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 i=this._loadVectors(t,e,this.schema.fields),n=se({type:new sr(this.schema.fields),length:t.length,children:i});return new fr(this.schema,n)}_loadDictionaryBatch(t,e){const{id:i,isDelta:n}=t,{dictionaries:s,schema:o}=this,a=s.get(i),l=o.dictionaries.get(i),u=this._loadVectors(t.data,e,[l]);return(a&&n?a.concat(new Me(u)):new Me(u)).memoize()}_loadVectors(t,e,i){return new a0(e,t.nodes,t.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(i)}}class Nl extends _0{constructor(t,e){super(e),this._reader=rh(t)?new kO(this._handle=t):new y0(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=w0(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):De}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):De}next(){if(this.closed)return De;let t;const{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;const i=t.header(),n=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const i=t.header(),n=e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vf(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}}class Ll extends _0{constructor(t,e){super(e),this._reader=new BO(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Zt(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 Zt(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=w0(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return Zt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):De})}return(t){return Zt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):De})}next(){return Zt(this,void 0,void 0,function*(){if(this.closed)return De;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 i=t.header(),n=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const i=t.header(),n=yield e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vf(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return Zt(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}}class b0 extends Nl{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 Ap?t:new Ap(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 i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&this._handle.seek(i.offset)){const n=this._reader.readMessage(fe.RecordBatch);if(n!=null&&n.isRecordBatch()){const s=n.header(),o=this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null}_readDictionaryBatch(t){var e;const i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&this._handle.seek(i.offset)){const n=this._reader.readMessage(fe.DictionaryBatch);if(n!=null&&n.isDictionaryBatch()){const s=n.header(),o=this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}}_readFooter(){const{_handle:t}=this,e=t.size-g0,i=t.readInt32(e),n=t.readAt(e-i,i);return Ko.decode(n)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Zt(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){return Zt(this,void 0,void 0,function*(){var e;if(this.closed)return null;this._footer||(yield this.open());const i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&(yield this._handle.seek(i.offset))){const n=yield this._reader.readMessage(fe.RecordBatch);if(n!=null&&n.isRecordBatch()){const s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null})}_readDictionaryBatch(t){return Zt(this,void 0,void 0,function*(){var e;const i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&(yield this._handle.seek(i.offset))){const n=yield this._reader.readMessage(fe.DictionaryBatch);if(n!=null&&n.isDictionaryBatch()){const s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}})}_readFooter(){return Zt(this,void 0,void 0,function*(){const{_handle:t}=this;t._pending&&(yield t._pending);const e=t.size-g0,i=yield t.readInt32(e),n=yield t.readAt(e-i,i);return Ko.decode(n)})}_readNextMessageAndValidate(t){return Zt(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?wf(t)?new v0(new b0(r.read())):new Dl(new Nl(r)):new Dl(new Nl(function*(){}()))}function WO(r){return Zt(this,void 0,void 0,function*(){const t=yield r.peek(ca+7&-8);return t&&t.byteLength>=4?wf(t)?new v0(new b0(yield r.read())):new Rl(new Ll(r)):new Rl(new Ll(function(){return dr(this,arguments,function*(){})}()))})}function HO(r){return Zt(this,void 0,void 0,function*(){const{size:t}=yield r.stat(),e=new Ml(r,t);return t>=UO&&wf(yield e.readAt(0,ca+7&-8))?new zO(new jO(e)):new Rl(new Ll(e))})}class Ne extends ie{static assemble(...t){const e=n=>n.flatMap(s=>Array.isArray(s)?e(s):s instanceof fr?s.data.children:s.data),i=new Ne;return i.visitMany(e(t)),i}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof Me)return this.visitMany(t.data),this;const{type:e}=t;if(!At.isDictionary(e)){const{length:i}=t;if(i>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");if(At.isUnion(e))this.nodes.push(new vn(i,0));else{const{nullCount:n}=t;At.isNull(e)||ti.call(this,n<=0?new Uint8Array(0):Cl(t.offset,i,t.nullBitmap)),this.nodes.push(new vn(i,n))}}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 ti(r){const t=r.byteLength+7&-8;return this.buffers.push(r),this.bufferRegions.push(new vi(this._byteLength,t)),this._byteLength+=t,this}function XO(r){var t;const{type:e,length:i,typeIds:n,valueOffsets:s}=r;if(ti.call(this,n),e.mode===er.Sparse)return mh.call(this,r);if(e.mode===er.Dense){if(r.offset<=0)return ti.call(this,s),mh.call(this,r);{const o=new Int32Array(i),a=Object.create(null),l=Object.create(null);for(let u,c,h=-1;++h{const h=e.typeIds[c],p=a[h],f=l[h];return u.slice(p,Math.min(i,f))}))}}return this}function YO(r){let t;return r.nullCount>=r.length?ti.call(this,new Uint8Array(0)):(t=r.values)instanceof Uint8Array?ti.call(this,Cl(r.offset,r.length,t)):ti.call(this,Al(r.values))}function Yi(r){return ti.call(this,r.values.subarray(0,r.length*r.stride))}function nu(r){const{length:t,values:e,valueOffsets:i}=r,n=we(i[0]),s=we(i[t]),o=Math.min(s-n,e.byteLength-n);return ti.call(this,Iv(-n,t+1,i)),ti.call(this,e.subarray(n,n+o)),this}function xf(r){const{length:t,valueOffsets:e}=r;if(e){const{[0]:i,[t]:n}=e;return ti.call(this,Iv(-i,t+1,e)),this.visit(r.children[0].slice(i,n-i))}return this.visit(r.children[0])}function mh(r){return this.visitMany(r.type.children.map((t,e)=>r.children[e]).filter(Boolean))[0]}Ne.prototype.visitBool=YO;Ne.prototype.visitInt=Yi;Ne.prototype.visitFloat=Yi;Ne.prototype.visitUtf8=nu;Ne.prototype.visitLargeUtf8=nu;Ne.prototype.visitBinary=nu;Ne.prototype.visitLargeBinary=nu;Ne.prototype.visitFixedSizeBinary=Yi;Ne.prototype.visitDate=Yi;Ne.prototype.visitTimestamp=Yi;Ne.prototype.visitTime=Yi;Ne.prototype.visitDecimal=Yi;Ne.prototype.visitList=xf;Ne.prototype.visitStruct=mh;Ne.prototype.visitUnion=XO;Ne.prototype.visitInterval=Yi;Ne.prototype.visitDuration=Yi;Ne.prototype.visitFixedSizeList=xf;Ne.prototype.visitMap=xf;class x0 extends df{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 Wa,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,pr(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 rs(t)?t.then(e=>this.writeAll(e)):no(t)?Ef(this,t):If(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 Wa?this._sink=t:(this._sink=new Wa,t&&SC(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&TC(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||!dh(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 gn&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof fr&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!dh(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof fr?t instanceof vf||this._writeRecordBatch(t):t instanceof gn?this.writeAll(t.batches):oa(t)&&this.writeAll(t)}_writeMessage(t,e=8){const i=e-1,n=or.encode(t),s=n.byteLength,o=this._writeLegacyIpcFormat?4:8,a=s+o+i&~i,l=a-s-o;return t.headerType===fe.RecordBatch?this._recordBatchBlocks.push(new mn(a,t.bodyLength,this._position)):t.headerType===fe.DictionaryBatch&&this._dictionaryBlocks.push(new mn(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-o)),s>0&&this._write(n),this._writePadding(l)}_write(t){if(this._started){const e=ae(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(or.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(Zo)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){const{byteLength:e,nodes:i,bufferRegions:n,buffers:s}=Ne.assemble(t),o=new Fr(t.numRows,i,n),a=or.from(o,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(s)}_writeDictionaryBatch(t,e,i=!1){const{byteLength:n,nodes:s,bufferRegions:o,buffers:a}=Ne.assemble(new Me([t])),l=new Fr(t.length,s,o),u=new Ti(l,e,i),c=or.from(u,n);return this._writeMessage(c)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,i,n;for(let s=-1,o=t.length;++s0&&(this._write(e),(n=(i+7&-8)-i)>0&&this._writePadding(n));return this}_writeDictionaries(t){var e,i;for(const[n,s]of t.dictionaries){const o=(e=s==null?void 0:s.data)!==null&&e!==void 0?e:[],a=this._seenDictionaries.get(n),l=(i=this._dictionaryDeltaOffsets.get(n))!==null&&i!==void 0?i:0;if(!a||a.data[0]!==o[0])for(const[u,c]of o.entries())this._writeDictionaryBatch(c,n,u>0);else if(li.writeAll(n)):no(t)?Ef(i,t):If(i,t)}}class Tf extends x0{static writeAll(t){const e=new Tf;return rs(t)?t.then(i=>e.writeAll(i)):no(t)?Ef(e,t):If(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(t,e,i=!1){if(!i&&this._seenDictionaries.has(e))throw new Error("The Arrow File format does not support replacement dictionaries. ");return super._writeDictionaryBatch(t,e,i)}_writeFooter(t){const e=Ko.encode(new Ko(t,ke.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}}function If(r,t){let e=t;t instanceof gn&&(e=t.batches,r.reset(void 0,t.schema));for(const i of e)r.write(i);return r.finish()}function Ef(r,t){return Zt(this,void 0,void 0,function*(){var e,i,n,s,o,a,l;try{for(e=!0,i=bi(t);n=yield i.next(),s=n.done,!s;e=!0){l=n.value,e=!1;const u=l;r.write(u)}}catch(u){o={error:u}}finally{try{!e&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return r.finish()})}function qO(r,t="stream"){return(t==="stream"?Sf:Tf).writeAll(r).toUint8Array(!0)}var QO=Object.create,S0=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,ZO=Object.getOwnPropertyNames,JO=Object.getPrototypeOf,t2=Object.prototype.hasOwnProperty,e2=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),r2=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ZO(t))!t2.call(r,n)&&n!==e&&S0(r,n,{get:()=>t[n],enumerable:!(i=KO(t,n))||i.enumerable});return r},i2=(r,t,e)=>(e=r!=null?QO(JO(r)):{},r2(!r||!r.__esModule?S0(e,"default",{value:r,enumerable:!0}):e,r)),n2=e2((r,t)=>{t.exports=Worker}),T0=(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))(T0||{}),s2=(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))(s2||{}),o2=(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))(o2||{}),a2=(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))(a2||{}),l2=(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))(l2||{}),u2=(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))(u2||{}),c2=class{log(r){}},I0=class{constructor(r=2){this.level=r}log(r){r.level>=this.level&&console.log(r)}},h2=(r=>(r[r.SUCCESS=0]="SUCCESS",r))(h2||{}),f2=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=Vr.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new gn(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 i=new E0(this._bindings,this._conn,e),n=await Vr.from(i);return console.assert(n.isAsync()),console.assert(n.isStream()),n}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 d2(this._bindings,this._conn,t)}async insertArrowTable(r,t){let e=qO(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)}},E0=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}},d2=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=Vr.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new gn(e)}async send(...r){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,r),e=new E0(this.bindings,this.connectionId,t),i=await Vr.from(e);return console.assert(i.isAsync()),console.assert(i.isStream()),i}},p2=(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))(p2||{}),m2=(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))(m2||{}),ue=class{constructor(r,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=r,this.data=t,this.promise=new Promise((e,i)=>{this.promiseResolver=e,this.promiseRejecter=i})}};function Ya(r){switch(r.typeId){case L.Binary:return{sqlType:"binary"};case L.Bool:return{sqlType:"bool"};case L.Date:return{sqlType:"date"};case L.DateDay:return{sqlType:"date32[d]"};case L.DateMillisecond:return{sqlType:"date64[ms]"};case L.Decimal:{let t=r;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case L.Float:return{sqlType:"float"};case L.Float16:return{sqlType:"float16"};case L.Float32:return{sqlType:"float32"};case L.Float64:return{sqlType:"float64"};case L.Int:return{sqlType:"int32"};case L.Int16:return{sqlType:"int16"};case L.Int32:return{sqlType:"int32"};case L.Int64:return{sqlType:"int64"};case L.Uint16:return{sqlType:"uint16"};case L.Uint32:return{sqlType:"uint32"};case L.Uint64:return{sqlType:"uint64"};case L.Uint8:return{sqlType:"uint8"};case L.IntervalDayTime:return{sqlType:"interval[dt]"};case L.IntervalYearMonth:return{sqlType:"interval[m]"};case L.List:return{sqlType:"list",valueType:Ya(r.valueType)};case L.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:r.byteWidth};case L.Null:return{sqlType:"null"};case L.Utf8:return{sqlType:"utf8"};case L.Struct:return{sqlType:"struct",fields:r.children.map(t=>yh(t.name,t.type))};case L.Map:{let t=r;return{sqlType:"map",keyType:Ya(t.keyType),valueType:Ya(t.valueType)}}case L.Time:return{sqlType:"time[s]"};case L.TimeMicrosecond:return{sqlType:"time[us]"};case L.TimeMillisecond:return{sqlType:"time[ms]"};case L.TimeNanosecond:return{sqlType:"time[ns]"};case L.TimeSecond:return{sqlType:"time[s]"};case L.Timestamp:return{sqlType:"timestamp",timezone:r.timezone||void 0};case L.TimestampSecond:return{sqlType:"timestamp[s]",timezone:r.timezone||void 0};case L.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:r.timezone||void 0};case L.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:r.timezone||void 0};case L.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:r.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(r.toString()))}function yh(r,t){let e=Ya(t);return e.name=r,e}var y2=new TextEncoder,g2=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 n of this._onInstantiationProgress)n(e.data);return}}let i=this._pendingRequests.get(e.requestId);if(!i){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let n=new Error(e.data.message);n.name=e.data.name,(t=Object.getOwnPropertyDescriptor(n,"stack"))!=null&&t.writable&&(n.stack=e.data.stack),i.promiseRejecter(n);return}switch(i.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"){i.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){i.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){i.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){i.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){i.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){i.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){i.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){i.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){i.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){i.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){i.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){i.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){i.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){i.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){i.promiseResolver(e.data);return}break}i.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 ue("RESET",null);return await this.postTask(r)}async ping(){let r=new ue("PING",null);await this.postTask(r)}async dropFile(r){let t=new ue("DROP_FILE",r);return await this.postTask(t)}async dropFiles(){let r=new ue("DROP_FILES",null);return await this.postTask(r)}async flushFiles(){let r=new ue("FLUSH_FILES",null);return await this.postTask(r)}async instantiate(r,t=null,e=i=>{}){this._onInstantiationProgress.push(e);let i=new ue("INSTANTIATE",[r,t]);return await this.postTask(i)}async getVersion(){let r=new ue("GET_VERSION",null);return await this.postTask(r)}async getFeatureFlags(){let r=new ue("GET_FEATURE_FLAGS",null);return await this.postTask(r)}async open(r){let t=new ue("OPEN",r);await this.postTask(t)}async tokenize(r){let t=new ue("TOKENIZE",r);return await this.postTask(t)}async connectInternal(){let r=new ue("CONNECT",null);return await this.postTask(r)}async connect(){let r=await this.connectInternal();return new f2(this,r)}async disconnect(r){let t=new ue("DISCONNECT",r);await this.postTask(t)}async runQuery(r,t){let e=new ue("RUN_QUERY",[r,t]);return await this.postTask(e)}async startPendingQuery(r,t,e=!1){let i=new ue("START_PENDING_QUERY",[r,t,e]);return await this.postTask(i)}async pollPendingQuery(r){let t=new ue("POLL_PENDING_QUERY",r);return await this.postTask(t)}async cancelPendingQuery(r){let t=new ue("CANCEL_PENDING_QUERY",r);return await this.postTask(t)}async fetchQueryResults(r){let t=new ue("FETCH_QUERY_RESULTS",r);return await this.postTask(t)}async getTableNames(r,t){let e=new ue("GET_TABLE_NAMES",[r,t]);return await this.postTask(e)}async createPrepared(r,t){let e=new ue("CREATE_PREPARED",[r,t]);return await this.postTask(e)}async closePrepared(r,t){let e=new ue("CLOSE_PREPARED",[r,t]);await this.postTask(e)}async runPrepared(r,t,e){let i=new ue("RUN_PREPARED",[r,t,e]);return await this.postTask(i)}async sendPrepared(r,t,e){let i=new ue("SEND_PREPARED",[r,t,e]);return await this.postTask(i)}async globFiles(r){let t=new ue("GLOB_FILE_INFOS",r);return await this.postTask(t)}async registerFileText(r,t){let e=y2.encode(t);await this.registerFileBuffer(r,e)}async registerFileURL(r,t,e,i){t===void 0&&(t=r);let n=new ue("REGISTER_FILE_URL",[r,t,e,i]);await this.postTask(n)}async registerEmptyFileBuffer(r){}async registerFileBuffer(r,t){let e=new ue("REGISTER_FILE_BUFFER",[r,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(r,t,e,i){let n=new ue("REGISTER_FILE_HANDLE",[r,t,e,i]);await this.postTask(n,[])}async registerOPFSFileName(r){let t=new ue("REGISTER_OPFS_FILE_NAME",[r]);await this.postTask(t,[])}async collectFileStatistics(r,t){let e=new ue("COLLECT_FILE_STATISTICS",[r,t]);await this.postTask(e,[])}async exportFileStatistics(r){let t=new ue("EXPORT_FILE_STATISTICS",r);return await this.postTask(t,[])}async copyFileToBuffer(r){let t=new ue("COPY_FILE_TO_BUFFER",r);return await this.postTask(t)}async copyFileToPath(r,t){let e=new ue("COPY_FILE_TO_PATH",[r,t]);await this.postTask(e)}async insertArrowFromIPCStream(r,t,e){if(t.length==0)return;let i=new ue("INSERT_ARROW_FROM_IPC_STREAM",[r,t,e]);await this.postTask(i,[t.buffer])}async insertCSVFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(yh(s,o))}e.columnsFlat=n,delete e.columns}let i=new ue("IMPORT_CSV_FROM_PATH",[r,t,e]);await this.postTask(i)}async insertJSONFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(yh(s,o))}e.columnsFlat=n,delete e.columns}let i=new ue("IMPORT_JSON_FROM_PATH",[r,t,e]);await this.postTask(i)}};function v2(){let r=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),r.decode(t))}v2();var _2=(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))(_2||{}),b2=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])),w2=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])),x2=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])),S2=()=>(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])),T2={version:"1.29.1-dev68.0"},Cf=T2.version.split(".");Cf[0];Cf[1];Cf[2];var I2=()=>typeof navigator>"u",Ku=null,Zu=null,Ju=null,tc=null,ec=null;async function E2(){return Ku==null&&(Ku=typeof BigInt64Array<"u"),Zu==null&&(Zu=await w2()),Ju==null&&(Ju=await S2()),tc==null&&(tc=await x2()),ec==null&&(ec=await b2()),{bigInt64Array:Ku,crossOriginIsolated:I2()||globalThis.crossOriginIsolated||!1,wasmExceptions:Zu,wasmSIMD:tc,wasmThreads:Ju,wasmBulkMemory:ec}}async function kp(r){let t=await E2();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}}i2(n2());const rc={},Mo={};function Lo(r,t){try{const i=(rc[r]||(rc[r]=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour:"numeric",timeZoneName:"longOffset"}).format))(t).split("GMT")[1]||"";return i in Mo?Mo[i]:Up(i,i.split(":"))}catch{if(r in Mo)return Mo[r];const e=r==null?void 0:r.match(C2);return e?Up(r,e.slice(1)):NaN}}const C2=/([+-]\d\d):?(\d\d)?/;function Up(r,t){const e=+t[0],i=+(t[1]||0);return Mo[r]=e>0?e*60+i:e*60-i}class Er extends Date{constructor(...t){super(),t.length>1&&typeof t[t.length-1]=="string"&&(this.timeZone=t.pop()),this.internal=new Date,isNaN(Lo(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)),C0(this),gh(this)):this.setTime(Date.now())}static tz(t,...e){return e.length?new Er(...e,t):new Er(Date.now(),t)}withTimeZone(t){return new Er(+this,t)}getTimezoneOffset(){return-Lo(this.timeZone,this)}setTime(t){return Date.prototype.setTime.apply(this,arguments),gh(this),+this}[Symbol.for("constructDateFrom")](t){return new Er(+new Date(t),this.timeZone)}}const zp=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(r=>{if(!zp.test(r))return;const t=r.replace(zp,"$1UTC");Er.prototype[t]&&(r.startsWith("get")?Er.prototype[r]=function(){return this.internal[t]()}:(Er.prototype[r]=function(){return Date.prototype[t].apply(this.internal,arguments),A2(this),+this},Er.prototype[t]=function(){return Date.prototype[t].apply(this,arguments),gh(this),+this}))});function gh(r){r.internal.setTime(+r),r.internal.setUTCMinutes(r.internal.getUTCMinutes()-r.getTimezoneOffset())}function A2(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()),C0(r)}function C0(r){const t=Lo(r.timeZone,r),e=new Date(+r);e.setUTCHours(e.getUTCHours()-1);const i=-new Date(+r).getTimezoneOffset(),n=-new Date(+e).getTimezoneOffset(),s=i-n,o=Date.prototype.getHours.apply(r)!==r.internal.getUTCHours();s&&o&&r.internal.setUTCMinutes(r.internal.getUTCMinutes()+s);const a=i-t;a&&Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+a);const l=Lo(r.timeZone,r),c=-new Date(+r).getTimezoneOffset()-l,h=l!==t,p=c-a;if(h&&p){Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+p);const f=Lo(r.timeZone,r),y=l-f;y&&(r.internal.setUTCMinutes(r.internal.getUTCMinutes()+y),Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+y))}}const O2=new TextDecoder("utf-8"),F2=r=>O2.decode(r),P2=new TextEncoder,A0=r=>P2.encode(r),hi=r=>typeof r=="function",ha=r=>r!=null&&Object(r)===r,M2=r=>ha(r)&&hi(r.then),O0=r=>ha(r)&&hi(r[Symbol.iterator]),D2=r=>ha(r)&&hi(r[Symbol.asyncIterator]),R2=r=>ha(r)&&"done"in r&&"value"in r,N2=r=>ha(r)&&hi(r.clear)&&hi(r.bytes)&&hi(r.position)&&hi(r.setPosition)&&hi(r.capacity)&&hi(r.getBufferIdentifier)&&hi(r.createLong),Af=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function L2(r){const t=r[0]?[r[0]]:[];let e,i,n,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let n,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,i);for(const c=e.length;++lrr(Int8Array,r),U2=r=>rr(Int16Array,r),z2=r=>rr(Int32Array,r),j2=r=>rr(BigInt64Array,r),$2=r=>rr(Uint8Array,r),V2=r=>rr(Uint16Array,r),G2=r=>rr(Uint32Array,r),W2=r=>rr(BigUint64Array,r),H2=r=>rr(Float32Array,r),X2=r=>rr(Float64Array,r),Y2=r=>rr(Uint8ClampedArray,r),_h=r=>(r.next(),r);function*Oi(r,t){const e=function*(n){yield n},i=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof Af?e(t):O0(t)?t:e(t);return yield*_h(function*(n){let s=null;do s=n.next(yield rr(r,s));while(!s.done)}(i[Symbol.iterator]())),new r}const q2=r=>Oi(Int8Array,r),Q2=r=>Oi(Int16Array,r),K2=r=>Oi(Int32Array,r),Z2=r=>Oi(Uint8Array,r),J2=r=>Oi(Uint16Array,r),tF=r=>Oi(Uint32Array,r),eF=r=>Oi(Float32Array,r),rF=r=>Oi(Float64Array,r),iF=r=>Oi(Uint8ClampedArray,r);function ii(r,t){return dr(this,arguments,function*(){if(M2(t))return yield Pt(yield Pt(yield*ts(bi(ii(r,yield Pt(t))))));const i=function(o){return dr(this,arguments,function*(){yield yield Pt(yield Pt(o))})},n=function(o){return dr(this,arguments,function*(){yield Pt(yield*ts(bi(_h(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 Af?i(t):O0(t)?n(t):D2(t)?t:i(t);return yield Pt(yield*ts(bi(_h(function(o){return dr(this,arguments,function*(){let a=null;do a=yield Pt(o.next(yield yield Pt(rr(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Pt(new r)})}const nF=r=>ii(Int8Array,r),sF=r=>ii(Int16Array,r),oF=r=>ii(Int32Array,r),aF=r=>ii(Uint8Array,r),lF=r=>ii(Uint16Array,r),uF=r=>ii(Uint32Array,r),cF=r=>ii(Float32Array,r),hF=r=>ii(Float64Array,r),fF=r=>ii(Uint8ClampedArray,r);function dF(r,t,e){if(r!==0){e=e.slice(0,t);for(let i=-1,n=e.length;++i0)do if(r[e]!==t[e])return!1;while(++eeo(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}const yF=Object.freeze(Object.defineProperty({__proto__:null,valueToString:eo},Symbol.toStringTag,{value:"Module"}));function ar(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 P0(r,t){return ar(r/t)+ar(r%t)/ar(t)}const M0=Symbol.for("isArrowBigNum");function ni(r,...t){return t.length===0?Object.setPrototypeOf(rr(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}ni.prototype[M0]=!0;ni.prototype.toJSON=function(){return`"${ro(this)}"`};ni.prototype.valueOf=function(r){return Of(this,r)};ni.prototype.toString=function(){return ro(this)};ni.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Of(this);case"string":return ro(this);case"default":return D0(this)}return ro(this)};function Gs(...r){return ni.apply(this,r)}function Ws(...r){return ni.apply(this,r)}function Jo(...r){return ni.apply(this,r)}Object.setPrototypeOf(Gs.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(Ws.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Jo.prototype,Object.create(Uint32Array.prototype));Object.assign(Gs.prototype,ni.prototype,{constructor:Gs,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(Ws.prototype,ni.prototype,{constructor:Ws,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Jo.prototype,ni.prototype,{constructor:Jo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const gF=BigInt(4294967296)*BigInt(4294967296),vF=gF-BigInt(1);function Of(r,t){const{buffer:e,byteOffset:i,byteLength:n,signed:s}=r,o=new BigUint64Array(e,i,n/8),a=s&&o.at(-1)&BigInt(1)<=0)return ic(r);t=t.slice();let i=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(Et.prototype);class jp extends Et{constructor(){super(W.Null)}toString(){return"Null"}}N0=Symbol.toStringTag;jp[N0]=(r=>r[Symbol.toStringTag]="Null")(jp.prototype);class $p extends Et{constructor(t,e){super(W.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}`}}L0=Symbol.toStringTag;$p[L0]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))($p.prototype);class Vp extends Et{constructor(t){super(W.Float),this.precision=t}get ArrayType(){switch(this.precision){case Cr.HALF:return Uint16Array;case Cr.SINGLE:return Float32Array;case Cr.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}B0=Symbol.toStringTag;Vp[B0]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(Vp.prototype);class Gp extends Et{constructor(){super(W.Binary)}toString(){return"Binary"}}k0=Symbol.toStringTag;Gp[k0]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(Gp.prototype);class Wp extends Et{constructor(){super(W.LargeBinary)}toString(){return"LargeBinary"}}U0=Symbol.toStringTag;Wp[U0]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(Wp.prototype);class Hp extends Et{constructor(){super(W.Utf8)}toString(){return"Utf8"}}z0=Symbol.toStringTag;Hp[z0]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(Hp.prototype);class Xp extends Et{constructor(){super(W.LargeUtf8)}toString(){return"LargeUtf8"}}j0=Symbol.toStringTag;Xp[j0]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(Xp.prototype);class Yp extends Et{constructor(){super(W.Bool)}toString(){return"Bool"}}$0=Symbol.toStringTag;Yp[$0]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(Yp.prototype);class qp extends Et{constructor(t,e,i=128){super(W.Decimal),this.scale=t,this.precision=e,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}V0=Symbol.toStringTag;qp[V0]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(qp.prototype);class Qp extends Et{constructor(t){super(W.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${_n[this.unit]}>`}get ArrayType(){return this.unit===_n.DAY?Int32Array:BigInt64Array}}G0=Symbol.toStringTag;Qp[G0]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(Qp.prototype);class Kp extends Et{constructor(t,e){super(W.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${Jt[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}W0=Symbol.toStringTag;Kp[W0]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(Kp.prototype);class Zp extends Et{constructor(t,e){super(W.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${Jt[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}H0=Symbol.toStringTag;Zp[H0]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(Zp.prototype);class Jp extends Et{constructor(t){super(W.Interval),this.unit=t}toString(){return`Interval<${ns[this.unit]}>`}}X0=Symbol.toStringTag;Jp[X0]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(Jp.prototype);class tm extends Et{constructor(t){super(W.Duration),this.unit=t}toString(){return`Duration<${Jt[this.unit]}>`}}Y0=Symbol.toStringTag;tm[Y0]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(tm.prototype);class em extends Et{constructor(t){super(W.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}}q0=Symbol.toStringTag;em[q0]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(em.prototype);class bh extends Et{constructor(t){super(W.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}}Q0=Symbol.toStringTag;bh[Q0]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(bh.prototype);class rm extends Et{constructor(t,e,i){super(W.Union),this.mode=t,this.children=i,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((n,s,o)=>(n[s]=o)&&n||n,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}}K0=Symbol.toStringTag;rm[K0]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))(rm.prototype);class im extends Et{constructor(t){super(W.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}Z0=Symbol.toStringTag;im[Z0]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(im.prototype);class nm extends Et{constructor(t,e){super(W.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}>`}}J0=Symbol.toStringTag;nm[J0]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(nm.prototype);class sm extends Et{constructor(t,e=!1){var i,n,s;if(super(W.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((i=t==null?void 0:t.type)===null||i===void 0)&&i.children)){const o=(n=t==null?void 0:t.type)===null||n===void 0?void 0:n.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(", ")}}>`}}tb=Symbol.toStringTag;sm[tb]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(sm.prototype);const bF=(r=>()=>++r)(-1);class om extends Et{constructor(t,e,i,n){super(W.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=n||!1,this.id=i==null?bF():ar(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}eb=Symbol.toStringTag;om[eb]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(om.prototype);function rb(r){const t=r;switch(r.typeId){case W.Decimal:return r.bitWidth/32;case W.Interval:return 1+t.unit;case W.FixedSizeList:return t.listSize;case W.FixedSizeBinary:return t.byteWidth;default:return 1}}class le{visitMany(t,...e){return t.map((i,n)=>this.visit(i,...e.map(s=>s[n])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return wF(this,t,e)}getVisitFnByTypeId(t,e=!0){return Ps(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 wF(r,t,e=!0){return typeof t=="number"?Ps(r,t,e):typeof t=="string"&&t in W?Ps(r,W[t],e):t&&t instanceof Et?Ps(r,am(t),e):t!=null&&t.type&&t.type instanceof Et?Ps(r,am(t.type),e):Ps(r,W.NONE,e)}function Ps(r,t,e=!0){let i=null;switch(t){case W.Null:i=r.visitNull;break;case W.Bool:i=r.visitBool;break;case W.Int:i=r.visitInt;break;case W.Int8:i=r.visitInt8||r.visitInt;break;case W.Int16:i=r.visitInt16||r.visitInt;break;case W.Int32:i=r.visitInt32||r.visitInt;break;case W.Int64:i=r.visitInt64||r.visitInt;break;case W.Uint8:i=r.visitUint8||r.visitInt;break;case W.Uint16:i=r.visitUint16||r.visitInt;break;case W.Uint32:i=r.visitUint32||r.visitInt;break;case W.Uint64:i=r.visitUint64||r.visitInt;break;case W.Float:i=r.visitFloat;break;case W.Float16:i=r.visitFloat16||r.visitFloat;break;case W.Float32:i=r.visitFloat32||r.visitFloat;break;case W.Float64:i=r.visitFloat64||r.visitFloat;break;case W.Utf8:i=r.visitUtf8;break;case W.LargeUtf8:i=r.visitLargeUtf8;break;case W.Binary:i=r.visitBinary;break;case W.LargeBinary:i=r.visitLargeBinary;break;case W.FixedSizeBinary:i=r.visitFixedSizeBinary;break;case W.Date:i=r.visitDate;break;case W.DateDay:i=r.visitDateDay||r.visitDate;break;case W.DateMillisecond:i=r.visitDateMillisecond||r.visitDate;break;case W.Timestamp:i=r.visitTimestamp;break;case W.TimestampSecond:i=r.visitTimestampSecond||r.visitTimestamp;break;case W.TimestampMillisecond:i=r.visitTimestampMillisecond||r.visitTimestamp;break;case W.TimestampMicrosecond:i=r.visitTimestampMicrosecond||r.visitTimestamp;break;case W.TimestampNanosecond:i=r.visitTimestampNanosecond||r.visitTimestamp;break;case W.Time:i=r.visitTime;break;case W.TimeSecond:i=r.visitTimeSecond||r.visitTime;break;case W.TimeMillisecond:i=r.visitTimeMillisecond||r.visitTime;break;case W.TimeMicrosecond:i=r.visitTimeMicrosecond||r.visitTime;break;case W.TimeNanosecond:i=r.visitTimeNanosecond||r.visitTime;break;case W.Decimal:i=r.visitDecimal;break;case W.List:i=r.visitList;break;case W.Struct:i=r.visitStruct;break;case W.Union:i=r.visitUnion;break;case W.DenseUnion:i=r.visitDenseUnion||r.visitUnion;break;case W.SparseUnion:i=r.visitSparseUnion||r.visitUnion;break;case W.Dictionary:i=r.visitDictionary;break;case W.Interval:i=r.visitInterval;break;case W.IntervalDayTime:i=r.visitIntervalDayTime||r.visitInterval;break;case W.IntervalYearMonth:i=r.visitIntervalYearMonth||r.visitInterval;break;case W.Duration:i=r.visitDuration;break;case W.DurationSecond:i=r.visitDurationSecond||r.visitDuration;break;case W.DurationMillisecond:i=r.visitDurationMillisecond||r.visitDuration;break;case W.DurationMicrosecond:i=r.visitDurationMicrosecond||r.visitDuration;break;case W.DurationNanosecond:i=r.visitDurationNanosecond||r.visitDuration;break;case W.FixedSizeList:i=r.visitFixedSizeList;break;case W.Map:i=r.visitMap;break}if(typeof i=="function")return i;if(!e)return()=>null;throw new Error(`Unrecognized type '${W[t]}'`)}function am(r){switch(r.typeId){case W.Null:return W.Null;case W.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?W.Int8:W.Uint8;case 16:return e?W.Int16:W.Uint16;case 32:return e?W.Int32:W.Uint32;case 64:return e?W.Int64:W.Uint64}return W.Int}case W.Float:switch(r.precision){case Cr.HALF:return W.Float16;case Cr.SINGLE:return W.Float32;case Cr.DOUBLE:return W.Float64}return W.Float;case W.Binary:return W.Binary;case W.LargeBinary:return W.LargeBinary;case W.Utf8:return W.Utf8;case W.LargeUtf8:return W.LargeUtf8;case W.Bool:return W.Bool;case W.Decimal:return W.Decimal;case W.Time:switch(r.unit){case Jt.SECOND:return W.TimeSecond;case Jt.MILLISECOND:return W.TimeMillisecond;case Jt.MICROSECOND:return W.TimeMicrosecond;case Jt.NANOSECOND:return W.TimeNanosecond}return W.Time;case W.Timestamp:switch(r.unit){case Jt.SECOND:return W.TimestampSecond;case Jt.MILLISECOND:return W.TimestampMillisecond;case Jt.MICROSECOND:return W.TimestampMicrosecond;case Jt.NANOSECOND:return W.TimestampNanosecond}return W.Timestamp;case W.Date:switch(r.unit){case _n.DAY:return W.DateDay;case _n.MILLISECOND:return W.DateMillisecond}return W.Date;case W.Interval:switch(r.unit){case ns.DAY_TIME:return W.IntervalDayTime;case ns.YEAR_MONTH:return W.IntervalYearMonth}return W.Interval;case W.Duration:switch(r.unit){case Jt.SECOND:return W.DurationSecond;case Jt.MILLISECOND:return W.DurationMillisecond;case Jt.MICROSECOND:return W.DurationMicrosecond;case Jt.NANOSECOND:return W.DurationNanosecond}return W.Duration;case W.Map:return W.Map;case W.List:return W.List;case W.Struct:return W.Struct;case W.Union:switch(r.mode){case Ii.Dense:return W.DenseUnion;case Ii.Sparse:return W.SparseUnion}return W.Union;case W.FixedSizeBinary:return W.FixedSizeBinary;case W.FixedSizeList:return W.FixedSizeList;case W.Dictionary:return W.Dictionary}throw new Error(`Unrecognized type '${W[r.typeId]}'`)}le.prototype.visitInt8=null;le.prototype.visitInt16=null;le.prototype.visitInt32=null;le.prototype.visitInt64=null;le.prototype.visitUint8=null;le.prototype.visitUint16=null;le.prototype.visitUint32=null;le.prototype.visitUint64=null;le.prototype.visitFloat16=null;le.prototype.visitFloat32=null;le.prototype.visitFloat64=null;le.prototype.visitDateDay=null;le.prototype.visitDateMillisecond=null;le.prototype.visitTimestampSecond=null;le.prototype.visitTimestampMillisecond=null;le.prototype.visitTimestampMicrosecond=null;le.prototype.visitTimestampNanosecond=null;le.prototype.visitTimeSecond=null;le.prototype.visitTimeMillisecond=null;le.prototype.visitTimeMicrosecond=null;le.prototype.visitTimeNanosecond=null;le.prototype.visitDenseUnion=null;le.prototype.visitSparseUnion=null;le.prototype.visitIntervalDayTime=null;le.prototype.visitIntervalYearMonth=null;le.prototype.visitDuration=null;le.prototype.visitDurationSecond=null;le.prototype.visitDurationMillisecond=null;le.prototype.visitDurationMicrosecond=null;le.prototype.visitDurationNanosecond=null;const ib=new Float64Array(1),vs=new Uint32Array(ib.buffer);function Ff(r){const t=(r&31744)>>10,e=(r&1023)/1024,i=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return i*(e?Number.NaN:1/0);case 0:return i*(e?6103515625e-14*e:0)}return i*Math.pow(2,t-15)*(1+e)}function nb(r){if(r!==r)return 32256;ib[0]=r;const t=(vs[1]&2147483648)>>16&65535;let e=vs[1]&2146435072,i=0;return e>=1089470464?vs[0]>0?e=31744:(e=(e&2080374784)>>16,i=(vs[1]&1048575)>>10):e<=1056964608?(i=1048576+(vs[1]&1048575),i=1048576+(i<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,i=(vs[1]&1048575)+512>>10),t|e|i&65535}const xF=Object.freeze(Object.defineProperty({__proto__:null,float64ToUint16:nb,uint16ToFloat64:Ff},Symbol.toStringTag,{value:"Module"}));class Gt extends le{}function Yt(r){return(t,e,i)=>{if(t.setValid(e,i!=null))return r(t,e,i)}}const SF=(r,t,e)=>{r[t]=Math.floor(e/864e5)},sb=(r,t,e,i)=>{if(e+1{const n=r+e;i?t[n>>3]|=1<>3]&=~(1<{r[t]=e},Pf=({values:r},t,e)=>{r[t]=e},ob=({values:r},t,e)=>{r[t]=nb(e)},IF=(r,t,e)=>{switch(r.type.precision){case Cr.HALF:return ob(r,t,e);case Cr.SINGLE:case Cr.DOUBLE:return Pf(r,t,e)}},ab=({values:r},t,e)=>{SF(r,t,e.valueOf())},lb=({values:r},t,e)=>{r[t]=BigInt(e)},EF=({stride:r,values:t},e,i)=>{t.set(i.subarray(0,r),r*e)},ub=({values:r,valueOffsets:t},e,i)=>sb(r,t,e,i),cb=({values:r,valueOffsets:t},e,i)=>sb(r,t,e,A0(i)),CF=(r,t,e)=>{r.type.unit===_n.DAY?ab(r,t,e):lb(r,t,e)},hb=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},fb=({values:r},t,e)=>{r[t]=BigInt(e)},db=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},pb=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},AF=(r,t,e)=>{switch(r.type.unit){case Jt.SECOND:return hb(r,t,e);case Jt.MILLISECOND:return fb(r,t,e);case Jt.MICROSECOND:return db(r,t,e);case Jt.NANOSECOND:return pb(r,t,e)}},mb=({values:r},t,e)=>{r[t]=e},yb=({values:r},t,e)=>{r[t]=e},gb=({values:r},t,e)=>{r[t]=e},vb=({values:r},t,e)=>{r[t]=e},OF=(r,t,e)=>{switch(r.type.unit){case Jt.SECOND:return mb(r,t,e);case Jt.MILLISECOND:return yb(r,t,e);case Jt.MICROSECOND:return gb(r,t,e);case Jt.NANOSECOND:return vb(r,t,e)}},FF=({values:r,stride:t},e,i)=>{r.set(i.subarray(0,t),t*e)},PF=(r,t,e)=>{const i=r.children[0],n=r.valueOffsets,s=Ei.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=n[t],l=n[t+1];a{const i=r.children[0],{valueOffsets:n}=r,s=Ei.getVisitFn(i);let{[t]:o,[t+1]:a}=n;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(i,o,u),++o>=a)break},DF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[s]),RF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(s)),NF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(n.name)),LF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[n.name]),BF=(r,t,e)=>{const i=r.type.children.map(s=>Ei.getVisitFn(s.type)),n=e instanceof Map?NF(t,e):e instanceof Qe?RF(t,e):Array.isArray(e)?DF(t,e):LF(t,e);r.type.children.forEach((s,o)=>n(i[o],r.children[o],s,o))},kF=(r,t,e)=>{r.type.mode===Ii.Dense?_b(r,t,e):bb(r,t,e)},_b=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Ei.visit(n,r.valueOffsets[t],e)},bb=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Ei.visit(n,t,e)},UF=(r,t,e)=>{var i;(i=r.dictionary)===null||i===void 0||i.set(r.values[t],e)},zF=(r,t,e)=>{r.type.unit===ns.DAY_TIME?wb(r,t,e):xb(r,t,e)},wb=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},xb=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},Sb=({values:r},t,e)=>{r[t]=e},Tb=({values:r},t,e)=>{r[t]=e},Ib=({values:r},t,e)=>{r[t]=e},Eb=({values:r},t,e)=>{r[t]=e},jF=(r,t,e)=>{switch(r.type.unit){case Jt.SECOND:return Sb(r,t,e);case Jt.MILLISECOND:return Tb(r,t,e);case Jt.MICROSECOND:return Ib(r,t,e);case Jt.NANOSECOND:return Eb(r,t,e)}},$F=(r,t,e)=>{const{stride:i}=r,n=r.children[0],s=Ei.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=t*i;++o`${eo(t)}: ${eo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new VF(this[Zr],this[Hs])}}class VF{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[Zr].type.children.some(i=>i.name===e)}getOwnPropertyDescriptor(t,e){if(t[Zr].type.children.some(i=>i.name===e))return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Zr].type.children.findIndex(n=>n.name===e);if(i!==-1){const n=Yr.visit(t[Zr].children[i],t[Hs]);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Zr].type.children.findIndex(s=>s.name===e);return n!==-1?(Ei.visit(t[Zr].children[n],t[Hs],i),Reflect.set(t,e,i)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,i):!1}}const WF=new GF;class Lt extends le{}function Wt(r){return(t,e)=>t.getValid(e)?r(t,e):null}const HF=(r,t)=>864e5*r[t],XF=(r,t)=>null,Cb=(r,t,e)=>{if(e+1>=t.length)return null;const i=ar(t[e]),n=ar(t[e+1]);return r.subarray(i,n)},YF=({offset:r,values:t},e)=>{const i=r+e;return(t[i>>3]&1<HF(r,t),Ob=({values:r},t)=>ar(r[t]),xn=({stride:r,values:t},e)=>t[r*e],qF=({stride:r,values:t},e)=>Ff(t[r*e]),Fb=({values:r},t)=>r[t],QF=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),Pb=({values:r,valueOffsets:t},e)=>Cb(r,t,e),Mb=({values:r,valueOffsets:t},e)=>{const i=Cb(r,t,e);return i!==null?F2(i):null},KF=({values:r},t)=>r[t],ZF=({type:r,values:t},e)=>r.precision!==Cr.HALF?t[e]:Ff(t[e]),JF=(r,t)=>r.type.unit===_n.DAY?Ab(r,t):Ob(r,t),Db=({values:r},t)=>1e3*ar(r[t]),Rb=({values:r},t)=>ar(r[t]),Nb=({values:r},t)=>P0(r[t],BigInt(1e3)),Lb=({values:r},t)=>P0(r[t],BigInt(1e6)),tP=(r,t)=>{switch(r.type.unit){case Jt.SECOND:return Db(r,t);case Jt.MILLISECOND:return Rb(r,t);case Jt.MICROSECOND:return Nb(r,t);case Jt.NANOSECOND:return Lb(r,t)}},Bb=({values:r},t)=>r[t],kb=({values:r},t)=>r[t],Ub=({values:r},t)=>r[t],zb=({values:r},t)=>r[t],eP=(r,t)=>{switch(r.type.unit){case Jt.SECOND:return Bb(r,t);case Jt.MILLISECOND:return kb(r,t);case Jt.MICROSECOND:return Ub(r,t);case Jt.NANOSECOND:return zb(r,t)}},rP=({values:r,stride:t},e)=>su.decimal(r.subarray(t*e,t*(e+1))),iP=(r,t)=>{const{valueOffsets:e,stride:i,children:n}=r,{[t*i]:s,[t*i+1]:o}=e,l=n[0].slice(s,o-s);return new Qe([l])},nP=(r,t)=>{const{valueOffsets:e,children:i}=r,{[t]:n,[t+1]:s}=e,o=i[0];return new Df(o.slice(n,s-n))},sP=(r,t)=>new Mf(r,t),oP=(r,t)=>r.type.mode===Ii.Dense?jb(r,t):$b(r,t),jb=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return Yr.visit(i,r.valueOffsets[t])},$b=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return Yr.visit(i,t)},aP=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},lP=(r,t)=>r.type.unit===ns.DAY_TIME?Vb(r,t):Gb(r,t),Vb=({values:r},t)=>r.subarray(2*t,2*(t+1)),Gb=({values:r},t)=>{const e=r[t],i=new Int32Array(2);return i[0]=Math.trunc(e/12),i[1]=Math.trunc(e%12),i},Wb=({values:r},t)=>r[t],Hb=({values:r},t)=>r[t],Xb=({values:r},t)=>r[t],Yb=({values:r},t)=>r[t],uP=(r,t)=>{switch(r.type.unit){case Jt.SECOND:return Wb(r,t);case Jt.MILLISECOND:return Hb(r,t);case Jt.MICROSECOND:return Xb(r,t);case Jt.NANOSECOND:return Yb(r,t)}},cP=(r,t)=>{const{stride:e,children:i}=r,s=i[0].slice(t*e,e);return new Qe([s])};Lt.prototype.visitNull=Wt(XF);Lt.prototype.visitBool=Wt(YF);Lt.prototype.visitInt=Wt(KF);Lt.prototype.visitInt8=Wt(xn);Lt.prototype.visitInt16=Wt(xn);Lt.prototype.visitInt32=Wt(xn);Lt.prototype.visitInt64=Wt(Fb);Lt.prototype.visitUint8=Wt(xn);Lt.prototype.visitUint16=Wt(xn);Lt.prototype.visitUint32=Wt(xn);Lt.prototype.visitUint64=Wt(Fb);Lt.prototype.visitFloat=Wt(ZF);Lt.prototype.visitFloat16=Wt(qF);Lt.prototype.visitFloat32=Wt(xn);Lt.prototype.visitFloat64=Wt(xn);Lt.prototype.visitUtf8=Wt(Mb);Lt.prototype.visitLargeUtf8=Wt(Mb);Lt.prototype.visitBinary=Wt(Pb);Lt.prototype.visitLargeBinary=Wt(Pb);Lt.prototype.visitFixedSizeBinary=Wt(QF);Lt.prototype.visitDate=Wt(JF);Lt.prototype.visitDateDay=Wt(Ab);Lt.prototype.visitDateMillisecond=Wt(Ob);Lt.prototype.visitTimestamp=Wt(tP);Lt.prototype.visitTimestampSecond=Wt(Db);Lt.prototype.visitTimestampMillisecond=Wt(Rb);Lt.prototype.visitTimestampMicrosecond=Wt(Nb);Lt.prototype.visitTimestampNanosecond=Wt(Lb);Lt.prototype.visitTime=Wt(eP);Lt.prototype.visitTimeSecond=Wt(Bb);Lt.prototype.visitTimeMillisecond=Wt(kb);Lt.prototype.visitTimeMicrosecond=Wt(Ub);Lt.prototype.visitTimeNanosecond=Wt(zb);Lt.prototype.visitDecimal=Wt(rP);Lt.prototype.visitList=Wt(iP);Lt.prototype.visitStruct=Wt(sP);Lt.prototype.visitUnion=Wt(oP);Lt.prototype.visitDenseUnion=Wt(jb);Lt.prototype.visitSparseUnion=Wt($b);Lt.prototype.visitDictionary=Wt(aP);Lt.prototype.visitInterval=Wt(lP);Lt.prototype.visitIntervalDayTime=Wt(Vb);Lt.prototype.visitIntervalYearMonth=Wt(Gb);Lt.prototype.visitDuration=Wt(uP);Lt.prototype.visitDurationSecond=Wt(Wb);Lt.prototype.visitDurationMillisecond=Wt(Hb);Lt.prototype.visitDurationMicrosecond=Wt(Xb);Lt.prototype.visitDurationNanosecond=Wt(Yb);Lt.prototype.visitFixedSizeList=Wt(cP);Lt.prototype.visitMap=Wt(nP);const Yr=new Lt,Ms=Symbol.for("keys"),Xs=Symbol.for("vals"),Ds=Symbol.for("kKeysAsStrings"),wh=Symbol.for("_kKeysAsStrings");class Df{constructor(t){return this[Ms]=new Qe([t.children[0]]).memoize(),this[Xs]=t.children[1],new Proxy(this,new fP)}get[Ds](){return this[wh]||(this[wh]=Array.from(this[Ms].toArray(),String))}[Symbol.iterator](){return new hP(this[Ms],this[Xs])}get size(){return this[Ms].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[Ms],e=this[Xs],i={};for(let n=-1,s=t.length;++n`${eo(t)}: ${eo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class hP{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),Yr.visit(this.vals,t)]})}}class fP{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[Ds]}has(t,e){return t[Ds].includes(e)}getOwnPropertyDescriptor(t,e){if(t[Ds].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Ds].indexOf(e);if(i!==-1){const n=Yr.visit(Reflect.get(t,Xs),i);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Ds].indexOf(e);return n!==-1?(Ei.visit(Reflect.get(t,Xs),n,i),Reflect.set(t,e,i)):Reflect.has(t,e)?Reflect.set(t,e,i):!1}}Object.defineProperties(Df.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[Ms]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Xs]:{writable:!0,enumerable:!1,configurable:!1,value:null},[wh]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let lm;function qb(r,t,e,i){const{length:n=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?n:e;return s<0&&(s=(s%n+n)%n),o<0&&(o=(o%n+n)%n),on&&(o=n),i?i(r,s,o):[s,o]}const Qb=(r,t)=>r<0?t+r:r,um=r=>r!==r;function cs(r){if(typeof r!=="object"||r===null)return um(r)?um:e=>e===r;if(r instanceof Date){const e=r.valueOf();return i=>i instanceof Date?i.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?F0(r,e):!1:r instanceof Map?pP(r):Array.isArray(r)?dP(r):r instanceof Qe?mP(r):yP(r,!0)}function dP(r){const t=[];for(let e=-1,i=r.length;++e!1;const i=[];for(let n=-1,s=e.length;++n{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return gP(r,e);case Map:return cm(r,e,e.keys());case Df:case Mf:case Object:case void 0:return cm(r,e,t||Object.keys(e))}return e instanceof Qe?vP(r,e):!1}}function gP(r,t){const e=r.length;if(t.length!==e)return!1;for(let i=-1;++i>i}function bP(r,t,e){return e?!!(r[t>>3]|=1<>3]&=~(1<0||e.byteLength>3):Zb(new au(e,r,t,null,Rf)).subarray(0,i)),n}return e}function Zb(r){const t=[];let e=0,i=0,n=0;for(const o of r)o&&(n|=1<0)&&(t[e++]=n);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}class au{constructor(t,e,i,n,s){this.bytes=t,this.length=i,this.context=n,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,n=t+(t%8===0?0:8-t%8);return Bl(r,t,n)+Bl(r,i,e)+Jb(r,n>>3,i-n>>3)}function Jb(r,t,e){let i=0,n=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:n+e;for(;o-n>=4;)i+=qa(s.getUint32(n)),n+=4;for(;o-n>=2;)i+=qa(s.getUint16(n)),n+=2;for(;o-n>=1;)i+=qa(s.getUint8(n)),n+=1;return i}function qa(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 wP=Object.freeze(Object.defineProperty({__proto__:null,BitIterator:au,getBit:Kb,getBool:Rf,packBools:Zb,popcnt_array:Jb,popcnt_bit_range:Bl,popcnt_uint32:qa,setBool:bP,truncateBitmap:xh},Symbol.toStringTag,{value:"Module"})),xP=-1;class ta{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 Et.isSparseUnion(t)?this.children.some(e=>e.nullable):Et.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:i,nullBitmap:n,typeIds:s}=this;return e&&(t+=e.byteLength),i&&(t+=i.byteLength),n&&(t+=n.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(Et.isUnion(this.type))return this.children.reduce((i,n)=>i+n.nullCount,0);let t=this._nullCount,e;return t<=xP&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-Bl(e,this.offset,this.offset+this.length)),t}constructor(t,e,i,n,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(i||0,0)),this._nullCount=Math.floor(Math.max(n||0,-1));let l;s instanceof ta?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=rb(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(Et.isUnion(e)){const i=e,n=this.children[i.typeIdToChildIndex[this.typeIds[t]]],s=i.mode===Ii.Dense?this.valueOffsets[t]:t;return n.getValid(s)}if(this.nullable&&this.nullCount>0){const i=this.offset+t;return(this.nullBitmap[i>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(xh(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];i=(h&u)!==0,s[c]=e?h|u:h&~u}return i!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,i=this.length,n=this._nullCount,s=this,o=this.children){return new ta(t,e,i,n,s,o,this.dictionary)}slice(t,e){const{stride:i,typeId:n,children:s}=this,o=+(this._nullCount===0)-1,a=n===16?i:1,l=this._sliceBuffers(t,e,i,n);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===W.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:i}=this,n=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);n[e>>3]=(1<0&&n.set(xh(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[zi.VALIDITY]=n,this.clone(this.type,0,t,i+(t-e),s)}_sliceBuffers(t,e,i,n){let s;const{buffers:o}=this;return(s=o[zi.TYPE])&&(o[zi.TYPE]=s.subarray(t,t+e)),(s=o[zi.OFFSET])&&(o[zi.OFFSET]=s.subarray(t,t+e+1))||(s=o[zi.DATA])&&(o[zi.DATA]=n===6?s:s.subarray(i*t,i*(t+e))),o}_sliceChildren(t,e,i){return t.map(n=>n.slice(e,i))}}ta.prototype.children=Object.freeze([]);class hm{constructor(t=0,e){this.numChunks=t,this.getChunkIterator=e,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndext.nullable)}function TP(r){return r.reduce((t,e)=>t+e.nullCount,0)}function IP(r){return r.reduce((t,e,i)=>(t[i+1]=t[i]+e.length,t),new Uint32Array(r.length+1))}function EP(r,t,e,i){const n=[];for(let s=-1,o=r.length;++s=i)break;if(e>=l+u)continue;if(l>=e&&l+u<=i){n.push(a);continue}const c=Math.max(0,e-l),h=Math.min(i-l,u);n.push(a.slice(c,h-c))}return n.length===0&&n.push(r[0].slice(0,0)),n}function Nf(r,t,e,i){let n=0,s=0,o=t.length-1;do{if(n>=o-1)return e0?0:-1}function FP(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let i=0;for(const n of new au(e,r.offset+(t||0),r.length,e,Rf)){if(!n)return i;++i}return-1}function Kt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case W.Union:break;case W.Dictionary:break;default:return FP(r,e)}const i=Yr.getVisitFn(r),n=cs(t);for(let s=(e||0)-1,o=r.length;++s{const n=r.data[i];return n.values.subarray(0,n.length)[Symbol.iterator]()});let e=0;return new hm(r.data.length,i=>{const s=r.data[i].length,o=r.slice(e,e+s);return e+=s,new PP(o)})}class PP{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof ta)))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}=iw[o.typeId],c=s[0];this.isValid=h=>tw(c,h),this.get=h=>a(c,h),this.set=(h,p)=>l(c,h,p),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,nw[o.typeId]),this._offsets=IP(s);break}this.data=s,this.type=o,this.stride=rb(o),this.numChildren=(n=(i=o.children)===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return SP(this.data)}get nullCount(){return TP(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${W[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(Qb(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return MP.visit(this)}concat(...t){return new Qe(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new Qe(qb(this,t,e,({data:i,_offsets:n},s,o)=>EP(i,n,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:i,stride:n,ArrayType:s}=this;switch(t.typeId){case W.Int:case W.Float:case W.Decimal:case W.Time:case W.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,i*n);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*n),o.offset),o.offset+=l*n,o),{array:new s(i*n),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(i=>i.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return Et.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(Et.isDictionary(this.type)){const t=new kl(this.data[0].dictionary),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new Qe(e)}return new kl(this)}unmemoize(){if(Et.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new Qe(e)}return this}}rw=Symbol.toStringTag;Qe[rw]=(r=>{r.type=Et.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(W).map(e=>W[e]).filter(e=>typeof e=="number"&&e!==W.NONE);for(const e of t){const i=Yr.getVisitFnByTypeId(e),n=Ei.getVisitFnByTypeId(e),s=dm.getVisitFnByTypeId(e);iw[e]={get:i,set:n,indexOf:s},nw[e]=Object.create(r,{isValid:{value:fm(tw)},get:{value:fm(Yr.getVisitFnByTypeId(e))},set:{value:CP(Ei.getVisitFnByTypeId(e))},indexOf:{value:AP(dm.getVisitFnByTypeId(e))}})}return"Vector"})(Qe.prototype);class kl extends Qe{constructor(t){super(t.data);const e=this.get,i=this.set,n=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){i.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new kl(n.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Qe(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}const DP=65536;function Ls(r){return r<0&&(r=4294967295+r+1),`0x${r.toString(16)}`}const io=8,Lf=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8];class Bf{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]),i=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let n=e[3]*i[3];this.buffer[0]=n&65535;let s=n>>>16;return n=e[2]*i[3],s+=n,n=e[3]*i[2]>>>0,s+=n,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*i[3]+e[2]*i[2]+e[3]*i[1],this.buffer[1]+=e[0]*i[3]+e[1]*i[2]+e[2]*i[1]+e[3]*i[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`${Ls(this.buffer[3])} ${Ls(this.buffer[2])} ${Ls(this.buffer[1])} ${Ls(this.buffer[0])}`}static multiply(t,e){return new ci(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new ci(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return ci.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return ci.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const i=t.startsWith("-"),n=t.length,s=new ci(e);for(let o=i?1:0;othis.compareFields(i,e[n]))}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 ur(r,t){return t instanceof r.constructor}function hs(r,t){return r===t||ur(r,t)}function Qi(r,t){return r===t||ur(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function lu(r,t){return r===t||ur(r,t)&&r.precision===t.precision}function NP(r,t){return r===t||ur(r,t)&&r.byteWidth===t.byteWidth}function kf(r,t){return r===t||ur(r,t)&&r.unit===t.unit}function fa(r,t){return r===t||ur(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function da(r,t){return r===t||ur(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function LP(r,t){return r===t||ur(r,t)&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}function BP(r,t){return r===t||ur(r,t)&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}function Uf(r,t){return r===t||ur(r,t)&&r.mode===t.mode&&r.typeIds.every((e,i)=>e===t.typeIds[i])&&Ci.compareManyFields(r.children,t.children)}function kP(r,t){return r===t||ur(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&Ci.visit(r.indices,t.indices)&&Ci.visit(r.dictionary,t.dictionary)}function zf(r,t){return r===t||ur(r,t)&&r.unit===t.unit}function pa(r,t){return r===t||ur(r,t)&&r.unit===t.unit}function UP(r,t){return r===t||ur(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}function zP(r,t){return r===t||ur(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}Ut.prototype.visitNull=hs;Ut.prototype.visitBool=hs;Ut.prototype.visitInt=Qi;Ut.prototype.visitInt8=Qi;Ut.prototype.visitInt16=Qi;Ut.prototype.visitInt32=Qi;Ut.prototype.visitInt64=Qi;Ut.prototype.visitUint8=Qi;Ut.prototype.visitUint16=Qi;Ut.prototype.visitUint32=Qi;Ut.prototype.visitUint64=Qi;Ut.prototype.visitFloat=lu;Ut.prototype.visitFloat16=lu;Ut.prototype.visitFloat32=lu;Ut.prototype.visitFloat64=lu;Ut.prototype.visitUtf8=hs;Ut.prototype.visitLargeUtf8=hs;Ut.prototype.visitBinary=hs;Ut.prototype.visitLargeBinary=hs;Ut.prototype.visitFixedSizeBinary=NP;Ut.prototype.visitDate=kf;Ut.prototype.visitDateDay=kf;Ut.prototype.visitDateMillisecond=kf;Ut.prototype.visitTimestamp=fa;Ut.prototype.visitTimestampSecond=fa;Ut.prototype.visitTimestampMillisecond=fa;Ut.prototype.visitTimestampMicrosecond=fa;Ut.prototype.visitTimestampNanosecond=fa;Ut.prototype.visitTime=da;Ut.prototype.visitTimeSecond=da;Ut.prototype.visitTimeMillisecond=da;Ut.prototype.visitTimeMicrosecond=da;Ut.prototype.visitTimeNanosecond=da;Ut.prototype.visitDecimal=hs;Ut.prototype.visitList=LP;Ut.prototype.visitStruct=BP;Ut.prototype.visitUnion=Uf;Ut.prototype.visitDenseUnion=Uf;Ut.prototype.visitSparseUnion=Uf;Ut.prototype.visitDictionary=kP;Ut.prototype.visitInterval=zf;Ut.prototype.visitIntervalDayTime=zf;Ut.prototype.visitIntervalYearMonth=zf;Ut.prototype.visitDuration=pa;Ut.prototype.visitDurationSecond=pa;Ut.prototype.visitDurationMillisecond=pa;Ut.prototype.visitDurationMicrosecond=pa;Ut.prototype.visitDurationNanosecond=pa;Ut.prototype.visitFixedSizeList=UP;Ut.prototype.visitMap=zP;const Ci=new Ut;function jP(r,t){return Ci.compareSchemas(r,t)}function $P(r,t){return Ci.compareFields(r,t)}function VP(r,t){return Ci.visit(r,t)}const pm=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},_F),RP),wP),xF),pF),_P),yF),{compareSchemas:jP,compareFields:$P,compareTypes:VP}),sw=6048e5,GP=864e5,mm=Symbol.for("constructDateFrom");function Gi(r,t){return typeof r=="function"?r(t):r&&typeof r=="object"&&mm in r?r[mm](t):r instanceof Date?new r.constructor(t):new Date(t)}function qr(r,t){return Gi(t||r,r)}let WP={};function uu(){return WP}function ea(r,t){var a,l,u,c;const e=uu(),i=(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,n=qr(r,t==null?void 0:t.in),s=n.getDay(),o=(s=s.getTime()?i+1:e.getTime()>=a.getTime()?i:i-1}function ym(r){const t=qr(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 HP(r,...t){const e=Gi.bind(null,t.find(i=>typeof i=="object"));return t.map(e)}function gm(r,t){const e=qr(r,t==null?void 0:t.in);return e.setHours(0,0,0,0),e}function XP(r,t,e){const[i,n]=HP(e==null?void 0:e.in,r,t),s=gm(i),o=gm(n),a=+s-ym(s),l=+o-ym(o);return Math.round((a-l)/GP)}function YP(r,t){const e=ow(r,t),i=Gi(r,0);return i.setFullYear(e,0,4),i.setHours(0,0,0,0),Ul(i)}function qP(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function QP(r){return!(!qP(r)&&typeof r!="number"||isNaN(+qr(r)))}function KP(r,t){const e=qr(r,t==null?void 0:t.in);return e.setFullYear(e.getFullYear(),0,1),e.setHours(0,0,0,0),e}const ZP={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"}},JP=(r,t,e)=>{let i;const n=ZP[r];return typeof n=="string"?i=n:t===1?i=n.one:i=n.other.replace("{{count}}",t.toString()),e!=null&&e.addSuffix?e.comparison&&e.comparison>0?"in "+i:i+" ago":i};function nc(r){return(t={})=>{const e=t.width?String(t.width):r.defaultWidth;return r.formats[e]||r.formats[r.defaultWidth]}}const tM={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},eM={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},rM={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},iM={date:nc({formats:tM,defaultWidth:"full"}),time:nc({formats:eM,defaultWidth:"full"}),dateTime:nc({formats:rM,defaultWidth:"full"})},nM={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},sM=(r,t,e,i)=>nM[r];function go(r){return(t,e)=>{const i=e!=null&&e.context?String(e.context):"standalone";let n;if(i==="formatting"&&r.formattingValues){const o=r.defaultFormattingWidth||r.defaultWidth,a=e!=null&&e.width?String(e.width):o;n=r.formattingValues[a]||r.formattingValues[o]}else{const o=r.defaultWidth,a=e!=null&&e.width?String(e.width):r.defaultWidth;n=r.values[a]||r.values[o]}const s=r.argumentCallback?r.argumentCallback(t):t;return n[s]}}const oM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},aM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},lM={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"]},uM={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"]},cM={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"}},hM={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"}},fM=(r,t)=>{const e=Number(r),i=e%100;if(i>20||i<10)switch(i%10){case 1:return e+"st";case 2:return e+"nd";case 3:return e+"rd"}return e+"th"},dM={ordinalNumber:fM,era:go({values:oM,defaultWidth:"wide"}),quarter:go({values:aM,defaultWidth:"wide",argumentCallback:r=>r-1}),month:go({values:lM,defaultWidth:"wide"}),day:go({values:uM,defaultWidth:"wide"}),dayPeriod:go({values:cM,defaultWidth:"wide",formattingValues:hM,defaultFormattingWidth:"wide"})};function vo(r){return(t,e={})=>{const i=e.width,n=i&&r.matchPatterns[i]||r.matchPatterns[r.defaultMatchWidth],s=t.match(n);if(!s)return null;const o=s[0],a=i&&r.parsePatterns[i]||r.parsePatterns[r.defaultParseWidth],l=Array.isArray(a)?mM(a,h=>h.test(o)):pM(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 pM(r,t){for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)&&t(r[e]))return e}function mM(r,t){for(let e=0;e{const i=t.match(r.matchPattern);if(!i)return null;const n=i[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(n.length);return{value:o,rest:a}}}const gM=/^(\d+)(th|st|nd|rd)?/i,vM=/\d+/i,_M={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},bM={any:[/^b/i,/^(a|c)/i]},wM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},xM={any:[/1/i,/2/i,/3/i,/4/i]},SM={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},TM={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]},IM={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},EM={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]},CM={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},AM={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}},OM={ordinalNumber:yM({matchPattern:gM,parsePattern:vM,valueCallback:r=>parseInt(r,10)}),era:vo({matchPatterns:_M,defaultMatchWidth:"wide",parsePatterns:bM,defaultParseWidth:"any"}),quarter:vo({matchPatterns:wM,defaultMatchWidth:"wide",parsePatterns:xM,defaultParseWidth:"any",valueCallback:r=>r+1}),month:vo({matchPatterns:SM,defaultMatchWidth:"wide",parsePatterns:TM,defaultParseWidth:"any"}),day:vo({matchPatterns:IM,defaultMatchWidth:"wide",parsePatterns:EM,defaultParseWidth:"any"}),dayPeriod:vo({matchPatterns:CM,defaultMatchWidth:"any",parsePatterns:AM,defaultParseWidth:"any"})},FM={code:"en-US",formatDistance:JP,formatLong:iM,formatRelative:sM,localize:dM,match:OM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function PM(r,t){const e=qr(r,t==null?void 0:t.in);return XP(e,KP(e))+1}function MM(r,t){const e=qr(r,t==null?void 0:t.in),i=+Ul(e)-+YP(e);return Math.round(i/sw)+1}function aw(r,t){var c,h,p,f;const e=qr(r,t==null?void 0:t.in),i=e.getFullYear(),n=uu(),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)??n.firstWeekContainsDate??((f=(p=n.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,o=Gi((t==null?void 0:t.in)||r,0);o.setFullYear(i+1,0,s),o.setHours(0,0,0,0);const a=ea(o,t),l=Gi((t==null?void 0:t.in)||r,0);l.setFullYear(i,0,s),l.setHours(0,0,0,0);const u=ea(l,t);return+e>=+a?i+1:+e>=+u?i:i-1}function DM(r,t){var a,l,u,c;const e=uu(),i=(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,n=aw(r,t),s=Gi((t==null?void 0:t.in)||r,0);return s.setFullYear(n,0,i),s.setHours(0,0,0,0),ea(s,t)}function RM(r,t){const e=qr(r,t==null?void 0:t.in),i=+ea(e,t)-+DM(e,t);return Math.round(i/sw)+1}function ve(r,t){const e=r<0?"-":"",i=Math.abs(r).toString().padStart(t,"0");return e+i}const rn={y(r,t){const e=r.getFullYear(),i=e>0?e:1-e;return ve(t==="yy"?i%100:i,t.length)},M(r,t){const e=r.getMonth();return t==="M"?String(e+1):ve(e+1,2)},d(r,t){return ve(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 ve(r.getHours()%12||12,t.length)},H(r,t){return ve(r.getHours(),t.length)},m(r,t){return ve(r.getMinutes(),t.length)},s(r,t){return ve(r.getSeconds(),t.length)},S(r,t){const e=t.length,i=r.getMilliseconds(),n=Math.trunc(i*Math.pow(10,e-3));return ve(n,t.length)}},_s={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},vm={G:function(r,t,e){const i=r.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return e.era(i,{width:"abbreviated"});case"GGGGG":return e.era(i,{width:"narrow"});case"GGGG":default:return e.era(i,{width:"wide"})}},y:function(r,t,e){if(t==="yo"){const i=r.getFullYear(),n=i>0?i:1-i;return e.ordinalNumber(n,{unit:"year"})}return rn.y(r,t)},Y:function(r,t,e,i){const n=aw(r,i),s=n>0?n:1-n;if(t==="YY"){const o=s%100;return ve(o,2)}return t==="Yo"?e.ordinalNumber(s,{unit:"year"}):ve(s,t.length)},R:function(r,t){const e=ow(r);return ve(e,t.length)},u:function(r,t){const e=r.getFullYear();return ve(e,t.length)},Q:function(r,t,e){const i=Math.ceil((r.getMonth()+1)/3);switch(t){case"Q":return String(i);case"QQ":return ve(i,2);case"Qo":return e.ordinalNumber(i,{unit:"quarter"});case"QQQ":return e.quarter(i,{width:"abbreviated",context:"formatting"});case"QQQQQ":return e.quarter(i,{width:"narrow",context:"formatting"});case"QQQQ":default:return e.quarter(i,{width:"wide",context:"formatting"})}},q:function(r,t,e){const i=Math.ceil((r.getMonth()+1)/3);switch(t){case"q":return String(i);case"qq":return ve(i,2);case"qo":return e.ordinalNumber(i,{unit:"quarter"});case"qqq":return e.quarter(i,{width:"abbreviated",context:"standalone"});case"qqqqq":return e.quarter(i,{width:"narrow",context:"standalone"});case"qqqq":default:return e.quarter(i,{width:"wide",context:"standalone"})}},M:function(r,t,e){const i=r.getMonth();switch(t){case"M":case"MM":return rn.M(r,t);case"Mo":return e.ordinalNumber(i+1,{unit:"month"});case"MMM":return e.month(i,{width:"abbreviated",context:"formatting"});case"MMMMM":return e.month(i,{width:"narrow",context:"formatting"});case"MMMM":default:return e.month(i,{width:"wide",context:"formatting"})}},L:function(r,t,e){const i=r.getMonth();switch(t){case"L":return String(i+1);case"LL":return ve(i+1,2);case"Lo":return e.ordinalNumber(i+1,{unit:"month"});case"LLL":return e.month(i,{width:"abbreviated",context:"standalone"});case"LLLLL":return e.month(i,{width:"narrow",context:"standalone"});case"LLLL":default:return e.month(i,{width:"wide",context:"standalone"})}},w:function(r,t,e,i){const n=RM(r,i);return t==="wo"?e.ordinalNumber(n,{unit:"week"}):ve(n,t.length)},I:function(r,t,e){const i=MM(r);return t==="Io"?e.ordinalNumber(i,{unit:"week"}):ve(i,t.length)},d:function(r,t,e){return t==="do"?e.ordinalNumber(r.getDate(),{unit:"date"}):rn.d(r,t)},D:function(r,t,e){const i=PM(r);return t==="Do"?e.ordinalNumber(i,{unit:"dayOfYear"}):ve(i,t.length)},E:function(r,t,e){const i=r.getDay();switch(t){case"E":case"EE":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"})}},e:function(r,t,e,i){const n=r.getDay(),s=(n-i.weekStartsOn+8)%7||7;switch(t){case"e":return String(s);case"ee":return ve(s,2);case"eo":return e.ordinalNumber(s,{unit:"day"});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"})}},c:function(r,t,e,i){const n=r.getDay(),s=(n-i.weekStartsOn+8)%7||7;switch(t){case"c":return String(s);case"cc":return ve(s,t.length);case"co":return e.ordinalNumber(s,{unit:"day"});case"ccc":return e.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return e.day(n,{width:"narrow",context:"standalone"});case"cccccc":return e.day(n,{width:"short",context:"standalone"});case"cccc":default:return e.day(n,{width:"wide",context:"standalone"})}},i:function(r,t,e){const i=r.getDay(),n=i===0?7:i;switch(t){case"i":return String(n);case"ii":return ve(n,t.length);case"io":return e.ordinalNumber(n,{unit:"day"});case"iii":return e.day(i,{width:"abbreviated",context:"formatting"});case"iiiii":return e.day(i,{width:"narrow",context:"formatting"});case"iiiiii":return e.day(i,{width:"short",context:"formatting"});case"iiii":default:return e.day(i,{width:"wide",context:"formatting"})}},a:function(r,t,e){const n=r.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return e.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return e.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(r,t,e){const i=r.getHours();let n;switch(i===12?n=_s.noon:i===0?n=_s.midnight:n=i/12>=1?"pm":"am",t){case"b":case"bb":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return e.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return e.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(r,t,e){const i=r.getHours();let n;switch(i>=17?n=_s.evening:i>=12?n=_s.afternoon:i>=4?n=_s.morning:n=_s.night,t){case"B":case"BB":case"BBB":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return e.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return e.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(r,t,e){if(t==="ho"){let i=r.getHours()%12;return i===0&&(i=12),e.ordinalNumber(i,{unit:"hour"})}return rn.h(r,t)},H:function(r,t,e){return t==="Ho"?e.ordinalNumber(r.getHours(),{unit:"hour"}):rn.H(r,t)},K:function(r,t,e){const i=r.getHours()%12;return t==="Ko"?e.ordinalNumber(i,{unit:"hour"}):ve(i,t.length)},k:function(r,t,e){let i=r.getHours();return i===0&&(i=24),t==="ko"?e.ordinalNumber(i,{unit:"hour"}):ve(i,t.length)},m:function(r,t,e){return t==="mo"?e.ordinalNumber(r.getMinutes(),{unit:"minute"}):rn.m(r,t)},s:function(r,t,e){return t==="so"?e.ordinalNumber(r.getSeconds(),{unit:"second"}):rn.s(r,t)},S:function(r,t){return rn.S(r,t)},X:function(r,t,e){const i=r.getTimezoneOffset();if(i===0)return"Z";switch(t){case"X":return bm(i);case"XXXX":case"XX":return Vn(i);case"XXXXX":case"XXX":default:return Vn(i,":")}},x:function(r,t,e){const i=r.getTimezoneOffset();switch(t){case"x":return bm(i);case"xxxx":case"xx":return Vn(i);case"xxxxx":case"xxx":default:return Vn(i,":")}},O:function(r,t,e){const i=r.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+_m(i,":");case"OOOO":default:return"GMT"+Vn(i,":")}},z:function(r,t,e){const i=r.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+_m(i,":");case"zzzz":default:return"GMT"+Vn(i,":")}},t:function(r,t,e){const i=Math.trunc(+r/1e3);return ve(i,t.length)},T:function(r,t,e){return ve(+r,t.length)}};function _m(r,t=""){const e=r>0?"-":"+",i=Math.abs(r),n=Math.trunc(i/60),s=i%60;return s===0?e+String(n):e+String(n)+t+ve(s,2)}function bm(r,t){return r%60===0?(r>0?"-":"+")+ve(Math.abs(r)/60,2):Vn(r,t)}function Vn(r,t=""){const e=r>0?"-":"+",i=Math.abs(r),n=ve(Math.trunc(i/60),2),s=ve(i%60,2);return e+n+t+s}const wm=(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"})}},lw=(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"})}},NM=(r,t)=>{const e=r.match(/(P+)(p+)?/)||[],i=e[1],n=e[2];if(!n)return wm(r,t);let s;switch(i){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}}",wm(i,t)).replace("{{time}}",lw(n,t))},LM={p:lw,P:NM},BM=/^D+$/,kM=/^Y+$/,UM=["D","DD","YY","YYYY"];function zM(r){return BM.test(r)}function jM(r){return kM.test(r)}function $M(r,t,e){const i=VM(r,t,e);if(console.warn(i),UM.includes(r))throw new RangeError(i)}function VM(r,t,e){const i=r[0]==="Y"?"years":"days of the month";return`Use \`${r.toLowerCase()}\` instead of \`${r}\` (in \`${t}\`) for formatting ${i} to the input \`${e}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const GM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,WM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,HM=/^'([^]*?)'?$/,XM=/''/g,YM=/[a-zA-Z]/;function uw(r,t,e){var c,h,p,f;const i=uu(),n=i.locale??FM,s=i.firstWeekContainsDate??((h=(c=i.locale)==null?void 0:c.options)==null?void 0:h.firstWeekContainsDate)??1,o=i.weekStartsOn??((f=(p=i.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,a=qr(r,e==null?void 0:e.in);if(!QP(a))throw new RangeError("Invalid time value");let l=t.match(WM).map(y=>{const g=y[0];if(g==="p"||g==="P"){const d=LM[g];return d(y,n.formatLong)}return y}).join("").match(GM).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const g=y[0];if(g==="'")return{isToken:!1,value:qM(y)};if(vm[g])return{isToken:!0,value:y};if(g.match(YM))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:y}});n.localize.preprocessor&&(l=n.localize.preprocessor(a,l));const u={firstWeekContainsDate:s,weekStartsOn:o,locale:n};return l.map(y=>{if(!y.isToken)return y.value;const g=y.value;(jM(g)||zM(g))&&$M(g,t,String(r));const d=vm[g[0]];return d(a,g,n.localize,u)}).join("")}function qM(r){const t=r.match(HM);return t?t[1].replace(XM,"'"):r}function QM(r,t){return qr(r*1e3,t==null?void 0:t.in)}function KM(r,t){const e=ZM(t)?new t(0):Gi(t,0);return e.setFullYear(r.getFullYear(),r.getMonth(),r.getDate()),e.setHours(r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()),e}function ZM(r){var t;return typeof r=="function"&&((t=r.prototype)==null?void 0:t.constructor)===r}function JM(r,t){let e=r.length;switch("string"){case"string":{if(t.length!==1)throw new Error("The 'chars' parameter should be a single character string.");for(;e>0&&r[e-1]===t;)e--;break}}return r.substring(0,e)}function gr(r){return r==null}function tD(r){return r!=null}async function Sh(){if(typeof window<"u"&&window!==null)return"browser";try{const r=await ln(()=>import("./__vite-browser-external-FmFgRqLi.js"),[]);return typeof r<"u"&&r.versions!=null&&r.versions.node!=null?"node":"unknown"}catch{return"unknown"}}function eD(r){return gr(r)?!1:Et.isInt(r.type)&&!cw(r)||rD(r)}function rD(r){return gr(r)?!1:Et.isInt(r.type)&&r.type.isSigned===!1}function iD(r){return gr(r)?!1:Et.isFloat(r.type)??!1}function nD(r){return gr(r)?!1:Et.isDecimal(r.type)}function sD(r){return gr(r)?!1:Et.isBool(r.type)}function oD(r){return gr(r)?!1:Et.isDuration(r.type)}function cw(r){return gr(r)?!1:Et.isInt(r.type)&&r.metadata.get("ARROW:extension:name")==="period"}function aD(r){return gr(r)?!1:Et.isTimestamp(r.type)}function lD(r){return gr(r)?!1:Et.isDate(r.type)}function uD(r){return gr(r)?!1:Et.isTime(r.type)}function cD(r){return gr(r)?!1:Et.isList(r.type)||Et.isFixedSizeList(r.type)}function hD(r){return gr(r)?!1:Et.isStruct(r.type)||Et.isMap(r.type)}function fD(r){return gr(r)?!1:Et.isStruct(r.type)&&r.metadata.get("ARROW:extension:name")==="interval"||Et.isInterval(r.type)}function dD(r,t){let e;if(t===Jt.MILLISECOND)e=1e3;else if(t===Jt.MICROSECOND)e=1e3*1e3;else if(t===Jt.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 pD(r,t){var i;const e=dD(r,((i=t==null?void 0:t.type)==null?void 0:i.unit)??Jt.SECOND);return QM(e)}function mD(r,t){const e=pD(r,t);return uw(e,e.getMilliseconds()===0?"HH:mm:ss":"HH:mm:ss.SSS")}function yD(r){const t="yyyy-MM-dd";return r instanceof Date||typeof r=="number"&&Number.isFinite(r)?uw(r,t):(console.warn(`Unsupported date value: ${r}`),String(r))}function gD(r,t){var n;if(!(r instanceof Date||typeof r=="number"&&Number.isFinite(r)))return console.warn(`Unsupported datetime value: ${r}`),null;let e;const i=(n=t==null?void 0:t.type)==null?void 0:n.timezone;return typeof r=="number"?i?e=new Er(r,i):e=new Er(r):i?e=new Er(r,i):e=new Er(r),KM(e,Date)}function vD(r,t){var a;const e=((a=t==null?void 0:t.type)==null?void 0:a.scale)||0;let i=pm.bigNumToString(new pm.BN(r)).padStart(e,"0");if(e===0)return i;let n="";i.startsWith("-")&&(n="-",i=i.slice(1));const s=i.slice(0,-e)||"0",o=JM(i.slice(-e),"0")||"";return`${n}${s}${o?`.${o}`:""}`}function _D(r){const t=r[0],e=r[1],i=[];return t!==0&&i.push(`${t} year${t>1?"s":""}`),e!==0&&i.push(`${e} month${e>1?"s":""}`),i.length?i.join(" "):"0 months"}function bD(r,t){var i,n,s,o;if(Et.isInterval(t==null?void 0:t.type))return _D(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"?"]":")",p=Th(u.left,(n=(i=t.type)==null?void 0:i.children)==null?void 0:n[0]),f=Th(u.right,(o=(s=t.type)==null?void 0:s.children)==null?void 0:o[1]);return`${c+p}, ${f+h}`}return String(r)}function wD(r,t){return(t==null?void 0:t.type)instanceof bh?JSON.parse(JSON.stringify(r,(e,i)=>{if(tD(i))return typeof i=="bigint"?Number(i):i})):JSON.parse(JSON.stringify(r,(e,i)=>typeof i=="bigint"?Number(i):i))}function Th(r,t){if(gr(r))return null;const e=r instanceof Date||Number.isFinite(r);if(e&&lD(t))return yD(r);if(typeof r=="bigint"&&uD(t))return mD(Number(r),t);if(e&&aD(t))return gD(r,t);if(cw(t))throw new Error("Period type is not supported yet");if(fD(t))return bD(r,t);if(oD(t))throw new Error("Duration type is not supported yet");return nD(t)?vD(r,t):iD(t)&&Number.isFinite(r)||eD(t)?r:hD(t)||cD(t)?wD(r,t):sD(t)?!!r:String(r)}function xm(r){return((r.toArray()||[]).map(i=>i.toJSON())||[]).map(i=>(r.schema.fields.forEach(n=>i[n.name]=Th(i[n.name],n)),i))}var ra=(r=>(r.ORIGIN_PRIVATE_FS="origin-private-fs",r.NODE_FS="node-fs",r))(ra||{});async function hw(r){const t=Cx(r,{logger:!1});let e,i;const n=await Sh();if(n==="browser"){if(typeof t.bundles>"u"){const{getBundles:l}=await ln(async()=>{const{getBundles:u}=await import("./default-browser-BrgSDbLD.js");return{getBundles:u}},[]);t.bundles=await l()}i=await kp(await t.bundles),e=new Worker(i.mainWorker)}else if(n==="node"){if(typeof t.bundles>"u"){const{getBundles:c}=await ln(async()=>{const{getBundles:h}=await import("./default-node-S5EYlj5_.js");return{getBundles:h}},__vite__mapDeps([0,1,2]));t.bundles=await c()}i=await kp(await t.bundles);let l=i.mainWorker;l.startsWith("/@fs/")&&(l=l.replace("/@fs/","file://"));const u=await ln(()=>import("./index-Cp8iQ_hy.js"),[]);e=new u.default(l,{type:"module"})}else throw new Error(`Unsupported environment: ${n}`);let s;t.logger===!0?s=new I0:t.logger===!1?s=new c2:s=t.logger;const o=new g2(s,e);if(await o.instantiate(i.mainModule,i.pthreadWorker),t.storage)switch(t.storage.type){case ra.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 ra.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 f=await a.query(l);return xm(f)}const c=await a.prepare(l),h=await c.query(...u),p=xm(h);return c.close(),p},close:async()=>{await a.close(),await o.terminate(),await e.terminate()}}}async function xD(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 SD(r,t,e){await(await r).conn.send(`SAVEPOINT ${t}`);try{const i=await e(r);return await(await r).conn.send(`RELEASE SAVEPOINT ${t}`),i}catch(i){throw await(await r).conn.send(`ROLLBACK TO SAVEPOINT ${t}`),i}}const xt=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,xt))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(xt in e&&e[xt]===t[xt])return!0;e=Object.getPrototypeOf(e)}return!1}var Mm;Mm=xt;class Ke{constructor(t,e){G(this,"name");G(this,"keyAsName");G(this,"primary");G(this,"notNull");G(this,"default");G(this,"defaultFn");G(this,"onUpdateFn");G(this,"hasDefault");G(this,"isUnique");G(this,"uniqueName");G(this,"uniqueType");G(this,"dataType");G(this,"columnType");G(this,"enumValues");G(this,"generated");G(this,"generatedIdentity");G(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"}}G(Ke,Mm,"Column");const Ys=Symbol.for("drizzle:Name");function TD(r,t){return`${r[Ys]}_${t.join("_")}_unique`}var Dm,Rm;class Ar extends(Rm=Ke,Dm=xt,Rm){constructor(t,e){e.uniqueName||(e.uniqueName=TD(t,[e.name])),super(t,e),this.table=t}}G(Ar,Dm,"PgColumn");const Sm=Symbol.for("drizzle:isPgEnum");function ID(r){return!!r&&typeof r=="function"&&Sm in r&&r[Sm]===!0}var Nm;Nm=xt;class Or{constructor(t,e,i,n=!1){this._={brand:"Subquery",sql:t,selectedFields:e,alias:i,isWith:n}}}G(Or,Nm,"Subquery");var Lm,Bm;class jf extends(Bm=Or,Lm=xt,Bm){}G(jf,Lm,"WithSubquery");const Pr={startActiveSpan(r,t){return t()}},He=Symbol.for("drizzle:ViewBaseConfig"),Qa=Symbol.for("drizzle:Schema"),Ih=Symbol.for("drizzle:Columns"),Tm=Symbol.for("drizzle:ExtraConfigColumns"),sc=Symbol.for("drizzle:OriginalName"),oc=Symbol.for("drizzle:BaseName"),zl=Symbol.for("drizzle:IsAlias"),Im=Symbol.for("drizzle:ExtraConfigBuilder"),ED=Symbol.for("drizzle:IsDrizzleTable");var km,Um,zm,jm,$m,Vm,Gm,Wm,Hm,Xm;Xm=xt,Hm=Ys,Wm=sc,Gm=Qa,Vm=Ih,$m=Tm,jm=oc,zm=zl,Um=ED,km=Im;class Tt{constructor(t,e,i){G(this,Hm);G(this,Wm);G(this,Gm);G(this,Vm);G(this,$m);G(this,jm);G(this,zm,!1);G(this,Um,!0);G(this,km);this[Ys]=this[sc]=t,this[Qa]=e,this[oc]=i}}G(Tt,Xm,"Table"),G(Tt,"Symbol",{Name:Ys,Schema:Qa,OriginalName:sc,Columns:Ih,ExtraConfigColumns:Tm,BaseName:oc,IsAlias:zl,ExtraConfigBuilder:Im});function qn(r){return r[Ys]}function ia(r){return`${r[Qa]??"public"}.${r[Ys]}`}function fw(r){return r!=null&&typeof r.getSQL=="function"}function CD(r){var e;const t={sql:"",params:[]};for(const i of r)t.sql+=i.sql,t.params.push(...i.params),(e=i.typings)!=null&&e.length&&(t.typings||(t.typings=[]),t.typings.push(...i.typings));return t}var Ym;Ym=xt;class Xe{constructor(t){G(this,"value");this.value=Array.isArray(t)?t:[t]}getSQL(){return new Ft([this])}}G(Xe,Ym,"StringChunk");var qm;qm=xt;const Hn=class Hn{constructor(t){G(this,"decoder",dw);G(this,"shouldInlineParams",!1);this.queryChunks=t}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return Pr.startActiveSpan("drizzle.buildSQL",e=>{const i=this.buildQueryFromSourceParams(this.queryChunks,t);return e==null||e.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(t,e){const i=Object.assign({},e,{inlineParams:e.inlineParams||this.shouldInlineParams,paramStartIndex:e.paramStartIndex||{value:0}}),{casing:n,escapeName:s,escapeParam:o,prepareTyping:a,inlineParams:l,paramStartIndex:u}=i;return CD(t.map(c=>{var h;if(lt(c,Xe))return{sql:c.value.join(""),params:[]};if(lt(c,jl))return{sql:s(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){const p=[new Xe("(")];for(const[f,y]of c.entries())p.push(y),fr},pw={mapToDriverValue:r=>r};({...dw,...pw});var Km;Km=xt;class Wi{constructor(t,e=pw){G(this,"brand");this.value=t,this.encoder=e}getSQL(){return new Ft([this])}}G(Wi,Km,"Param");function X(r,...t){const e=[];(t.length>0||r.length>0&&r[0]!=="")&&e.push(new Xe(r[0]));for(const[i,n]of t.entries())e.push(n,new Xe(r[i+1]));return new Ft(e)}(r=>{function t(){return new Ft([])}r.empty=t;function e(l){return new Ft(l)}r.fromList=e;function i(l){return new Ft([new Xe(l)])}r.raw=i;function n(l,u){const c=[];for(const[h,p]of l.entries())h>0&&u!==void 0&&c.push(u),c.push(p);return new Ft(c)}r.join=n;function s(l){return new jl(l)}r.identifier=s;function o(l){return new ss(l)}r.placeholder=o;function a(l,u){return new Wi(l,u)}r.param=a})(X||(X={}));(r=>{var e;e=xt;const i=class i{constructor(s,o){G(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=o}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};G(i,e,"SQL.Aliased");let t=i;r.Aliased=t})(Ft||(Ft={}));var Zm;Zm=xt;class ss{constructor(t){this.name=t}getSQL(){return new Ft([this])}}G(ss,Zm,"Placeholder");function Em(r,t){return r.map(e=>{if(lt(e,ss)){if(!(e.name in t))throw new Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(lt(e,Wi)&<(e.value,ss)){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 OD=Symbol.for("drizzle:IsDrizzleView");var Jm,ty,ey;ey=xt,ty=He,Jm=OD;class Sn{constructor({name:t,schema:e,selectedFields:i,query:n}){G(this,ty);G(this,Jm,!0);this[He]={name:t,originalName:t,schema:e,selectedFields:i,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new Ft([this])}}G(Sn,ey,"View");Ke.prototype.getSQL=function(){return new Ft([this])};Tt.prototype.getSQL=function(){return new Ft([this])};Or.prototype.getSQL=function(){return new Ft([this])};var ry;ry=xt;class na{constructor(t){this.table=t}get(t,e){return e==="table"?this.table:t[e]}}G(na,ry,"ColumnAliasProxyHandler");var iy;iy=xt;class cu{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===He)return{...t[He],name:this.alias,isAlias:!0};if(e===Tt.Symbol.Columns){const n=t[Tt.Symbol.Columns];if(!n)return n;const s={};return Object.keys(n).map(o=>{s[o]=new Proxy(n[o],new na(new Proxy(t,this)))}),s}const i=t[e];return lt(i,Ke)?new Proxy(i,new na(new Proxy(t,this))):i}}G(cu,iy,"TableAliasProxyHandler");function ac(r,t){return new Proxy(r,new cu(t,!1))}function Li(r,t){return new Proxy(r,new na(new Proxy(r.table,new cu(t,!1))))}function mw(r,t){return new Ft.Aliased($l(r.sql,t),r.fieldAlias)}function $l(r,t){return X.join(r.queryChunks.map(e=>lt(e,Ke)?Li(e,t):lt(e,Ft)?$l(e,t):lt(e,Ft.Aliased)?mw(e,t):e))}var ny,sy;class $f extends(sy=Error,ny=xt,sy){constructor({message:t,cause:e}){super(t),this.name="DrizzleError",this.cause=e}}G($f,ny,"DrizzleError");var oy,ay;class yw extends(ay=$f,oy=xt,ay){constructor(){super({message:"Rollback"})}}G(yw,oy,"TransactionRollbackError");function yr(r,t){return AD(t)&&!fw(r)&&!lt(r,Wi)&&!lt(r,ss)&&!lt(r,Ke)&&!lt(r,Tt)&&!lt(r,Sn)?new Wi(r,t):r}const gw=(r,t)=>X`${r} = ${yr(t,r)}`,FD=(r,t)=>X`${r} <> ${yr(t,r)}`;function Eh(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Ft(t):new Ft([new Xe("("),X.join(t,new Xe(" and ")),new Xe(")")])}function PD(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Ft(t):new Ft([new Xe("("),X.join(t,new Xe(" or ")),new Xe(")")])}function MD(r){return X`not ${r}`}const DD=(r,t)=>X`${r} > ${yr(t,r)}`,RD=(r,t)=>X`${r} >= ${yr(t,r)}`,ND=(r,t)=>X`${r} < ${yr(t,r)}`,LD=(r,t)=>X`${r} <= ${yr(t,r)}`;function BD(r,t){return Array.isArray(t)?t.length===0?X`false`:X`${r} in ${t.map(e=>yr(e,r))}`:X`${r} in ${yr(t,r)}`}function kD(r,t){return Array.isArray(t)?t.length===0?X`true`:X`${r} not in ${t.map(e=>yr(e,r))}`:X`${r} not in ${yr(t,r)}`}function UD(r){return X`${r} is null`}function zD(r){return X`${r} is not null`}function jD(r){return X`exists ${r}`}function $D(r){return X`not exists ${r}`}function VD(r,t,e){return X`${r} between ${yr(t,r)} and ${yr(e,r)}`}function GD(r,t,e){return X`${r} not between ${yr(t,r)} and ${yr(e,r)}`}function WD(r,t){return X`${r} like ${t}`}function HD(r,t){return X`${r} not like ${t}`}function XD(r,t){return X`${r} ilike ${t}`}function YD(r,t){return X`${r} not ilike ${t}`}function qD(r){return X`${r} asc`}function QD(r){return X`${r} desc`}var ly;ly=xt;class vw{write(t){console.log(t)}}G(vw,ly,"ConsoleLogWriter");var uy;uy=xt;class _w{constructor(t){G(this,"writer");this.writer=(t==null?void 0:t.writer)??new vw}logQuery(t,e){const i=e.map(s=>{try{return JSON.stringify(s)}catch{return String(s)}}),n=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${t}${n}`)}}G(_w,uy,"DefaultLogger");var cy;cy=xt;class bw{logQuery(){}}G(bw,cy,"NoopLogger");var hy,fy;fy=xt,hy=Symbol.toStringTag;class Tn{constructor(){G(this,hy,"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)}}G(Tn,fy,"QueryPromise");function os(r,t){return Object.entries(r).reduce((e,[i,n])=>{if(typeof i!="string")return e;const s=t?[...t,i]:[i];return lt(n,Ke)||lt(n,Ft)||lt(n,Ft.Aliased)?e.push({path:s,field:n}):lt(n,Tt)?e.push(...os(n[Tt.Symbol.Columns],s)):e.push(...os(n,s)),e},[])}function Vf(r,t){const e=Object.keys(r),i=Object.keys(t);if(e.length!==i.length)return!1;for(const[n,s]of e.entries())if(s!==i[n])return!1;return!0}function ww(r,t){const e=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>lt(n,Ft)||lt(n,Ke)?[i,n]:[i,new Wi(n,r[Tt.Symbol.Columns][i])]);if(e.length===0)throw new Error("No values to set");return Object.fromEntries(e)}function KD(r,t){for(const e of t)for(const i of Object.getOwnPropertyNames(e.prototype))i!=="constructor"&&Object.defineProperty(r.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))}function ZD(r){return r[Tt.Symbol.Columns]}function Wn(r){return lt(r,Or)?r._.alias:lt(r,Sn)?r[He].name:lt(r,Ft)?void 0:r[Tt.Symbol.IsAlias]?r[Tt.Symbol.Name]:r[Tt.Symbol.BaseName]}function JD(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 dy,py;class xw extends(py=Ar,dy=xt,py){getSQLType(){return"date"}mapFromDriverValue(t){return new Date(t)}mapToDriverValue(t){return t.toISOString()}}G(xw,dy,"PgDate");var my,yy;class Sw extends(yy=Ar,my=xt,yy){getSQLType(){return"date"}}G(Sw,my,"PgDateString");var gy,vy;class Tw extends(vy=Ar,gy=xt,vy){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}}G(Tw,gy,"PgJson");var _y,by;class Iw extends(by=Ar,_y=xt,by){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}}G(Iw,_y,"PgJsonb");var wy,xy;class Ew extends(xy=Ar,wy=xt,xy){constructor(e,i){super(e,i);G(this,"precision");G(this,"scale");this.precision=i.precision,this.scale=i.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})`}}G(Ew,wy,"PgNumeric");var Sy,Ty;class Cw extends(Ty=Ar,Sy=xt,Ty){constructor(e,i){super(e,i);G(this,"withTimezone");G(this,"precision");this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}G(Cw,Sy,"PgTime");var Iy,Ey;class Aw extends(Ey=Ar,Iy=xt,Ey){constructor(e,i){super(e,i);G(this,"withTimezone");G(this,"precision");G(this,"mapFromDriverValue",e=>new Date(this.withTimezone?e:e+"+0000"));G(this,"mapToDriverValue",e=>e.toISOString());this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}}G(Aw,Iy,"PgTimestamp");var Cy,Ay;class Ow extends(Ay=Ar,Cy=xt,Ay){constructor(e,i){super(e,i);G(this,"withTimezone");G(this,"precision");this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}G(Ow,Cy,"PgTimestampString");var Oy,Fy;class Fw extends(Fy=Ar,Oy=xt,Fy){getSQLType(){return"uuid"}}G(Fw,Oy,"PgUUID");const Cm=Symbol.for("drizzle:PgInlineForeignKeys"),Am=Symbol.for("drizzle:EnableRLS");var Py,My,Dy,Ry,Ny,Ly;class Br extends(Ly=Tt,Ny=xt,Ry=Cm,Dy=Am,My=Tt.Symbol.ExtraConfigBuilder,Py=Tt.Symbol.ExtraConfigColumns,Ly){constructor(){super(...arguments);G(this,Ry,[]);G(this,Dy,!1);G(this,My);G(this,Py,{})}}G(Br,Ny,"PgTable"),G(Br,"Symbol",Object.assign({},Tt.Symbol,{InlineForeignKeys:Cm,EnableRLS:Am}));var By;By=xt;class Pw{constructor(t,e){G(this,"columns");G(this,"name");this.columns=t,this.name=e}build(t){return new Mw(t,this.columns,this.name)}}G(Pw,By,"PgPrimaryKeyBuilder");var ky;ky=xt;class Mw{constructor(t,e,i){G(this,"columns");G(this,"name");this.table=t,this.columns=e,this.name=i}getName(){return this.name??`${this.table[Br.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}}G(Mw,ky,"PgPrimaryKey");var Uy;Uy=xt;class Gf{constructor(t,e,i){G(this,"referencedTableName");G(this,"fieldName");this.sourceTable=t,this.referencedTable=e,this.relationName=i,this.referencedTableName=e[Tt.Symbol.Name]}}G(Gf,Uy,"Relation");var zy;zy=xt;class Dw{constructor(t,e){this.table=t,this.config=e}}G(Dw,zy,"Relations");var jy,$y;const Wl=class Wl extends($y=Gf,jy=xt,$y){constructor(t,e,i,n){super(t,e,i==null?void 0:i.relationName),this.config=i,this.isNullable=n}withFieldName(t){const e=new Wl(this.sourceTable,this.referencedTable,this.config,this.isNullable);return e.fieldName=t,e}};G(Wl,jy,"One");let as=Wl;var Vy,Gy;const Hl=class Hl extends(Gy=Gf,Vy=xt,Gy){constructor(t,e,i){super(t,e,i==null?void 0:i.relationName),this.config=i}withFieldName(t){const e=new Hl(this.sourceTable,this.referencedTable,this.config);return e.fieldName=t,e}};G(Hl,Vy,"Many");let Vl=Hl;function tR(){return{and:Eh,between:VD,eq:gw,exists:jD,gt:DD,gte:RD,ilike:XD,inArray:BD,isNull:UD,isNotNull:zD,like:WD,lt:ND,lte:LD,ne:FD,not:MD,notBetween:GD,notExists:$D,notLike:HD,notIlike:YD,notInArray:kD,or:PD,sql:X}}function eR(){return{sql:X,asc:qD,desc:QD}}function rR(r,t){var s;Object.keys(r).length===1&&"default"in r&&!lt(r.default,Tt)&&(r=r.default);const e={},i={},n={};for(const[o,a]of Object.entries(r))if(lt(a,Tt)){const l=ia(a),u=i[l];e[l]=o,n[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&&n[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,Pw)&&n[o].primaryKey.push(...h.columns)}else if(lt(a,Dw)){const l=ia(a.table),u=e[l],c=a.config(t(a.table));let h;for(const[p,f]of Object.entries(c))if(u){const y=n[u];y.relations[p]=f}else l in i||(i[l]={relations:{},primaryKey:h}),i[l].relations[p]=f}return{tables:n,tableNamesMap:e}}function iR(r){return function(e,i){return new as(r,e,i,(i==null?void 0:i.fields.reduce((n,s)=>n&&s.notNull,!0))??!1)}}function nR(r){return function(e,i){return new Vl(r,e,i)}}function sR(r,t,e){if(lt(e,as)&&e.config)return{fields:e.config.fields,references:e.config.references};const i=t[ia(e.referencedTable)];if(!i)throw new Error(`Table "${e.referencedTable[Tt.Symbol.Name]}" not found in schema`);const n=r[i];if(!n)throw new Error(`Table "${i}" not found in schema`);const s=e.sourceTable,o=t[ia(s)];if(!o)throw new Error(`Table "${s[Tt.Symbol.Name]}" not found in schema`);const a=[];for(const l of Object.values(n.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 "${i}"`):new Error(`There are multiple relations between "${i}" and "${e.sourceTable[Tt.Symbol.Name]}". Please specify relation name`);if(a[0]&<(a[0],as)&&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 oR(r){return{one:iR(r),many:nR(r)}}function Ch(r,t,e,i,n=s=>s){const s={};for(const[o,a]of i.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,as)?c&&Ch(r,r[a.relationTableTsKey],c,a.selection,n):c.map(h=>Ch(r,r[a.relationTableTsKey],h,a.selection,n))}else{const l=n(e[o]),u=a.field;let c;lt(u,Ke)?c=u:lt(u,Ft)?c=u.decoder:c=u.sql.decoder,s[a.tsKey]=l===null?null:c.mapFromDriverValue(l)}return s}var Wy;Wy=xt;const Xl=class Xl{constructor(t){G(this,"config");this.config={...t}}get(t,e){if(e==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(e===He)return{...t[He],selectedFields:new Proxy(t[He].selectedFields,this)};if(typeof e=="symbol")return t[e];const n=(lt(t,Or)?t._.selectedFields:lt(t,Sn)?t[He].selectedFields:t)[e];if(lt(n,Ft.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!n.isSelectionField)return n.sql;const s=n.clone();return s.isSelectionField=!0,s}if(lt(n,Ft)){if(this.config.sqlBehavior==="sql")return n;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(n,Ke)?this.config.alias?new Proxy(n,new na(new Proxy(n.table,new cu(this.config.alias,this.config.replaceOriginalName??!1)))):n:typeof n!="object"||n===null?n:new Proxy(n,new Xl(this.config))}};G(Xl,Wy,"SelectionProxyHandler");let Je=Xl;var Hy,Xy;class Ah extends(Xy=Tn,Hy=xt,Xy){constructor(e,i,n,s){super();G(this,"config");G(this,"authToken");G(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=i,this.dialect=n,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=os(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){return Pr.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 Je({alias:qn(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}G(Ah,Hy,"PgDelete");function aR(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function lR(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,i,n)=>{const s=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return e+s},"")}function uR(r){return r}var Yy;Yy=xt;class Rw{constructor(t){G(this,"cache",{});G(this,"cachedTables",{});G(this,"convert");this.convert=t==="snake_case"?aR:t==="camelCase"?lR:uR}getColumnCasing(t){if(!t.keyAsName)return t.name;const e=t.table[Tt.Symbol.Schema]??"public",i=t.table[Tt.Symbol.OriginalName],n=`${e}.${i}.${t.name}`;return this.cache[n]||this.cacheTable(t.table),this.cache[n]}cacheTable(t){const e=t[Tt.Symbol.Schema]??"public",i=t[Tt.Symbol.OriginalName],n=`${e}.${i}`;if(!this.cachedTables[n]){for(const s of Object.values(t[Tt.Symbol.Columns])){const o=`${n}.${s.name}`;this.cache[o]=this.convert(s.name)}this.cachedTables[n]=!0}}clearCache(){this.cache={},this.cachedTables={}}}G(Rw,Yy,"CasingCache");var qy,Qy;class Wf extends(Qy=Sn,qy=xt,Qy){}G(Wf,qy,"PgViewBase");var Ky;Ky=xt;class Bo{constructor(t){G(this,"casing");this.casing=new Rw(t==null?void 0:t.casing)}async migrate(t,e,i){const n=typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",s=typeof i=="string"?"drizzle":i.migrationsSchema??"drizzle",o=X` - CREATE TABLE IF NOT EXISTS ${X.identifier(s)}.${X.identifier(n)} ( +]`}concat(...t){const e=this.schema,i=this.data.concat(t.flatMap(({data:n})=>n));return new $n(e,i.map(n=>new fr(e,n)))}slice(t,e){const i=this.schema;[t,e]=Y_({length:this.numRows},t,e);const n=Z_(this.data,this._offsets,t,e);return new $n(i,n.map(s=>new fr(i,s)))}getChild(t){return this.getChildAt(this.schema.fields.findIndex(e=>e.name===t))}getChildAt(t){if(t>-1&&ti.children[t]);if(e.length===0){const{type:i}=this.schema.fields[t],n=se({type:i,length:0,nullCount:0});e.push(n._changeLengthAndBackfillNullBitmap(this.numRows))}return new Me(e)}return null}setChild(t,e){var i;return this.setChildAt((i=this.schema.fields)===null||i===void 0?void 0:i.findIndex(n=>n.name===t),e)}setChildAt(t,e){let i=this.schema,n=[...this.batches];if(t>-1&&tthis.getChildAt(u));[s[t],a[t]]=[o,e],[i,n]=qu(i,a)}return new $n(i,n)}select(t){const e=this.schema.fields.reduce((i,n,s)=>i.set(n.name,s),new Map);return this.selectAt(t.map(i=>e.get(i)).filter(i=>i>-1))}selectAt(t){const e=this.schema.selectAt(t),i=this.batches.map(n=>n.selectAt(t));return new $n(e,i)}assign(t){const e=this.schema.fields,[i,n]=t.schema.fields.reduce((a,l,u)=>{const[c,h]=a,p=e.findIndex(f=>f.name===l.name);return~p?h[p]=u:c.push(u),a},[[],[]]),s=this.schema.assign(t.schema),o=[...e.map((a,l)=>[l,n[l]]).map(([a,l])=>l===void 0?this.getChildAt(a):t.getChildAt(l)),...i.map(a=>t.getChildAt(a))].filter(Boolean);return new $n(...qu(s,o))}};l0=Symbol.toStringTag;gn[l0]=(r=>(r.schema=null,r.batches=[],r._offsets=new Uint32Array([0]),r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,r.isValid=Ol(hf),r.get=Ol(mr.getVisitFn(L.Struct)),r.set=J_(Xr.getVisitFn(L.Struct)),r.indexOf=t0(Fl.getVisitFn(L.Struct)),"Table"))(gn.prototype);var u0;let fr=class Po{constructor(...t){switch(t.length){case 2:{if([this.schema]=t,!(this.schema instanceof Pe))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");if([,this.data=se({nullCount:0,type:new sr(this.schema.fields),children:this.schema.fields.map(e=>se({type:e.type,nullCount:0}))})]=t,!(this.data instanceof Se))throw new TypeError("RecordBatch constructor expects a [Schema, Data] pair.");[this.schema,this.data]=Op(this.schema,this.data.children);break}case 1:{const[e]=t,{fields:i,children:n,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]=Ce.new({name:u,type:e[u].type,nullable:!0}),l),{length:0,fields:new Array,children:new Array}),o=new Pe(i),a=se({type:new sr(i),length:s,children:n,nullCount:0});[this.schema,this.data]=Op(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=c0(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 mr.visit(this.data,t)}at(t){return this.get(lf(t,this.numRows))}set(t,e){return Xr.visit(this.data,t,e)}indexOf(t,e){return Fl.visit(this.data,t,e)}[Symbol.iterator](){return ff.visit(new Me([this.data]))}toArray(){return[...this]}concat(...t){return new gn(this.schema,[this,...t])}slice(t,e){const[i]=new Me([this.data]).slice(t,e).data;return new Po(this.schema,i)}getChild(t){var e;return this.getChildAt((e=this.schema.fields)===null||e===void 0?void 0:e.findIndex(i=>i.name===t))}getChildAt(t){return t>-1&&tn.name===t),e)}setChildAt(t,e){let i=this.schema,n=this.data;if(t>-1&&ta.name===s);~o&&(n[o]=this.data.children[o])}return new Po(e,se({type:i,length:this.numRows,children:n}))}selectAt(t){const e=this.schema.selectAt(t),i=t.map(s=>this.data.children[s]).filter(Boolean),n=se({type:new sr(e.fields),length:this.numRows,children:i});return new Po(e,n)}};u0=Symbol.toStringTag;fr[u0]=(r=>(r._nullCount=-1,r[Symbol.isConcatSpreadable]=!0,"RecordBatch"))(fr.prototype);function Op(r,t,e=t.reduce((i,n)=>Math.max(i,n.length),0)){var i;const n=[...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)&&(n[a]=l.clone({nullable:!0}),s[a]=(i=u==null?void 0:u._changeLengthAndBackfillNullBitmap(e))!==null&&i!==void 0?i:se({type:l.type,length:e,nullCount:e,nullBitmap:new Uint8Array(o)}))}return[r.assign(n),se({type:new sr(n),length:e,children:s})]}function c0(r,t,e=new Map){var i,n;if(((i=r==null?void 0:r.length)!==null&&i!==void 0?i:0)>0&&(r==null?void 0:r.length)===(t==null?void 0:t.length))for(let s=-1,o=r.length;++sse({type:n.type})),i=se({type:new sr(t.fields),nullCount:0,children:e});super(t,i)}}let en=class ai{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 ai).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMessage(t,e){return t.setPosition(t.position()+me),(e||new ai).__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):ke.V1}headerType(){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):fe.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 i=this.bb.__offset(this.bb_pos,12);return i?(e||new We).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+i)+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,ke.V1)}static addHeaderType(t,e){t.addFieldInt8(1,e,fe.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 i=e.length-1;i>=0;i--)t.addOffset(e[i]);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,i,n,s,o){return ai.startMessage(t),ai.addVersion(t,e),ai.addHeaderType(t,i),ai.addHeader(t,n),ai.addBodyLength(t,s),ai.addCustomMetadata(t,o),ai.endMessage(t)}};class hO extends ie{visit(t,e){return t==null||e==null?void 0:super.visit(t,e)}visitNull(t,e){return _p.startNull(e),_p.endNull(e)}visitInt(t,e){return xr.startInt(e),xr.addBitWidth(e,t.bitWidth),xr.addIsSigned(e,t.isSigned),xr.endInt(e)}visitFloat(t,e){return mi.startFloatingPoint(e),mi.addPrecision(e,t.precision),mi.endFloatingPoint(e)}visitBinary(t,e){return pp.startBinary(e),pp.endBinary(e)}visitLargeBinary(t,e){return yp.startLargeBinary(e),yp.endLargeBinary(e)}visitBool(t,e){return mp.startBool(e),mp.endBool(e)}visitUtf8(t,e){return bp.startUtf8(e),bp.endUtf8(e)}visitLargeUtf8(t,e){return gp.startLargeUtf8(e),gp.endLargeUtf8(e)}visitDecimal(t,e){return Ss.startDecimal(e),Ss.addScale(e,t.scale),Ss.addPrecision(e,t.precision),Ss.addBitWidth(e,t.bitWidth),Ss.endDecimal(e)}visitDate(t,e){return Ua.startDate(e),Ua.addUnit(e,t.unit),Ua.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 i=t.timezone&&e.createString(t.timezone)||void 0;return jr.startTimestamp(e),jr.addUnit(e,t.unit),i!==void 0&&jr.addTimezone(e,i),jr.endTimestamp(e)}visitInterval(t,e){return yi.startInterval(e),yi.addUnit(e,t.unit),yi.endInterval(e)}visitDuration(t,e){return za.startDuration(e),za.addUnit(e,t.unit),za.endDuration(e)}visitList(t,e){return vp.startList(e),vp.endList(e)}visitStruct(t,e){return Yn.startStruct_(e),Yn.endStruct_(e)}visitUnion(t,e){hr.startTypeIdsVector(e,t.typeIds.length);const i=hr.createTypeIdsVector(e,t.typeIds);return hr.startUnion(e),hr.addMode(e,t.mode),hr.addTypeIds(e,i),hr.endUnion(e)}visitDictionary(t,e){const i=this.visit(t.indices,e);return $i.startDictionaryEncoding(e),$i.addId(e,BigInt(t.id)),$i.addIsOrdered(e,t.isOrdered),i!==void 0&&$i.addIndexType(e,i),$i.endDictionaryEncoding(e)}visitFixedSizeBinary(t,e){return ja.startFixedSizeBinary(e),ja.addByteWidth(e,t.byteWidth),ja.endFixedSizeBinary(e)}visitFixedSizeList(t,e){return $a.startFixedSizeList(e),$a.addListSize(e,t.listSize),$a.endFixedSizeList(e)}visitMap(t,e){return Va.startMap(e),Va.addKeysSorted(e,t.keysSorted),Va.endMap(e)}}const Qu=new hO;function fO(r,t=new Map){return new Pe(pO(r,t),Ha(r.metadata),t)}function h0(r){return new Fr(r.count,f0(r.columns),d0(r.columns))}function dO(r){return new Ti(h0(r.data),r.id,r.isDelta)}function pO(r,t){return(r.fields||[]).filter(Boolean).map(e=>Ce.fromJSON(e,t))}function Fp(r,t){return(r.children||[]).filter(Boolean).map(e=>Ce.fromJSON(e,t))}function f0(r){return(r||[]).reduce((t,e)=>[...t,new vn(e.count,mO(e.VALIDITY)),...f0(e.children)],[])}function d0(r,t=[]){for(let e=-1,i=(r||[]).length;++et+ +(e===0),0)}function yO(r,t){let e,i,n,s,o,a;return!t||!(s=r.dictionary)?(o=Mp(r,Fp(r,t)),n=new Ce(r.name,o,r.nullable,Ha(r.metadata))):t.has(e=s.id)?(i=(i=s.indexType)?Pp(i):new Qo,a=new Zs(t.get(e),i,e,s.isOrdered),n=new Ce(r.name,a,r.nullable,Ha(r.metadata))):(i=(i=s.indexType)?Pp(i):new Qo,t.set(e,o=Mp(r,Fp(r,t))),a=new Zs(o,i,e,s.isOrdered),n=new Ce(r.name,a,r.nullable,Ha(r.metadata))),n||null}function Ha(r=[]){return new Map(r.map(({key:t,value:e})=>[t,e]))}function Pp(r){return new is(r.isSigned,r.bitWidth)}function Mp(r,t){const e=r.type.name;switch(e){case"NONE":return new pn;case"null":return new pn;case"binary":return new hl;case"largebinary":return new fl;case"utf8":return new dl;case"largeutf8":return new pl;case"bool":return new ml;case"list":return new xl((t||[])[0]);case"struct":return new sr(t||[]);case"struct_":return new sr(t||[])}switch(e){case"int":{const i=r.type;return new is(i.isSigned,i.bitWidth)}case"floatingpoint":{const i=r.type;return new cl(tr[i.precision])}case"decimal":{const i=r.type;return new yl(i.scale,i.precision,i.bitWidth)}case"date":{const i=r.type;return new gl(Hr[i.unit])}case"time":{const i=r.type;return new vl(zt[i.unit],i.bitWidth)}case"timestamp":{const i=r.type;return new _l(zt[i.unit],i.timezone)}case"interval":{const i=r.type;return new bl(Si[i.unit])}case"duration":{const i=r.type;return new wl(zt[i.unit])}case"union":{const i=r.type,[n,...s]=(i.mode+"").toLowerCase(),o=n.toUpperCase()+s.join("");return new Sl(er[o],i.typeIds||[],t||[])}case"fixedsizebinary":{const i=r.type;return new Tl(i.byteWidth)}case"fixedsizelist":{const i=r.type;return new Il(i.listSize,(t||[])[0])}case"map":{const i=r.type;return new El((t||[])[0],i.keysSorted)}}throw new Error(`Unrecognized type: "${e}"`)}var gO=Cv,vO=Qs;class or{static fromJSON(t,e){const i=new or(0,ke.V5,e);return i._createHeader=_O(t,e),i}static decode(t){t=new vO(ae(t));const e=en.getRootAsMessage(t),i=e.bodyLength(),n=e.version(),s=e.headerType(),o=new or(i,n,s);return o._createHeader=bO(e,s),o}static encode(t){const e=new gO;let i=-1;return t.isSchema()?i=Pe.encode(e,t.header()):t.isRecordBatch()?i=Fr.encode(e,t.header()):t.isDictionaryBatch()&&(i=Ti.encode(e,t.header())),en.startMessage(e),en.addVersion(e,ke.V5),en.addHeader(e,i),en.addHeaderType(e,t.headerType),en.addBodyLength(e,BigInt(t.bodyLength)),en.finishMessageBuffer(e,en.endMessage(e)),e.asUint8Array()}static from(t,e=0){if(t instanceof Pe)return new or(0,ke.V5,fe.Schema,t);if(t instanceof Fr)return new or(e,ke.V5,fe.RecordBatch,t);if(t instanceof Ti)return new or(e,ke.V5,fe.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===fe.Schema}isRecordBatch(){return this.headerType===fe.RecordBatch}isDictionaryBatch(){return this.headerType===fe.DictionaryBatch}constructor(t,e,i,n){this._version=e,this._headerType=i,this.body=new Uint8Array(0),n&&(this._createHeader=()=>n),this._bodyLength=we(t)}}class Fr{get nodes(){return this._nodes}get length(){return this._length}get buffers(){return this._buffers}constructor(t,e,i){this._nodes=e,this._buffers=i,this._length=we(t)}}class Ti{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,i=!1){this._data=t,this._isDelta=i,this._id=we(e)}}class vi{constructor(t,e){this.offset=we(t),this.length=we(e)}}class vn{constructor(t,e){this.length=we(t),this.nullCount=we(e)}}function _O(r,t){return()=>{switch(t){case fe.Schema:return Pe.fromJSON(r);case fe.RecordBatch:return Fr.fromJSON(r);case fe.DictionaryBatch:return Ti.fromJSON(r)}throw new Error(`Unrecognized Message type: { name: ${fe[t]}, type: ${t} }`)}}function bO(r,t){return()=>{switch(t){case fe.Schema:return Pe.decode(r.header(new ui),new Map,r.version());case fe.RecordBatch:return Fr.decode(r.header(new Bi),r.version());case fe.DictionaryBatch:return Ti.decode(r.header(new ws),r.version())}throw new Error(`Unrecognized Message type: { name: ${fe[t]}, type: ${t} }`)}}Ce.encode=PO;Ce.decode=OO;Ce.fromJSON=yO;Pe.encode=FO;Pe.decode=wO;Pe.fromJSON=fO;Fr.encode=MO;Fr.decode=xO;Fr.fromJSON=h0;Ti.encode=DO;Ti.decode=SO;Ti.fromJSON=dO;vn.encode=RO;vn.decode=IO;vi.encode=NO;vi.decode=TO;function wO(r,t=new Map,e=ke.V5){const i=AO(r,t);return new Pe(i,Xa(r),t,e)}function xO(r,t=ke.V5){if(r.compression()!==null)throw new Error("Record batch compression not implemented");return new Fr(r.length(),EO(r),CO(r,t))}function SO(r,t=ke.V5){return new Ti(Fr.decode(r.data(),t),r.id(),r.isDelta())}function TO(r){return new vi(r.offset(),r.length())}function IO(r){return new vn(r.length(),r.nullCount())}function EO(r){const t=[];for(let e,i=-1,n=-1,s=r.nodesLength();++iCe.encode(r,s));ui.startFieldsVector(r,e.length);const i=ui.createFieldsVector(r,e),n=t.metadata&&t.metadata.size>0?ui.createCustomMetadataVector(r,[...t.metadata].map(([s,o])=>{const a=r.createString(`${s}`),l=r.createString(`${o}`);return We.startKeyValue(r),We.addKey(r,a),We.addValue(r,l),We.endKeyValue(r)})):-1;return ui.startSchema(r),ui.addFields(r,i),ui.addEndianness(r,LO?Ks.Little:Ks.Big),n!==-1&&ui.addCustomMetadata(r,n),ui.endSchema(r)}function PO(r,t){let e=-1,i=-1,n=-1;const s=t.type;let o=t.typeId;At.isDictionary(s)?(o=s.dictionary.typeId,n=Qu.visit(s,r),i=Qu.visit(s.dictionary,r)):i=Qu.visit(s,r);const a=(s.children||[]).map(c=>Ce.encode(r,c)),l=Nr.createChildrenVector(r,a),u=t.metadata&&t.metadata.size>0?Nr.createCustomMetadataVector(r,[...t.metadata].map(([c,h])=>{const p=r.createString(`${c}`),f=r.createString(`${h}`);return We.startKeyValue(r),We.addKey(r,p),We.addValue(r,f),We.endKeyValue(r)})):-1;return t.name&&(e=r.createString(t.name)),Nr.startField(r),Nr.addType(r,i),Nr.addTypeType(r,o),Nr.addChildren(r,l),Nr.addNullable(r,!!t.nullable),e!==-1&&Nr.addName(r,e),n!==-1&&Nr.addDictionary(r,n),u!==-1&&Nr.addCustomMetadata(r,u),Nr.endField(r)}function MO(r,t){const e=t.nodes||[],i=t.buffers||[];Bi.startNodesVector(r,e.length);for(const o of e.slice().reverse())vn.encode(r,o);const n=r.endVector();Bi.startBuffersVector(r,i.length);for(const o of i.slice().reverse())vi.encode(r,o);const s=r.endVector();return Bi.startRecordBatch(r),Bi.addLength(r,BigInt(t.length)),Bi.addNodes(r,n),Bi.addBuffers(r,s),Bi.endRecordBatch(r)}function DO(r,t){const e=Fr.encode(r,t.data);return ws.startDictionaryBatch(r),ws.addId(r,BigInt(t.id)),ws.addIsDelta(r,t.isDelta),ws.addData(r,e),ws.endDictionaryBatch(r)}function RO(r,t){return Fv.createFieldNode(r,BigInt(t.length),BigInt(t.nullCount))}function NO(r,t){return Ov.createBuffer(r,BigInt(t.offset),BigInt(t.length))}const LO=(()=>{const r=new ArrayBuffer(2);return new DataView(r).setInt16(0,256,!0),new Int16Array(r)[0]===256})(),_f=r=>`Expected ${fe[r]} Message in stream, but was null or length 0.`,bf=r=>`Header pointer of flatbuffer-encoded ${fe[r]} Message is null or length 0.`,p0=(r,t)=>`Expected to read ${r} metadata bytes, but only read ${t}.`,m0=(r,t)=>`Expected to read ${r} bytes for message body, but only read ${t}.`;class y0{constructor(t){this.source=t instanceof Pl?t:new Pl(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?De: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(_f(t));return e.value}readMessageBody(t){if(t<=0)return new Uint8Array(0);const e=ae(this.source.read(t));if(e.byteLength[...n,...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(_f(t));return e.value}readSchema(){const t=fe.Schema,e=this.readMessage(t),i=e==null?void 0:e.header();if(!e||!i)throw new Error(bf(t));return i}}const iu=4,ph="ARROW1",Zo=new Uint8Array(ph.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 kr.toDOMStream(this.isSync()?{[Symbol.iterator]:()=>this}:{[Symbol.asyncIterator]:()=>this})}toNodeStream(){return kr.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 Vr?t:rh(t)?VO(t):wv(t)?HO(t):rs(t)?Zt(this,void 0,void 0,function*(){return yield Vr.from(yield t)}):xv(t)||rf(t)||Sv(t)||no(t)?WO(new Js(t)):GO(new Pl(t))}static readAll(t){return t instanceof Vr?t.isSync()?Lp(t):Bp(t):rh(t)||ArrayBuffer.isView(t)||oa(t)||bv(t)?Lp(t):Bp(t)}}class Dl extends Vr{constructor(t){super(t),this._impl=t}readAll(){return[...this]}[Symbol.iterator](){return this._impl[Symbol.iterator]()}[Symbol.asyncIterator](){return dr(this,arguments,function*(){yield Pt(yield*ts(bi(this[Symbol.iterator]())))})}}class Rl extends Vr{constructor(t){super(t),this._impl=t}readAll(){return Zt(this,void 0,void 0,function*(){var t,e,i,n;const s=new Array;try{for(var o=!0,a=bi(this),l;l=yield a.next(),t=l.done,!t;o=!0){n=l.value,o=!1;const u=n;s.push(u)}}catch(u){e={error:u}}finally{try{!o&&!t&&(i=a.return)&&(yield i.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 v0 extends Dl{constructor(t){super(t),this._impl=t}}class zO extends Rl{constructor(t){super(t),this._impl=t}}class _0{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 i=this._loadVectors(t,e,this.schema.fields),n=se({type:new sr(this.schema.fields),length:t.length,children:i});return new fr(this.schema,n)}_loadDictionaryBatch(t,e){const{id:i,isDelta:n}=t,{dictionaries:s,schema:o}=this,a=s.get(i),l=o.dictionaries.get(i),u=this._loadVectors(t.data,e,[l]);return(a&&n?a.concat(new Me(u)):new Me(u)).memoize()}_loadVectors(t,e,i){return new a0(e,t.nodes,t.buffers,this.dictionaries,this.schema.metadataVersion).visitMany(i)}}class Nl extends _0{constructor(t,e){super(e),this._reader=rh(t)?new kO(this._handle=t):new y0(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=w0(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):De}return(t){return!this.closed&&this.autoDestroy&&(this.closed=!0)?this.reset()._reader.return(t):De}next(){if(this.closed)return De;let t;const{_reader:e}=this;for(;t=this._readNextMessageAndValidate();)if(t.isSchema())this.reset(t.header());else if(t.isRecordBatch()){this._recordBatchIndex++;const i=t.header(),n=e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const i=t.header(),n=e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vf(this.schema)}):this.return()}_readNextMessageAndValidate(t){return this._reader.readMessage(t)}}class Ll extends _0{constructor(t,e){super(e),this._reader=new BO(this._handle=t)}isAsync(){return!0}isStream(){return!0}[Symbol.asyncIterator](){return this}cancel(){return Zt(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 Zt(this,void 0,void 0,function*(){return this.closed||(this.autoDestroy=w0(this,t),this.schema||(this.schema=yield this._reader.readSchema())||(yield this.cancel())),this})}throw(t){return Zt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.throw(t):De})}return(t){return Zt(this,void 0,void 0,function*(){return!this.closed&&this.autoDestroy&&(this.closed=!0)?yield this.reset()._reader.return(t):De})}next(){return Zt(this,void 0,void 0,function*(){if(this.closed)return De;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 i=t.header(),n=yield e.readMessageBody(t.bodyLength);return{done:!1,value:this._loadRecordBatch(i,n)}}else if(t.isDictionaryBatch()){this._dictionaryIndex++;const i=t.header(),n=yield e.readMessageBody(t.bodyLength),s=this._loadDictionaryBatch(i,n);this.dictionaries.set(i.id,s)}return this.schema&&this._recordBatchIndex===0?(this._recordBatchIndex++,{done:!1,value:new vf(this.schema)}):yield this.return()})}_readNextMessageAndValidate(t){return Zt(this,void 0,void 0,function*(){return yield this._reader.readMessage(t)})}}class b0 extends Nl{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 Ap?t:new Ap(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 i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&this._handle.seek(i.offset)){const n=this._reader.readMessage(fe.RecordBatch);if(n!=null&&n.isRecordBatch()){const s=n.header(),o=this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null}_readDictionaryBatch(t){var e;const i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&this._handle.seek(i.offset)){const n=this._reader.readMessage(fe.DictionaryBatch);if(n!=null&&n.isDictionaryBatch()){const s=n.header(),o=this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}}_readFooter(){const{_handle:t}=this,e=t.size-g0,i=t.readInt32(e),n=t.readAt(e-i,i);return Ko.decode(n)}_readNextMessageAndValidate(t){var e;if(this._footer||this.open(),this._footer&&this._recordBatchIndexsuper.open}});return Zt(this,void 0,void 0,function*(){if(!this.closed&&!this._footer){this.schema=(this._footer=yield this._readFooter()).schema;for(const i of this._footer.dictionaryBatches())i&&(yield this._readDictionaryBatch(this._dictionaryIndex++))}return yield e.open.call(this,t)})}readRecordBatch(t){return Zt(this,void 0,void 0,function*(){var e;if(this.closed)return null;this._footer||(yield this.open());const i=(e=this._footer)===null||e===void 0?void 0:e.getRecordBatch(t);if(i&&(yield this._handle.seek(i.offset))){const n=yield this._reader.readMessage(fe.RecordBatch);if(n!=null&&n.isRecordBatch()){const s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength);return this._loadRecordBatch(s,o)}}return null})}_readDictionaryBatch(t){return Zt(this,void 0,void 0,function*(){var e;const i=(e=this._footer)===null||e===void 0?void 0:e.getDictionaryBatch(t);if(i&&(yield this._handle.seek(i.offset))){const n=yield this._reader.readMessage(fe.DictionaryBatch);if(n!=null&&n.isDictionaryBatch()){const s=n.header(),o=yield this._reader.readMessageBody(n.bodyLength),a=this._loadDictionaryBatch(s,o);this.dictionaries.set(s.id,a)}}})}_readFooter(){return Zt(this,void 0,void 0,function*(){const{_handle:t}=this;t._pending&&(yield t._pending);const e=t.size-g0,i=yield t.readInt32(e),n=yield t.readAt(e-i,i);return Ko.decode(n)})}_readNextMessageAndValidate(t){return Zt(this,void 0,void 0,function*(){if(this._footer||(yield this.open()),this._footer&&this._recordBatchIndex=4?wf(t)?new v0(new b0(r.read())):new Dl(new Nl(r)):new Dl(new Nl(function*(){}()))}function WO(r){return Zt(this,void 0,void 0,function*(){const t=yield r.peek(ca+7&-8);return t&&t.byteLength>=4?wf(t)?new v0(new b0(yield r.read())):new Rl(new Ll(r)):new Rl(new Ll(function(){return dr(this,arguments,function*(){})}()))})}function HO(r){return Zt(this,void 0,void 0,function*(){const{size:t}=yield r.stat(),e=new Ml(r,t);return t>=UO&&wf(yield e.readAt(0,ca+7&-8))?new zO(new jO(e)):new Rl(new Ll(e))})}class Ne extends ie{static assemble(...t){const e=n=>n.flatMap(s=>Array.isArray(s)?e(s):s instanceof fr?s.data.children:s.data),i=new Ne;return i.visitMany(e(t)),i}constructor(){super(),this._byteLength=0,this._nodes=[],this._buffers=[],this._bufferRegions=[]}visit(t){if(t instanceof Me)return this.visitMany(t.data),this;const{type:e}=t;if(!At.isDictionary(e)){const{length:i}=t;if(i>2147483647)throw new RangeError("Cannot write arrays larger than 2^31 - 1 in length");if(At.isUnion(e))this.nodes.push(new vn(i,0));else{const{nullCount:n}=t;At.isNull(e)||ti.call(this,n<=0?new Uint8Array(0):Cl(t.offset,i,t.nullBitmap)),this.nodes.push(new vn(i,n))}}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 ti(r){const t=r.byteLength+7&-8;return this.buffers.push(r),this.bufferRegions.push(new vi(this._byteLength,t)),this._byteLength+=t,this}function XO(r){var t;const{type:e,length:i,typeIds:n,valueOffsets:s}=r;if(ti.call(this,n),e.mode===er.Sparse)return mh.call(this,r);if(e.mode===er.Dense){if(r.offset<=0)return ti.call(this,s),mh.call(this,r);{const o=new Int32Array(i),a=Object.create(null),l=Object.create(null);for(let u,c,h=-1;++h{const h=e.typeIds[c],p=a[h],f=l[h];return u.slice(p,Math.min(i,f))}))}}return this}function YO(r){let t;return r.nullCount>=r.length?ti.call(this,new Uint8Array(0)):(t=r.values)instanceof Uint8Array?ti.call(this,Cl(r.offset,r.length,t)):ti.call(this,Al(r.values))}function Yi(r){return ti.call(this,r.values.subarray(0,r.length*r.stride))}function nu(r){const{length:t,values:e,valueOffsets:i}=r,n=we(i[0]),s=we(i[t]),o=Math.min(s-n,e.byteLength-n);return ti.call(this,Iv(-n,t+1,i)),ti.call(this,e.subarray(n,n+o)),this}function xf(r){const{length:t,valueOffsets:e}=r;if(e){const{[0]:i,[t]:n}=e;return ti.call(this,Iv(-i,t+1,e)),this.visit(r.children[0].slice(i,n-i))}return this.visit(r.children[0])}function mh(r){return this.visitMany(r.type.children.map((t,e)=>r.children[e]).filter(Boolean))[0]}Ne.prototype.visitBool=YO;Ne.prototype.visitInt=Yi;Ne.prototype.visitFloat=Yi;Ne.prototype.visitUtf8=nu;Ne.prototype.visitLargeUtf8=nu;Ne.prototype.visitBinary=nu;Ne.prototype.visitLargeBinary=nu;Ne.prototype.visitFixedSizeBinary=Yi;Ne.prototype.visitDate=Yi;Ne.prototype.visitTimestamp=Yi;Ne.prototype.visitTime=Yi;Ne.prototype.visitDecimal=Yi;Ne.prototype.visitList=xf;Ne.prototype.visitStruct=mh;Ne.prototype.visitUnion=XO;Ne.prototype.visitInterval=Yi;Ne.prototype.visitDuration=Yi;Ne.prototype.visitFixedSizeList=xf;Ne.prototype.visitMap=xf;class x0 extends df{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 Wa,this._schema=null,this._dictionaryBlocks=[],this._recordBatchBlocks=[],this._seenDictionaries=new Map,this._dictionaryDeltaOffsets=new Map,pr(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 rs(t)?t.then(e=>this.writeAll(e)):no(t)?Ef(this,t):If(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 Wa?this._sink=t:(this._sink=new Wa,t&&SC(t)?this.toDOMStream({type:"bytes"}).pipeTo(t):t&&TC(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||!dh(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 gn&&!(e=t.schema))return this.finish()&&void 0;if(t instanceof fr&&!(e=t.schema))return this.finish()&&void 0}else throw new Error("RecordBatchWriter is closed");if(e&&!dh(e,this._schema)){if(this._started&&this._autoDestroy)return this.close();this.reset(this._sink,e)}t instanceof fr?t instanceof vf||this._writeRecordBatch(t):t instanceof gn?this.writeAll(t.batches):oa(t)&&this.writeAll(t)}_writeMessage(t,e=8){const i=e-1,n=or.encode(t),s=n.byteLength,o=this._writeLegacyIpcFormat?4:8,a=s+o+i&~i,l=a-s-o;return t.headerType===fe.RecordBatch?this._recordBatchBlocks.push(new mn(a,t.bodyLength,this._position)):t.headerType===fe.DictionaryBatch&&this._dictionaryBlocks.push(new mn(a,t.bodyLength,this._position)),this._writeLegacyIpcFormat||this._write(Int32Array.of(-1)),this._write(Int32Array.of(a-o)),s>0&&this._write(n),this._writePadding(l)}_write(t){if(this._started){const e=ae(t);e&&e.byteLength>0&&(this._sink.write(e),this._position+=e.byteLength)}return this}_writeSchema(t){return this._writeMessage(or.from(t))}_writeFooter(t){return this._writeLegacyIpcFormat?this._write(Int32Array.of(0)):this._write(Int32Array.of(-1,0))}_writeMagic(){return this._write(Zo)}_writePadding(t){return t>0?this._write(new Uint8Array(t)):this}_writeRecordBatch(t){const{byteLength:e,nodes:i,bufferRegions:n,buffers:s}=Ne.assemble(t),o=new Fr(t.numRows,i,n),a=or.from(o,e);return this._writeDictionaries(t)._writeMessage(a)._writeBodyBuffers(s)}_writeDictionaryBatch(t,e,i=!1){const{byteLength:n,nodes:s,bufferRegions:o,buffers:a}=Ne.assemble(new Me([t])),l=new Fr(t.length,s,o),u=new Ti(l,e,i),c=or.from(u,n);return this._writeMessage(c)._writeBodyBuffers(a)}_writeBodyBuffers(t){let e,i,n;for(let s=-1,o=t.length;++s0&&(this._write(e),(n=(i+7&-8)-i)>0&&this._writePadding(n));return this}_writeDictionaries(t){var e,i;for(const[n,s]of t.dictionaries){const o=(e=s==null?void 0:s.data)!==null&&e!==void 0?e:[],a=this._seenDictionaries.get(n),l=(i=this._dictionaryDeltaOffsets.get(n))!==null&&i!==void 0?i:0;if(!a||a.data[0]!==o[0])for(const[u,c]of o.entries())this._writeDictionaryBatch(c,n,u>0);else if(li.writeAll(n)):no(t)?Ef(i,t):If(i,t)}}class Tf extends x0{static writeAll(t){const e=new Tf;return rs(t)?t.then(i=>e.writeAll(i)):no(t)?Ef(e,t):If(e,t)}constructor(){super(),this._autoDestroy=!0}_writeSchema(t){return this._writeMagic()._writePadding(2)}_writeDictionaryBatch(t,e,i=!1){if(!i&&this._seenDictionaries.has(e))throw new Error("The Arrow File format does not support replacement dictionaries. ");return super._writeDictionaryBatch(t,e,i)}_writeFooter(t){const e=Ko.encode(new Ko(t,ke.V5,this._recordBatchBlocks,this._dictionaryBlocks));return super._writeFooter(t)._write(e)._write(Int32Array.of(e.byteLength))._writeMagic()}}function If(r,t){let e=t;t instanceof gn&&(e=t.batches,r.reset(void 0,t.schema));for(const i of e)r.write(i);return r.finish()}function Ef(r,t){return Zt(this,void 0,void 0,function*(){var e,i,n,s,o,a,l;try{for(e=!0,i=bi(t);n=yield i.next(),s=n.done,!s;e=!0){l=n.value,e=!1;const u=l;r.write(u)}}catch(u){o={error:u}}finally{try{!e&&!s&&(a=i.return)&&(yield a.call(i))}finally{if(o)throw o.error}}return r.finish()})}function qO(r,t="stream"){return(t==="stream"?Sf:Tf).writeAll(r).toUint8Array(!0)}var QO=Object.create,S0=Object.defineProperty,KO=Object.getOwnPropertyDescriptor,ZO=Object.getOwnPropertyNames,JO=Object.getPrototypeOf,t2=Object.prototype.hasOwnProperty,e2=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),r2=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ZO(t))!t2.call(r,n)&&n!==e&&S0(r,n,{get:()=>t[n],enumerable:!(i=KO(t,n))||i.enumerable});return r},i2=(r,t,e)=>(e=r!=null?QO(JO(r)):{},r2(!r||!r.__esModule?S0(e,"default",{value:r,enumerable:!0}):e,r)),n2=e2((r,t)=>{t.exports=Worker}),T0=(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))(T0||{}),s2=(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))(s2||{}),o2=(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))(o2||{}),a2=(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))(a2||{}),l2=(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))(l2||{}),u2=(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))(u2||{}),c2=class{log(r){}},I0=class{constructor(r=2){this.level=r}log(r){r.level>=this.level&&console.log(r)}},h2=(r=>(r[r.SUCCESS=0]="SUCCESS",r))(h2||{}),f2=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=Vr.from(t);return console.assert(e.isSync(),"Reader is not sync"),console.assert(e.isFile(),"Reader is not file"),new gn(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 i=new E0(this._bindings,this._conn,e),n=await Vr.from(i);return console.assert(n.isAsync()),console.assert(n.isStream()),n}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 d2(this._bindings,this._conn,t)}async insertArrowTable(r,t){let e=qO(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)}},E0=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}},d2=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=Vr.from(t);return console.assert(e.isSync()),console.assert(e.isFile()),new gn(e)}async send(...r){let t=await this.bindings.sendPrepared(this.connectionId,this.statementId,r),e=new E0(this.bindings,this.connectionId,t),i=await Vr.from(e);return console.assert(i.isAsync()),console.assert(i.isStream()),i}},p2=(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))(p2||{}),m2=(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))(m2||{}),ue=class{constructor(r,t){this.promiseResolver=()=>{},this.promiseRejecter=()=>{},this.type=r,this.data=t,this.promise=new Promise((e,i)=>{this.promiseResolver=e,this.promiseRejecter=i})}};function Ya(r){switch(r.typeId){case L.Binary:return{sqlType:"binary"};case L.Bool:return{sqlType:"bool"};case L.Date:return{sqlType:"date"};case L.DateDay:return{sqlType:"date32[d]"};case L.DateMillisecond:return{sqlType:"date64[ms]"};case L.Decimal:{let t=r;return{sqlType:"decimal",precision:t.precision,scale:t.scale}}case L.Float:return{sqlType:"float"};case L.Float16:return{sqlType:"float16"};case L.Float32:return{sqlType:"float32"};case L.Float64:return{sqlType:"float64"};case L.Int:return{sqlType:"int32"};case L.Int16:return{sqlType:"int16"};case L.Int32:return{sqlType:"int32"};case L.Int64:return{sqlType:"int64"};case L.Uint16:return{sqlType:"uint16"};case L.Uint32:return{sqlType:"uint32"};case L.Uint64:return{sqlType:"uint64"};case L.Uint8:return{sqlType:"uint8"};case L.IntervalDayTime:return{sqlType:"interval[dt]"};case L.IntervalYearMonth:return{sqlType:"interval[m]"};case L.List:return{sqlType:"list",valueType:Ya(r.valueType)};case L.FixedSizeBinary:return{sqlType:"fixedsizebinary",byteWidth:r.byteWidth};case L.Null:return{sqlType:"null"};case L.Utf8:return{sqlType:"utf8"};case L.Struct:return{sqlType:"struct",fields:r.children.map(t=>yh(t.name,t.type))};case L.Map:{let t=r;return{sqlType:"map",keyType:Ya(t.keyType),valueType:Ya(t.valueType)}}case L.Time:return{sqlType:"time[s]"};case L.TimeMicrosecond:return{sqlType:"time[us]"};case L.TimeMillisecond:return{sqlType:"time[ms]"};case L.TimeNanosecond:return{sqlType:"time[ns]"};case L.TimeSecond:return{sqlType:"time[s]"};case L.Timestamp:return{sqlType:"timestamp",timezone:r.timezone||void 0};case L.TimestampSecond:return{sqlType:"timestamp[s]",timezone:r.timezone||void 0};case L.TimestampMicrosecond:return{sqlType:"timestamp[us]",timezone:r.timezone||void 0};case L.TimestampNanosecond:return{sqlType:"timestamp[ns]",timezone:r.timezone||void 0};case L.TimestampMillisecond:return{sqlType:"timestamp[ms]",timezone:r.timezone||void 0}}throw new Error("unsupported arrow type: ".concat(r.toString()))}function yh(r,t){let e=Ya(t);return e.name=r,e}var y2=new TextEncoder,g2=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 n of this._onInstantiationProgress)n(e.data);return}}let i=this._pendingRequests.get(e.requestId);if(!i){console.warn("unassociated response: [".concat(e.requestId,", ").concat(e.type.toString(),"]"));return}if(this._pendingRequests.delete(e.requestId),e.type=="ERROR"){let n=new Error(e.data.message);n.name=e.data.name,(t=Object.getOwnPropertyDescriptor(n,"stack"))!=null&&t.writable&&(n.stack=e.data.stack),i.promiseRejecter(n);return}switch(i.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"){i.promiseResolver(e.data);return}break;case"INSTANTIATE":if(this._onInstantiationProgress=[],e.type=="OK"){i.promiseResolver(e.data);return}break;case"GLOB_FILE_INFOS":if(e.type=="FILE_INFOS"){i.promiseResolver(e.data);return}break;case"GET_VERSION":if(e.type=="VERSION_STRING"){i.promiseResolver(e.data);return}break;case"GET_FEATURE_FLAGS":if(e.type=="FEATURE_FLAGS"){i.promiseResolver(e.data);return}break;case"GET_TABLE_NAMES":if(e.type=="TABLE_NAMES"){i.promiseResolver(e.data);return}break;case"TOKENIZE":if(e.type=="SCRIPT_TOKENS"){i.promiseResolver(e.data);return}break;case"COPY_FILE_TO_BUFFER":if(e.type=="FILE_BUFFER"){i.promiseResolver(e.data);return}break;case"EXPORT_FILE_STATISTICS":if(e.type=="FILE_STATISTICS"){i.promiseResolver(e.data);return}break;case"CONNECT":if(e.type=="CONNECTION_INFO"){i.promiseResolver(e.data);return}break;case"RUN_PREPARED":case"RUN_QUERY":if(e.type=="QUERY_RESULT"){i.promiseResolver(e.data);return}break;case"SEND_PREPARED":if(e.type=="QUERY_RESULT_HEADER"){i.promiseResolver(e.data);return}break;case"START_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"POLL_PENDING_QUERY":if(e.type=="QUERY_RESULT_HEADER_OR_NULL"){i.promiseResolver(e.data);return}break;case"CANCEL_PENDING_QUERY":if(this._onInstantiationProgress=[],e.type=="SUCCESS"){i.promiseResolver(e.data);return}break;case"FETCH_QUERY_RESULTS":if(e.type=="QUERY_RESULT_CHUNK"){i.promiseResolver(e.data);return}break;case"CREATE_PREPARED":if(e.type=="PREPARED_STATEMENT_ID"){i.promiseResolver(e.data);return}break}i.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 ue("RESET",null);return await this.postTask(r)}async ping(){let r=new ue("PING",null);await this.postTask(r)}async dropFile(r){let t=new ue("DROP_FILE",r);return await this.postTask(t)}async dropFiles(){let r=new ue("DROP_FILES",null);return await this.postTask(r)}async flushFiles(){let r=new ue("FLUSH_FILES",null);return await this.postTask(r)}async instantiate(r,t=null,e=i=>{}){this._onInstantiationProgress.push(e);let i=new ue("INSTANTIATE",[r,t]);return await this.postTask(i)}async getVersion(){let r=new ue("GET_VERSION",null);return await this.postTask(r)}async getFeatureFlags(){let r=new ue("GET_FEATURE_FLAGS",null);return await this.postTask(r)}async open(r){let t=new ue("OPEN",r);await this.postTask(t)}async tokenize(r){let t=new ue("TOKENIZE",r);return await this.postTask(t)}async connectInternal(){let r=new ue("CONNECT",null);return await this.postTask(r)}async connect(){let r=await this.connectInternal();return new f2(this,r)}async disconnect(r){let t=new ue("DISCONNECT",r);await this.postTask(t)}async runQuery(r,t){let e=new ue("RUN_QUERY",[r,t]);return await this.postTask(e)}async startPendingQuery(r,t,e=!1){let i=new ue("START_PENDING_QUERY",[r,t,e]);return await this.postTask(i)}async pollPendingQuery(r){let t=new ue("POLL_PENDING_QUERY",r);return await this.postTask(t)}async cancelPendingQuery(r){let t=new ue("CANCEL_PENDING_QUERY",r);return await this.postTask(t)}async fetchQueryResults(r){let t=new ue("FETCH_QUERY_RESULTS",r);return await this.postTask(t)}async getTableNames(r,t){let e=new ue("GET_TABLE_NAMES",[r,t]);return await this.postTask(e)}async createPrepared(r,t){let e=new ue("CREATE_PREPARED",[r,t]);return await this.postTask(e)}async closePrepared(r,t){let e=new ue("CLOSE_PREPARED",[r,t]);await this.postTask(e)}async runPrepared(r,t,e){let i=new ue("RUN_PREPARED",[r,t,e]);return await this.postTask(i)}async sendPrepared(r,t,e){let i=new ue("SEND_PREPARED",[r,t,e]);return await this.postTask(i)}async globFiles(r){let t=new ue("GLOB_FILE_INFOS",r);return await this.postTask(t)}async registerFileText(r,t){let e=y2.encode(t);await this.registerFileBuffer(r,e)}async registerFileURL(r,t,e,i){t===void 0&&(t=r);let n=new ue("REGISTER_FILE_URL",[r,t,e,i]);await this.postTask(n)}async registerEmptyFileBuffer(r){}async registerFileBuffer(r,t){let e=new ue("REGISTER_FILE_BUFFER",[r,t]);await this.postTask(e,[t.buffer])}async registerFileHandle(r,t,e,i){let n=new ue("REGISTER_FILE_HANDLE",[r,t,e,i]);await this.postTask(n,[])}async registerOPFSFileName(r){let t=new ue("REGISTER_OPFS_FILE_NAME",[r]);await this.postTask(t,[])}async collectFileStatistics(r,t){let e=new ue("COLLECT_FILE_STATISTICS",[r,t]);await this.postTask(e,[])}async exportFileStatistics(r){let t=new ue("EXPORT_FILE_STATISTICS",r);return await this.postTask(t,[])}async copyFileToBuffer(r){let t=new ue("COPY_FILE_TO_BUFFER",r);return await this.postTask(t)}async copyFileToPath(r,t){let e=new ue("COPY_FILE_TO_PATH",[r,t]);await this.postTask(e)}async insertArrowFromIPCStream(r,t,e){if(t.length==0)return;let i=new ue("INSERT_ARROW_FROM_IPC_STREAM",[r,t,e]);await this.postTask(i,[t.buffer])}async insertCSVFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(yh(s,o))}e.columnsFlat=n,delete e.columns}let i=new ue("IMPORT_CSV_FROM_PATH",[r,t,e]);await this.postTask(i)}async insertJSONFromPath(r,t,e){if(e.columns!==void 0){let n=[];for(let s in e.columns){let o=e.columns[s];n.push(yh(s,o))}e.columnsFlat=n,delete e.columns}let i=new ue("IMPORT_JSON_FROM_PATH",[r,t,e]);await this.postTask(i)}};function v2(){let r=new TextDecoder;return t=>(typeof SharedArrayBuffer<"u"&&t.buffer instanceof SharedArrayBuffer&&(t=new Uint8Array(t)),r.decode(t))}v2();var _2=(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))(_2||{}),b2=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])),w2=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])),x2=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])),S2=()=>(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])),T2={version:"1.29.1-dev68.0"},Cf=T2.version.split(".");Cf[0];Cf[1];Cf[2];var I2=()=>typeof navigator>"u",Ku=null,Zu=null,Ju=null,tc=null,ec=null;async function E2(){return Ku==null&&(Ku=typeof BigInt64Array<"u"),Zu==null&&(Zu=await w2()),Ju==null&&(Ju=await S2()),tc==null&&(tc=await x2()),ec==null&&(ec=await b2()),{bigInt64Array:Ku,crossOriginIsolated:I2()||globalThis.crossOriginIsolated||!1,wasmExceptions:Zu,wasmSIMD:tc,wasmThreads:Ju,wasmBulkMemory:ec}}async function kp(r){let t=await E2();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}}i2(n2());const rc={},Mo={};function Lo(r,t){try{const i=(rc[r]||(rc[r]=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour:"numeric",timeZoneName:"longOffset"}).format))(t).split("GMT")[1]||"";return i in Mo?Mo[i]:Up(i,i.split(":"))}catch{if(r in Mo)return Mo[r];const e=r==null?void 0:r.match(C2);return e?Up(r,e.slice(1)):NaN}}const C2=/([+-]\d\d):?(\d\d)?/;function Up(r,t){const e=+t[0],i=+(t[1]||0);return Mo[r]=e>0?e*60+i:e*60-i}class Er extends Date{constructor(...t){super(),t.length>1&&typeof t[t.length-1]=="string"&&(this.timeZone=t.pop()),this.internal=new Date,isNaN(Lo(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)),C0(this),gh(this)):this.setTime(Date.now())}static tz(t,...e){return e.length?new Er(...e,t):new Er(Date.now(),t)}withTimeZone(t){return new Er(+this,t)}getTimezoneOffset(){return-Lo(this.timeZone,this)}setTime(t){return Date.prototype.setTime.apply(this,arguments),gh(this),+this}[Symbol.for("constructDateFrom")](t){return new Er(+new Date(t),this.timeZone)}}const zp=/^(get|set)(?!UTC)/;Object.getOwnPropertyNames(Date.prototype).forEach(r=>{if(!zp.test(r))return;const t=r.replace(zp,"$1UTC");Er.prototype[t]&&(r.startsWith("get")?Er.prototype[r]=function(){return this.internal[t]()}:(Er.prototype[r]=function(){return Date.prototype[t].apply(this.internal,arguments),A2(this),+this},Er.prototype[t]=function(){return Date.prototype[t].apply(this,arguments),gh(this),+this}))});function gh(r){r.internal.setTime(+r),r.internal.setUTCMinutes(r.internal.getUTCMinutes()-r.getTimezoneOffset())}function A2(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()),C0(r)}function C0(r){const t=Lo(r.timeZone,r),e=new Date(+r);e.setUTCHours(e.getUTCHours()-1);const i=-new Date(+r).getTimezoneOffset(),n=-new Date(+e).getTimezoneOffset(),s=i-n,o=Date.prototype.getHours.apply(r)!==r.internal.getUTCHours();s&&o&&r.internal.setUTCMinutes(r.internal.getUTCMinutes()+s);const a=i-t;a&&Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+a);const l=Lo(r.timeZone,r),c=-new Date(+r).getTimezoneOffset()-l,h=l!==t,p=c-a;if(h&&p){Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+p);const f=Lo(r.timeZone,r),y=l-f;y&&(r.internal.setUTCMinutes(r.internal.getUTCMinutes()+y),Date.prototype.setUTCMinutes.call(r,Date.prototype.getUTCMinutes.call(r)+y))}}const O2=new TextDecoder("utf-8"),F2=r=>O2.decode(r),P2=new TextEncoder,A0=r=>P2.encode(r),hi=r=>typeof r=="function",ha=r=>r!=null&&Object(r)===r,M2=r=>ha(r)&&hi(r.then),O0=r=>ha(r)&&hi(r[Symbol.iterator]),D2=r=>ha(r)&&hi(r[Symbol.asyncIterator]),R2=r=>ha(r)&&"done"in r&&"value"in r,N2=r=>ha(r)&&hi(r.clear)&&hi(r.bytes)&&hi(r.position)&&hi(r.setPosition)&&hi(r.capacity)&&hi(r.getBufferIdentifier)&&hi(r.createLong),Af=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:ArrayBuffer;function L2(r){const t=r[0]?[r[0]]:[];let e,i,n,s;for(let o,a,l=0,u=0,c=r.length;++lc+h.byteLength,0);let n,s,o,a=0,l=-1;const u=Math.min(t||Number.POSITIVE_INFINITY,i);for(const c=e.length;++lrr(Int8Array,r),U2=r=>rr(Int16Array,r),z2=r=>rr(Int32Array,r),j2=r=>rr(BigInt64Array,r),$2=r=>rr(Uint8Array,r),V2=r=>rr(Uint16Array,r),G2=r=>rr(Uint32Array,r),W2=r=>rr(BigUint64Array,r),H2=r=>rr(Float32Array,r),X2=r=>rr(Float64Array,r),Y2=r=>rr(Uint8ClampedArray,r),_h=r=>(r.next(),r);function*Oi(r,t){const e=function*(n){yield n},i=typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof Af?e(t):O0(t)?t:e(t);return yield*_h(function*(n){let s=null;do s=n.next(yield rr(r,s));while(!s.done)}(i[Symbol.iterator]())),new r}const q2=r=>Oi(Int8Array,r),Q2=r=>Oi(Int16Array,r),K2=r=>Oi(Int32Array,r),Z2=r=>Oi(Uint8Array,r),J2=r=>Oi(Uint16Array,r),tF=r=>Oi(Uint32Array,r),eF=r=>Oi(Float32Array,r),rF=r=>Oi(Float64Array,r),iF=r=>Oi(Uint8ClampedArray,r);function ii(r,t){return dr(this,arguments,function*(){if(M2(t))return yield Pt(yield Pt(yield*ts(bi(ii(r,yield Pt(t))))));const i=function(o){return dr(this,arguments,function*(){yield yield Pt(yield Pt(o))})},n=function(o){return dr(this,arguments,function*(){yield Pt(yield*ts(bi(_h(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 Af?i(t):O0(t)?n(t):D2(t)?t:i(t);return yield Pt(yield*ts(bi(_h(function(o){return dr(this,arguments,function*(){let a=null;do a=yield Pt(o.next(yield yield Pt(rr(r,a))));while(!a.done)})}(s[Symbol.asyncIterator]()))))),yield Pt(new r)})}const nF=r=>ii(Int8Array,r),sF=r=>ii(Int16Array,r),oF=r=>ii(Int32Array,r),aF=r=>ii(Uint8Array,r),lF=r=>ii(Uint16Array,r),uF=r=>ii(Uint32Array,r),cF=r=>ii(Float32Array,r),hF=r=>ii(Float64Array,r),fF=r=>ii(Uint8ClampedArray,r);function dF(r,t,e){if(r!==0){e=e.slice(0,t);for(let i=-1,n=e.length;++i0)do if(r[e]!==t[e])return!1;while(++eeo(t))}]`:`[${r}]`:ArrayBuffer.isView(r)?`[${r}]`:JSON.stringify(r,(t,e)=>typeof e=="bigint"?`${e}`:e)}const yF=Object.freeze(Object.defineProperty({__proto__:null,valueToString:eo},Symbol.toStringTag,{value:"Module"}));function ar(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 P0(r,t){return ar(r/t)+ar(r%t)/ar(t)}const M0=Symbol.for("isArrowBigNum");function ni(r,...t){return t.length===0?Object.setPrototypeOf(rr(this.TypedArray,r),this.constructor.prototype):Object.setPrototypeOf(new this.TypedArray(r,...t),this.constructor.prototype)}ni.prototype[M0]=!0;ni.prototype.toJSON=function(){return`"${ro(this)}"`};ni.prototype.valueOf=function(r){return Of(this,r)};ni.prototype.toString=function(){return ro(this)};ni.prototype[Symbol.toPrimitive]=function(r="default"){switch(r){case"number":return Of(this);case"string":return ro(this);case"default":return D0(this)}return ro(this)};function Gs(...r){return ni.apply(this,r)}function Ws(...r){return ni.apply(this,r)}function Jo(...r){return ni.apply(this,r)}Object.setPrototypeOf(Gs.prototype,Object.create(Int32Array.prototype));Object.setPrototypeOf(Ws.prototype,Object.create(Uint32Array.prototype));Object.setPrototypeOf(Jo.prototype,Object.create(Uint32Array.prototype));Object.assign(Gs.prototype,ni.prototype,{constructor:Gs,signed:!0,TypedArray:Int32Array,BigIntArray:BigInt64Array});Object.assign(Ws.prototype,ni.prototype,{constructor:Ws,signed:!1,TypedArray:Uint32Array,BigIntArray:BigUint64Array});Object.assign(Jo.prototype,ni.prototype,{constructor:Jo,signed:!0,TypedArray:Uint32Array,BigIntArray:BigUint64Array});const gF=BigInt(4294967296)*BigInt(4294967296),vF=gF-BigInt(1);function Of(r,t){const{buffer:e,byteOffset:i,byteLength:n,signed:s}=r,o=new BigUint64Array(e,i,n/8),a=s&&o.at(-1)&BigInt(1)<=0)return ic(r);t=t.slice();let i=1;for(let s=0;s(r.children=null,r.ArrayType=Array,r.OffsetArrayType=Int32Array,r[Symbol.toStringTag]="DataType"))(Et.prototype);class jp extends Et{constructor(){super(W.Null)}toString(){return"Null"}}N0=Symbol.toStringTag;jp[N0]=(r=>r[Symbol.toStringTag]="Null")(jp.prototype);class $p extends Et{constructor(t,e){super(W.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}`}}L0=Symbol.toStringTag;$p[L0]=(r=>(r.isSigned=null,r.bitWidth=null,r[Symbol.toStringTag]="Int"))($p.prototype);class Vp extends Et{constructor(t){super(W.Float),this.precision=t}get ArrayType(){switch(this.precision){case Cr.HALF:return Uint16Array;case Cr.SINGLE:return Float32Array;case Cr.DOUBLE:return Float64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}toString(){return`Float${this.precision<<5||16}`}}B0=Symbol.toStringTag;Vp[B0]=(r=>(r.precision=null,r[Symbol.toStringTag]="Float"))(Vp.prototype);class Gp extends Et{constructor(){super(W.Binary)}toString(){return"Binary"}}k0=Symbol.toStringTag;Gp[k0]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Binary"))(Gp.prototype);class Wp extends Et{constructor(){super(W.LargeBinary)}toString(){return"LargeBinary"}}U0=Symbol.toStringTag;Wp[U0]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeBinary"))(Wp.prototype);class Hp extends Et{constructor(){super(W.Utf8)}toString(){return"Utf8"}}z0=Symbol.toStringTag;Hp[z0]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Utf8"))(Hp.prototype);class Xp extends Et{constructor(){super(W.LargeUtf8)}toString(){return"LargeUtf8"}}j0=Symbol.toStringTag;Xp[j0]=(r=>(r.ArrayType=Uint8Array,r.OffsetArrayType=BigInt64Array,r[Symbol.toStringTag]="LargeUtf8"))(Xp.prototype);class Yp extends Et{constructor(){super(W.Bool)}toString(){return"Bool"}}$0=Symbol.toStringTag;Yp[$0]=(r=>(r.ArrayType=Uint8Array,r[Symbol.toStringTag]="Bool"))(Yp.prototype);class qp extends Et{constructor(t,e,i=128){super(W.Decimal),this.scale=t,this.precision=e,this.bitWidth=i}toString(){return`Decimal[${this.precision}e${this.scale>0?"+":""}${this.scale}]`}}V0=Symbol.toStringTag;qp[V0]=(r=>(r.scale=null,r.precision=null,r.ArrayType=Uint32Array,r[Symbol.toStringTag]="Decimal"))(qp.prototype);class Qp extends Et{constructor(t){super(W.Date),this.unit=t}toString(){return`Date${(this.unit+1)*32}<${_n[this.unit]}>`}get ArrayType(){return this.unit===_n.DAY?Int32Array:BigInt64Array}}G0=Symbol.toStringTag;Qp[G0]=(r=>(r.unit=null,r[Symbol.toStringTag]="Date"))(Qp.prototype);class Kp extends Et{constructor(t,e){super(W.Time),this.unit=t,this.bitWidth=e}toString(){return`Time${this.bitWidth}<${Jt[this.unit]}>`}get ArrayType(){switch(this.bitWidth){case 32:return Int32Array;case 64:return BigInt64Array}throw new Error(`Unrecognized ${this[Symbol.toStringTag]} type`)}}W0=Symbol.toStringTag;Kp[W0]=(r=>(r.unit=null,r.bitWidth=null,r[Symbol.toStringTag]="Time"))(Kp.prototype);class Zp extends Et{constructor(t,e){super(W.Timestamp),this.unit=t,this.timezone=e}toString(){return`Timestamp<${Jt[this.unit]}${this.timezone?`, ${this.timezone}`:""}>`}}H0=Symbol.toStringTag;Zp[H0]=(r=>(r.unit=null,r.timezone=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Timestamp"))(Zp.prototype);class Jp extends Et{constructor(t){super(W.Interval),this.unit=t}toString(){return`Interval<${ns[this.unit]}>`}}X0=Symbol.toStringTag;Jp[X0]=(r=>(r.unit=null,r.ArrayType=Int32Array,r[Symbol.toStringTag]="Interval"))(Jp.prototype);class tm extends Et{constructor(t){super(W.Duration),this.unit=t}toString(){return`Duration<${Jt[this.unit]}>`}}Y0=Symbol.toStringTag;tm[Y0]=(r=>(r.unit=null,r.ArrayType=BigInt64Array,r[Symbol.toStringTag]="Duration"))(tm.prototype);class em extends Et{constructor(t){super(W.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}}q0=Symbol.toStringTag;em[q0]=(r=>(r.children=null,r[Symbol.toStringTag]="List"))(em.prototype);class bh extends Et{constructor(t){super(W.Struct),this.children=t}toString(){return`Struct<{${this.children.map(t=>`${t.name}:${t.type}`).join(", ")}}>`}}Q0=Symbol.toStringTag;bh[Q0]=(r=>(r.children=null,r[Symbol.toStringTag]="Struct"))(bh.prototype);class rm extends Et{constructor(t,e,i){super(W.Union),this.mode=t,this.children=i,this.typeIds=e=Int32Array.from(e),this.typeIdToChildIndex=e.reduce((n,s,o)=>(n[s]=o)&&n||n,Object.create(null))}toString(){return`${this[Symbol.toStringTag]}<${this.children.map(t=>`${t.type}`).join(" | ")}>`}}K0=Symbol.toStringTag;rm[K0]=(r=>(r.mode=null,r.typeIds=null,r.children=null,r.typeIdToChildIndex=null,r.ArrayType=Int8Array,r[Symbol.toStringTag]="Union"))(rm.prototype);class im extends Et{constructor(t){super(W.FixedSizeBinary),this.byteWidth=t}toString(){return`FixedSizeBinary[${this.byteWidth}]`}}Z0=Symbol.toStringTag;im[Z0]=(r=>(r.byteWidth=null,r.ArrayType=Uint8Array,r[Symbol.toStringTag]="FixedSizeBinary"))(im.prototype);class nm extends Et{constructor(t,e){super(W.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}>`}}J0=Symbol.toStringTag;nm[J0]=(r=>(r.children=null,r.listSize=null,r[Symbol.toStringTag]="FixedSizeList"))(nm.prototype);class sm extends Et{constructor(t,e=!1){var i,n,s;if(super(W.Map),this.children=[t],this.keysSorted=e,t&&(t.name="entries",!((i=t==null?void 0:t.type)===null||i===void 0)&&i.children)){const o=(n=t==null?void 0:t.type)===null||n===void 0?void 0:n.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(", ")}}>`}}tb=Symbol.toStringTag;sm[tb]=(r=>(r.children=null,r.keysSorted=null,r[Symbol.toStringTag]="Map_"))(sm.prototype);const bF=(r=>()=>++r)(-1);class om extends Et{constructor(t,e,i,n){super(W.Dictionary),this.indices=e,this.dictionary=t,this.isOrdered=n||!1,this.id=i==null?bF():ar(i)}get children(){return this.dictionary.children}get valueType(){return this.dictionary}get ArrayType(){return this.dictionary.ArrayType}toString(){return`Dictionary<${this.indices}, ${this.dictionary}>`}}eb=Symbol.toStringTag;om[eb]=(r=>(r.id=null,r.indices=null,r.isOrdered=null,r.dictionary=null,r[Symbol.toStringTag]="Dictionary"))(om.prototype);function rb(r){const t=r;switch(r.typeId){case W.Decimal:return r.bitWidth/32;case W.Interval:return 1+t.unit;case W.FixedSizeList:return t.listSize;case W.FixedSizeBinary:return t.byteWidth;default:return 1}}class le{visitMany(t,...e){return t.map((i,n)=>this.visit(i,...e.map(s=>s[n])))}visit(...t){return this.getVisitFn(t[0],!1).apply(this,t)}getVisitFn(t,e=!0){return wF(this,t,e)}getVisitFnByTypeId(t,e=!0){return Ps(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 wF(r,t,e=!0){return typeof t=="number"?Ps(r,t,e):typeof t=="string"&&t in W?Ps(r,W[t],e):t&&t instanceof Et?Ps(r,am(t),e):t!=null&&t.type&&t.type instanceof Et?Ps(r,am(t.type),e):Ps(r,W.NONE,e)}function Ps(r,t,e=!0){let i=null;switch(t){case W.Null:i=r.visitNull;break;case W.Bool:i=r.visitBool;break;case W.Int:i=r.visitInt;break;case W.Int8:i=r.visitInt8||r.visitInt;break;case W.Int16:i=r.visitInt16||r.visitInt;break;case W.Int32:i=r.visitInt32||r.visitInt;break;case W.Int64:i=r.visitInt64||r.visitInt;break;case W.Uint8:i=r.visitUint8||r.visitInt;break;case W.Uint16:i=r.visitUint16||r.visitInt;break;case W.Uint32:i=r.visitUint32||r.visitInt;break;case W.Uint64:i=r.visitUint64||r.visitInt;break;case W.Float:i=r.visitFloat;break;case W.Float16:i=r.visitFloat16||r.visitFloat;break;case W.Float32:i=r.visitFloat32||r.visitFloat;break;case W.Float64:i=r.visitFloat64||r.visitFloat;break;case W.Utf8:i=r.visitUtf8;break;case W.LargeUtf8:i=r.visitLargeUtf8;break;case W.Binary:i=r.visitBinary;break;case W.LargeBinary:i=r.visitLargeBinary;break;case W.FixedSizeBinary:i=r.visitFixedSizeBinary;break;case W.Date:i=r.visitDate;break;case W.DateDay:i=r.visitDateDay||r.visitDate;break;case W.DateMillisecond:i=r.visitDateMillisecond||r.visitDate;break;case W.Timestamp:i=r.visitTimestamp;break;case W.TimestampSecond:i=r.visitTimestampSecond||r.visitTimestamp;break;case W.TimestampMillisecond:i=r.visitTimestampMillisecond||r.visitTimestamp;break;case W.TimestampMicrosecond:i=r.visitTimestampMicrosecond||r.visitTimestamp;break;case W.TimestampNanosecond:i=r.visitTimestampNanosecond||r.visitTimestamp;break;case W.Time:i=r.visitTime;break;case W.TimeSecond:i=r.visitTimeSecond||r.visitTime;break;case W.TimeMillisecond:i=r.visitTimeMillisecond||r.visitTime;break;case W.TimeMicrosecond:i=r.visitTimeMicrosecond||r.visitTime;break;case W.TimeNanosecond:i=r.visitTimeNanosecond||r.visitTime;break;case W.Decimal:i=r.visitDecimal;break;case W.List:i=r.visitList;break;case W.Struct:i=r.visitStruct;break;case W.Union:i=r.visitUnion;break;case W.DenseUnion:i=r.visitDenseUnion||r.visitUnion;break;case W.SparseUnion:i=r.visitSparseUnion||r.visitUnion;break;case W.Dictionary:i=r.visitDictionary;break;case W.Interval:i=r.visitInterval;break;case W.IntervalDayTime:i=r.visitIntervalDayTime||r.visitInterval;break;case W.IntervalYearMonth:i=r.visitIntervalYearMonth||r.visitInterval;break;case W.Duration:i=r.visitDuration;break;case W.DurationSecond:i=r.visitDurationSecond||r.visitDuration;break;case W.DurationMillisecond:i=r.visitDurationMillisecond||r.visitDuration;break;case W.DurationMicrosecond:i=r.visitDurationMicrosecond||r.visitDuration;break;case W.DurationNanosecond:i=r.visitDurationNanosecond||r.visitDuration;break;case W.FixedSizeList:i=r.visitFixedSizeList;break;case W.Map:i=r.visitMap;break}if(typeof i=="function")return i;if(!e)return()=>null;throw new Error(`Unrecognized type '${W[t]}'`)}function am(r){switch(r.typeId){case W.Null:return W.Null;case W.Int:{const{bitWidth:t,isSigned:e}=r;switch(t){case 8:return e?W.Int8:W.Uint8;case 16:return e?W.Int16:W.Uint16;case 32:return e?W.Int32:W.Uint32;case 64:return e?W.Int64:W.Uint64}return W.Int}case W.Float:switch(r.precision){case Cr.HALF:return W.Float16;case Cr.SINGLE:return W.Float32;case Cr.DOUBLE:return W.Float64}return W.Float;case W.Binary:return W.Binary;case W.LargeBinary:return W.LargeBinary;case W.Utf8:return W.Utf8;case W.LargeUtf8:return W.LargeUtf8;case W.Bool:return W.Bool;case W.Decimal:return W.Decimal;case W.Time:switch(r.unit){case Jt.SECOND:return W.TimeSecond;case Jt.MILLISECOND:return W.TimeMillisecond;case Jt.MICROSECOND:return W.TimeMicrosecond;case Jt.NANOSECOND:return W.TimeNanosecond}return W.Time;case W.Timestamp:switch(r.unit){case Jt.SECOND:return W.TimestampSecond;case Jt.MILLISECOND:return W.TimestampMillisecond;case Jt.MICROSECOND:return W.TimestampMicrosecond;case Jt.NANOSECOND:return W.TimestampNanosecond}return W.Timestamp;case W.Date:switch(r.unit){case _n.DAY:return W.DateDay;case _n.MILLISECOND:return W.DateMillisecond}return W.Date;case W.Interval:switch(r.unit){case ns.DAY_TIME:return W.IntervalDayTime;case ns.YEAR_MONTH:return W.IntervalYearMonth}return W.Interval;case W.Duration:switch(r.unit){case Jt.SECOND:return W.DurationSecond;case Jt.MILLISECOND:return W.DurationMillisecond;case Jt.MICROSECOND:return W.DurationMicrosecond;case Jt.NANOSECOND:return W.DurationNanosecond}return W.Duration;case W.Map:return W.Map;case W.List:return W.List;case W.Struct:return W.Struct;case W.Union:switch(r.mode){case Ii.Dense:return W.DenseUnion;case Ii.Sparse:return W.SparseUnion}return W.Union;case W.FixedSizeBinary:return W.FixedSizeBinary;case W.FixedSizeList:return W.FixedSizeList;case W.Dictionary:return W.Dictionary}throw new Error(`Unrecognized type '${W[r.typeId]}'`)}le.prototype.visitInt8=null;le.prototype.visitInt16=null;le.prototype.visitInt32=null;le.prototype.visitInt64=null;le.prototype.visitUint8=null;le.prototype.visitUint16=null;le.prototype.visitUint32=null;le.prototype.visitUint64=null;le.prototype.visitFloat16=null;le.prototype.visitFloat32=null;le.prototype.visitFloat64=null;le.prototype.visitDateDay=null;le.prototype.visitDateMillisecond=null;le.prototype.visitTimestampSecond=null;le.prototype.visitTimestampMillisecond=null;le.prototype.visitTimestampMicrosecond=null;le.prototype.visitTimestampNanosecond=null;le.prototype.visitTimeSecond=null;le.prototype.visitTimeMillisecond=null;le.prototype.visitTimeMicrosecond=null;le.prototype.visitTimeNanosecond=null;le.prototype.visitDenseUnion=null;le.prototype.visitSparseUnion=null;le.prototype.visitIntervalDayTime=null;le.prototype.visitIntervalYearMonth=null;le.prototype.visitDuration=null;le.prototype.visitDurationSecond=null;le.prototype.visitDurationMillisecond=null;le.prototype.visitDurationMicrosecond=null;le.prototype.visitDurationNanosecond=null;const ib=new Float64Array(1),vs=new Uint32Array(ib.buffer);function Ff(r){const t=(r&31744)>>10,e=(r&1023)/1024,i=Math.pow(-1,(r&32768)>>15);switch(t){case 31:return i*(e?Number.NaN:1/0);case 0:return i*(e?6103515625e-14*e:0)}return i*Math.pow(2,t-15)*(1+e)}function nb(r){if(r!==r)return 32256;ib[0]=r;const t=(vs[1]&2147483648)>>16&65535;let e=vs[1]&2146435072,i=0;return e>=1089470464?vs[0]>0?e=31744:(e=(e&2080374784)>>16,i=(vs[1]&1048575)>>10):e<=1056964608?(i=1048576+(vs[1]&1048575),i=1048576+(i<<(e>>20)-998)>>21,e=0):(e=e-1056964608>>10,i=(vs[1]&1048575)+512>>10),t|e|i&65535}const xF=Object.freeze(Object.defineProperty({__proto__:null,float64ToUint16:nb,uint16ToFloat64:Ff},Symbol.toStringTag,{value:"Module"}));class Gt extends le{}function Yt(r){return(t,e,i)=>{if(t.setValid(e,i!=null))return r(t,e,i)}}const SF=(r,t,e)=>{r[t]=Math.floor(e/864e5)},sb=(r,t,e,i)=>{if(e+1{const n=r+e;i?t[n>>3]|=1<>3]&=~(1<{r[t]=e},Pf=({values:r},t,e)=>{r[t]=e},ob=({values:r},t,e)=>{r[t]=nb(e)},IF=(r,t,e)=>{switch(r.type.precision){case Cr.HALF:return ob(r,t,e);case Cr.SINGLE:case Cr.DOUBLE:return Pf(r,t,e)}},ab=({values:r},t,e)=>{SF(r,t,e.valueOf())},lb=({values:r},t,e)=>{r[t]=BigInt(e)},EF=({stride:r,values:t},e,i)=>{t.set(i.subarray(0,r),r*e)},ub=({values:r,valueOffsets:t},e,i)=>sb(r,t,e,i),cb=({values:r,valueOffsets:t},e,i)=>sb(r,t,e,A0(i)),CF=(r,t,e)=>{r.type.unit===_n.DAY?ab(r,t,e):lb(r,t,e)},hb=({values:r},t,e)=>{r[t]=BigInt(e/1e3)},fb=({values:r},t,e)=>{r[t]=BigInt(e)},db=({values:r},t,e)=>{r[t]=BigInt(e*1e3)},pb=({values:r},t,e)=>{r[t]=BigInt(e*1e6)},AF=(r,t,e)=>{switch(r.type.unit){case Jt.SECOND:return hb(r,t,e);case Jt.MILLISECOND:return fb(r,t,e);case Jt.MICROSECOND:return db(r,t,e);case Jt.NANOSECOND:return pb(r,t,e)}},mb=({values:r},t,e)=>{r[t]=e},yb=({values:r},t,e)=>{r[t]=e},gb=({values:r},t,e)=>{r[t]=e},vb=({values:r},t,e)=>{r[t]=e},OF=(r,t,e)=>{switch(r.type.unit){case Jt.SECOND:return mb(r,t,e);case Jt.MILLISECOND:return yb(r,t,e);case Jt.MICROSECOND:return gb(r,t,e);case Jt.NANOSECOND:return vb(r,t,e)}},FF=({values:r,stride:t},e,i)=>{r.set(i.subarray(0,t),t*e)},PF=(r,t,e)=>{const i=r.children[0],n=r.valueOffsets,s=Ei.getVisitFn(i);if(Array.isArray(e))for(let o=-1,a=n[t],l=n[t+1];a{const i=r.children[0],{valueOffsets:n}=r,s=Ei.getVisitFn(i);let{[t]:o,[t+1]:a}=n;const l=e instanceof Map?e.entries():Object.entries(e);for(const u of l)if(s(i,o,u),++o>=a)break},DF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[s]),RF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(s)),NF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t.get(n.name)),LF=(r,t)=>(e,i,n,s)=>i&&e(i,r,t[n.name]),BF=(r,t,e)=>{const i=r.type.children.map(s=>Ei.getVisitFn(s.type)),n=e instanceof Map?NF(t,e):e instanceof Qe?RF(t,e):Array.isArray(e)?DF(t,e):LF(t,e);r.type.children.forEach((s,o)=>n(i[o],r.children[o],s,o))},kF=(r,t,e)=>{r.type.mode===Ii.Dense?_b(r,t,e):bb(r,t,e)},_b=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Ei.visit(n,r.valueOffsets[t],e)},bb=(r,t,e)=>{const i=r.type.typeIdToChildIndex[r.typeIds[t]],n=r.children[i];Ei.visit(n,t,e)},UF=(r,t,e)=>{var i;(i=r.dictionary)===null||i===void 0||i.set(r.values[t],e)},zF=(r,t,e)=>{r.type.unit===ns.DAY_TIME?wb(r,t,e):xb(r,t,e)},wb=({values:r},t,e)=>{r.set(e.subarray(0,2),2*t)},xb=({values:r},t,e)=>{r[t]=e[0]*12+e[1]%12},Sb=({values:r},t,e)=>{r[t]=e},Tb=({values:r},t,e)=>{r[t]=e},Ib=({values:r},t,e)=>{r[t]=e},Eb=({values:r},t,e)=>{r[t]=e},jF=(r,t,e)=>{switch(r.type.unit){case Jt.SECOND:return Sb(r,t,e);case Jt.MILLISECOND:return Tb(r,t,e);case Jt.MICROSECOND:return Ib(r,t,e);case Jt.NANOSECOND:return Eb(r,t,e)}},$F=(r,t,e)=>{const{stride:i}=r,n=r.children[0],s=Ei.getVisitFn(n);if(Array.isArray(e))for(let o=-1,a=t*i;++o`${eo(t)}: ${eo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}[Symbol.iterator](){return new VF(this[Zr],this[Hs])}}class VF{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[Zr].type.children.some(i=>i.name===e)}getOwnPropertyDescriptor(t,e){if(t[Zr].type.children.some(i=>i.name===e))return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Zr].type.children.findIndex(n=>n.name===e);if(i!==-1){const n=Yr.visit(t[Zr].children[i],t[Hs]);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Zr].type.children.findIndex(s=>s.name===e);return n!==-1?(Ei.visit(t[Zr].children[n],t[Hs],i),Reflect.set(t,e,i)):Reflect.has(t,e)||typeof e=="symbol"?Reflect.set(t,e,i):!1}}const WF=new GF;class Lt extends le{}function Wt(r){return(t,e)=>t.getValid(e)?r(t,e):null}const HF=(r,t)=>864e5*r[t],XF=(r,t)=>null,Cb=(r,t,e)=>{if(e+1>=t.length)return null;const i=ar(t[e]),n=ar(t[e+1]);return r.subarray(i,n)},YF=({offset:r,values:t},e)=>{const i=r+e;return(t[i>>3]&1<HF(r,t),Ob=({values:r},t)=>ar(r[t]),xn=({stride:r,values:t},e)=>t[r*e],qF=({stride:r,values:t},e)=>Ff(t[r*e]),Fb=({values:r},t)=>r[t],QF=({stride:r,values:t},e)=>t.subarray(r*e,r*(e+1)),Pb=({values:r,valueOffsets:t},e)=>Cb(r,t,e),Mb=({values:r,valueOffsets:t},e)=>{const i=Cb(r,t,e);return i!==null?F2(i):null},KF=({values:r},t)=>r[t],ZF=({type:r,values:t},e)=>r.precision!==Cr.HALF?t[e]:Ff(t[e]),JF=(r,t)=>r.type.unit===_n.DAY?Ab(r,t):Ob(r,t),Db=({values:r},t)=>1e3*ar(r[t]),Rb=({values:r},t)=>ar(r[t]),Nb=({values:r},t)=>P0(r[t],BigInt(1e3)),Lb=({values:r},t)=>P0(r[t],BigInt(1e6)),tP=(r,t)=>{switch(r.type.unit){case Jt.SECOND:return Db(r,t);case Jt.MILLISECOND:return Rb(r,t);case Jt.MICROSECOND:return Nb(r,t);case Jt.NANOSECOND:return Lb(r,t)}},Bb=({values:r},t)=>r[t],kb=({values:r},t)=>r[t],Ub=({values:r},t)=>r[t],zb=({values:r},t)=>r[t],eP=(r,t)=>{switch(r.type.unit){case Jt.SECOND:return Bb(r,t);case Jt.MILLISECOND:return kb(r,t);case Jt.MICROSECOND:return Ub(r,t);case Jt.NANOSECOND:return zb(r,t)}},rP=({values:r,stride:t},e)=>su.decimal(r.subarray(t*e,t*(e+1))),iP=(r,t)=>{const{valueOffsets:e,stride:i,children:n}=r,{[t*i]:s,[t*i+1]:o}=e,l=n[0].slice(s,o-s);return new Qe([l])},nP=(r,t)=>{const{valueOffsets:e,children:i}=r,{[t]:n,[t+1]:s}=e,o=i[0];return new Df(o.slice(n,s-n))},sP=(r,t)=>new Mf(r,t),oP=(r,t)=>r.type.mode===Ii.Dense?jb(r,t):$b(r,t),jb=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return Yr.visit(i,r.valueOffsets[t])},$b=(r,t)=>{const e=r.type.typeIdToChildIndex[r.typeIds[t]],i=r.children[e];return Yr.visit(i,t)},aP=(r,t)=>{var e;return(e=r.dictionary)===null||e===void 0?void 0:e.get(r.values[t])},lP=(r,t)=>r.type.unit===ns.DAY_TIME?Vb(r,t):Gb(r,t),Vb=({values:r},t)=>r.subarray(2*t,2*(t+1)),Gb=({values:r},t)=>{const e=r[t],i=new Int32Array(2);return i[0]=Math.trunc(e/12),i[1]=Math.trunc(e%12),i},Wb=({values:r},t)=>r[t],Hb=({values:r},t)=>r[t],Xb=({values:r},t)=>r[t],Yb=({values:r},t)=>r[t],uP=(r,t)=>{switch(r.type.unit){case Jt.SECOND:return Wb(r,t);case Jt.MILLISECOND:return Hb(r,t);case Jt.MICROSECOND:return Xb(r,t);case Jt.NANOSECOND:return Yb(r,t)}},cP=(r,t)=>{const{stride:e,children:i}=r,s=i[0].slice(t*e,e);return new Qe([s])};Lt.prototype.visitNull=Wt(XF);Lt.prototype.visitBool=Wt(YF);Lt.prototype.visitInt=Wt(KF);Lt.prototype.visitInt8=Wt(xn);Lt.prototype.visitInt16=Wt(xn);Lt.prototype.visitInt32=Wt(xn);Lt.prototype.visitInt64=Wt(Fb);Lt.prototype.visitUint8=Wt(xn);Lt.prototype.visitUint16=Wt(xn);Lt.prototype.visitUint32=Wt(xn);Lt.prototype.visitUint64=Wt(Fb);Lt.prototype.visitFloat=Wt(ZF);Lt.prototype.visitFloat16=Wt(qF);Lt.prototype.visitFloat32=Wt(xn);Lt.prototype.visitFloat64=Wt(xn);Lt.prototype.visitUtf8=Wt(Mb);Lt.prototype.visitLargeUtf8=Wt(Mb);Lt.prototype.visitBinary=Wt(Pb);Lt.prototype.visitLargeBinary=Wt(Pb);Lt.prototype.visitFixedSizeBinary=Wt(QF);Lt.prototype.visitDate=Wt(JF);Lt.prototype.visitDateDay=Wt(Ab);Lt.prototype.visitDateMillisecond=Wt(Ob);Lt.prototype.visitTimestamp=Wt(tP);Lt.prototype.visitTimestampSecond=Wt(Db);Lt.prototype.visitTimestampMillisecond=Wt(Rb);Lt.prototype.visitTimestampMicrosecond=Wt(Nb);Lt.prototype.visitTimestampNanosecond=Wt(Lb);Lt.prototype.visitTime=Wt(eP);Lt.prototype.visitTimeSecond=Wt(Bb);Lt.prototype.visitTimeMillisecond=Wt(kb);Lt.prototype.visitTimeMicrosecond=Wt(Ub);Lt.prototype.visitTimeNanosecond=Wt(zb);Lt.prototype.visitDecimal=Wt(rP);Lt.prototype.visitList=Wt(iP);Lt.prototype.visitStruct=Wt(sP);Lt.prototype.visitUnion=Wt(oP);Lt.prototype.visitDenseUnion=Wt(jb);Lt.prototype.visitSparseUnion=Wt($b);Lt.prototype.visitDictionary=Wt(aP);Lt.prototype.visitInterval=Wt(lP);Lt.prototype.visitIntervalDayTime=Wt(Vb);Lt.prototype.visitIntervalYearMonth=Wt(Gb);Lt.prototype.visitDuration=Wt(uP);Lt.prototype.visitDurationSecond=Wt(Wb);Lt.prototype.visitDurationMillisecond=Wt(Hb);Lt.prototype.visitDurationMicrosecond=Wt(Xb);Lt.prototype.visitDurationNanosecond=Wt(Yb);Lt.prototype.visitFixedSizeList=Wt(cP);Lt.prototype.visitMap=Wt(nP);const Yr=new Lt,Ms=Symbol.for("keys"),Xs=Symbol.for("vals"),Ds=Symbol.for("kKeysAsStrings"),wh=Symbol.for("_kKeysAsStrings");class Df{constructor(t){return this[Ms]=new Qe([t.children[0]]).memoize(),this[Xs]=t.children[1],new Proxy(this,new fP)}get[Ds](){return this[wh]||(this[wh]=Array.from(this[Ms].toArray(),String))}[Symbol.iterator](){return new hP(this[Ms],this[Xs])}get size(){return this[Ms].length}toArray(){return Object.values(this.toJSON())}toJSON(){const t=this[Ms],e=this[Xs],i={};for(let n=-1,s=t.length;++n`${eo(t)}: ${eo(e)}`).join(", ")}}`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class hP{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),Yr.visit(this.vals,t)]})}}class fP{isExtensible(){return!1}deleteProperty(){return!1}preventExtensions(){return!0}ownKeys(t){return t[Ds]}has(t,e){return t[Ds].includes(e)}getOwnPropertyDescriptor(t,e){if(t[Ds].indexOf(e)!==-1)return{writable:!0,enumerable:!0,configurable:!0}}get(t,e){if(Reflect.has(t,e))return t[e];const i=t[Ds].indexOf(e);if(i!==-1){const n=Yr.visit(Reflect.get(t,Xs),i);return Reflect.set(t,e,n),n}}set(t,e,i){const n=t[Ds].indexOf(e);return n!==-1?(Ei.visit(Reflect.get(t,Xs),n,i),Reflect.set(t,e,i)):Reflect.has(t,e)?Reflect.set(t,e,i):!1}}Object.defineProperties(Df.prototype,{[Symbol.toStringTag]:{enumerable:!1,configurable:!1,value:"Row"},[Ms]:{writable:!0,enumerable:!1,configurable:!1,value:null},[Xs]:{writable:!0,enumerable:!1,configurable:!1,value:null},[wh]:{writable:!0,enumerable:!1,configurable:!1,value:null}});let lm;function qb(r,t,e,i){const{length:n=0}=r;let s=typeof t!="number"?0:t,o=typeof e!="number"?n:e;return s<0&&(s=(s%n+n)%n),o<0&&(o=(o%n+n)%n),on&&(o=n),i?i(r,s,o):[s,o]}const Qb=(r,t)=>r<0?t+r:r,um=r=>r!==r;function cs(r){if(typeof r!=="object"||r===null)return um(r)?um:e=>e===r;if(r instanceof Date){const e=r.valueOf();return i=>i instanceof Date?i.valueOf()===e:!1}return ArrayBuffer.isView(r)?e=>e?F0(r,e):!1:r instanceof Map?pP(r):Array.isArray(r)?dP(r):r instanceof Qe?mP(r):yP(r,!0)}function dP(r){const t=[];for(let e=-1,i=r.length;++e!1;const i=[];for(let n=-1,s=e.length;++n{if(!e||typeof e!="object")return!1;switch(e.constructor){case Array:return gP(r,e);case Map:return cm(r,e,e.keys());case Df:case Mf:case Object:case void 0:return cm(r,e,t||Object.keys(e))}return e instanceof Qe?vP(r,e):!1}}function gP(r,t){const e=r.length;if(t.length!==e)return!1;for(let i=-1;++i>i}function bP(r,t,e){return e?!!(r[t>>3]|=1<>3]&=~(1<0||e.byteLength>3):Zb(new au(e,r,t,null,Rf)).subarray(0,i)),n}return e}function Zb(r){const t=[];let e=0,i=0,n=0;for(const o of r)o&&(n|=1<0)&&(t[e++]=n);const s=new Uint8Array(t.length+7&-8);return s.set(t),s}class au{constructor(t,e,i,n,s){this.bytes=t,this.length=i,this.context=n,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,n=t+(t%8===0?0:8-t%8);return Bl(r,t,n)+Bl(r,i,e)+Jb(r,n>>3,i-n>>3)}function Jb(r,t,e){let i=0,n=Math.trunc(t);const s=new DataView(r.buffer,r.byteOffset,r.byteLength),o=e===void 0?r.byteLength:n+e;for(;o-n>=4;)i+=qa(s.getUint32(n)),n+=4;for(;o-n>=2;)i+=qa(s.getUint16(n)),n+=2;for(;o-n>=1;)i+=qa(s.getUint8(n)),n+=1;return i}function qa(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 wP=Object.freeze(Object.defineProperty({__proto__:null,BitIterator:au,getBit:Kb,getBool:Rf,packBools:Zb,popcnt_array:Jb,popcnt_bit_range:Bl,popcnt_uint32:qa,setBool:bP,truncateBitmap:xh},Symbol.toStringTag,{value:"Module"})),xP=-1;class ta{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 Et.isSparseUnion(t)?this.children.some(e=>e.nullable):Et.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:i,nullBitmap:n,typeIds:s}=this;return e&&(t+=e.byteLength),i&&(t+=i.byteLength),n&&(t+=n.byteLength),s&&(t+=s.byteLength),this.children.reduce((o,a)=>o+a.byteLength,t)}get nullCount(){if(Et.isUnion(this.type))return this.children.reduce((i,n)=>i+n.nullCount,0);let t=this._nullCount,e;return t<=xP&&(e=this.nullBitmap)&&(this._nullCount=t=e.length===0?0:this.length-Bl(e,this.offset,this.offset+this.length)),t}constructor(t,e,i,n,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(i||0,0)),this._nullCount=Math.floor(Math.max(n||0,-1));let l;s instanceof ta?(this.stride=s.stride,this.values=s.values,this.typeIds=s.typeIds,this.nullBitmap=s.nullBitmap,this.valueOffsets=s.valueOffsets):(this.stride=rb(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(Et.isUnion(e)){const i=e,n=this.children[i.typeIdToChildIndex[this.typeIds[t]]],s=i.mode===Ii.Dense?this.valueOffsets[t]:t;return n.getValid(s)}if(this.nullable&&this.nullCount>0){const i=this.offset+t;return(this.nullBitmap[i>>3]&1<>3;(!s||s.byteLength<=c)&&(s=new Uint8Array((o+a+63&-64)>>3).fill(255),this.nullCount>0?(s.set(xh(o,a,this.nullBitmap),0),Object.assign(this,{nullBitmap:s})):Object.assign(this,{nullBitmap:s,_nullCount:0}));const h=s[c];i=(h&u)!==0,s[c]=e?h|u:h&~u}return i!==!!e&&(this._nullCount=this.nullCount+(e?-1:1)),e}clone(t=this.type,e=this.offset,i=this.length,n=this._nullCount,s=this,o=this.children){return new ta(t,e,i,n,s,o,this.dictionary)}slice(t,e){const{stride:i,typeId:n,children:s}=this,o=+(this._nullCount===0)-1,a=n===16?i:1,l=this._sliceBuffers(t,e,i,n);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===W.Null)return this.clone(this.type,0,t,0);const{length:e,nullCount:i}=this,n=new Uint8Array((t+63&-64)>>3).fill(255,0,e>>3);n[e>>3]=(1<0&&n.set(xh(this.offset,e,this.nullBitmap),0);const s=this.buffers;return s[zi.VALIDITY]=n,this.clone(this.type,0,t,i+(t-e),s)}_sliceBuffers(t,e,i,n){let s;const{buffers:o}=this;return(s=o[zi.TYPE])&&(o[zi.TYPE]=s.subarray(t,t+e)),(s=o[zi.OFFSET])&&(o[zi.OFFSET]=s.subarray(t,t+e+1))||(s=o[zi.DATA])&&(o[zi.DATA]=n===6?s:s.subarray(i*t,i*(t+e))),o}_sliceChildren(t,e,i){return t.map(n=>n.slice(e,i))}}ta.prototype.children=Object.freeze([]);class hm{constructor(t=0,e){this.numChunks=t,this.getChunkIterator=e,this.chunkIndex=0,this.chunkIterator=this.getChunkIterator(0)}next(){for(;this.chunkIndext.nullable)}function TP(r){return r.reduce((t,e)=>t+e.nullCount,0)}function IP(r){return r.reduce((t,e,i)=>(t[i+1]=t[i]+e.length,t),new Uint32Array(r.length+1))}function EP(r,t,e,i){const n=[];for(let s=-1,o=r.length;++s=i)break;if(e>=l+u)continue;if(l>=e&&l+u<=i){n.push(a);continue}const c=Math.max(0,e-l),h=Math.min(i-l,u);n.push(a.slice(c,h-c))}return n.length===0&&n.push(r[0].slice(0,0)),n}function Nf(r,t,e,i){let n=0,s=0,o=t.length-1;do{if(n>=o-1)return e0?0:-1}function FP(r,t){const{nullBitmap:e}=r;if(!e||r.nullCount<=0)return-1;let i=0;for(const n of new au(e,r.offset+(t||0),r.length,e,Rf)){if(!n)return i;++i}return-1}function Kt(r,t,e){if(t===void 0)return-1;if(t===null)switch(r.typeId){case W.Union:break;case W.Dictionary:break;default:return FP(r,e)}const i=Yr.getVisitFn(r),n=cs(t);for(let s=(e||0)-1,o=r.length;++s{const n=r.data[i];return n.values.subarray(0,n.length)[Symbol.iterator]()});let e=0;return new hm(r.data.length,i=>{const s=r.data[i].length,o=r.slice(e,e+s);return e+=s,new PP(o)})}class PP{constructor(t){this.vector=t,this.index=0}next(){return this.indexa.data):t;if(s.length===0||s.some(a=>!(a instanceof ta)))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}=iw[o.typeId],c=s[0];this.isValid=h=>tw(c,h),this.get=h=>a(c,h),this.set=(h,p)=>l(c,h,p),this.indexOf=h=>u(c,h),this._offsets=[0,c.length];break}default:Object.setPrototypeOf(this,nw[o.typeId]),this._offsets=IP(s);break}this.data=s,this.type=o,this.stride=rb(o),this.numChildren=(n=(i=o.children)===null||i===void 0?void 0:i.length)!==null&&n!==void 0?n:0,this.length=this._offsets.at(-1)}get byteLength(){return this.data.reduce((t,e)=>t+e.byteLength,0)}get nullable(){return SP(this.data)}get nullCount(){return TP(this.data)}get ArrayType(){return this.type.ArrayType}get[Symbol.toStringTag](){return`${this.VectorName}<${this.type[Symbol.toStringTag]}>`}get VectorName(){return`${W[this.type.typeId]}Vector`}isValid(t){return!1}get(t){return null}at(t){return this.get(Qb(t,this.length))}set(t,e){}indexOf(t,e){return-1}includes(t,e){return this.indexOf(t,e)>-1}[Symbol.iterator](){return MP.visit(this)}concat(...t){return new Qe(this.data.concat(t.flatMap(e=>e.data).flat(Number.POSITIVE_INFINITY)))}slice(t,e){return new Qe(qb(this,t,e,({data:i,_offsets:n},s,o)=>EP(i,n,s,o)))}toJSON(){return[...this]}toArray(){const{type:t,data:e,length:i,stride:n,ArrayType:s}=this;switch(t.typeId){case W.Int:case W.Float:case W.Decimal:case W.Time:case W.Timestamp:switch(e.length){case 0:return new s;case 1:return e[0].values.subarray(0,i*n);default:return e.reduce((o,{values:a,length:l})=>(o.array.set(a.subarray(0,l*n),o.offset),o.offset+=l*n,o),{array:new s(i*n),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(i=>i.name===t))}getChildAt(t){return t>-1&&te[t])):null}get isMemoized(){return Et.isDictionary(this.type)?this.data[0].dictionary.isMemoized:!1}memoize(){if(Et.isDictionary(this.type)){const t=new kl(this.data[0].dictionary),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new Qe(e)}return new kl(this)}unmemoize(){if(Et.isDictionary(this.type)&&this.isMemoized){const t=this.data[0].dictionary.unmemoize(),e=this.data.map(i=>{const n=i.clone();return n.dictionary=t,n});return new Qe(e)}return this}}rw=Symbol.toStringTag;Qe[rw]=(r=>{r.type=Et.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(W).map(e=>W[e]).filter(e=>typeof e=="number"&&e!==W.NONE);for(const e of t){const i=Yr.getVisitFnByTypeId(e),n=Ei.getVisitFnByTypeId(e),s=dm.getVisitFnByTypeId(e);iw[e]={get:i,set:n,indexOf:s},nw[e]=Object.create(r,{isValid:{value:fm(tw)},get:{value:fm(Yr.getVisitFnByTypeId(e))},set:{value:CP(Ei.getVisitFnByTypeId(e))},indexOf:{value:AP(dm.getVisitFnByTypeId(e))}})}return"Vector"})(Qe.prototype);class kl extends Qe{constructor(t){super(t.data);const e=this.get,i=this.set,n=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){i.call(this,o,a),s[o]=a}}),Object.defineProperty(this,"slice",{value:(o,a)=>new kl(n.call(this,o,a))}),Object.defineProperty(this,"isMemoized",{value:!0}),Object.defineProperty(this,"unmemoize",{value:()=>new Qe(this.data)}),Object.defineProperty(this,"memoize",{value:()=>this})}}const DP=65536;function Ls(r){return r<0&&(r=4294967295+r+1),`0x${r.toString(16)}`}const io=8,Lf=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8];class Bf{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]),i=new Uint32Array([t.buffer[1]>>>16,t.buffer[1]&65535,t.buffer[0]>>>16,t.buffer[0]&65535]);let n=e[3]*i[3];this.buffer[0]=n&65535;let s=n>>>16;return n=e[2]*i[3],s+=n,n=e[3]*i[2]>>>0,s+=n,this.buffer[0]+=s<<16,this.buffer[1]=s>>>0>>16,this.buffer[1]+=e[1]*i[3]+e[2]*i[2]+e[3]*i[1],this.buffer[1]+=e[0]*i[3]+e[1]*i[2]+e[2]*i[1]+e[3]*i[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`${Ls(this.buffer[3])} ${Ls(this.buffer[2])} ${Ls(this.buffer[1])} ${Ls(this.buffer[0])}`}static multiply(t,e){return new ci(new Uint32Array(t.buffer)).times(e)}static add(t,e){return new ci(new Uint32Array(t.buffer)).plus(e)}static from(t,e=new Uint32Array(4)){return ci.fromString(typeof t=="string"?t:t.toString(),e)}static fromNumber(t,e=new Uint32Array(4)){return ci.fromString(t.toString(),e)}static fromString(t,e=new Uint32Array(4)){const i=t.startsWith("-"),n=t.length,s=new ci(e);for(let o=i?1:0;othis.compareFields(i,e[n]))}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 ur(r,t){return t instanceof r.constructor}function hs(r,t){return r===t||ur(r,t)}function Qi(r,t){return r===t||ur(r,t)&&r.bitWidth===t.bitWidth&&r.isSigned===t.isSigned}function lu(r,t){return r===t||ur(r,t)&&r.precision===t.precision}function NP(r,t){return r===t||ur(r,t)&&r.byteWidth===t.byteWidth}function kf(r,t){return r===t||ur(r,t)&&r.unit===t.unit}function fa(r,t){return r===t||ur(r,t)&&r.unit===t.unit&&r.timezone===t.timezone}function da(r,t){return r===t||ur(r,t)&&r.unit===t.unit&&r.bitWidth===t.bitWidth}function LP(r,t){return r===t||ur(r,t)&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}function BP(r,t){return r===t||ur(r,t)&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}function Uf(r,t){return r===t||ur(r,t)&&r.mode===t.mode&&r.typeIds.every((e,i)=>e===t.typeIds[i])&&Ci.compareManyFields(r.children,t.children)}function kP(r,t){return r===t||ur(r,t)&&r.id===t.id&&r.isOrdered===t.isOrdered&&Ci.visit(r.indices,t.indices)&&Ci.visit(r.dictionary,t.dictionary)}function zf(r,t){return r===t||ur(r,t)&&r.unit===t.unit}function pa(r,t){return r===t||ur(r,t)&&r.unit===t.unit}function UP(r,t){return r===t||ur(r,t)&&r.listSize===t.listSize&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}function zP(r,t){return r===t||ur(r,t)&&r.keysSorted===t.keysSorted&&r.children.length===t.children.length&&Ci.compareManyFields(r.children,t.children)}Ut.prototype.visitNull=hs;Ut.prototype.visitBool=hs;Ut.prototype.visitInt=Qi;Ut.prototype.visitInt8=Qi;Ut.prototype.visitInt16=Qi;Ut.prototype.visitInt32=Qi;Ut.prototype.visitInt64=Qi;Ut.prototype.visitUint8=Qi;Ut.prototype.visitUint16=Qi;Ut.prototype.visitUint32=Qi;Ut.prototype.visitUint64=Qi;Ut.prototype.visitFloat=lu;Ut.prototype.visitFloat16=lu;Ut.prototype.visitFloat32=lu;Ut.prototype.visitFloat64=lu;Ut.prototype.visitUtf8=hs;Ut.prototype.visitLargeUtf8=hs;Ut.prototype.visitBinary=hs;Ut.prototype.visitLargeBinary=hs;Ut.prototype.visitFixedSizeBinary=NP;Ut.prototype.visitDate=kf;Ut.prototype.visitDateDay=kf;Ut.prototype.visitDateMillisecond=kf;Ut.prototype.visitTimestamp=fa;Ut.prototype.visitTimestampSecond=fa;Ut.prototype.visitTimestampMillisecond=fa;Ut.prototype.visitTimestampMicrosecond=fa;Ut.prototype.visitTimestampNanosecond=fa;Ut.prototype.visitTime=da;Ut.prototype.visitTimeSecond=da;Ut.prototype.visitTimeMillisecond=da;Ut.prototype.visitTimeMicrosecond=da;Ut.prototype.visitTimeNanosecond=da;Ut.prototype.visitDecimal=hs;Ut.prototype.visitList=LP;Ut.prototype.visitStruct=BP;Ut.prototype.visitUnion=Uf;Ut.prototype.visitDenseUnion=Uf;Ut.prototype.visitSparseUnion=Uf;Ut.prototype.visitDictionary=kP;Ut.prototype.visitInterval=zf;Ut.prototype.visitIntervalDayTime=zf;Ut.prototype.visitIntervalYearMonth=zf;Ut.prototype.visitDuration=pa;Ut.prototype.visitDurationSecond=pa;Ut.prototype.visitDurationMillisecond=pa;Ut.prototype.visitDurationMicrosecond=pa;Ut.prototype.visitDurationNanosecond=pa;Ut.prototype.visitFixedSizeList=UP;Ut.prototype.visitMap=zP;const Ci=new Ut;function jP(r,t){return Ci.compareSchemas(r,t)}function $P(r,t){return Ci.compareFields(r,t)}function VP(r,t){return Ci.visit(r,t)}const pm=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},_F),RP),wP),xF),pF),_P),yF),{compareSchemas:jP,compareFields:$P,compareTypes:VP}),sw=6048e5,GP=864e5,mm=Symbol.for("constructDateFrom");function Gi(r,t){return typeof r=="function"?r(t):r&&typeof r=="object"&&mm in r?r[mm](t):r instanceof Date?new r.constructor(t):new Date(t)}function qr(r,t){return Gi(t||r,r)}let WP={};function uu(){return WP}function ea(r,t){var a,l,u,c;const e=uu(),i=(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,n=qr(r,t==null?void 0:t.in),s=n.getDay(),o=(s=s.getTime()?i+1:e.getTime()>=a.getTime()?i:i-1}function ym(r){const t=qr(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 HP(r,...t){const e=Gi.bind(null,t.find(i=>typeof i=="object"));return t.map(e)}function gm(r,t){const e=qr(r,t==null?void 0:t.in);return e.setHours(0,0,0,0),e}function XP(r,t,e){const[i,n]=HP(e==null?void 0:e.in,r,t),s=gm(i),o=gm(n),a=+s-ym(s),l=+o-ym(o);return Math.round((a-l)/GP)}function YP(r,t){const e=ow(r,t),i=Gi(r,0);return i.setFullYear(e,0,4),i.setHours(0,0,0,0),Ul(i)}function qP(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function QP(r){return!(!qP(r)&&typeof r!="number"||isNaN(+qr(r)))}function KP(r,t){const e=qr(r,t==null?void 0:t.in);return e.setFullYear(e.getFullYear(),0,1),e.setHours(0,0,0,0),e}const ZP={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"}},JP=(r,t,e)=>{let i;const n=ZP[r];return typeof n=="string"?i=n:t===1?i=n.one:i=n.other.replace("{{count}}",t.toString()),e!=null&&e.addSuffix?e.comparison&&e.comparison>0?"in "+i:i+" ago":i};function nc(r){return(t={})=>{const e=t.width?String(t.width):r.defaultWidth;return r.formats[e]||r.formats[r.defaultWidth]}}const tM={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},eM={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},rM={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},iM={date:nc({formats:tM,defaultWidth:"full"}),time:nc({formats:eM,defaultWidth:"full"}),dateTime:nc({formats:rM,defaultWidth:"full"})},nM={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},sM=(r,t,e,i)=>nM[r];function go(r){return(t,e)=>{const i=e!=null&&e.context?String(e.context):"standalone";let n;if(i==="formatting"&&r.formattingValues){const o=r.defaultFormattingWidth||r.defaultWidth,a=e!=null&&e.width?String(e.width):o;n=r.formattingValues[a]||r.formattingValues[o]}else{const o=r.defaultWidth,a=e!=null&&e.width?String(e.width):r.defaultWidth;n=r.values[a]||r.values[o]}const s=r.argumentCallback?r.argumentCallback(t):t;return n[s]}}const oM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},aM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},lM={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"]},uM={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"]},cM={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"}},hM={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"}},fM=(r,t)=>{const e=Number(r),i=e%100;if(i>20||i<10)switch(i%10){case 1:return e+"st";case 2:return e+"nd";case 3:return e+"rd"}return e+"th"},dM={ordinalNumber:fM,era:go({values:oM,defaultWidth:"wide"}),quarter:go({values:aM,defaultWidth:"wide",argumentCallback:r=>r-1}),month:go({values:lM,defaultWidth:"wide"}),day:go({values:uM,defaultWidth:"wide"}),dayPeriod:go({values:cM,defaultWidth:"wide",formattingValues:hM,defaultFormattingWidth:"wide"})};function vo(r){return(t,e={})=>{const i=e.width,n=i&&r.matchPatterns[i]||r.matchPatterns[r.defaultMatchWidth],s=t.match(n);if(!s)return null;const o=s[0],a=i&&r.parsePatterns[i]||r.parsePatterns[r.defaultParseWidth],l=Array.isArray(a)?mM(a,h=>h.test(o)):pM(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 pM(r,t){for(const e in r)if(Object.prototype.hasOwnProperty.call(r,e)&&t(r[e]))return e}function mM(r,t){for(let e=0;e{const i=t.match(r.matchPattern);if(!i)return null;const n=i[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(n.length);return{value:o,rest:a}}}const gM=/^(\d+)(th|st|nd|rd)?/i,vM=/\d+/i,_M={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},bM={any:[/^b/i,/^(a|c)/i]},wM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},xM={any:[/1/i,/2/i,/3/i,/4/i]},SM={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},TM={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]},IM={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},EM={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]},CM={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},AM={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}},OM={ordinalNumber:yM({matchPattern:gM,parsePattern:vM,valueCallback:r=>parseInt(r,10)}),era:vo({matchPatterns:_M,defaultMatchWidth:"wide",parsePatterns:bM,defaultParseWidth:"any"}),quarter:vo({matchPatterns:wM,defaultMatchWidth:"wide",parsePatterns:xM,defaultParseWidth:"any",valueCallback:r=>r+1}),month:vo({matchPatterns:SM,defaultMatchWidth:"wide",parsePatterns:TM,defaultParseWidth:"any"}),day:vo({matchPatterns:IM,defaultMatchWidth:"wide",parsePatterns:EM,defaultParseWidth:"any"}),dayPeriod:vo({matchPatterns:CM,defaultMatchWidth:"any",parsePatterns:AM,defaultParseWidth:"any"})},FM={code:"en-US",formatDistance:JP,formatLong:iM,formatRelative:sM,localize:dM,match:OM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function PM(r,t){const e=qr(r,t==null?void 0:t.in);return XP(e,KP(e))+1}function MM(r,t){const e=qr(r,t==null?void 0:t.in),i=+Ul(e)-+YP(e);return Math.round(i/sw)+1}function aw(r,t){var c,h,p,f;const e=qr(r,t==null?void 0:t.in),i=e.getFullYear(),n=uu(),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)??n.firstWeekContainsDate??((f=(p=n.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,o=Gi((t==null?void 0:t.in)||r,0);o.setFullYear(i+1,0,s),o.setHours(0,0,0,0);const a=ea(o,t),l=Gi((t==null?void 0:t.in)||r,0);l.setFullYear(i,0,s),l.setHours(0,0,0,0);const u=ea(l,t);return+e>=+a?i+1:+e>=+u?i:i-1}function DM(r,t){var a,l,u,c;const e=uu(),i=(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,n=aw(r,t),s=Gi((t==null?void 0:t.in)||r,0);return s.setFullYear(n,0,i),s.setHours(0,0,0,0),ea(s,t)}function RM(r,t){const e=qr(r,t==null?void 0:t.in),i=+ea(e,t)-+DM(e,t);return Math.round(i/sw)+1}function ve(r,t){const e=r<0?"-":"",i=Math.abs(r).toString().padStart(t,"0");return e+i}const rn={y(r,t){const e=r.getFullYear(),i=e>0?e:1-e;return ve(t==="yy"?i%100:i,t.length)},M(r,t){const e=r.getMonth();return t==="M"?String(e+1):ve(e+1,2)},d(r,t){return ve(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 ve(r.getHours()%12||12,t.length)},H(r,t){return ve(r.getHours(),t.length)},m(r,t){return ve(r.getMinutes(),t.length)},s(r,t){return ve(r.getSeconds(),t.length)},S(r,t){const e=t.length,i=r.getMilliseconds(),n=Math.trunc(i*Math.pow(10,e-3));return ve(n,t.length)}},_s={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},vm={G:function(r,t,e){const i=r.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return e.era(i,{width:"abbreviated"});case"GGGGG":return e.era(i,{width:"narrow"});case"GGGG":default:return e.era(i,{width:"wide"})}},y:function(r,t,e){if(t==="yo"){const i=r.getFullYear(),n=i>0?i:1-i;return e.ordinalNumber(n,{unit:"year"})}return rn.y(r,t)},Y:function(r,t,e,i){const n=aw(r,i),s=n>0?n:1-n;if(t==="YY"){const o=s%100;return ve(o,2)}return t==="Yo"?e.ordinalNumber(s,{unit:"year"}):ve(s,t.length)},R:function(r,t){const e=ow(r);return ve(e,t.length)},u:function(r,t){const e=r.getFullYear();return ve(e,t.length)},Q:function(r,t,e){const i=Math.ceil((r.getMonth()+1)/3);switch(t){case"Q":return String(i);case"QQ":return ve(i,2);case"Qo":return e.ordinalNumber(i,{unit:"quarter"});case"QQQ":return e.quarter(i,{width:"abbreviated",context:"formatting"});case"QQQQQ":return e.quarter(i,{width:"narrow",context:"formatting"});case"QQQQ":default:return e.quarter(i,{width:"wide",context:"formatting"})}},q:function(r,t,e){const i=Math.ceil((r.getMonth()+1)/3);switch(t){case"q":return String(i);case"qq":return ve(i,2);case"qo":return e.ordinalNumber(i,{unit:"quarter"});case"qqq":return e.quarter(i,{width:"abbreviated",context:"standalone"});case"qqqqq":return e.quarter(i,{width:"narrow",context:"standalone"});case"qqqq":default:return e.quarter(i,{width:"wide",context:"standalone"})}},M:function(r,t,e){const i=r.getMonth();switch(t){case"M":case"MM":return rn.M(r,t);case"Mo":return e.ordinalNumber(i+1,{unit:"month"});case"MMM":return e.month(i,{width:"abbreviated",context:"formatting"});case"MMMMM":return e.month(i,{width:"narrow",context:"formatting"});case"MMMM":default:return e.month(i,{width:"wide",context:"formatting"})}},L:function(r,t,e){const i=r.getMonth();switch(t){case"L":return String(i+1);case"LL":return ve(i+1,2);case"Lo":return e.ordinalNumber(i+1,{unit:"month"});case"LLL":return e.month(i,{width:"abbreviated",context:"standalone"});case"LLLLL":return e.month(i,{width:"narrow",context:"standalone"});case"LLLL":default:return e.month(i,{width:"wide",context:"standalone"})}},w:function(r,t,e,i){const n=RM(r,i);return t==="wo"?e.ordinalNumber(n,{unit:"week"}):ve(n,t.length)},I:function(r,t,e){const i=MM(r);return t==="Io"?e.ordinalNumber(i,{unit:"week"}):ve(i,t.length)},d:function(r,t,e){return t==="do"?e.ordinalNumber(r.getDate(),{unit:"date"}):rn.d(r,t)},D:function(r,t,e){const i=PM(r);return t==="Do"?e.ordinalNumber(i,{unit:"dayOfYear"}):ve(i,t.length)},E:function(r,t,e){const i=r.getDay();switch(t){case"E":case"EE":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"})}},e:function(r,t,e,i){const n=r.getDay(),s=(n-i.weekStartsOn+8)%7||7;switch(t){case"e":return String(s);case"ee":return ve(s,2);case"eo":return e.ordinalNumber(s,{unit:"day"});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"})}},c:function(r,t,e,i){const n=r.getDay(),s=(n-i.weekStartsOn+8)%7||7;switch(t){case"c":return String(s);case"cc":return ve(s,t.length);case"co":return e.ordinalNumber(s,{unit:"day"});case"ccc":return e.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return e.day(n,{width:"narrow",context:"standalone"});case"cccccc":return e.day(n,{width:"short",context:"standalone"});case"cccc":default:return e.day(n,{width:"wide",context:"standalone"})}},i:function(r,t,e){const i=r.getDay(),n=i===0?7:i;switch(t){case"i":return String(n);case"ii":return ve(n,t.length);case"io":return e.ordinalNumber(n,{unit:"day"});case"iii":return e.day(i,{width:"abbreviated",context:"formatting"});case"iiiii":return e.day(i,{width:"narrow",context:"formatting"});case"iiiiii":return e.day(i,{width:"short",context:"formatting"});case"iiii":default:return e.day(i,{width:"wide",context:"formatting"})}},a:function(r,t,e){const n=r.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return e.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return e.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(r,t,e){const i=r.getHours();let n;switch(i===12?n=_s.noon:i===0?n=_s.midnight:n=i/12>=1?"pm":"am",t){case"b":case"bb":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return e.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return e.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(r,t,e){const i=r.getHours();let n;switch(i>=17?n=_s.evening:i>=12?n=_s.afternoon:i>=4?n=_s.morning:n=_s.night,t){case"B":case"BB":case"BBB":return e.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return e.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return e.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(r,t,e){if(t==="ho"){let i=r.getHours()%12;return i===0&&(i=12),e.ordinalNumber(i,{unit:"hour"})}return rn.h(r,t)},H:function(r,t,e){return t==="Ho"?e.ordinalNumber(r.getHours(),{unit:"hour"}):rn.H(r,t)},K:function(r,t,e){const i=r.getHours()%12;return t==="Ko"?e.ordinalNumber(i,{unit:"hour"}):ve(i,t.length)},k:function(r,t,e){let i=r.getHours();return i===0&&(i=24),t==="ko"?e.ordinalNumber(i,{unit:"hour"}):ve(i,t.length)},m:function(r,t,e){return t==="mo"?e.ordinalNumber(r.getMinutes(),{unit:"minute"}):rn.m(r,t)},s:function(r,t,e){return t==="so"?e.ordinalNumber(r.getSeconds(),{unit:"second"}):rn.s(r,t)},S:function(r,t){return rn.S(r,t)},X:function(r,t,e){const i=r.getTimezoneOffset();if(i===0)return"Z";switch(t){case"X":return bm(i);case"XXXX":case"XX":return Vn(i);case"XXXXX":case"XXX":default:return Vn(i,":")}},x:function(r,t,e){const i=r.getTimezoneOffset();switch(t){case"x":return bm(i);case"xxxx":case"xx":return Vn(i);case"xxxxx":case"xxx":default:return Vn(i,":")}},O:function(r,t,e){const i=r.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+_m(i,":");case"OOOO":default:return"GMT"+Vn(i,":")}},z:function(r,t,e){const i=r.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+_m(i,":");case"zzzz":default:return"GMT"+Vn(i,":")}},t:function(r,t,e){const i=Math.trunc(+r/1e3);return ve(i,t.length)},T:function(r,t,e){return ve(+r,t.length)}};function _m(r,t=""){const e=r>0?"-":"+",i=Math.abs(r),n=Math.trunc(i/60),s=i%60;return s===0?e+String(n):e+String(n)+t+ve(s,2)}function bm(r,t){return r%60===0?(r>0?"-":"+")+ve(Math.abs(r)/60,2):Vn(r,t)}function Vn(r,t=""){const e=r>0?"-":"+",i=Math.abs(r),n=ve(Math.trunc(i/60),2),s=ve(i%60,2);return e+n+t+s}const wm=(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"})}},lw=(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"})}},NM=(r,t)=>{const e=r.match(/(P+)(p+)?/)||[],i=e[1],n=e[2];if(!n)return wm(r,t);let s;switch(i){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}}",wm(i,t)).replace("{{time}}",lw(n,t))},LM={p:lw,P:NM},BM=/^D+$/,kM=/^Y+$/,UM=["D","DD","YY","YYYY"];function zM(r){return BM.test(r)}function jM(r){return kM.test(r)}function $M(r,t,e){const i=VM(r,t,e);if(console.warn(i),UM.includes(r))throw new RangeError(i)}function VM(r,t,e){const i=r[0]==="Y"?"years":"days of the month";return`Use \`${r.toLowerCase()}\` instead of \`${r}\` (in \`${t}\`) for formatting ${i} to the input \`${e}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const GM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,WM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,HM=/^'([^]*?)'?$/,XM=/''/g,YM=/[a-zA-Z]/;function uw(r,t,e){var c,h,p,f;const i=uu(),n=i.locale??FM,s=i.firstWeekContainsDate??((h=(c=i.locale)==null?void 0:c.options)==null?void 0:h.firstWeekContainsDate)??1,o=i.weekStartsOn??((f=(p=i.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,a=qr(r,e==null?void 0:e.in);if(!QP(a))throw new RangeError("Invalid time value");let l=t.match(WM).map(y=>{const g=y[0];if(g==="p"||g==="P"){const d=LM[g];return d(y,n.formatLong)}return y}).join("").match(GM).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const g=y[0];if(g==="'")return{isToken:!1,value:qM(y)};if(vm[g])return{isToken:!0,value:y};if(g.match(YM))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:y}});n.localize.preprocessor&&(l=n.localize.preprocessor(a,l));const u={firstWeekContainsDate:s,weekStartsOn:o,locale:n};return l.map(y=>{if(!y.isToken)return y.value;const g=y.value;(jM(g)||zM(g))&&$M(g,t,String(r));const d=vm[g[0]];return d(a,g,n.localize,u)}).join("")}function qM(r){const t=r.match(HM);return t?t[1].replace(XM,"'"):r}function QM(r,t){return qr(r*1e3,t==null?void 0:t.in)}function KM(r,t){const e=ZM(t)?new t(0):Gi(t,0);return e.setFullYear(r.getFullYear(),r.getMonth(),r.getDate()),e.setHours(r.getHours(),r.getMinutes(),r.getSeconds(),r.getMilliseconds()),e}function ZM(r){var t;return typeof r=="function"&&((t=r.prototype)==null?void 0:t.constructor)===r}function JM(r,t){let e=r.length;switch("string"){case"string":{if(t.length!==1)throw new Error("The 'chars' parameter should be a single character string.");for(;e>0&&r[e-1]===t;)e--;break}}return r.substring(0,e)}function gr(r){return r==null}function tD(r){return r!=null}async function Sh(){if(typeof window<"u"&&window!==null)return"browser";try{const r=await ln(()=>import("./__vite-browser-external-FmFgRqLi.js"),[]);return typeof r<"u"&&r.versions!=null&&r.versions.node!=null?"node":"unknown"}catch{return"unknown"}}function eD(r){return gr(r)?!1:Et.isInt(r.type)&&!cw(r)||rD(r)}function rD(r){return gr(r)?!1:Et.isInt(r.type)&&r.type.isSigned===!1}function iD(r){return gr(r)?!1:Et.isFloat(r.type)??!1}function nD(r){return gr(r)?!1:Et.isDecimal(r.type)}function sD(r){return gr(r)?!1:Et.isBool(r.type)}function oD(r){return gr(r)?!1:Et.isDuration(r.type)}function cw(r){return gr(r)?!1:Et.isInt(r.type)&&r.metadata.get("ARROW:extension:name")==="period"}function aD(r){return gr(r)?!1:Et.isTimestamp(r.type)}function lD(r){return gr(r)?!1:Et.isDate(r.type)}function uD(r){return gr(r)?!1:Et.isTime(r.type)}function cD(r){return gr(r)?!1:Et.isList(r.type)||Et.isFixedSizeList(r.type)}function hD(r){return gr(r)?!1:Et.isStruct(r.type)||Et.isMap(r.type)}function fD(r){return gr(r)?!1:Et.isStruct(r.type)&&r.metadata.get("ARROW:extension:name")==="interval"||Et.isInterval(r.type)}function dD(r,t){let e;if(t===Jt.MILLISECOND)e=1e3;else if(t===Jt.MICROSECOND)e=1e3*1e3;else if(t===Jt.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 pD(r,t){var i;const e=dD(r,((i=t==null?void 0:t.type)==null?void 0:i.unit)??Jt.SECOND);return QM(e)}function mD(r,t){const e=pD(r,t);return uw(e,e.getMilliseconds()===0?"HH:mm:ss":"HH:mm:ss.SSS")}function yD(r){const t="yyyy-MM-dd";return r instanceof Date||typeof r=="number"&&Number.isFinite(r)?uw(r,t):(console.warn(`Unsupported date value: ${r}`),String(r))}function gD(r,t){var n;if(!(r instanceof Date||typeof r=="number"&&Number.isFinite(r)))return console.warn(`Unsupported datetime value: ${r}`),null;let e;const i=(n=t==null?void 0:t.type)==null?void 0:n.timezone;return typeof r=="number"?i?e=new Er(r,i):e=new Er(r):i?e=new Er(r,i):e=new Er(r),KM(e,Date)}function vD(r,t){var a;const e=((a=t==null?void 0:t.type)==null?void 0:a.scale)||0;let i=pm.bigNumToString(new pm.BN(r)).padStart(e,"0");if(e===0)return i;let n="";i.startsWith("-")&&(n="-",i=i.slice(1));const s=i.slice(0,-e)||"0",o=JM(i.slice(-e),"0")||"";return`${n}${s}${o?`.${o}`:""}`}function _D(r){const t=r[0],e=r[1],i=[];return t!==0&&i.push(`${t} year${t>1?"s":""}`),e!==0&&i.push(`${e} month${e>1?"s":""}`),i.length?i.join(" "):"0 months"}function bD(r,t){var i,n,s,o;if(Et.isInterval(t==null?void 0:t.type))return _D(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"?"]":")",p=Th(u.left,(n=(i=t.type)==null?void 0:i.children)==null?void 0:n[0]),f=Th(u.right,(o=(s=t.type)==null?void 0:s.children)==null?void 0:o[1]);return`${c+p}, ${f+h}`}return String(r)}function wD(r,t){return(t==null?void 0:t.type)instanceof bh?JSON.parse(JSON.stringify(r,(e,i)=>{if(tD(i))return typeof i=="bigint"?Number(i):i})):JSON.parse(JSON.stringify(r,(e,i)=>typeof i=="bigint"?Number(i):i))}function Th(r,t){if(gr(r))return null;const e=r instanceof Date||Number.isFinite(r);if(e&&lD(t))return yD(r);if(typeof r=="bigint"&&uD(t))return mD(Number(r),t);if(e&&aD(t))return gD(r,t);if(cw(t))throw new Error("Period type is not supported yet");if(fD(t))return bD(r,t);if(oD(t))throw new Error("Duration type is not supported yet");return nD(t)?vD(r,t):iD(t)&&Number.isFinite(r)||eD(t)?r:hD(t)||cD(t)?wD(r,t):sD(t)?!!r:String(r)}function xm(r){return((r.toArray()||[]).map(i=>i.toJSON())||[]).map(i=>(r.schema.fields.forEach(n=>i[n.name]=Th(i[n.name],n)),i))}var ra=(r=>(r.ORIGIN_PRIVATE_FS="origin-private-fs",r.NODE_FS="node-fs",r))(ra||{});async function hw(r){const t=Cx(r,{logger:!1});let e,i;const n=await Sh();if(n==="browser"){if(typeof t.bundles>"u"){const{getBundles:l}=await ln(async()=>{const{getBundles:u}=await import("./default-browser-BrgSDbLD.js");return{getBundles:u}},[]);t.bundles=await l()}i=await kp(await t.bundles),e=new Worker(i.mainWorker)}else if(n==="node"){if(typeof t.bundles>"u"){const{getBundles:c}=await ln(async()=>{const{getBundles:h}=await import("./default-node-DAs8YCRC.js");return{getBundles:h}},__vite__mapDeps([0,1,2]));t.bundles=await c()}i=await kp(await t.bundles);let l=i.mainWorker;l.startsWith("/@fs/")&&(l=l.replace("/@fs/","file://"));const u=await ln(()=>import("./index-Cp8iQ_hy.js"),[]);e=new u.default(l,{type:"module"})}else throw new Error(`Unsupported environment: ${n}`);let s;t.logger===!0?s=new I0:t.logger===!1?s=new c2:s=t.logger;const o=new g2(s,e);if(await o.instantiate(i.mainModule,i.pthreadWorker),t.storage)switch(t.storage.type){case ra.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 ra.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 f=await a.query(l);return xm(f)}const c=await a.prepare(l),h=await c.query(...u),p=xm(h);return c.close(),p},close:async()=>{await a.close(),await o.terminate(),await e.terminate()}}}async function xD(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 SD(r,t,e){await(await r).conn.send(`SAVEPOINT ${t}`);try{const i=await e(r);return await(await r).conn.send(`RELEASE SAVEPOINT ${t}`),i}catch(i){throw await(await r).conn.send(`ROLLBACK TO SAVEPOINT ${t}`),i}}const xt=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,xt))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(xt in e&&e[xt]===t[xt])return!0;e=Object.getPrototypeOf(e)}return!1}var Mm;Mm=xt;class Ke{constructor(t,e){$(this,"name");$(this,"keyAsName");$(this,"primary");$(this,"notNull");$(this,"default");$(this,"defaultFn");$(this,"onUpdateFn");$(this,"hasDefault");$(this,"isUnique");$(this,"uniqueName");$(this,"uniqueType");$(this,"dataType");$(this,"columnType");$(this,"enumValues");$(this,"generated");$(this,"generatedIdentity");$(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"}}$(Ke,Mm,"Column");const Ys=Symbol.for("drizzle:Name");function TD(r,t){return`${r[Ys]}_${t.join("_")}_unique`}var Dm,Rm;class Ar extends(Rm=Ke,Dm=xt,Rm){constructor(t,e){e.uniqueName||(e.uniqueName=TD(t,[e.name])),super(t,e),this.table=t}}$(Ar,Dm,"PgColumn");const Sm=Symbol.for("drizzle:isPgEnum");function ID(r){return!!r&&typeof r=="function"&&Sm in r&&r[Sm]===!0}var Nm;Nm=xt;class Or{constructor(t,e,i,n=!1){this._={brand:"Subquery",sql:t,selectedFields:e,alias:i,isWith:n}}}$(Or,Nm,"Subquery");var Lm,Bm;class jf extends(Bm=Or,Lm=xt,Bm){}$(jf,Lm,"WithSubquery");const Pr={startActiveSpan(r,t){return t()}},He=Symbol.for("drizzle:ViewBaseConfig"),Qa=Symbol.for("drizzle:Schema"),Ih=Symbol.for("drizzle:Columns"),Tm=Symbol.for("drizzle:ExtraConfigColumns"),sc=Symbol.for("drizzle:OriginalName"),oc=Symbol.for("drizzle:BaseName"),zl=Symbol.for("drizzle:IsAlias"),Im=Symbol.for("drizzle:ExtraConfigBuilder"),ED=Symbol.for("drizzle:IsDrizzleTable");var km,Um,zm,jm,$m,Vm,Gm,Wm,Hm,Xm;Xm=xt,Hm=Ys,Wm=sc,Gm=Qa,Vm=Ih,$m=Tm,jm=oc,zm=zl,Um=ED,km=Im;class Tt{constructor(t,e,i){$(this,Hm);$(this,Wm);$(this,Gm);$(this,Vm);$(this,$m);$(this,jm);$(this,zm,!1);$(this,Um,!0);$(this,km);this[Ys]=this[sc]=t,this[Qa]=e,this[oc]=i}}$(Tt,Xm,"Table"),$(Tt,"Symbol",{Name:Ys,Schema:Qa,OriginalName:sc,Columns:Ih,ExtraConfigColumns:Tm,BaseName:oc,IsAlias:zl,ExtraConfigBuilder:Im});function qn(r){return r[Ys]}function ia(r){return`${r[Qa]??"public"}.${r[Ys]}`}function fw(r){return r!=null&&typeof r.getSQL=="function"}function CD(r){var e;const t={sql:"",params:[]};for(const i of r)t.sql+=i.sql,t.params.push(...i.params),(e=i.typings)!=null&&e.length&&(t.typings||(t.typings=[]),t.typings.push(...i.typings));return t}var Ym;Ym=xt;class Xe{constructor(t){$(this,"value");this.value=Array.isArray(t)?t:[t]}getSQL(){return new Ft([this])}}$(Xe,Ym,"StringChunk");var qm;qm=xt;const Hn=class Hn{constructor(t){$(this,"decoder",dw);$(this,"shouldInlineParams",!1);this.queryChunks=t}append(t){return this.queryChunks.push(...t.queryChunks),this}toQuery(t){return Pr.startActiveSpan("drizzle.buildSQL",e=>{const i=this.buildQueryFromSourceParams(this.queryChunks,t);return e==null||e.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(t,e){const i=Object.assign({},e,{inlineParams:e.inlineParams||this.shouldInlineParams,paramStartIndex:e.paramStartIndex||{value:0}}),{casing:n,escapeName:s,escapeParam:o,prepareTyping:a,inlineParams:l,paramStartIndex:u}=i;return CD(t.map(c=>{var h;if(lt(c,Xe))return{sql:c.value.join(""),params:[]};if(lt(c,jl))return{sql:s(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){const p=[new Xe("(")];for(const[f,y]of c.entries())p.push(y),fr},pw={mapToDriverValue:r=>r};({...dw,...pw});var Km;Km=xt;class Wi{constructor(t,e=pw){$(this,"brand");this.value=t,this.encoder=e}getSQL(){return new Ft([this])}}$(Wi,Km,"Param");function H(r,...t){const e=[];(t.length>0||r.length>0&&r[0]!=="")&&e.push(new Xe(r[0]));for(const[i,n]of t.entries())e.push(n,new Xe(r[i+1]));return new Ft(e)}(r=>{function t(){return new Ft([])}r.empty=t;function e(l){return new Ft(l)}r.fromList=e;function i(l){return new Ft([new Xe(l)])}r.raw=i;function n(l,u){const c=[];for(const[h,p]of l.entries())h>0&&u!==void 0&&c.push(u),c.push(p);return new Ft(c)}r.join=n;function s(l){return new jl(l)}r.identifier=s;function o(l){return new ss(l)}r.placeholder=o;function a(l,u){return new Wi(l,u)}r.param=a})(H||(H={}));(r=>{var e;e=xt;const i=class i{constructor(s,o){$(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=o}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};$(i,e,"SQL.Aliased");let t=i;r.Aliased=t})(Ft||(Ft={}));var Zm;Zm=xt;class ss{constructor(t){this.name=t}getSQL(){return new Ft([this])}}$(ss,Zm,"Placeholder");function Em(r,t){return r.map(e=>{if(lt(e,ss)){if(!(e.name in t))throw new Error(`No value for placeholder "${e.name}" was provided`);return t[e.name]}if(lt(e,Wi)&<(e.value,ss)){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 OD=Symbol.for("drizzle:IsDrizzleView");var Jm,ty,ey;ey=xt,ty=He,Jm=OD;class Sn{constructor({name:t,schema:e,selectedFields:i,query:n}){$(this,ty);$(this,Jm,!0);this[He]={name:t,originalName:t,schema:e,selectedFields:i,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new Ft([this])}}$(Sn,ey,"View");Ke.prototype.getSQL=function(){return new Ft([this])};Tt.prototype.getSQL=function(){return new Ft([this])};Or.prototype.getSQL=function(){return new Ft([this])};var ry;ry=xt;class na{constructor(t){this.table=t}get(t,e){return e==="table"?this.table:t[e]}}$(na,ry,"ColumnAliasProxyHandler");var iy;iy=xt;class cu{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===He)return{...t[He],name:this.alias,isAlias:!0};if(e===Tt.Symbol.Columns){const n=t[Tt.Symbol.Columns];if(!n)return n;const s={};return Object.keys(n).map(o=>{s[o]=new Proxy(n[o],new na(new Proxy(t,this)))}),s}const i=t[e];return lt(i,Ke)?new Proxy(i,new na(new Proxy(t,this))):i}}$(cu,iy,"TableAliasProxyHandler");function ac(r,t){return new Proxy(r,new cu(t,!1))}function Li(r,t){return new Proxy(r,new na(new Proxy(r.table,new cu(t,!1))))}function mw(r,t){return new Ft.Aliased($l(r.sql,t),r.fieldAlias)}function $l(r,t){return H.join(r.queryChunks.map(e=>lt(e,Ke)?Li(e,t):lt(e,Ft)?$l(e,t):lt(e,Ft.Aliased)?mw(e,t):e))}var ny,sy;class $f extends(sy=Error,ny=xt,sy){constructor({message:t,cause:e}){super(t),this.name="DrizzleError",this.cause=e}}$($f,ny,"DrizzleError");var oy,ay;class yw extends(ay=$f,oy=xt,ay){constructor(){super({message:"Rollback"})}}$(yw,oy,"TransactionRollbackError");var ly;ly=xt;class gw{write(t){console.log(t)}}$(gw,ly,"ConsoleLogWriter");var uy;uy=xt;class vw{constructor(t){$(this,"writer");this.writer=(t==null?void 0:t.writer)??new gw}logQuery(t,e){const i=e.map(s=>{try{return JSON.stringify(s)}catch{return String(s)}}),n=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${t}${n}`)}}$(vw,uy,"DefaultLogger");var cy;cy=xt;class _w{logQuery(){}}$(_w,cy,"NoopLogger");var hy,fy;fy=xt,hy=Symbol.toStringTag;class Tn{constructor(){$(this,hy,"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)}}$(Tn,fy,"QueryPromise");function os(r,t){return Object.entries(r).reduce((e,[i,n])=>{if(typeof i!="string")return e;const s=t?[...t,i]:[i];return lt(n,Ke)||lt(n,Ft)||lt(n,Ft.Aliased)?e.push({path:s,field:n}):lt(n,Tt)?e.push(...os(n[Tt.Symbol.Columns],s)):e.push(...os(n,s)),e},[])}function Vf(r,t){const e=Object.keys(r),i=Object.keys(t);if(e.length!==i.length)return!1;for(const[n,s]of e.entries())if(s!==i[n])return!1;return!0}function bw(r,t){const e=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>lt(n,Ft)||lt(n,Ke)?[i,n]:[i,new Wi(n,r[Tt.Symbol.Columns][i])]);if(e.length===0)throw new Error("No values to set");return Object.fromEntries(e)}function FD(r,t){for(const e of t)for(const i of Object.getOwnPropertyNames(e.prototype))i!=="constructor"&&Object.defineProperty(r.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))}function PD(r){return r[Tt.Symbol.Columns]}function Wn(r){return lt(r,Or)?r._.alias:lt(r,Sn)?r[He].name:lt(r,Ft)?void 0:r[Tt.Symbol.IsAlias]?r[Tt.Symbol.Name]:r[Tt.Symbol.BaseName]}function MD(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 dy,py;class ww extends(py=Ar,dy=xt,py){getSQLType(){return"date"}mapFromDriverValue(t){return new Date(t)}mapToDriverValue(t){return t.toISOString()}}$(ww,dy,"PgDate");var my,yy;class xw extends(yy=Ar,my=xt,yy){getSQLType(){return"date"}}$(xw,my,"PgDateString");var gy,vy;class Sw extends(vy=Ar,gy=xt,vy){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}}$(Sw,gy,"PgJson");var _y,by;class Tw extends(by=Ar,_y=xt,by){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}}$(Tw,_y,"PgJsonb");var wy,xy;class Iw extends(xy=Ar,wy=xt,xy){constructor(e,i){super(e,i);$(this,"precision");$(this,"scale");this.precision=i.precision,this.scale=i.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})`}}$(Iw,wy,"PgNumeric");var Sy,Ty;class Ew extends(Ty=Ar,Sy=xt,Ty){constructor(e,i){super(e,i);$(this,"withTimezone");$(this,"precision");this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}$(Ew,Sy,"PgTime");var Iy,Ey;class Cw extends(Ey=Ar,Iy=xt,Ey){constructor(e,i){super(e,i);$(this,"withTimezone");$(this,"precision");$(this,"mapFromDriverValue",e=>new Date(this.withTimezone?e:e+"+0000"));$(this,"mapToDriverValue",e=>e.toISOString());this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}}$(Cw,Iy,"PgTimestamp");var Cy,Ay;class Aw extends(Ay=Ar,Cy=xt,Ay){constructor(e,i){super(e,i);$(this,"withTimezone");$(this,"precision");this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}$(Aw,Cy,"PgTimestampString");var Oy,Fy;class Ow extends(Fy=Ar,Oy=xt,Fy){getSQLType(){return"uuid"}}$(Ow,Oy,"PgUUID");const Cm=Symbol.for("drizzle:PgInlineForeignKeys"),Am=Symbol.for("drizzle:EnableRLS");var Py,My,Dy,Ry,Ny,Ly;class Br extends(Ly=Tt,Ny=xt,Ry=Cm,Dy=Am,My=Tt.Symbol.ExtraConfigBuilder,Py=Tt.Symbol.ExtraConfigColumns,Ly){constructor(){super(...arguments);$(this,Ry,[]);$(this,Dy,!1);$(this,My);$(this,Py,{})}}$(Br,Ny,"PgTable"),$(Br,"Symbol",Object.assign({},Tt.Symbol,{InlineForeignKeys:Cm,EnableRLS:Am}));var By;By=xt;class Fw{constructor(t,e){$(this,"columns");$(this,"name");this.columns=t,this.name=e}build(t){return new Pw(t,this.columns,this.name)}}$(Fw,By,"PgPrimaryKeyBuilder");var ky;ky=xt;class Pw{constructor(t,e,i){$(this,"columns");$(this,"name");this.table=t,this.columns=e,this.name=i}getName(){return this.name??`${this.table[Br.Symbol.Name]}_${this.columns.map(t=>t.name).join("_")}_pk`}}$(Pw,ky,"PgPrimaryKey");function yr(r,t){return AD(t)&&!fw(r)&&!lt(r,Wi)&&!lt(r,ss)&&!lt(r,Ke)&&!lt(r,Tt)&&!lt(r,Sn)?new Wi(r,t):r}const Mw=(r,t)=>H`${r} = ${yr(t,r)}`,DD=(r,t)=>H`${r} <> ${yr(t,r)}`;function Eh(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Ft(t):new Ft([new Xe("("),H.join(t,new Xe(" and ")),new Xe(")")])}function RD(...r){const t=r.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new Ft(t):new Ft([new Xe("("),H.join(t,new Xe(" or ")),new Xe(")")])}function ND(r){return H`not ${r}`}const LD=(r,t)=>H`${r} > ${yr(t,r)}`,BD=(r,t)=>H`${r} >= ${yr(t,r)}`,kD=(r,t)=>H`${r} < ${yr(t,r)}`,UD=(r,t)=>H`${r} <= ${yr(t,r)}`;function zD(r,t){return Array.isArray(t)?t.length===0?H`false`:H`${r} in ${t.map(e=>yr(e,r))}`:H`${r} in ${yr(t,r)}`}function jD(r,t){return Array.isArray(t)?t.length===0?H`true`:H`${r} not in ${t.map(e=>yr(e,r))}`:H`${r} not in ${yr(t,r)}`}function $D(r){return H`${r} is null`}function VD(r){return H`${r} is not null`}function GD(r){return H`exists ${r}`}function WD(r){return H`not exists ${r}`}function HD(r,t,e){return H`${r} between ${yr(t,r)} and ${yr(e,r)}`}function XD(r,t,e){return H`${r} not between ${yr(t,r)} and ${yr(e,r)}`}function YD(r,t){return H`${r} like ${t}`}function qD(r,t){return H`${r} not like ${t}`}function QD(r,t){return H`${r} ilike ${t}`}function KD(r,t){return H`${r} not ilike ${t}`}function ZD(r){return H`${r} asc`}function JD(r){return H`${r} desc`}var Uy;Uy=xt;class Gf{constructor(t,e,i){$(this,"referencedTableName");$(this,"fieldName");this.sourceTable=t,this.referencedTable=e,this.relationName=i,this.referencedTableName=e[Tt.Symbol.Name]}}$(Gf,Uy,"Relation");var zy;zy=xt;class Dw{constructor(t,e){this.table=t,this.config=e}}$(Dw,zy,"Relations");var jy,$y;const Wl=class Wl extends($y=Gf,jy=xt,$y){constructor(t,e,i,n){super(t,e,i==null?void 0:i.relationName),this.config=i,this.isNullable=n}withFieldName(t){const e=new Wl(this.sourceTable,this.referencedTable,this.config,this.isNullable);return e.fieldName=t,e}};$(Wl,jy,"One");let as=Wl;var Vy,Gy;const Hl=class Hl extends(Gy=Gf,Vy=xt,Gy){constructor(t,e,i){super(t,e,i==null?void 0:i.relationName),this.config=i}withFieldName(t){const e=new Hl(this.sourceTable,this.referencedTable,this.config);return e.fieldName=t,e}};$(Hl,Vy,"Many");let Vl=Hl;function tR(){return{and:Eh,between:HD,eq:Mw,exists:GD,gt:LD,gte:BD,ilike:QD,inArray:zD,isNull:$D,isNotNull:VD,like:YD,lt:kD,lte:UD,ne:DD,not:ND,notBetween:XD,notExists:WD,notLike:qD,notIlike:KD,notInArray:jD,or:RD,sql:H}}function eR(){return{sql:H,asc:ZD,desc:JD}}function rR(r,t){var s;Object.keys(r).length===1&&"default"in r&&!lt(r.default,Tt)&&(r=r.default);const e={},i={},n={};for(const[o,a]of Object.entries(r))if(lt(a,Tt)){const l=ia(a),u=i[l];e[l]=o,n[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&&n[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,Fw)&&n[o].primaryKey.push(...h.columns)}else if(lt(a,Dw)){const l=ia(a.table),u=e[l],c=a.config(t(a.table));let h;for(const[p,f]of Object.entries(c))if(u){const y=n[u];y.relations[p]=f}else l in i||(i[l]={relations:{},primaryKey:h}),i[l].relations[p]=f}return{tables:n,tableNamesMap:e}}function iR(r){return function(e,i){return new as(r,e,i,(i==null?void 0:i.fields.reduce((n,s)=>n&&s.notNull,!0))??!1)}}function nR(r){return function(e,i){return new Vl(r,e,i)}}function sR(r,t,e){if(lt(e,as)&&e.config)return{fields:e.config.fields,references:e.config.references};const i=t[ia(e.referencedTable)];if(!i)throw new Error(`Table "${e.referencedTable[Tt.Symbol.Name]}" not found in schema`);const n=r[i];if(!n)throw new Error(`Table "${i}" not found in schema`);const s=e.sourceTable,o=t[ia(s)];if(!o)throw new Error(`Table "${s[Tt.Symbol.Name]}" not found in schema`);const a=[];for(const l of Object.values(n.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 "${i}"`):new Error(`There are multiple relations between "${i}" and "${e.sourceTable[Tt.Symbol.Name]}". Please specify relation name`);if(a[0]&<(a[0],as)&&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 oR(r){return{one:iR(r),many:nR(r)}}function Ch(r,t,e,i,n=s=>s){const s={};for(const[o,a]of i.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,as)?c&&Ch(r,r[a.relationTableTsKey],c,a.selection,n):c.map(h=>Ch(r,r[a.relationTableTsKey],h,a.selection,n))}else{const l=n(e[o]),u=a.field;let c;lt(u,Ke)?c=u:lt(u,Ft)?c=u.decoder:c=u.sql.decoder,s[a.tsKey]=l===null?null:c.mapFromDriverValue(l)}return s}var Wy;Wy=xt;const Xl=class Xl{constructor(t){$(this,"config");this.config={...t}}get(t,e){if(e==="_")return{...t._,selectedFields:new Proxy(t._.selectedFields,this)};if(e===He)return{...t[He],selectedFields:new Proxy(t[He].selectedFields,this)};if(typeof e=="symbol")return t[e];const n=(lt(t,Or)?t._.selectedFields:lt(t,Sn)?t[He].selectedFields:t)[e];if(lt(n,Ft.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!n.isSelectionField)return n.sql;const s=n.clone();return s.isSelectionField=!0,s}if(lt(n,Ft)){if(this.config.sqlBehavior==="sql")return n;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(n,Ke)?this.config.alias?new Proxy(n,new na(new Proxy(n.table,new cu(this.config.alias,this.config.replaceOriginalName??!1)))):n:typeof n!="object"||n===null?n:new Proxy(n,new Xl(this.config))}};$(Xl,Wy,"SelectionProxyHandler");let Je=Xl;var Hy,Xy;class Ah extends(Xy=Tn,Hy=xt,Xy){constructor(e,i,n,s){super();$(this,"config");$(this,"authToken");$(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=i,this.dialect=n,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=os(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){return Pr.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 Je({alias:qn(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}$(Ah,Hy,"PgDelete");function aR(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function lR(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,i,n)=>{const s=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return e+s},"")}function uR(r){return r}var Yy;Yy=xt;class Rw{constructor(t){$(this,"cache",{});$(this,"cachedTables",{});$(this,"convert");this.convert=t==="snake_case"?aR:t==="camelCase"?lR:uR}getColumnCasing(t){if(!t.keyAsName)return t.name;const e=t.table[Tt.Symbol.Schema]??"public",i=t.table[Tt.Symbol.OriginalName],n=`${e}.${i}.${t.name}`;return this.cache[n]||this.cacheTable(t.table),this.cache[n]}cacheTable(t){const e=t[Tt.Symbol.Schema]??"public",i=t[Tt.Symbol.OriginalName],n=`${e}.${i}`;if(!this.cachedTables[n]){for(const s of Object.values(t[Tt.Symbol.Columns])){const o=`${n}.${s.name}`;this.cache[o]=this.convert(s.name)}this.cachedTables[n]=!0}}clearCache(){this.cache={},this.cachedTables={}}}$(Rw,Yy,"CasingCache");var qy,Qy;class Wf extends(Qy=Sn,qy=xt,Qy){}$(Wf,qy,"PgViewBase");var Ky;Ky=xt;class Bo{constructor(t){$(this,"casing");this.casing=new Rw(t==null?void 0:t.casing)}async migrate(t,e,i){const n=typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",s=typeof i=="string"?"drizzle":i.migrationsSchema??"drizzle",o=H` + CREATE TABLE IF NOT EXISTS ${H.identifier(s)}.${H.identifier(n)} ( id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint ) - `;await e.execute(X`CREATE SCHEMA IF NOT EXISTS ${X.identifier(s)}`),await e.execute(o);const l=(await e.all(X`select id, hash, created_at from ${X.identifier(s)}.${X.identifier(n)} 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=i[o])==null?void 0:a.onUpdateFn)!==void 0}),s=n.length;return X.join(n.flatMap((o,a)=>{const l=i[o],u=e[o]??X.param(l.onUpdateFn(),l),c=X`${X.identifier(this.casing.getColumnCasing(l))} = ${u}`;return a{const a=[];if(lt(s,Ft.Aliased)&&s.isSelectionField)a.push(X.identifier(s.fieldAlias));else if(lt(s,Ft.Aliased)||lt(s,Ft)){const l=lt(s,Ft.Aliased)?s.sql:s;e?a.push(new Ft(l.queryChunks.map(u=>lt(u,Ar)?X.identifier(this.casing.getColumnCasing(u)):u))):a.push(l),lt(s,Ft.Aliased)&&a.push(X` as ${X.identifier(s.fieldAlias)}`)}else lt(s,Ke)&&(e?a.push(X.identifier(this.casing.getColumnCasing(s))):a.push(s));return oa==null?void 0:a.some(({alias:M})=>M===(it[Tt.Symbol.IsAlias]?qn(it):it[Tt.Symbol.BaseName])))(w.field.table)){const it=qn(w.field.table);throw new Error(`Your "${w.path.join("->")}" field references a column "${it}"."${w.field.name}", but the table "${it}" is not part of the query! Did you forget to join it?`)}const d=!a||a.length===0,m=this.buildWithCTE(t);let _;f&&(_=f===!0?X` distinct`:X` distinct on (${X.join(f.on,X`, `)})`);const S=this.buildSelection(g,{isSingleTable:d}),E=this.buildFromTable(o),b=this.buildJoins(a),F=n?X` where ${n}`:void 0,x=s?X` having ${s}`:void 0;let z;l&&l.length>0&&(z=X` order by ${X.join(l,X`, `)}`);let B;u&&u.length>0&&(B=X` group by ${X.join(u,X`, `)}`);const tt=typeof c=="object"||typeof c=="number"&&c>=0?X` limit ${c}`:void 0,st=h?X` offset ${h}`:void 0,I=X.empty();if(p){const w=X` for ${X.raw(p.strength)}`;p.config.of&&w.append(X` of ${X.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],X`, `)}`),p.config.noWait?w.append(X` no wait`):p.config.skipLocked&&w.append(X` skip locked`),I.append(w)}const Z=X`${m}select${_} ${S} from ${E}${b}${F}${B}${x}${z}${tt}${st}${I}`;return y.length>0?this.buildSetOperations(Z,y):Z}buildSetOperations(t,e){const[i,...n]=e;if(!i)throw new Error("Cannot pass undefined values to any set operator");return n.length===0?this.buildSetOperationQuery({leftSelect:t,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:t,setOperator:i}),n)}buildSetOperationQuery({leftSelect:t,setOperator:{type:e,isAll:i,rightSelect:n,limit:s,orderBy:o,offset:a}}){const l=X`(${t.getSQL()}) `,u=X`(${n.getSQL()})`;let c;if(o&&o.length>0){const y=[];for(const g of o)if(lt(g,Ar))y.push(X.identifier(g.name));else if(lt(g,Ft)){for(let d=0;d=0?X` limit ${s}`:void 0,p=X.raw(`${e} ${i?"all ":""}`),f=a?X` offset ${a}`:void 0;return X`${l}${p}${u}${c}${h}${f}`}buildInsertQuery({table:t,values:e,onConflict:i,returning:n,withList:s,select:o,overridingSystemValue_:a}){const l=[],u=t[Tt.Symbol.Columns],c=Object.entries(u).filter(([m,_])=>!_.shouldDisableInsert()),h=c.map(([,m])=>X.identifier(this.casing.getColumnCasing(m)));if(o){const m=e;lt(m,Ft)?l.push(m):l.push(m.getSQL())}else{const m=e;l.push(X.raw("values "));for(const[_,S]of m.entries()){const E=[];for(const[b,F]of c){const x=S[b];if(x===void 0||lt(x,Wi)&&x.value===void 0)if(F.defaultFn!==void 0){const z=F.defaultFn(),B=lt(z,Ft)?z:X.param(z,F);E.push(B)}else if(!F.default&&F.onUpdateFn!==void 0){const z=F.onUpdateFn(),B=lt(z,Ft)?z:X.param(z,F);E.push(B)}else E.push(X`default`);else E.push(x)}l.push(E),_({dbKey:S.name,tsKey:_,field:Li(S,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const m=Object.fromEntries(Object.entries(s.columns).map(([x,z])=>[x,Li(z,a)]));if(o.where){const x=typeof o.where=="function"?o.where(m,tR()):o.where;y=x&&$l(x,a)}const _=[];let S=[];if(o.columns){let x=!1;for(const[z,B]of Object.entries(o.columns))B!==void 0&&z in s.columns&&(!x&&B===!0&&(x=!0),S.push(z));S.length>0&&(S=x?S.filter(z=>{var B;return((B=o.columns)==null?void 0:B[z])===!0}):Object.keys(s.columns).filter(z=>!S.includes(z)))}else S=Object.keys(s.columns);for(const x of S){const z=s.columns[x];_.push({tsKey:x,value:z})}let E=[];o.with&&(E=Object.entries(o.with).filter(x=>!!x[1]).map(([x,z])=>({tsKey:x,queryConfig:z,relation:s.relations[x]})));let b;if(o.extras){b=typeof o.extras=="function"?o.extras(m,{sql:X}):o.extras;for(const[x,z]of Object.entries(b))_.push({tsKey:x,value:mw(z,a)})}for(const{tsKey:x,value:z}of _)c.push({dbKey:lt(z,Ft.Aliased)?z.fieldAlias:s.columns[x].name,tsKey:x,field:lt(z,Ke)?Li(z,a):z,relationTableTsKey:void 0,isJson:!1,selection:[]});let F=typeof o.orderBy=="function"?o.orderBy(m,eR()):o.orderBy??[];Array.isArray(F)||(F=[F]),f=F.map(x=>lt(x,Ke)?Li(x,a):$l(x,a)),h=o.limit,p=o.offset;for(const{tsKey:x,queryConfig:z,relation:B}of E){const tt=sR(e,i,B),st=ia(B.referencedTable),I=i[st],Z=`${a}_${x}`,w=Eh(...tt.fields.map((O,D)=>gw(Li(tt.references[D],Z),Li(O,a)))),it=this.buildRelationalQueryWithoutPK({fullSchema:t,schema:e,tableNamesMap:i,table:t[I],tableConfig:e[I],queryConfig:lt(B,as)?z===!0?{limit:1}:{...z,limit:1}:z,tableAlias:Z,joinOn:w,nestedQueryRelation:B}),M=X`${X.identifier(Z)}.${X.identifier("data")}`.as(x);g.push({on:X`true`,table:new Or(it.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),c.push({dbKey:x,tsKey:x,field:M,relationTableTsKey:I,isJson:!0,selection:it.selection})}}if(c.length===0)throw new $f({message:`No fields selected for table "${s.tsName}" ("${a}")`});let d;if(y=Eh(u,y),l){let m=X`json_build_array(${X.join(c.map(({field:E,tsKey:b,isJson:F})=>F?X`${X.identifier(`${a}_${b}`)}.${X.identifier("data")}`:lt(E,Ft.Aliased)?E.sql:E),X`, `)})`;lt(l,Vl)&&(m=X`coalesce(json_agg(${m}${f.length>0?X` order by ${X.join(f,X`, `)}`:void 0}), '[]'::json)`);const _=[{dbKey:"data",tsKey:"data",field:m.as("data"),isJson:!0,relationTableTsKey:s.tsName,selection:c}];h!==void 0||p!==void 0||f.length>0?(d=this.buildSelectQuery({table:ac(n,a),fields:{},fieldsFlat:[{path:[],field:X.raw("*")}],where:y,limit:h,offset:p,orderBy:f,setOperators:[]}),y=void 0,h=void 0,p=void 0,f=[]):d=ac(n,a),d=this.buildSelectQuery({table:lt(d,Br)?d:new Or(d,{},a),fields:{},fieldsFlat:_.map(({field:E})=>({path:[],field:lt(E,Ke)?Li(E,a):E})),joins:g,where:y,limit:h,offset:p,orderBy:f,setOperators:[]})}else d=this.buildSelectQuery({table:ac(n,a),fields:{},fieldsFlat:c.map(({field:m})=>({path:[],field:lt(m,Ke)?Li(m,a):m})),joins:g,where:y,limit:h,offset:p,orderBy:f,setOperators:[]});return{tableTsKey:s.tsName,sql:d,selection:c}}}G(Bo,Ky,"PgDialect");var Zy;Zy=xt;class Nw{getSelectedFields(){return this._.selectedFields}}G(Nw,Zy,"TypedQueryBuilder");var Jy;Jy=xt;class Sr{constructor(t){G(this,"fields");G(this,"session");G(this,"dialect");G(this,"withList",[]);G(this,"distinct");G(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,i=t;let n;return this.fields?n=this.fields:lt(i,Or)?n=Object.fromEntries(Object.keys(i._.selectedFields).map(s=>[s,i[s]])):lt(i,Wf)?n=i[He].selectedFields:lt(i,Ft)?n={}:n=ZD(i),new Hf({table:i,fields:n,isPartialSelect:e,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}G(Sr,Jy,"PgSelectBuilder");var tg,eg;class Lw extends(eg=Nw,tg=xt,eg){constructor({table:e,fields:i,isPartialSelect:n,session:s,dialect:o,withList:a,distinct:l}){super();G(this,"_");G(this,"config");G(this,"joinsNotNullableMap");G(this,"tableName");G(this,"isPartialSelect");G(this,"session");G(this,"dialect");G(this,"leftJoin",this.createJoin("left"));G(this,"rightJoin",this.createJoin("right"));G(this,"innerJoin",this.createJoin("inner"));G(this,"fullJoin",this.createJoin("full"));G(this,"union",this.createSetOperator("union",!1));G(this,"unionAll",this.createSetOperator("union",!0));G(this,"intersect",this.createSetOperator("intersect",!1));G(this,"intersectAll",this.createSetOperator("intersect",!0));G(this,"except",this.createSetOperator("except",!1));G(this,"exceptAll",this.createSetOperator("except",!0));this.config={withList:a,table:e,fields:{...i},distinct:l,setOperators:[]},this.isPartialSelect=n,this.session=s,this.dialect=o,this._={selectedFields:i},this.tableName=Wn(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e){return(i,n)=>{var a;const s=this.tableName,o=Wn(i);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(i,Ft))){const l=lt(i,Or)?i._.selectedFields:lt(i,Sn)?i[He].selectedFields:i[Tt.Symbol.Columns];this.config.fields[o]=l}if(typeof n=="function"&&(n=n(new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:n,table:i,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,i){return n=>{const s=typeof n=="function"?n(cR()):n;if(!Vf(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:i,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 Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const i=e[0](new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(i)?i:[i]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const i=e[0](new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(i)?i:[i];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{const i=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}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,i={}){return this.config.lockingClause={strength:e,config:i},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}as(e){return new Proxy(new Or(this.getSQL(),this.config.fields,e),new Je({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Je({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}G(Lw,tg,"PgSelectQueryBuilder");var rg,ig;class Hf extends(ig=Lw,rg=xt,ig){constructor(){super(...arguments);G(this,"authToken");G(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)))}_prepare(e){const{session:i,config:n,dialect:s,joinsNotNullableMap:o,authToken:a}=this;if(!i)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Pr.startActiveSpan("drizzle.prepareQuery",()=>{const l=os(n.fields),u=i.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}}G(Hf,rg,"PgSelect");KD(Hf,[Tn]);function oo(r,t){return(e,i,...n)=>{const s=[i,...n].map(o=>({type:r,isAll:t,rightSelect:o}));for(const o of s)if(!Vf(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 cR=()=>({union:hR,unionAll:fR,intersect:dR,intersectAll:pR,except:mR,exceptAll:yR}),hR=oo("union",!1),fR=oo("union",!0),dR=oo("intersect",!1),pR=oo("intersect",!0),mR=oo("except",!1),yR=oo("except",!0);var ng;ng=xt;class Xf{constructor(t){G(this,"dialect");G(this,"dialectConfig");G(this,"$with",(t,e)=>{const i=this;return{as:s=>(typeof s=="function"&&(s=s(i)),new Proxy(new jf(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new Je({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});this.dialect=lt(t,Bo)?t:void 0,this.dialectConfig=lt(t,Bo)?void 0:t}with(...t){const e=this;function i(o){return new Sr({fields:o??void 0,session:void 0,dialect:e.getDialect(),withList:t})}function n(o){return new Sr({fields:o??void 0,session:void 0,dialect:e.getDialect(),distinct:!0})}function s(o,a){return new Sr({fields:a??void 0,session:void 0,dialect:e.getDialect(),distinct:{on:o}})}return{select:i,selectDistinct:n,selectDistinctOn:s}}select(t){return new Sr({fields:t??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(t){return new Sr({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(t,e){return new Sr({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:t}})}getDialect(){return this.dialect||(this.dialect=new Bo(this.dialectConfig)),this.dialect}}G(Xf,ng,"PgQueryBuilder");var sg;sg=xt;class Oh{constructor(t,e,i,n,s){G(this,"authToken");this.table=t,this.session=e,this.dialect=i,this.withList=n,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(i=>{const n={},s=this.table[Tt.Symbol.Columns];for(const o of Object.keys(i)){const a=i[o];n[o]=lt(a,Ft)?a:new Wi(a,s[o])}return n});return new Fh(this.table,e,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(t){const e=typeof t=="function"?t(new Xf):t;if(!lt(e,Ft)&&!Vf(this.table[Ih],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 Fh(this.table,e,this.session,this.dialect,this.withList,!0)}}G(Oh,sg,"PgInsertBuilder");var og,ag;class Fh extends(ag=Tn,og=xt,ag){constructor(e,i,n,s,o,a,l){super();G(this,"config");G(this,"authToken");G(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=n,this.dialect=s,this.config={table:e,values:i,withList:o,select:a,overridingSystemValue_:l}}returning(e=this.config.table[Tt.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=os(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=X`do nothing`;else{let i="";i=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 n=e.where?X` where ${e.where}`:void 0;this.config.onConflict=X`(${X.raw(i)})${n} 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 i=e.where?X` where ${e.where}`:void 0,n=e.targetWhere?X` where ${e.targetWhere}`:void 0,s=e.setWhere?X` where ${e.setWhere}`:void 0,o=this.dialect.buildUpdateSet(this.config.table,ww(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=X`(${X.raw(a)})${n} do update set ${o}${i}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){return Pr.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 Je({alias:qn(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}G(Fh,og,"PgInsert");var lg,ug;class Bw extends(ug=Tn,lg=xt,ug){constructor(e,i,n){super();G(this,"config");G(this,"authToken");G(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=i,this.dialect=n,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,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){return Pr.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}}G(Bw,lg,"PgRefreshMaterializedView");var cg;cg=xt;class Ph{constructor(t,e,i,n){G(this,"authToken");this.table=t,this.session=e,this.dialect=i,this.withList=n}setToken(t){return this.authToken=t,this}set(t){return new kw(this.table,ww(this.table,t),this.session,this.dialect,this.withList).setToken(this.authToken)}}G(Ph,cg,"PgUpdateBuilder");var hg,fg;class kw extends(fg=Tn,hg=xt,fg){constructor(e,i,n,s,o){super();G(this,"config");G(this,"tableName");G(this,"joinsNotNullableMap");G(this,"leftJoin",this.createJoin("left"));G(this,"rightJoin",this.createJoin("right"));G(this,"innerJoin",this.createJoin("inner"));G(this,"fullJoin",this.createJoin("full"));G(this,"authToken");G(this,"execute",e=>this._prepare().execute(e,this.authToken));this.session=n,this.dialect=s,this.config={set:i,table:e,withList:o,joins:[]},this.tableName=Wn(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}from(e){const i=e,n=Wn(i);return typeof n=="string"&&(this.joinsNotNullableMap[n]=!0),this.config.from=i,this}getTableLikeFields(e){return lt(e,Br)?e[Tt.Symbol.Columns]:lt(e,Or)?e._.selectedFields:e[He].selectedFields}createJoin(e){return(i,n)=>{const s=Wn(i);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 n=="function"){const o=this.config.from&&!lt(this.config.from,Ft)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[Tt.Symbol.Columns],new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:i,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 i=Wn(this.config.from);if(typeof i=="string"&&this.config.from&&!lt(this.config.from,Ft)){const n=this.getTableLikeFields(this.config.from);e[i]=n}for(const n of this.config.joins){const s=Wn(n.table);if(typeof s=="string"&&!lt(n.table,Ft)){const o=this.getTableLikeFields(n.table);e[s]=o}}}return this.config.returningFields=e,this.config.returning=os(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){const i=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Je({alias:qn(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}G(kw,hg,"PgUpdate");var dg,pg,mg;const Uo=class Uo extends(mg=Ft,pg=xt,dg=Symbol.toStringTag,mg){constructor(e){super(Uo.buildEmbeddedCount(e.source,e.filters).queryChunks);G(this,"sql");G(this,"token");G(this,dg,"PgCountBuilder");G(this,"session");this.params=e,this.mapWith(Number),this.session=e.session,this.sql=Uo.buildCount(e.source,e.filters)}static buildEmbeddedCount(e,i){return X`(select count(*) from ${e}${X.raw(" where ").if(i)}${i})`}static buildCount(e,i){return X`select count(*) as count from ${e}${X.raw(" where ").if(i)}${i};`}setToken(e){return this.token=e,this}then(e,i){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,i)}catch(e){return this.then(void 0,e)}finally(e){return this.then(i=>(e==null||e(),i),i=>{throw e==null||e(),i})}};G(Uo,pg,"PgCountBuilder");let Mh=Uo;var yg;yg=xt;class Uw{constructor(t,e,i,n,s,o,a){this.fullSchema=t,this.schema=e,this.tableNamesMap=i,this.table=n,this.tableConfig=s,this.dialect=o,this.session=a}findMany(t){return new Dh(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t||{},"many")}findFirst(t){return new Dh(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t?{...t,limit:1}:{limit:1},"first")}}G(Uw,yg,"PgRelationalQueryBuilder");var gg,vg;class Dh extends(vg=Tn,gg=xt,vg){constructor(e,i,n,s,o,a,l,u,c){super();G(this,"authToken");this.fullSchema=e,this.schema=i,this.tableNamesMap=n,this.table=s,this.tableConfig=o,this.dialect=a,this.session=l,this.config=u,this.mode=c}_prepare(e){return Pr.startActiveSpan("drizzle.prepareQuery",()=>{const{query:i,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(s,o)=>{const a=s.map(l=>Ch(this.schema,this.tableConfig,l,i.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(),i=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:i}}toSQL(){return this._toSQL().builtQuery}setToken(e){return this.authToken=e,this}execute(){return Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}}G(Dh,gg,"PgRelationalQuery");var _g,bg;class zw extends(bg=Tn,_g=xt,bg){constructor(t,e,i,n){super(),this.execute=t,this.sql=e,this.query=i,this.mapBatchResult=n}getSQL(){return this.sql}getQuery(){return this.query}mapResult(t,e){return e?this.mapBatchResult(t):t}_prepare(){return this}isResponseInArrayMode(){return!1}}G(zw,_g,"PgRaw");var wg;wg=xt;class Yf{constructor(t,e,i){G(this,"query");G(this,"$with",(t,e)=>{const i=this;return{as:s=>(typeof s=="function"&&(s=s(new Xf(i.dialect))),new Proxy(new jf(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new Je({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});G(this,"authToken");if(this.dialect=t,this.session=e,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap,session:e}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:e},this.query={},this._.schema)for(const[n,s]of Object.entries(this._.schema))this.query[n]=new Uw(i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[n],s,t,e)}$count(t,e){return new Mh({source:t,filters:e,session:this.session})}with(...t){const e=this;function i(u){return new Sr({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t})}function n(u){return new Sr({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:!0})}function s(u,c){return new Sr({fields:c??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:{on:u}})}function o(u){return new Ph(u,e.session,e.dialect,t)}function a(u){return new Oh(u,e.session,e.dialect,t)}function l(u){return new Ah(u,e.session,e.dialect,t)}return{select:i,selectDistinct:n,selectDistinctOn:s,update:o,insert:a,delete:l}}select(t){return new Sr({fields:t??void 0,session:this.session,dialect:this.dialect})}selectDistinct(t){return new Sr({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(t,e){return new Sr({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:{on:t}})}update(t){return new Ph(t,this.session,this.dialect)}insert(t){return new Oh(t,this.session,this.dialect)}delete(t){return new Ah(t,this.session,this.dialect)}refreshMaterializedView(t){return new Bw(t,this.session,this.dialect)}execute(t){const e=typeof t=="string"?X.raw(t):t.getSQL(),i=this.dialect.sqlToQuery(e),n=this.session.prepareQuery(i,void 0,void 0,!1);return new zw(()=>n.execute(void 0,this.authToken),e,i,s=>n.mapResult(s,!0))}transaction(t,e){return this.session.transaction(t,e)}}G(Yf,wg,"PgDatabase");var xg;xg=xt;class jw{constructor(t){G(this,"authToken");G(this,"joinsNotNullableMap");this.query=t}getQuery(){return this.query}mapResult(t,e){return t}setToken(t){return this.authToken=t,this}}G(jw,xg,"PgPreparedQuery");var Sg;Sg=xt;class $w{constructor(t){this.dialect=t}execute(t,e){return Pr.startActiveSpan("drizzle.operation",()=>Pr.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 i=await this.execute(t,e);return Number(i[0].count)}}G($w,Sg,"PgSession");var Tg,Ig;class Vw extends(Ig=Yf,Tg=xt,Ig){constructor(t,e,i,n=0){super(t,e,i),this.schema=i,this.nestedIndex=n}rollback(){throw new yw}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"),X.raw(e.join(" "))}setTransaction(t){return this.session.execute(X`set transaction ${this.getTransactionConfigSQL(t)}`)}}G(Vw,Tg,"PgTransaction");function Om(r){return typeof r=="string"&&/^true$/i.test(r)}function gR(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 i=e.searchParams.get("logger");i&&Om(i)&&(t.logger=!0);const n=e.searchParams.get("storage");switch(n){case ra.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:ra.ORIGIN_PRIVATE_FS,path:e.pathname.startsWith("/")?e.pathname.slice(1):e.pathname,...s&&Om(s)&&{accessMode:T0.READ_WRITE}};break}case null:break;default:console.warn(`Unknown storage type "${n}"`);break}return t}var Eg,Cg;class Gw extends(Cg=jw,Eg=xt,Cg){constructor(t,e,i,n,s,o){super({sql:e,params:i}),this.client=t,this.queryString=e,this.params=i,this.logger=n,this.fields=s,this.customResultMapper=o}async execute(t={}){const e=Em(this.params,t);this.logger.logQuery(this.queryString,e);const{fields:i,queryString:n,client:s,customResultMapper:o}=this,a=await s;return a.query(n,e)}async all(t={}){const e=Em(this.params,t);return this.logger.logQuery(this.queryString,e),(await this.client).query(this.queryString,e)}}G(Gw,Eg,"DuckDBWasmPreparedQuery");var Ag,Og;const Yl=class Yl extends(Og=$w,Ag=xt,Og){constructor(e,i,n,s={}){super(i);G(this,"logger");this.client=e,this.schema=n,this.options=s,this.logger=s.logger??new bw}prepareQuery(e,i,n,s,o){return new Gw(this.client,e.sql,e.params,this.logger,i,o)}async query(e,i){return this.logger.logQuery(e,i),(await this.client).query(e,i)}async queryObjects(e,i){return this.logger.logQuery(e,i),(await this.client).query(e,i)}transaction(e,i){return xD(this.client,async n=>{const s=new Yl(n,this.dialect,this.schema,this.options),o=new Rh(this.dialect,s,this.schema);return i&&await o.setTransaction(i),e(o)})}};G(Yl,Ag,"DuckDBWasmSession");let Gl=Yl;var Fg,Pg;const ql=class ql extends(Pg=Vw,Fg=xt,Pg){constructor(e,i,n,s=0){super(e,i,n,s);G(this,"dialect");G(this,"session");this.dialect=e,this.session=i}async transaction(e){return SD(this.session.client,"",async i=>{const n=new Gl(i,this.dialect,this.schema,this.session.options),s=new ql(this.dialect,n,this.schema);return e(s)})}};G(ql,Fg,"DuckDBWasmTransaction");let Rh=ql;var Mg,Dg;class Ww extends(Dg=Yf,Mg=xt,Dg){}G(Ww,Mg,"DuckDBWasmDatabase");function ko(r,t={}){const e=new Bo({casing:t.casing});let i;t.logger===!0?i=new _w:t.logger!==!1&&(i=t.logger);let n;if(t.schema){const a=rR(t.schema,oR);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}const s=new Gl(r,e,n,{logger:i}),o=new Ww(e,s,n);return o.$client=r,o}function Fm(r,t){const e=gR(r);let i;return e.bundles==="import-url"?i=(async()=>{const s=await Sh();switch(s){case"browser":return(await ln(async()=>{const{getImportUrlBundles:o}=await import("./import-url-browser-CPN8ipMD.js");return{getImportUrlBundles:o}},__vite__mapDeps([3,4]))).getImportUrlBundles();case"node":return await(await ln(async()=>{const{getImportUrlBundles:o}=await import("./import-url-node-BfNoxhRr.js");return{getImportUrlBundles:o}},__vite__mapDeps([5,4]))).getImportUrlBundles();default:throw new Error(`Unsupported environment: "${s}"`)}})():i=(async()=>{const s=await Sh();switch(s){case"browser":return(await ln(async()=>{const{getBundles:o}=await import("./default-browser-BrgSDbLD.js");return{getBundles:o}},[])).getBundles();case"node":return await(await ln(async()=>{const{getBundles:o}=await import("./default-node-S5EYlj5_.js");return{getBundles:o}},__vite__mapDeps([0,1,2]))).getBundles();default:throw new Error(`Unsupported environment: "${s}"`)}})(),ko(hw({bundles:i,logger:e.logger?new I0:void 0,storage:e.storage}),t)}function Pm(...r){if(typeof r[0]=="string")return Fm(r[0],r[1]);if(JD(r[0])){const{connection:t,client:e,...i}=r[0];if(e)return ko(e,i);if(typeof t=="string")return Fm(t,i);if(typeof t>"u")throw new Error("connection option is required");return ko(hw({bundles:t.bundles,logger:t.logger,storage:t.storage}),i)}return ko(r[0],r[1])}(r=>{function t(e){return ko({options:{parsers:{},serializers:{}}},e)}r.mock=t})(Pm||(Pm={}));export{L1 as A,TR as D,xR as I,pC as J,eI as L,_c as M,wR as T,fi as a,Re as b,Pm as d,sa as e,SR as l}; + `;await e.execute(H`CREATE SCHEMA IF NOT EXISTS ${H.identifier(s)}`),await e.execute(o);const l=(await e.all(H`select id, hash, created_at from ${H.identifier(s)}.${H.identifier(n)} 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=i[o])==null?void 0:a.onUpdateFn)!==void 0}),s=n.length;return H.join(n.flatMap((o,a)=>{const l=i[o],u=e[o]??H.param(l.onUpdateFn(),l),c=H`${H.identifier(this.casing.getColumnCasing(l))} = ${u}`;return a{const a=[];if(lt(s,Ft.Aliased)&&s.isSelectionField)a.push(H.identifier(s.fieldAlias));else if(lt(s,Ft.Aliased)||lt(s,Ft)){const l=lt(s,Ft.Aliased)?s.sql:s;e?a.push(new Ft(l.queryChunks.map(u=>lt(u,Ar)?H.identifier(this.casing.getColumnCasing(u)):u))):a.push(l),lt(s,Ft.Aliased)&&a.push(H` as ${H.identifier(s.fieldAlias)}`)}else lt(s,Ke)&&(e?a.push(H.identifier(this.casing.getColumnCasing(s))):a.push(s));return oa==null?void 0:a.some(({alias:M})=>M===(it[Tt.Symbol.IsAlias]?qn(it):it[Tt.Symbol.BaseName])))(w.field.table)){const it=qn(w.field.table);throw new Error(`Your "${w.path.join("->")}" field references a column "${it}"."${w.field.name}", but the table "${it}" is not part of the query! Did you forget to join it?`)}const d=!a||a.length===0,m=this.buildWithCTE(t);let _;f&&(_=f===!0?H` distinct`:H` distinct on (${H.join(f.on,H`, `)})`);const S=this.buildSelection(g,{isSingleTable:d}),E=this.buildFromTable(o),b=this.buildJoins(a),F=n?H` where ${n}`:void 0,x=s?H` having ${s}`:void 0;let z;l&&l.length>0&&(z=H` order by ${H.join(l,H`, `)}`);let B;u&&u.length>0&&(B=H` group by ${H.join(u,H`, `)}`);const tt=typeof c=="object"||typeof c=="number"&&c>=0?H` limit ${c}`:void 0,st=h?H` offset ${h}`:void 0,I=H.empty();if(p){const w=H` for ${H.raw(p.strength)}`;p.config.of&&w.append(H` of ${H.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],H`, `)}`),p.config.noWait?w.append(H` nowait`):p.config.skipLocked&&w.append(H` skip locked`),I.append(w)}const Z=H`${m}select${_} ${S} from ${E}${b}${F}${B}${x}${z}${tt}${st}${I}`;return y.length>0?this.buildSetOperations(Z,y):Z}buildSetOperations(t,e){const[i,...n]=e;if(!i)throw new Error("Cannot pass undefined values to any set operator");return n.length===0?this.buildSetOperationQuery({leftSelect:t,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:t,setOperator:i}),n)}buildSetOperationQuery({leftSelect:t,setOperator:{type:e,isAll:i,rightSelect:n,limit:s,orderBy:o,offset:a}}){const l=H`(${t.getSQL()}) `,u=H`(${n.getSQL()})`;let c;if(o&&o.length>0){const y=[];for(const g of o)if(lt(g,Ar))y.push(H.identifier(g.name));else if(lt(g,Ft)){for(let d=0;d=0?H` limit ${s}`:void 0,p=H.raw(`${e} ${i?"all ":""}`),f=a?H` offset ${a}`:void 0;return H`${l}${p}${u}${c}${h}${f}`}buildInsertQuery({table:t,values:e,onConflict:i,returning:n,withList:s,select:o,overridingSystemValue_:a}){const l=[],u=t[Tt.Symbol.Columns],c=Object.entries(u).filter(([m,_])=>!_.shouldDisableInsert()),h=c.map(([,m])=>H.identifier(this.casing.getColumnCasing(m)));if(o){const m=e;lt(m,Ft)?l.push(m):l.push(m.getSQL())}else{const m=e;l.push(H.raw("values "));for(const[_,S]of m.entries()){const E=[];for(const[b,F]of c){const x=S[b];if(x===void 0||lt(x,Wi)&&x.value===void 0)if(F.defaultFn!==void 0){const z=F.defaultFn(),B=lt(z,Ft)?z:H.param(z,F);E.push(B)}else if(!F.default&&F.onUpdateFn!==void 0){const z=F.onUpdateFn(),B=lt(z,Ft)?z:H.param(z,F);E.push(B)}else E.push(H`default`);else E.push(x)}l.push(E),_({dbKey:S.name,tsKey:_,field:Li(S,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const m=Object.fromEntries(Object.entries(s.columns).map(([x,z])=>[x,Li(z,a)]));if(o.where){const x=typeof o.where=="function"?o.where(m,tR()):o.where;y=x&&$l(x,a)}const _=[];let S=[];if(o.columns){let x=!1;for(const[z,B]of Object.entries(o.columns))B!==void 0&&z in s.columns&&(!x&&B===!0&&(x=!0),S.push(z));S.length>0&&(S=x?S.filter(z=>{var B;return((B=o.columns)==null?void 0:B[z])===!0}):Object.keys(s.columns).filter(z=>!S.includes(z)))}else S=Object.keys(s.columns);for(const x of S){const z=s.columns[x];_.push({tsKey:x,value:z})}let E=[];o.with&&(E=Object.entries(o.with).filter(x=>!!x[1]).map(([x,z])=>({tsKey:x,queryConfig:z,relation:s.relations[x]})));let b;if(o.extras){b=typeof o.extras=="function"?o.extras(m,{sql:H}):o.extras;for(const[x,z]of Object.entries(b))_.push({tsKey:x,value:mw(z,a)})}for(const{tsKey:x,value:z}of _)c.push({dbKey:lt(z,Ft.Aliased)?z.fieldAlias:s.columns[x].name,tsKey:x,field:lt(z,Ke)?Li(z,a):z,relationTableTsKey:void 0,isJson:!1,selection:[]});let F=typeof o.orderBy=="function"?o.orderBy(m,eR()):o.orderBy??[];Array.isArray(F)||(F=[F]),f=F.map(x=>lt(x,Ke)?Li(x,a):$l(x,a)),h=o.limit,p=o.offset;for(const{tsKey:x,queryConfig:z,relation:B}of E){const tt=sR(e,i,B),st=ia(B.referencedTable),I=i[st],Z=`${a}_${x}`,w=Eh(...tt.fields.map((O,D)=>Mw(Li(tt.references[D],Z),Li(O,a)))),it=this.buildRelationalQueryWithoutPK({fullSchema:t,schema:e,tableNamesMap:i,table:t[I],tableConfig:e[I],queryConfig:lt(B,as)?z===!0?{limit:1}:{...z,limit:1}:z,tableAlias:Z,joinOn:w,nestedQueryRelation:B}),M=H`${H.identifier(Z)}.${H.identifier("data")}`.as(x);g.push({on:H`true`,table:new Or(it.sql,{},Z),alias:Z,joinType:"left",lateral:!0}),c.push({dbKey:x,tsKey:x,field:M,relationTableTsKey:I,isJson:!0,selection:it.selection})}}if(c.length===0)throw new $f({message:`No fields selected for table "${s.tsName}" ("${a}")`});let d;if(y=Eh(u,y),l){let m=H`json_build_array(${H.join(c.map(({field:E,tsKey:b,isJson:F})=>F?H`${H.identifier(`${a}_${b}`)}.${H.identifier("data")}`:lt(E,Ft.Aliased)?E.sql:E),H`, `)})`;lt(l,Vl)&&(m=H`coalesce(json_agg(${m}${f.length>0?H` order by ${H.join(f,H`, `)}`:void 0}), '[]'::json)`);const _=[{dbKey:"data",tsKey:"data",field:m.as("data"),isJson:!0,relationTableTsKey:s.tsName,selection:c}];h!==void 0||p!==void 0||f.length>0?(d=this.buildSelectQuery({table:ac(n,a),fields:{},fieldsFlat:[{path:[],field:H.raw("*")}],where:y,limit:h,offset:p,orderBy:f,setOperators:[]}),y=void 0,h=void 0,p=void 0,f=[]):d=ac(n,a),d=this.buildSelectQuery({table:lt(d,Br)?d:new Or(d,{},a),fields:{},fieldsFlat:_.map(({field:E})=>({path:[],field:lt(E,Ke)?Li(E,a):E})),joins:g,where:y,limit:h,offset:p,orderBy:f,setOperators:[]})}else d=this.buildSelectQuery({table:ac(n,a),fields:{},fieldsFlat:c.map(({field:m})=>({path:[],field:lt(m,Ke)?Li(m,a):m})),joins:g,where:y,limit:h,offset:p,orderBy:f,setOperators:[]});return{tableTsKey:s.tsName,sql:d,selection:c}}}$(Bo,Ky,"PgDialect");var Zy;Zy=xt;class Nw{getSelectedFields(){return this._.selectedFields}}$(Nw,Zy,"TypedQueryBuilder");var Jy;Jy=xt;class Sr{constructor(t){$(this,"fields");$(this,"session");$(this,"dialect");$(this,"withList",[]);$(this,"distinct");$(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,i=t;let n;return this.fields?n=this.fields:lt(i,Or)?n=Object.fromEntries(Object.keys(i._.selectedFields).map(s=>[s,i[s]])):lt(i,Wf)?n=i[He].selectedFields:lt(i,Ft)?n={}:n=PD(i),new Hf({table:i,fields:n,isPartialSelect:e,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}}$(Sr,Jy,"PgSelectBuilder");var tg,eg;class Lw extends(eg=Nw,tg=xt,eg){constructor({table:e,fields:i,isPartialSelect:n,session:s,dialect:o,withList:a,distinct:l}){super();$(this,"_");$(this,"config");$(this,"joinsNotNullableMap");$(this,"tableName");$(this,"isPartialSelect");$(this,"session");$(this,"dialect");$(this,"leftJoin",this.createJoin("left",!1));$(this,"leftJoinLateral",this.createJoin("left",!0));$(this,"rightJoin",this.createJoin("right",!1));$(this,"innerJoin",this.createJoin("inner",!1));$(this,"innerJoinLateral",this.createJoin("inner",!0));$(this,"fullJoin",this.createJoin("full",!1));$(this,"crossJoin",this.createJoin("cross",!1));$(this,"crossJoinLateral",this.createJoin("cross",!0));$(this,"union",this.createSetOperator("union",!1));$(this,"unionAll",this.createSetOperator("union",!0));$(this,"intersect",this.createSetOperator("intersect",!1));$(this,"intersectAll",this.createSetOperator("intersect",!0));$(this,"except",this.createSetOperator("except",!1));$(this,"exceptAll",this.createSetOperator("except",!0));this.config={withList:a,table:e,fields:{...i},distinct:l,setOperators:[]},this.isPartialSelect=n,this.session=s,this.dialect=o,this._={selectedFields:i},this.tableName=Wn(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}createJoin(e,i){return(n,s)=>{var l;const o=this.tableName,a=Wn(n);if(typeof a=="string"&&((l=this.config.joins)!=null&&l.some(u=>u.alias===a)))throw new Error(`Alias "${a}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof o=="string"&&(this.config.fields={[o]:this.config.fields}),typeof a=="string"&&!lt(n,Ft))){const u=lt(n,Or)?n._.selectedFields:lt(n,Sn)?n[He].selectedFields:n[Tt.Symbol.Columns];this.config.fields[a]=u}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:n,joinType:e,alias:a,lateral:i}),typeof a=="string")switch(e){case"left":{this.joinsNotNullableMap[a]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([u])=>[u,!1])),this.joinsNotNullableMap[a]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[a]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([u])=>[u,!1])),this.joinsNotNullableMap[a]=!1;break}}return this}}createSetOperator(e,i){return n=>{const s=typeof n=="function"?n(cR()):n;if(!Vf(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:i,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 Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){const i=e[0](new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(i)?i:[i]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){const i=e[0](new Proxy(this.config.fields,new Je({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),n=Array.isArray(i)?i:[i];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{const i=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}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,i={}){return this.config.lockingClause={strength:e,config:i},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}as(e){return new Proxy(new Or(this.getSQL(),this.config.fields,e),new Je({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Je({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}$(Lw,tg,"PgSelectQueryBuilder");var rg,ig;class Hf extends(ig=Lw,rg=xt,ig){constructor(){super(...arguments);$(this,"authToken");$(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)))}_prepare(e){const{session:i,config:n,dialect:s,joinsNotNullableMap:o,authToken:a}=this;if(!i)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Pr.startActiveSpan("drizzle.prepareQuery",()=>{const l=os(n.fields),u=i.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}}$(Hf,rg,"PgSelect");FD(Hf,[Tn]);function oo(r,t){return(e,i,...n)=>{const s=[i,...n].map(o=>({type:r,isAll:t,rightSelect:o}));for(const o of s)if(!Vf(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 cR=()=>({union:hR,unionAll:fR,intersect:dR,intersectAll:pR,except:mR,exceptAll:yR}),hR=oo("union",!1),fR=oo("union",!0),dR=oo("intersect",!1),pR=oo("intersect",!0),mR=oo("except",!1),yR=oo("except",!0);var ng;ng=xt;class Xf{constructor(t){$(this,"dialect");$(this,"dialectConfig");$(this,"$with",(t,e)=>{const i=this;return{as:s=>(typeof s=="function"&&(s=s(i)),new Proxy(new jf(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new Je({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});this.dialect=lt(t,Bo)?t:void 0,this.dialectConfig=lt(t,Bo)?void 0:t}with(...t){const e=this;function i(o){return new Sr({fields:o??void 0,session:void 0,dialect:e.getDialect(),withList:t})}function n(o){return new Sr({fields:o??void 0,session:void 0,dialect:e.getDialect(),distinct:!0})}function s(o,a){return new Sr({fields:a??void 0,session:void 0,dialect:e.getDialect(),distinct:{on:o}})}return{select:i,selectDistinct:n,selectDistinctOn:s}}select(t){return new Sr({fields:t??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(t){return new Sr({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(t,e){return new Sr({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:t}})}getDialect(){return this.dialect||(this.dialect=new Bo(this.dialectConfig)),this.dialect}}$(Xf,ng,"PgQueryBuilder");var sg;sg=xt;class Oh{constructor(t,e,i,n,s){$(this,"authToken");this.table=t,this.session=e,this.dialect=i,this.withList=n,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(i=>{const n={},s=this.table[Tt.Symbol.Columns];for(const o of Object.keys(i)){const a=i[o];n[o]=lt(a,Ft)?a:new Wi(a,s[o])}return n});return new Fh(this.table,e,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(t){const e=typeof t=="function"?t(new Xf):t;if(!lt(e,Ft)&&!Vf(this.table[Ih],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 Fh(this.table,e,this.session,this.dialect,this.withList,!0)}}$(Oh,sg,"PgInsertBuilder");var og,ag;class Fh extends(ag=Tn,og=xt,ag){constructor(e,i,n,s,o,a,l){super();$(this,"config");$(this,"authToken");$(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=n,this.dialect=s,this.config={table:e,values:i,withList:o,select:a,overridingSystemValue_:l}}returning(e=this.config.table[Tt.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=os(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=H`do nothing`;else{let i="";i=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 n=e.where?H` where ${e.where}`:void 0;this.config.onConflict=H`(${H.raw(i)})${n} 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 i=e.where?H` where ${e.where}`:void 0,n=e.targetWhere?H` where ${e.targetWhere}`:void 0,s=e.setWhere?H` where ${e.setWhere}`:void 0,o=this.dialect.buildUpdateSet(this.config.table,bw(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=H`(${H.raw(a)})${n} do update set ${o}${i}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){return Pr.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 Je({alias:qn(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}$(Fh,og,"PgInsert");var lg,ug;class Bw extends(ug=Tn,lg=xt,ug){constructor(e,i,n){super();$(this,"config");$(this,"authToken");$(this,"execute",e=>Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken)));this.session=i,this.dialect=n,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,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){return Pr.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}}$(Bw,lg,"PgRefreshMaterializedView");var cg;cg=xt;class Ph{constructor(t,e,i,n){$(this,"authToken");this.table=t,this.session=e,this.dialect=i,this.withList=n}setToken(t){return this.authToken=t,this}set(t){return new kw(this.table,bw(this.table,t),this.session,this.dialect,this.withList).setToken(this.authToken)}}$(Ph,cg,"PgUpdateBuilder");var hg,fg;class kw extends(fg=Tn,hg=xt,fg){constructor(e,i,n,s,o){super();$(this,"config");$(this,"tableName");$(this,"joinsNotNullableMap");$(this,"leftJoin",this.createJoin("left"));$(this,"rightJoin",this.createJoin("right"));$(this,"innerJoin",this.createJoin("inner"));$(this,"fullJoin",this.createJoin("full"));$(this,"authToken");$(this,"execute",e=>this._prepare().execute(e,this.authToken));this.session=n,this.dialect=s,this.config={set:i,table:e,withList:o,joins:[]},this.tableName=Wn(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}from(e){const i=e,n=Wn(i);return typeof n=="string"&&(this.joinsNotNullableMap[n]=!0),this.config.from=i,this}getTableLikeFields(e){return lt(e,Br)?e[Tt.Symbol.Columns]:lt(e,Or)?e._.selectedFields:e[He].selectedFields}createJoin(e){return(i,n)=>{const s=Wn(i);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 n=="function"){const o=this.config.from&&!lt(this.config.from,Ft)?this.getTableLikeFields(this.config.from):void 0;n=n(new Proxy(this.config.table[Tt.Symbol.Columns],new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),o&&new Proxy(o,new Je({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:n,table:i,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 i=Wn(this.config.from);if(typeof i=="string"&&this.config.from&&!lt(this.config.from,Ft)){const n=this.getTableLikeFields(this.config.from);e[i]=n}for(const n of this.config.joins){const s=Wn(n.table);if(typeof s=="string"&&!lt(n.table,Ft)){const o=this.getTableLikeFields(n.table);e[s]=o}}}return this.config.returningFields=e,this.config.returning=os(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:e,...i}=this.dialect.sqlToQuery(this.getSQL());return i}_prepare(e){const i=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}prepare(e){return this._prepare(e)}setToken(e){return this.authToken=e,this}getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new Je({alias:qn(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}}$(kw,hg,"PgUpdate");var dg,pg,mg;const Uo=class Uo extends(mg=Ft,pg=xt,dg=Symbol.toStringTag,mg){constructor(e){super(Uo.buildEmbeddedCount(e.source,e.filters).queryChunks);$(this,"sql");$(this,"token");$(this,dg,"PgCountBuilder");$(this,"session");this.params=e,this.mapWith(Number),this.session=e.session,this.sql=Uo.buildCount(e.source,e.filters)}static buildEmbeddedCount(e,i){return H`(select count(*) from ${e}${H.raw(" where ").if(i)}${i})`}static buildCount(e,i){return H`select count(*) as count from ${e}${H.raw(" where ").if(i)}${i};`}setToken(e){return this.token=e,this}then(e,i){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,i)}catch(e){return this.then(void 0,e)}finally(e){return this.then(i=>(e==null||e(),i),i=>{throw e==null||e(),i})}};$(Uo,pg,"PgCountBuilder");let Mh=Uo;var yg;yg=xt;class Uw{constructor(t,e,i,n,s,o,a){this.fullSchema=t,this.schema=e,this.tableNamesMap=i,this.table=n,this.tableConfig=s,this.dialect=o,this.session=a}findMany(t){return new Dh(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t||{},"many")}findFirst(t){return new Dh(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,t?{...t,limit:1}:{limit:1},"first")}}$(Uw,yg,"PgRelationalQueryBuilder");var gg,vg;class Dh extends(vg=Tn,gg=xt,vg){constructor(e,i,n,s,o,a,l,u,c){super();$(this,"authToken");this.fullSchema=e,this.schema=i,this.tableNamesMap=n,this.table=s,this.tableConfig=o,this.dialect=a,this.session=l,this.config=u,this.mode=c}_prepare(e){return Pr.startActiveSpan("drizzle.prepareQuery",()=>{const{query:i,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(s,o)=>{const a=s.map(l=>Ch(this.schema,this.tableConfig,l,i.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(),i=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:i}}toSQL(){return this._toSQL().builtQuery}setToken(e){return this.authToken=e,this}execute(){return Pr.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}}$(Dh,gg,"PgRelationalQuery");var _g,bg;class zw extends(bg=Tn,_g=xt,bg){constructor(t,e,i,n){super(),this.execute=t,this.sql=e,this.query=i,this.mapBatchResult=n}getSQL(){return this.sql}getQuery(){return this.query}mapResult(t,e){return e?this.mapBatchResult(t):t}_prepare(){return this}isResponseInArrayMode(){return!1}}$(zw,_g,"PgRaw");var wg;wg=xt;class Yf{constructor(t,e,i){$(this,"query");$(this,"$with",(t,e)=>{const i=this;return{as:s=>(typeof s=="function"&&(s=s(new Xf(i.dialect))),new Proxy(new jf(s.getSQL(),e??("getSelectedFields"in s?s.getSelectedFields()??{}:{}),t,!0),new Je({alias:t,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}});$(this,"authToken");if(this.dialect=t,this.session=e,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap,session:e}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:e},this.query={},this._.schema)for(const[n,s]of Object.entries(this._.schema))this.query[n]=new Uw(i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[n],s,t,e)}$count(t,e){return new Mh({source:t,filters:e,session:this.session})}with(...t){const e=this;function i(u){return new Sr({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t})}function n(u){return new Sr({fields:u??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:!0})}function s(u,c){return new Sr({fields:c??void 0,session:e.session,dialect:e.dialect,withList:t,distinct:{on:u}})}function o(u){return new Ph(u,e.session,e.dialect,t)}function a(u){return new Oh(u,e.session,e.dialect,t)}function l(u){return new Ah(u,e.session,e.dialect,t)}return{select:i,selectDistinct:n,selectDistinctOn:s,update:o,insert:a,delete:l}}select(t){return new Sr({fields:t??void 0,session:this.session,dialect:this.dialect})}selectDistinct(t){return new Sr({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(t,e){return new Sr({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:{on:t}})}update(t){return new Ph(t,this.session,this.dialect)}insert(t){return new Oh(t,this.session,this.dialect)}delete(t){return new Ah(t,this.session,this.dialect)}refreshMaterializedView(t){return new Bw(t,this.session,this.dialect)}execute(t){const e=typeof t=="string"?H.raw(t):t.getSQL(),i=this.dialect.sqlToQuery(e),n=this.session.prepareQuery(i,void 0,void 0,!1);return new zw(()=>n.execute(void 0,this.authToken),e,i,s=>n.mapResult(s,!0))}transaction(t,e){return this.session.transaction(t,e)}}$(Yf,wg,"PgDatabase");var xg;xg=xt;class jw{constructor(t){$(this,"authToken");$(this,"joinsNotNullableMap");this.query=t}getQuery(){return this.query}mapResult(t,e){return t}setToken(t){return this.authToken=t,this}}$(jw,xg,"PgPreparedQuery");var Sg;Sg=xt;class $w{constructor(t){this.dialect=t}execute(t,e){return Pr.startActiveSpan("drizzle.operation",()=>Pr.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 i=await this.execute(t,e);return Number(i[0].count)}}$($w,Sg,"PgSession");var Tg,Ig;class Vw extends(Ig=Yf,Tg=xt,Ig){constructor(t,e,i,n=0){super(t,e,i),this.schema=i,this.nestedIndex=n}rollback(){throw new yw}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"),H.raw(e.join(" "))}setTransaction(t){return this.session.execute(H`set transaction ${this.getTransactionConfigSQL(t)}`)}}$(Vw,Tg,"PgTransaction");function Om(r){return typeof r=="string"&&/^true$/i.test(r)}function gR(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 i=e.searchParams.get("logger");i&&Om(i)&&(t.logger=!0);const n=e.searchParams.get("storage");switch(n){case ra.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:ra.ORIGIN_PRIVATE_FS,path:e.pathname.startsWith("/")?e.pathname.slice(1):e.pathname,...s&&Om(s)&&{accessMode:T0.READ_WRITE}};break}case null:break;default:console.warn(`Unknown storage type "${n}"`);break}return t}var Eg,Cg;class Gw extends(Cg=jw,Eg=xt,Cg){constructor(t,e,i,n,s,o){super({sql:e,params:i}),this.client=t,this.queryString=e,this.params=i,this.logger=n,this.fields=s,this.customResultMapper=o}async execute(t={}){const e=Em(this.params,t);this.logger.logQuery(this.queryString,e);const{fields:i,queryString:n,client:s,customResultMapper:o}=this,a=await s;return a.query(n,e)}async all(t={}){const e=Em(this.params,t);return this.logger.logQuery(this.queryString,e),(await this.client).query(this.queryString,e)}}$(Gw,Eg,"DuckDBWasmPreparedQuery");var Ag,Og;const Yl=class Yl extends(Og=$w,Ag=xt,Og){constructor(e,i,n,s={}){super(i);$(this,"logger");this.client=e,this.schema=n,this.options=s,this.logger=s.logger??new _w}prepareQuery(e,i,n,s,o){return new Gw(this.client,e.sql,e.params,this.logger,i,o)}async query(e,i){return this.logger.logQuery(e,i),(await this.client).query(e,i)}async queryObjects(e,i){return this.logger.logQuery(e,i),(await this.client).query(e,i)}transaction(e,i){return xD(this.client,async n=>{const s=new Yl(n,this.dialect,this.schema,this.options),o=new Rh(this.dialect,s,this.schema);return i&&await o.setTransaction(i),e(o)})}};$(Yl,Ag,"DuckDBWasmSession");let Gl=Yl;var Fg,Pg;const ql=class ql extends(Pg=Vw,Fg=xt,Pg){constructor(e,i,n,s=0){super(e,i,n,s);$(this,"dialect");$(this,"session");this.dialect=e,this.session=i}async transaction(e){return SD(this.session.client,"",async i=>{const n=new Gl(i,this.dialect,this.schema,this.session.options),s=new ql(this.dialect,n,this.schema);return e(s)})}};$(ql,Fg,"DuckDBWasmTransaction");let Rh=ql;var Mg,Dg;class Ww extends(Dg=Yf,Mg=xt,Dg){}$(Ww,Mg,"DuckDBWasmDatabase");function ko(r,t={}){const e=new Bo({casing:t.casing});let i;t.logger===!0?i=new vw:t.logger!==!1&&(i=t.logger);let n;if(t.schema){const a=rR(t.schema,oR);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}const s=new Gl(r,e,n,{logger:i}),o=new Ww(e,s,n);return o.$client=r,o}function Fm(r,t){const e=gR(r);let i;return e.bundles==="import-url"?i=(async()=>{const s=await Sh();switch(s){case"browser":return(await ln(async()=>{const{getImportUrlBundles:o}=await import("./import-url-browser-CPN8ipMD.js");return{getImportUrlBundles:o}},__vite__mapDeps([3,4]))).getImportUrlBundles();case"node":return await(await ln(async()=>{const{getImportUrlBundles:o}=await import("./import-url-node-BfNoxhRr.js");return{getImportUrlBundles:o}},__vite__mapDeps([5,4]))).getImportUrlBundles();default:throw new Error(`Unsupported environment: "${s}"`)}})():i=(async()=>{const s=await Sh();switch(s){case"browser":return(await ln(async()=>{const{getBundles:o}=await import("./default-browser-BrgSDbLD.js");return{getBundles:o}},[])).getBundles();case"node":return await(await ln(async()=>{const{getBundles:o}=await import("./default-node-DAs8YCRC.js");return{getBundles:o}},__vite__mapDeps([0,1,2]))).getBundles();default:throw new Error(`Unsupported environment: "${s}"`)}})(),ko(hw({bundles:i,logger:e.logger?new I0:void 0,storage:e.storage}),t)}function Pm(...r){if(typeof r[0]=="string")return Fm(r[0],r[1]);if(MD(r[0])){const{connection:t,client:e,...i}=r[0];if(e)return ko(e,i);if(typeof t=="string")return Fm(t,i);if(typeof t>"u")throw new Error("connection option is required");return ko(hw({bundles:t.bundles,logger:t.logger,storage:t.storage}),i)}return ko(r[0],r[1])}(r=>{function t(e){return ko({options:{parsers:{},serializers:{}}},e)}r.mock=t})(Pm||(Pm={}));export{L1 as A,TR as D,xR as I,pC as J,eI as L,_c as M,wR as T,fi as a,Re as b,Pm as d,sa as e,SR as l}; diff --git a/assets/Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js b/assets/Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js similarity index 75% rename from assets/Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js rename to assets/Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js index a7c591f30a6823214f2436171ec798ff7fea09cd..28c3c55e9e45f5421f1a49d574d9ac3603bb8909 100644 --- a/assets/Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js +++ b/assets/Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js @@ -1 +1 @@ -import{_ as r}from"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";import{d as u,u as t,A as d,o as n}from"./index-BQKiy4UR.js";const p=u({__name:"Textarea",props:{modelValue:{default:""},modelModifiers:{}},emits:["update:modelValue"],setup(l){const e=t(l,"modelValue");return(s,a)=>(n(),d(r,{modelValue:e.value,"onUpdate:modelValue":a[0]||(a[0]=o=>e.value=o),border:"focus:primary-300 dark:focus:primary-400/50 2 solid neutral-100 dark:neutral-900",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-sm":"","outline-none":"",shadow:"sm",bg:"neutral-50 dark:neutral-950 focus:neutral-50 dark:focus:neutral-900"},null,8,["modelValue"]))}});export{p as _}; +import{_ as r}from"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";import{d as u,u as t,A as d,o as n}from"./index-CQudhZin.js";const p=u({__name:"Textarea",props:{modelValue:{default:""},modelModifiers:{}},emits:["update:modelValue"],setup(l){const e=t(l,"modelValue");return(s,a)=>(n(),d(r,{modelValue:e.value,"onUpdate:modelValue":a[0]||(a[0]=o=>e.value=o),border:"focus:primary-300 dark:focus:primary-400/50 2 solid neutral-100 dark:neutral-900",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-sm":"","outline-none":"",shadow:"sm",bg:"neutral-50 dark:neutral-950 focus:neutral-50 dark:focus:neutral-900"},null,8,["modelValue"]))}});export{p as _}; diff --git a/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js b/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js similarity index 93% rename from assets/TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js rename to assets/TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js index 578ca9eef7aee954bab37061a3a85a0d11f040b4..48bc1abe29bdf21ec272050581cecf4c499563aa 100644 --- a/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js +++ b/assets/TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js @@ -1 +1 @@ -import{d as T,A as l,o as m,T as B,w as b,f as v}from"./index-BQKiy4UR.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,A as l,o as m,T as B,w as b,f as v}from"./index-CQudhZin.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_-CkQbMceU.js b/assets/_...all_-P27fyW0_.js similarity index 64% rename from assets/_...all_-CkQbMceU.js rename to assets/_...all_-P27fyW0_.js index 32b3db5fc7afcbb5caef730ccc644b85341ce470..e776555a99548dc61ce62c5340989f3e7b530af6 100644 --- a/assets/_...all_-CkQbMceU.js +++ b/assets/_...all_-P27fyW0_.js @@ -1 +1 @@ -import{_ as e,c as _,o as c}from"./index-BQKiy4UR.js";const n={};function o(t,r){return c(),_("div",null," 404 - Page not found ")}const s=e(n,[["render",o]]);export{s as default}; +import{_ as e,c as _,o as c}from"./index-CQudhZin.js";const n={};function o(t,r){return c(),_("div",null," 404 - Page not found ")}const s=e(n,[["render",o]]);export{s as default}; diff --git a/assets/airi-card-BqSQR9SZ.js b/assets/airi-card-Bpd1towy.js similarity index 94% rename from assets/airi-card-BqSQR9SZ.js rename to assets/airi-card-Bpd1towy.js index ba1143aed14216da250aa01a022aee8d2ff04c4c..5766b0e10c711b719244b89af8acbad3447bf441 100644 --- a/assets/airi-card-BqSQR9SZ.js +++ b/assets/airi-card-Bpd1towy.js @@ -1,4 +1,4 @@ -import{p as W,q as L,h as g,s as O,H as $,g as q,v as D}from"./index-BQKiy4UR.js";import{E as G}from"./mini_xsschema-P_8cZcRg.js";import{u as N}from"./consciousness-DS3QILRV.js";import{u as b}from"./speech-Db_L6FBm.js";function k(a,u){return{role:"system",content:[a,G.map(n=>`- ${n}`).join(` +import{p as W,q as L,h as g,s as O,H as $,g as q,v as D}from"./index-CQudhZin.js";import{E as G}from"./mini_xsschema-P_8cZcRg.js";import{u as N}from"./consciousness-BmgC4h1A.js";import{u as b}from"./speech-nVAae-rt.js";function k(a,u){return{role:"system",content:[a,G.map(n=>`- ${n}`).join(` `),u].join(` `)}}const Q=W("airi-card",()=>{const a=L("airi-cards",new Map),u=L("airi-card-active-id","default"),n=g(()=>a.value.get(u.value)),P=N(),R=b(),{activeModel:l}=O(P),{activeSpeechVoiceId:m,activeSpeechModel:p}=O(R),B=s=>{const e=crypto.randomUUID();return a.value.set(e,h(s)),e},H=s=>{a.value.delete(s)},V=s=>a.value.get(s);function v(s){var t,r,i,c,d,f,_,y,S,x,C,M,I,E,w,A,T,U,j;const e="data"in s?(r=(t=s.data)==null?void 0:t.extensions)==null?void 0:r.airi:(i=s.extensions)==null?void 0:i.airi,o={consciousness:{model:l.value},speech:{model:p.value,voice_id:m.value}};return e?{modules:{consciousness:{model:((d=(c=e.modules)==null?void 0:c.consciousness)==null?void 0:d.model)??o.consciousness.model},speech:{model:((_=(f=e.modules)==null?void 0:f.speech)==null?void 0:_.model)??o.speech.model,voice_id:((S=(y=e.modules)==null?void 0:y.speech)==null?void 0:S.voice_id)??o.speech.voice_id,pitch:(C=(x=e.modules)==null?void 0:x.speech)==null?void 0:C.pitch,rate:(I=(M=e.modules)==null?void 0:M.speech)==null?void 0:I.rate,ssml:(w=(E=e.modules)==null?void 0:E.speech)==null?void 0:w.ssml,language:(T=(A=e.modules)==null?void 0:A.speech)==null?void 0:T.language},vrm:(U=e.modules)==null?void 0:U.vrm,live2d:(j=e.modules)==null?void 0:j.live2d},agents:e.agents??{}}:{modules:o,agents:{}}}function h(s){if("data"in s){const e=s;return{name:e.data.name,version:e.data.character_version??"1.0.0",description:e.data.description??"",creator:e.data.creator??"",notes:e.data.creator_notes??"",notesMultilingual:e.data.creator_notes_multilingual,personality:e.data.personality??"",scenario:e.data.scenario??"",greetings:[e.data.first_mes,...e.data.alternate_greetings??[]],greetingsGroupOnly:e.data.group_only_greetings??[],systemPrompt:e.data.system_prompt??"",postHistoryInstructions:e.data.post_history_instructions??"",messageExample:e.data.mes_example?e.data.mes_example.split(` diff --git a/assets/alibaba-cloud-model-studio-8BnjUB5R.js b/assets/alibaba-cloud-model-studio-BjeIv5w8.js similarity index 69% rename from assets/alibaba-cloud-model-studio-8BnjUB5R.js rename to assets/alibaba-cloud-model-studio-BjeIv5w8.js index 291c4bc34eaeae0bddcb7830fc5de4f1aecded01..4c8f8df37653b9c24c189bdb53a12a64da787eea 100644 --- a/assets/alibaba-cloud-model-studio-8BnjUB5R.js +++ b/assets/alibaba-cloud-model-studio-BjeIv5w8.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as x,r as m,s as k,g as F,h as V,H as $,v,A as B,o as I,w as h,i as c,b as i,e as U}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as E}from"./providers-kjOpfeNb.js";import{u as H}from"./speech-Db_L6FBm.js";import{_ as f}from"./FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as K,a as L}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js";import{b as y}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";const N={flex:"~ col gap-4"},o="alibaba-cloud-model-studio",P="cosyvoice-v1",T=x({__name:"alibaba-cloud-model-studio",setup(z){const u={speed:1},d=m(0),l=m(1),n=m(0),p=H(),r=E(),{providers:g}=k(r),{t:s}=F(),_=V(()=>{var e;return!!((e=g.value[o])!=null&&e.apiKey)}),w=V(()=>p.availableVoices[o]||[]);async function M(e,t,a){const b=r.getProviderInstance(o);if(!b)throw new Error("Failed to initialize speech provider");const C=r.getProviderConfig(o),S=C.model||P;return await p.speech(b,S,e,t,{...C,...u})}return $(async()=>{const e=r.getProviderConfig(o);await r.getProviderMetadata(o).validators.validateProviderConfig(e)?await p.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)}),v(d,async()=>{const e=r.getProviderConfig(o);e.pitch=d.value}),v(l,async()=>{const e=r.getProviderConfig(o);e.speed=l.value}),v(n,async()=>{const e=r.getProviderConfig(o);e.volume=n.value}),v(g,async()=>{const e=r.getProviderConfig(o);await r.getProviderMetadata(o).validators.validateProviderConfig(e)?await p.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)},{immediate:!0}),(e,t)=>(I(),B(i(L),{"provider-id":o,"default-model":P,"additional-settings":u},{"voice-settings":h(()=>[U("div",N,[c(i(f),{modelValue:d.value,"onUpdate:modelValue":t[0]||(t[0]=a=>d.value=a),label:i(s)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:i(s)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":a=>`${a}%`},null,8,["modelValue","label","description","format-value"]),c(i(f),{modelValue:l.value,"onUpdate:modelValue":t[1]||(t[1]=a=>l.value=a),label:i(s)("settings.pages.providers.provider.common.fields.field.speed.label"),description:i(s)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"]),c(i(f),{modelValue:n.value,"onUpdate:modelValue":t[2]||(t[2]=a=>n.value=a),label:i(s)("settings.pages.providers.provider.common.fields.field.volume.label"),description:i(s)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":a=>`${a}%`},null,8,["modelValue","label","description","format-value"])])]),playground:h(()=>[c(i(K),{"available-voices":w.value,"generate-speech":M,"api-key-configured":_.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof y=="function"&&y(T);export{T as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as x,r as m,s as k,g as F,h as V,H as $,v,A as B,o as I,w as h,i as c,b as i,e as U}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as E}from"./providers-Y3Mr8_DF.js";import{u as H}from"./speech-nVAae-rt.js";import{_ as f}from"./FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as K,a as L}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js";import{b as y}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";const N={flex:"~ col gap-4"},o="alibaba-cloud-model-studio",P="cosyvoice-v1",T=x({__name:"alibaba-cloud-model-studio",setup(z){const u={speed:1},d=m(0),l=m(1),n=m(0),p=H(),r=E(),{providers:g}=k(r),{t:s}=F(),_=V(()=>{var e;return!!((e=g.value[o])!=null&&e.apiKey)}),w=V(()=>p.availableVoices[o]||[]);async function M(e,t,a){const b=r.getProviderInstance(o);if(!b)throw new Error("Failed to initialize speech provider");const C=r.getProviderConfig(o),S=C.model||P;return await p.speech(b,S,e,t,{...C,...u})}return $(async()=>{const e=r.getProviderConfig(o);await r.getProviderMetadata(o).validators.validateProviderConfig(e)?await p.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)}),v(d,async()=>{const e=r.getProviderConfig(o);e.pitch=d.value}),v(l,async()=>{const e=r.getProviderConfig(o);e.speed=l.value}),v(n,async()=>{const e=r.getProviderConfig(o);e.volume=n.value}),v(g,async()=>{const e=r.getProviderConfig(o);await r.getProviderMetadata(o).validators.validateProviderConfig(e)?await p.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)},{immediate:!0}),(e,t)=>(I(),B(i(L),{"provider-id":o,"default-model":P,"additional-settings":u},{"voice-settings":h(()=>[U("div",N,[c(i(f),{modelValue:d.value,"onUpdate:modelValue":t[0]||(t[0]=a=>d.value=a),label:i(s)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:i(s)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":a=>`${a}%`},null,8,["modelValue","label","description","format-value"]),c(i(f),{modelValue:l.value,"onUpdate:modelValue":t[1]||(t[1]=a=>l.value=a),label:i(s)("settings.pages.providers.provider.common.fields.field.speed.label"),description:i(s)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"]),c(i(f),{modelValue:n.value,"onUpdate:modelValue":t[2]||(t[2]=a=>n.value=a),label:i(s)("settings.pages.providers.provider.common.fields.field.volume.label"),description:i(s)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":a=>`${a}%`},null,8,["modelValue","label","description","format-value"])])]),playground:h(()=>[c(i(K),{"available-voices":w.value,"generate-speech":M,"api-key-configured":_.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof y=="function"&&y(T);export{T as default}; diff --git a/assets/anthropic-DcMJ-RH8.js b/assets/anthropic-2GUn5SX-.js similarity index 74% rename from assets/anthropic-DcMJ-RH8.js rename to assets/anthropic-2GUn5SX-.js index 14faaf39da73b6ec5b959037d863dbcf257383f1..f5e07362506420037ba91bc529c881f34bca8518 100644 --- a/assets/anthropic-DcMJ-RH8.js +++ b/assets/anthropic-2GUn5SX-.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as S,g as x,S as U,s as w,h as v,H as V,v as C,A as K,o as R,w as c,e as i,i as l,k as p,b as a}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as A}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as O,a as $}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as I}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as N,a as B}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as T}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as g}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const e="anthropic",z=S({__name:"anthropic",setup(M){const{t:u}=x(),_=U(),h=A(),{providers:o}=w(h),m=v(()=>h.getProviderMetadata(e)),s=v({get:()=>{var t;return((t=o.value[e])==null?void 0:t.apiKey)||""},set:t=>{o.value[e]||(o.value[e]={}),o.value[e].apiKey=t}}),n=v({get:()=>{var t;return((t=o.value[e])==null?void 0:t.baseUrl)||"https://api.anthropic.com/v1/"},set:t=>{o.value[e]||(o.value[e]={}),o.value[e].baseUrl=t}});V(()=>{var t,r;o.value[e]||(o.value[e]={baseUrl:"https://api.anthropic.com/v1/"}),s.value=((t=o.value[e])==null?void 0:t.apiKey)||"",n.value=((r=o.value[e])==null?void 0:r.baseUrl)||"https://api.anthropic.com/v1/"}),C([s,n],()=>{o.value[e]={...o.value[e],apiKey:s.value,baseUrl:n.value||"https://api.anthropic.com/v1/"}});function y(){o.value[e]={baseUrl:"https://api.anthropic.com/v1/"}}return(t,r)=>{var f,b;return R(),K(a(T),{"provider-name":((f=m.value)==null?void 0:f.localizedName)||"Anthropic | Claude","provider-icon":(b=m.value)==null?void 0:b.icon,"on-back":()=>a(_).back()},{default:c(()=>[r[2]||(r[2]=i("div",{bg:"orange-50 dark:orange-900/20","rounded-xl":"","p-4":"",flex:"~ col gap-3"},[i("h2",{"text-xl":"","font-bold":"",text:"orange-700 dark:orange-500"}," Before you start "),i("p",null,[p(" While Anthropic recently did announce that they are having a beta support for OpenAI SDK compatibility "),i("a",{underline:"",href:"https://docs.anthropic.com/en/api/openai-sdk"},"(you can read more here)"),p(", but due to the implementation details comes with "),i("a",{underline:"",href:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS"},"CORS"),p(" restrictions which not aligned with the OpenAI SDK, it's currently not possible to use this provider in the browser. ")]),i("p",null,[p(" If you do need to use this provider, you will need a dedicated proxy backend like a Serverless Function running on "),i("a",{underline:"",href:"https://workers.cloudflare.com/"},"Cloudflare Workers"),p(" or some CORS bypassing services to bypass the CORS restrictions. ")])],-1)),l(a(N),null,{default:c(()=>[l(a(B),{title:a(u)("settings.pages.providers.common.section.basic.title"),description:a(u)("settings.pages.providers.common.section.basic.description"),"on-reset":y},{default:c(()=>{var d;return[l(a(I),{modelValue:s.value,"onUpdate:modelValue":r[0]||(r[0]=k=>s.value=k),"provider-name":((d=m.value)==null?void 0:d.localizedName)||"Anthropic",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(a(O),{title:a(u)("settings.pages.providers.common.section.advanced.title")},{default:c(()=>[l(a($),{modelValue:n.value,"onUpdate:modelValue":r[1]||(r[1]=d=>n.value=d),placeholder:"https://api.anthropic.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof g=="function"&&g(z);export{z as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as S,g as x,S as U,s as w,h as v,H as V,v as C,A as K,o as R,w as c,e as i,i as l,k as p,b as a}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as A}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as O,a as $}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as I}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as N,a as B}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as T}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as g}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const e="anthropic",z=S({__name:"anthropic",setup(M){const{t:u}=x(),_=U(),h=A(),{providers:o}=w(h),m=v(()=>h.getProviderMetadata(e)),s=v({get:()=>{var t;return((t=o.value[e])==null?void 0:t.apiKey)||""},set:t=>{o.value[e]||(o.value[e]={}),o.value[e].apiKey=t}}),n=v({get:()=>{var t;return((t=o.value[e])==null?void 0:t.baseUrl)||"https://api.anthropic.com/v1/"},set:t=>{o.value[e]||(o.value[e]={}),o.value[e].baseUrl=t}});V(()=>{var t,r;o.value[e]||(o.value[e]={baseUrl:"https://api.anthropic.com/v1/"}),s.value=((t=o.value[e])==null?void 0:t.apiKey)||"",n.value=((r=o.value[e])==null?void 0:r.baseUrl)||"https://api.anthropic.com/v1/"}),C([s,n],()=>{o.value[e]={...o.value[e],apiKey:s.value,baseUrl:n.value||"https://api.anthropic.com/v1/"}});function y(){o.value[e]={baseUrl:"https://api.anthropic.com/v1/"}}return(t,r)=>{var f,b;return R(),K(a(T),{"provider-name":((f=m.value)==null?void 0:f.localizedName)||"Anthropic | Claude","provider-icon":(b=m.value)==null?void 0:b.icon,"on-back":()=>a(_).back()},{default:c(()=>[r[2]||(r[2]=i("div",{bg:"orange-50 dark:orange-900/20","rounded-xl":"","p-4":"",flex:"~ col gap-3"},[i("h2",{"text-xl":"","font-bold":"",text:"orange-700 dark:orange-500"}," Before you start "),i("p",null,[p(" While Anthropic recently did announce that they are having a beta support for OpenAI SDK compatibility "),i("a",{underline:"",href:"https://docs.anthropic.com/en/api/openai-sdk"},"(you can read more here)"),p(", but due to the implementation details comes with "),i("a",{underline:"",href:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS"},"CORS"),p(" restrictions which not aligned with the OpenAI SDK, it's currently not possible to use this provider in the browser. ")]),i("p",null,[p(" If you do need to use this provider, you will need a dedicated proxy backend like a Serverless Function running on "),i("a",{underline:"",href:"https://workers.cloudflare.com/"},"Cloudflare Workers"),p(" or some CORS bypassing services to bypass the CORS restrictions. ")])],-1)),l(a(N),null,{default:c(()=>[l(a(B),{title:a(u)("settings.pages.providers.common.section.basic.title"),description:a(u)("settings.pages.providers.common.section.basic.description"),"on-reset":y},{default:c(()=>{var d;return[l(a(I),{modelValue:s.value,"onUpdate:modelValue":r[0]||(r[0]=k=>s.value=k),"provider-name":((d=m.value)==null?void 0:d.localizedName)||"Anthropic",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(a(O),{title:a(u)("settings.pages.providers.common.section.advanced.title")},{default:c(()=>[l(a($),{modelValue:n.value,"onUpdate:modelValue":r[1]||(r[1]=d=>n.value=d),placeholder:"https://api.anthropic.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof g=="function"&&g(z);export{z as default}; diff --git a/assets/audio-NB4UDUvk.js b/assets/audio-xRnZtF8v.js similarity index 88% rename from assets/audio-NB4UDUvk.js rename to assets/audio-xRnZtF8v.js index b45f885797885876cf8a8a975ef74b69eee4494a..5a424fecd503cfae9ff1c34c05be763ed1f8de7f 100644 --- a/assets/audio-NB4UDUvk.js +++ b/assets/audio-xRnZtF8v.js @@ -1 +1 @@ -import{d as s,r as f,c as d,o as p,e as t}from"./index-BQKiy4UR.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,r as f,c as d,o as p,e as t}from"./index-CQudhZin.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/background-remove-BBGqlHWm.js b/assets/background-remove-BBGqlHWm.js new file mode 100644 index 0000000000000000000000000000000000000000..d24f6ae70e2c53d53f0439c5581a03d11664d874 --- /dev/null +++ b/assets/background-remove-BBGqlHWm.js @@ -0,0 +1,2888 @@ +var _v=Object.defineProperty;var gv=(e,r,t)=>r in e?_v(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var Y=(e,r,t)=>gv(e,typeof r!="symbol"?r+"":r,t);import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as wv}from"./InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js";import{d as bv,r as zs,h as Mv,H as yv,c as Tn,o as En,e as Vr,i as vv,t as Ef,F as Pf,l as Cf,j as Sf,z as xv,b as Tv}from"./index-CQudhZin.js";import"./floating-ui.core-CgBsuaUc.js";const la=new Map,kn=[],Ev=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=la.get(e);if(s===void 0)la.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 o=kn.indexOf(e);o!==-1&&kn.splice(o,1);for(let n=0;n{const r=la.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}}},Cv=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?kn:t;let o;const n=[],i=new Set;for(const l of s){const u=await Pv(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},Sv="1.21.1";let $f="warning";const Ts={wasm:{},webgl:{},webgpu:{},versions:{common:Sv},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}`);$f=e}},get logLevel(){return $f}};Object.defineProperty(Ts,"logLevel",{enumerable:!0});const $v=Ts,kv=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let c=0,d=p,_=p*2,f=-1;i==="RGBA"?(c=0,d=p,_=p*2,f=p*3):i==="RGB"?(c=0,d=p,_=p*2):i==="RBG"&&(c=0,_=p,d=p*2);for(let v=0;v{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 c=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const d=4;let _=0,f=1,v=2,$=3,g=0,w=c,C=c*2,E=-1;a==="RGBA"?(g=0,w=c,C=c*2,E=c*3):a==="RGB"?(g=0,w=c,C=c*2):a==="RBG"&&(g=0,C=c,w=c*2),s=t.createImageData(o,n);for(let x=0;x{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,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let c=4,d=0,_=1,f=2,v=3,$=0,g=u,w=u*2,C=-1;a==="RGB"&&(c=3,d=0,_=1,f=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?($=0,w=u,g=u*2):l==="BGR"&&(w=0,g=u,$=u*2);for(let x=0;x{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,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")},u=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 c=u(p);if(c!=null){let d=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,_=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=d,a.width=_}else a.tensorFormat="RGBA",a.height=d,a.width=_;c.drawImage(e,0,0),i=c.getImageData(0,0,_,d).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){const d=l();d.width=c,d.height=p;const _=u(d);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 c=u(p);if(c!=null){const d=e.height,_=e.width;return c.drawImage(e,0,0,_,d),i=c.getImageData(0,0,_,d).data,a.height=d,a.width=_,Al(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{const d=l(),_=u(d);if(!e||!_)return c();const f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{d.width=f.width,d.height=f.height,_.drawImage(f,0,0,d.width,d.height);const v=_.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(Al(v.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Al(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Fv=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new us({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Ov=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new us({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Dv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new us({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Lv=(e,r,t)=>new us({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),ro=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ua=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let kf=!1;const zv=()=>{if(!kf){kf=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(ro.set("int64",BigInt64Array),ua.set(BigInt64Array,"int64")),r&&(ro.set("uint64",BigUint64Array),ua.set(BigUint64Array,"uint64")),s?(ro.set("float16",t),ua.set(t,"float16")):ro.set("float16",Uint16Array)}},Bv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new us(e.type,e.data,r);case"cpu-pinned":return new us({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new us({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new us({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new us({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let us=class{constructor(r,t,s){zv();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=ro.get(o);if(!a)throw new TypeError(`unsupported type "${o}" 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(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" 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(o=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 u=ro.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)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&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=ua.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,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 i=Bv(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return Av(r,t)}static fromTexture(r,t){return Fv(r,t)}static fromGpuBuffer(r,t){return Ov(r,t)}static fromMLTensor(r,t){return Dv(r,t)}static fromPinnedBuffer(r,t,s){return Lv(r,t,s)}toDataURL(r){return kv(this,r)}toImageData(r){return Iv(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 Rv(this,r)}};const eo=us,db=(e,r)=>{(typeof Ts.trace>"u"?!Ts.wasm.trace:!Ts.trace)||console.timeStamp(`${e}::ORT::${r}`)},pb=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof Ts.trace>"u"?!Ts.wasm.trace:!Ts.trace)||pb("BEGIN",e)},Fu=e=>{(typeof Ts.trace>"u"?!Ts.wasm.trace:!Ts.trace)||pb("END",e)};let jv=class hb{constructor(r){this.handler=r}async run(r,t,s){Au();const o={};let n={};if(typeof r!="object"||r===null||r instanceof eo||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof eo)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.");i=!1;for(const u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const c of this.outputNames)if(p.indexOf(c)!==-1){const d=t[c];(d===null||d instanceof eo)&&(u=!0,i=!1,o[c]=d)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof eo?l[u]=p:l[u]=new eo(p.type,p.data,p.dims)}return Fu(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){Au();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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 c=0,d=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-c,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Cv(i),u=await a.createInferenceSessionHandler(n,l);return Fu(),new hb(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const Nv=jv,Vv=Object.freeze(Object.defineProperty({__proto__:null,InferenceSession:Nv,TRACE:db,TRACE_FUNC_BEGIN:Au,TRACE_FUNC_END:Fu,Tensor:eo,env:$v,registerBackend:Ev},Symbol.toStringTag,{value:"Module"}));/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var Xu=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Wv=Object.getOwnPropertyNames,Gv=Object.prototype.hasOwnProperty,Kv=(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),io=(e,r)=>{for(var t in r)Xu(e,t,{get:r[t],enumerable:!0})},Hv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Wv(r))!Gv.call(e,o)&&o!==t&&Xu(e,o,{get:()=>r[o],enumerable:!(s=Uv(r,o))||s.enumerable});return e},Zo=e=>Hv(Xu({},"__esModule",{value:!0}),e),Bo,Js,Fn,If,mb,fb=je(()=>{Bo=new Map,Js=[],Fn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Bo.get(e);if(s===void 0)Bo.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 o=Js.indexOf(e);o!==-1&&Js.splice(o,1);for(let n=0;n{let r=Bo.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}}},mb=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Js:t,o,n=[],i=new Set;for(let l of s){let u=await If(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),qv=je(()=>{fb()}),_b,Qv=je(()=>{_b="1.22.0-dev.20250409-89f8206ba4"}),Fl,ls,gb=je(()=>{Qv(),Fl="warning",ls={wasm:{},webgl:{},webgpu:{},versions:{common:_b},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}`);Fl=e}},get logLevel(){return Fl}},Object.defineProperty(ls,"logLevel",{enumerable:!0})}),Yt,Xv=je(()=>{gb(),Yt=ls}),wb,bb,Jv=je(()=>{wb=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,c=0,d=p,_=p*2,f=-1;i==="RGBA"?(c=0,d=p,_=p*2,f=p*3):i==="RGB"?(c=0,d=p,_=p*2):i==="RBG"&&(c=0,_=p,d=p*2);for(let v=0;v{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 c=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,_=0,f=1,v=2,$=3,g=0,w=c,C=c*2,E=-1;a==="RGBA"?(g=0,w=c,C=c*2,E=c*3):a==="RGB"?(g=0,w=c,C=c*2):a==="RBG"&&(g=0,C=c,w=c*2),s=t.createImageData(o,n);for(let x=0;x{Ju(),qi=(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,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),c=4,d=0,_=1,f=2,v=3,$=0,g=u,w=u*2,C=-1;a==="RGB"&&(c=3,d=0,_=1,f=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?($=0,w=u,g=u*2):l==="BGR"&&(w=0,g=u,$=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,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")},u=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 c=u(p);if(c!=null){let d=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,_=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=d,a.width=_}else a.tensorFormat="RGBA",a.height=d,a.width=_;c.drawImage(e,0,0),i=c.getImageData(0,0,_,d).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){let d=l();d.width=c,d.height=p;let _=u(d);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 c=u(p);if(c!=null){let d=e.height,_=e.width;return c.drawImage(e,0,0,_,d),i=c.getImageData(0,0,_,d).data,a.height=d,a.width=_,qi(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{let d=l(),_=u(d);if(!e||!_)return c();let f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{d.width=f.width,d.height=f.height,_.drawImage(f,0,0,d.width,d.height);let v=_.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(qi(v.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return qi(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},yb=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Jr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},vb=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Jr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},xb=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Jr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Tb=(e,r,t)=>new Jr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),In,qo,Ol,Eb,Zv=je(()=>{In=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),qo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Ol=!1,Eb=()=>{if(!Ol){Ol=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(In.set("int64",BigInt64Array),qo.set(BigInt64Array,"int64")),r&&(In.set("uint64",BigUint64Array),qo.set(BigUint64Array,"uint64")),s?(In.set("float16",t),qo.set(t,"float16")):In.set("float16",Uint16Array)}}}),Pb,Cb,ex=je(()=>{Ju(),Pb=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Jr(e.type,e.data,r);case"cpu-pinned":return new Jr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Jr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Jr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Jr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Jr,Ju=je(()=>{Jv(),Yv(),Zv(),ex(),Jr=class{constructor(e,r,t){Eb();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=In.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,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.");i=r}else{let l=In.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"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=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)i=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",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=qo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=Pb(o);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=o,this.size=n}static async fromImage(e,r){return Mb(e,r)}static fromTexture(e,r){return yb(e,r)}static fromGpuBuffer(e,r){return vb(e,r)}static fromMLTensor(e,r){return xb(e,r)}static fromPinnedBuffer(e,r,t){return Tb(e,r,t)}toDataURL(e){return wb(this,e)}toImageData(e){return bb(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 Cb(this,e)}}}),xs,Sb=je(()=>{Ju(),xs=Jr}),ei,Dl,Es,cs,$b=je(()=>{gb(),ei=(e,r)=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||console.timeStamp(`${e}::ORT::${r}`)},Dl=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Dl("BEGIN",e)},cs=e=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Dl("END",e)}}),kb,tx=je(()=>{fb(),Sb(),$b(),kb=class Ib{constructor(r){this.handler=r}async run(r,t,s){Es();let o={},n={};if(typeof r!="object"||r===null||r instanceof xs||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof xs)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.");i=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let c of this.outputNames)if(p.indexOf(c)!==-1){let d=t[c];(d===null||d instanceof xs)&&(u=!0,i=!1,o[c]=d)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof xs?l[u]=p:l[u]=new xs(p.type,p.data,p.dims)}return cs(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){Es();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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,c=0,d=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-c,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await mb(i),u=await a.createInferenceSessionHandler(n,l);return cs(),new Ib(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Yu,rx=je(()=>{tx(),Yu=kb}),sx=je(()=>{}),nx=je(()=>{}),ox=je(()=>{}),ix=je(()=>{}),Ab={};io(Ab,{InferenceSession:()=>Yu,TRACE:()=>ei,TRACE_FUNC_BEGIN:()=>Es,TRACE_FUNC_END:()=>cs,Tensor:()=>xs,env:()=>Yt,registerBackend:()=>Fn});var Ps=je(()=>{qv(),Xv(),rx(),Sb(),sx(),nx(),$b(),ox(),ix()}),Zu=je(()=>{}),Fb={};io(Fb,{default:()=>Ob});var Ll,zl,Ob,ax=je(()=>{var e;R0(),zn(),ec(),Ll="ort-wasm-proxy-worker",zl=((e=globalThis.self)==null?void 0:e.name)===Ll,zl&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":tc(s.wasm).then(()=>{bc(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;Mc(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=wa(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;yc(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":vc(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;xc(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},Ec([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":Tc(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Ob=zl?null:r=>new Worker(r??Xr,{type:"module",name:Ll})}),Db={};io(Db,{default:()=>Lb});var Bl,Rl,Lb,Af,lx=je(()=>{var e,r;Rl=(Bl=import.meta.url,async function(t={}){var Qn;var s,o,n=t,i=new Promise((h,T)=>{s=h,o=T}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((Qn=self.name)==null?void 0:Qn.startsWith("em-pthread"));n.mountExternalData=(h,T)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,T)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...T)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:T[0],errors:[]},N=await h(...T);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let ue=L.errors;if(0Le),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=T;let I=n.Jb;n.jsepRegisterBuffer=(L,N,ue,Te)=>I.registerBuffer(L,N,ue,Te),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,N,ue)=>I.createDownloader(L,N,ue),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,N)=>{I.upload(L,N)}}else if(h==="webnn"){let I=T[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=T.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,N)=>{I.registerMLContext(L,N)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,N)=>I.createMLTensorDownloader(L,N),n.webnnRegisterMLTensor=(L,N,ue,Te)=>I.registerMLTensor(L,N,ue,Te),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,N,ue,Te,Le,Ke)=>I.registerMLConstant(L,N,ue,Te,Le,n.Eb,Ke),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let d=()=>{let h=(T,I,L)=>(...N)=>{let ue=Zt,Te=I==null?void 0:I();N=T(...N);let Le=I==null?void 0:I();return Te!==Le&&(T=Le,L(Te),I=L=null),Zt!=ue?new Promise((Ke,et)=>{qr={resolve:Ke,reject:et}}):N};(()=>{for(let T of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[T]=h(n[T],()=>n[T],I=>n[T]=I)})(),c!==void 0&&(n._OrtRun=c(n._OrtRun),n._OrtRunWithBinding=c(n._OrtRunWithBinding)),d=void 0};n.asyncInit=()=>{d==null||d()};var _,f,v=Object.assign({},n),$=(h,T)=>{throw T},g="";(a||l)&&(l?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),Bl&&(g=Bl),g=g.startsWith("blob:")?"":g.slice(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(f=h=>{var T=new XMLHttpRequest;return T.open("GET",h,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}),_=async h=>{if(V(h))return new Promise((I,L)=>{var N=new XMLHttpRequest;N.open("GET",h,!0),N.responseType="arraybuffer",N.onload=()=>{N.status==200||N.status==0&&N.response?I(N.response):L(N.status)},N.onerror=L,N.send(null)});var T=await fetch(h,{credentials:"same-origin"});if(T.ok)return T.arrayBuffer();throw Error(T.status+" : "+T.url)});var w=console.log.bind(console),C=console.error.bind(console),E=w,x=C;Object.assign(n,v),v=null;var b,y,S,F,z,K,q,R,Z,H,J,Q,se,fe=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function A(){return b.buffer!=F.buffer&&re(),F}function U(){return b.buffer!=F.buffer&&re(),z}function ee(){return b.buffer!=F.buffer&&re(),K}function _e(){return b.buffer!=F.buffer&&re(),q}function le(){return b.buffer!=F.buffer&&re(),R}function ye(){return b.buffer!=F.buffer&&re(),Z}function ze(){return b.buffer!=F.buffer&&re(),H}function Ue(){return b.buffer!=F.buffer&&re(),se}if(u){let h=function(T){try{var I=T.data,L=I.Bb;if(L==="load"){let N=[];self.onmessage=ue=>N.push(ue),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ue of N)h(ue);self.onmessage=h};for(let ue of I.Rb)n[ue]&&!n[ue].proxy||(n[ue]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ue,args:Te})},ue=="print"&&(E=n[ue]),ue=="printErr"&&(x=n[ue]));b=I.kc,re(),pe(I.lc)}else if(L==="run"){B(I.Ab),Wn(I.Ab,0,0,1,0,0),Zr(),xe(I.Ab),W||(Co(),W=!0);try{te(I.fc,I.Hb)}catch(N){if(N!="unwind")throw N}}else I.target!=="setimmediate"&&(L==="checkMailbox"?W&&Re():L&&(x(`worker: received unknown command ${L}`),x(I)))}catch(N){throw Gn(),N}};var pe,W=!1;x=function(...T){T=T.join(" "),console.error(T)},self.alert=function(...T){postMessage({Bb:"alert",text:T.join(" "),ic:mn()})},self.onunhandledrejection=T=>{throw T.reason||T},self.onmessage=h}function re(){var h=b.buffer;n.HEAP8=F=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=z=new Uint8Array(h),n.HEAPU16=q=new Uint16Array(h),n.HEAP32=R=new Int32Array(h),n.HEAPU32=Z=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=se=new Float64Array(h),n.HEAP64=J=new BigInt64Array(h),n.HEAPU64=Q=new BigUint64Array(h)}function G(){u?startWorker(n):ct.Ca()}u||(b=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),re());var be,we=0,Se=null;function Pe(){if(--we==0&&Se){var h=Se;Se=null,h()}}function $e(h){throw x(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function Fe(){return{a:{L:qe,Aa:He,b:Oe,$:yt,A:rt,pa:Bt,X:Xt,Z:Or,qa:es,na:ds,ga:ts,ma:Cs,J:jr,Y:Ss,V:Kr,oa:ps,W:$s,va:Is,E:it,Q:rs,O:rn,D:nn,u:on,r:an,P:As,z:j,R:X,ja:ie,T:Qe,aa:Ye,M:_t,F:Ot,ia:xe,sa:At,t:mr,Ba:br,w:Mr,o:dr,l:is,c:ns,n:ri,j:Us,v:oi,p:ii,f:ai,s:li,m:ui,e:lo,k:ci,i:di,g:uo,d:pi,da:co,ea:mi,fa:ho,ba:mo,ca:pn,N:fo,xa:_i,ua:wi,h:_o,C:bi,G:go,ta:gi,x:Ls,ra:Mi,U:ba,q:fi,y:yi,K:Ma,S:vi,za:xi,ya:Ti,ka:Mo,la:yo,_:St,B:Vn,I:vo,ha:xo,H:Eo,a:b,wa:Ie}}}var Be={829644:(h,T,I,L,N)=>{if(n===void 0||!n.Eb)return 1;if((h=lt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(T=Number(T>>>0),I=Number(I>>>0),L=Number(L>>>0),T+I>h.byteLength)return 3;try{let ue=h.subarray(T,T+I);switch(N){case 0:U().set(ue,L>>>0);break;case 1:n.mc?n.mc(L,ue):n.bc(L,ue);break;default:return 4}return 0}catch{return 4}},830468:(h,T,I)=>{n.Ob(h,U().subarray(T>>>0,T+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,T,I)=>{n.Kb(Number(h),Number(T),Number(I),!0)},830824:(h,T,I)=>{n.Kb(Number(h),Number(T),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,T,I)=>{n.jb("HardSigmoid",h,{alpha:T,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,T,I)=>{n.jb("Clip",h,{min:T,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,T)=>{n.jb("Elu",h,{alpha:T})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,T)=>{n.jb("LeakyRelu",h,{alpha:T})},832564:(h,T)=>{n.jb("ThresholdedRelu",h,{alpha:T})},832634:(h,T)=>{n.jb("Cast",h,{to:T})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,T,I,L,N)=>{n.jb("ReduceMean",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833403:(h,T,I,L,N)=>{n.jb("ReduceMax",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833577:(h,T,I,L,N)=>{n.jb("ReduceMin",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833751:(h,T,I,L,N)=>{n.jb("ReduceProd",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833926:(h,T,I,L,N)=>{n.jb("ReduceSum",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834100:(h,T,I,L,N)=>{n.jb("ReduceL1",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834273:(h,T,I,L,N)=>{n.jb("ReduceL2",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834446:(h,T,I,L,N)=>{n.jb("ReduceLogSum",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834623:(h,T,I,L,N)=>{n.jb("ReduceSumSquare",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834803:(h,T,I,L,N)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,T,I)=>{n.jb("Transpose",h,{perm:T?Array.from(le().subarray(Number(T)>>>0,Number(I)>>>0)):[]})},835160:(h,T,I,L)=>{n.jb("DepthToSpace",h,{blocksize:T,mode:lt(I),format:L?"NHWC":"NCHW"})},835293:(h,T,I,L)=>{n.jb("DepthToSpace",h,{blocksize:T,mode:lt(I),format:L?"NHWC":"NCHW"})},835426:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr,Os)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:T,dilations:[I],group:L,kernelShape:[N],pads:[ue,Te],strides:[Le],wIsConst:()=>!!A()[et>>>0],outputPadding:Mt?Array.from(le().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],outputShape:Wt?Array.from(le().subarray(Number(Wt)>>>0,Number(yr)>>>0)):[],activation:lt(Os)})},835859:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr)=>{n.jb("ConvTranspose",h,{format:Le?"NHWC":"NCHW",autoPad:T,dilations:Array.from(le().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(le().subarray(Number(N)>>>0,2+(Number(N)>>>0)>>>0)),pads:Array.from(le().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(le().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!A()[Ke>>>0],outputPadding:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],outputShape:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],activation:lt(yr)})},836520:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr,Os)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:T,dilations:[I],group:L,kernelShape:[N],pads:[ue,Te],strides:[Le],wIsConst:()=>!!A()[et>>>0],outputPadding:Mt?Array.from(le().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],outputShape:Wt?Array.from(le().subarray(Number(Wt)>>>0,Number(yr)>>>0)):[],activation:lt(Os)})},836953:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr)=>{n.jb("ConvTranspose",h,{format:Le?"NHWC":"NCHW",autoPad:T,dilations:Array.from(le().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(le().subarray(Number(N)>>>0,2+(Number(N)>>>0)>>>0)),pads:Array.from(le().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(le().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!A()[Ke>>>0],outputPadding:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],outputShape:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],activation:lt(yr)})},837614:(h,T)=>{n.jb("GlobalAveragePool",h,{format:T?"NHWC":"NCHW"})},837705:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},838184:(h,T)=>{n.jb("GlobalAveragePool",h,{format:T?"NHWC":"NCHW"})},838275:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},838754:(h,T)=>{n.jb("GlobalMaxPool",h,{format:T?"NHWC":"NCHW"})},838841:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},839316:(h,T)=>{n.jb("GlobalMaxPool",h,{format:T?"NHWC":"NCHW"})},839403:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},839878:(h,T,I,L,N)=>{n.jb("Gemm",h,{alpha:T,beta:I,transA:L,transB:N})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,T,I,L)=>{n.jb("ArgMax",h,{keepDims:!!T,selectLastIndex:!!I,axis:L})},840144:(h,T,I,L)=>{n.jb("ArgMin",h,{keepDims:!!T,selectLastIndex:!!I,axis:L})},840252:(h,T)=>{n.jb("Softmax",h,{axis:T})},840315:(h,T)=>{n.jb("Concat",h,{axis:T})},840375:(h,T,I,L,N)=>{n.jb("Split",h,{axis:T,numOutputs:I,splitSizes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,T)=>{n.jb("Gather",h,{axis:Number(T)})},840656:(h,T)=>{n.jb("GatherElements",h,{axis:Number(T)})},840735:(h,T)=>{n.jb("GatherND",h,{batch_dims:Number(T)})},840814:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt)=>{n.jb("Resize",h,{antialias:T,axes:I?Array.from(le().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:lt(N),cubicCoeffA:ue,excludeOutside:Te,extrapolationValue:Le,keepAspectRatioPolicy:lt(Ke),mode:lt(et),nearestMode:lt(Mt)})},841176:(h,T,I,L,N,ue,Te)=>{n.jb("Slice",h,{starts:T?Array.from(le().subarray(Number(T)>>>0,Number(I)>>>0)):[],ends:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[],axes:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,T,I)=>{n.jb("InstanceNormalization",h,{epsilon:T,format:I?"NHWC":"NCHW"})},841606:(h,T,I)=>{n.jb("InstanceNormalization",h,{epsilon:T,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,T)=>{n.jb("Einsum",h,{equation:lt(T)})},841854:(h,T,I,L,N)=>{n.jb("Pad",h,{mode:T,value:I,pads:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},841997:(h,T,I,L,N,ue)=>{n.jb("BatchNormalization",h,{epsilon:T,momentum:I,spatial:!!N,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842166:(h,T,I,L,N,ue)=>{n.jb("BatchNormalization",h,{epsilon:T,momentum:I,spatial:!!N,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842335:(h,T,I)=>{n.jb("CumSum",h,{exclusive:Number(T),reverse:Number(I)})},842432:(h,T,I)=>{n.jb("DequantizeLinear",h,{axis:T,blockSize:I})},842522:(h,T,I,L,N)=>{n.jb("GridSample",h,{align_corners:T,mode:lt(I),padding_mode:lt(L),format:N?"NHWC":"NCHW"})},842692:(h,T,I,L,N)=>{n.jb("GridSample",h,{align_corners:T,mode:lt(I),padding_mode:lt(L),format:N?"NHWC":"NCHW"})},842862:(h,T)=>{n.jb("ScatterND",h,{reduction:lt(T)})},842947:(h,T,I,L,N,ue,Te,Le,Ke)=>{n.jb("Attention",h,{numHeads:T,isUnidirectional:I,maskFilterValue:L,scale:N,doRotary:ue,qkvHiddenSizes:Te?Array.from(le().subarray(Number(Le)>>>0,Number(Le)+Te>>>0)):[],pastPresentShareBuffer:!!Ke})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,T,I,L,N,ue,Te,Le,Ke,et,Mt,kt,Wt,yr,Os,Pi)=>{n.jb("Conv",h,{format:kt?"NHWC":"NCHW",auto_pad:T,dilations:I?Array.from(le().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:N,kernel_shape:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],pads:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],strides:et?Array.from(le().subarray(Number(et)>>>0,Number(Mt)>>>0)):[],w_is_const:()=>!!A()[Number(Wt)>>>0],activation:lt(yr),activation_params:Os?Array.from(ze().subarray(Number(Os)>>>0,Number(Pi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,T,I,L,N,ue,Te,Le,Ke)=>{n.jb("GroupQueryAttention",h,{numHeads:T,kvNumHeads:I,scale:L,softcap:N,doRotary:ue,rotaryInterleaved:Te,smoothSoftmax:Le,localWindowSize:Ke})},844244:(h,T,I,L)=>{n.jb("LayerNormalization",h,{axis:T,epsilon:I,simplified:!!L})},844355:(h,T,I,L)=>{n.jb("LayerNormalization",h,{axis:T,epsilon:I,simplified:!!L})},844466:(h,T,I,L,N,ue)=>{n.jb("MatMulNBits",h,{k:T,n:I,accuracyLevel:L,bits:N,blockSize:ue})},844593:(h,T,I,L,N,ue)=>{n.jb("MultiHeadAttention",h,{numHeads:T,isUnidirectional:I,maskFilterValue:L,scale:N,doRotary:ue})},844752:(h,T)=>{n.jb("QuickGelu",h,{alpha:T})},844816:(h,T,I,L,N)=>{n.jb("RotaryEmbedding",h,{interleaved:!!T,numHeads:I,rotaryEmbeddingDim:L,scale:N})},844955:(h,T,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:T,simplified:!!I})},845057:(h,T,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:T,simplified:!!I})},845159:(h,T,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:T,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,T)=>n.ac(Number(h),Number(T),n.Fb.dc,n.Fb.errors)};function He(h,T,I){return Lr(async()=>{await n.Xb(Number(h),Number(T),Number(I))})}function qe(){return typeof wasmOffsetConverter<"u"}class ke{constructor(T){Y(this,"name","ExitStatus");this.message=`Program terminated with exit(${T})`,this.status=T}}var Ve=h=>{h.terminate(),h.onmessage=()=>{}},Ze=[],st=h=>{Vt.length==0&&(oe(),D(Vt[0]));var T=Vt.pop();if(!T)return 6;zt.push(T),or[h.Ab]=T,T.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return T.postMessage(I,h.Mb),0},at=0,Ge=(h,T,...I)=>{for(var L=2*I.length,N=wn(),ue=Hn(8*L),Te=ue>>>3,Le=0;Le>>0]=Ke)}return h=So(h,0,L,ue,T),gn(N),h};function Ie(h){if(u)return Ge(0,1,h);if(S=h,!(0{if(S=h,u)throw pt(h),"unwind";Ie(h)},Vt=[],zt=[],gr=[],or={},bt=h=>{var T=h.Ab;delete or[T],Vt.push(h),zt.splice(zt.indexOf(h),1),h.Ab=0,$o(T)};function Zr(){gr.forEach(h=>h())}var D=h=>new Promise(T=>{h.onmessage=N=>{var ue=(N=N.data).Bb;if(N.Gb&&N.Gb!=mn()){var Te=or[N.Gb];Te?Te.postMessage(N,N.Mb):x(`Internal error! Worker sent a message "${ue}" to target pthread ${N.Gb}, but that thread no longer exists!`)}else ue==="checkMailbox"?Re():ue==="spawnThread"?st(N):ue==="cleanupThread"?bt(or[N.hc]):ue==="loaded"?(h.loaded=!0,T(h)):ue==="alert"?alert(`Thread ${N.ic}: ${N.text}`):N.target==="setimmediate"?h.postMessage(N):ue==="callHandler"?n[N.Qb](...N.args):ue&&x(`worker sent an unknown command ${ue}`)},h.onerror=N=>{throw x(`worker sent an error! ${N.filename}:${N.lineno}: ${N.message}`),N};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:b,lc:y})});function oe(){var h=new Worker((()=>{let T=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new T("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Vt.push(h)}var B=h=>{re();var T=ye()[h+52>>>2>>>0];h=ye()[h+56>>>2>>>0],Kn(T,T-h),gn(T)},te=(h,T)=>{at=0,h=Ao(h,T),0>>=0);throw T>>>=0,I>>>=0,ye()[L.Ib+16>>>2>>>0]=0,ye()[L.Ib+4>>>2>>>0]=T,ye()[L.Ib+8>>>2>>>0]=I,h}function ve(h,T,I,L){return u?Ge(2,1,h,T,I,L):yt(h,T,I,L)}function yt(h,T,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var N=[];return u&&N.length===0?ve(h,T>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:N},u?(h.Bb="spawnThread",postMessage(h,N),0):st(h))}var Ft=typeof TextDecoder<"u"?new TextDecoder:void 0,ht=(h,T=0,I=NaN)=>{var L=(T>>>=0)+I;for(I=T;h[I]&&!(I>=L);)++I;if(16(N=(240&N)==224?(15&N)<<12|ue<<6|Te:(7&N)<<18|ue<<12|Te<<6|63&h[T++])?L+=String.fromCharCode(N):(N-=65536,L+=String.fromCharCode(55296|N>>10,56320|1023&N))}}else L+=String.fromCharCode(N)}return L},lt=(h,T)=>(h>>>=0)?ht(U(),h,T):"";function rt(h,T,I){return u?Ge(3,1,h,T,I):0}function Bt(h,T){if(u)return Ge(4,1,h,T)}var Ht=h=>{for(var T=0,I=0;I=L?T++:2047>=L?T+=2:55296<=L&&57343>=L?(T+=4,++I):T+=3}return T},wr=(h,T,I)=>{var L=U();if(T>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&h.charCodeAt(++ue)),127>=Te){if(T>=I)break;L[T++>>>0]=Te}else{if(2047>=Te){if(T+1>=I)break;L[T++>>>0]=192|Te>>6}else{if(65535>=Te){if(T+2>=I)break;L[T++>>>0]=224|Te>>12}else{if(T+3>=I)break;L[T++>>>0]=240|Te>>18,L[T++>>>0]=128|Te>>12&63}L[T++>>>0]=128|Te>>6&63}L[T++>>>0]=128|63&Te}}L[T>>>0]=0,h=T-N}else h=0;return h};function Xt(h,T){if(u)return Ge(5,1,h,T)}function Or(h,T,I){if(u)return Ge(6,1,h,T,I)}function es(h,T,I){return u?Ge(7,1,h,T,I):0}function ds(h,T){if(u)return Ge(8,1,h,T)}function ts(h,T,I){if(u)return Ge(9,1,h,T,I)}function Cs(h,T,I,L){if(u)return Ge(10,1,h,T,I,L)}function jr(h,T,I,L){if(u)return Ge(11,1,h,T,I,L)}function Ss(h,T,I,L){if(u)return Ge(12,1,h,T,I,L)}function Kr(h){if(u)return Ge(13,1,h)}function ps(h,T){if(u)return Ge(14,1,h,T)}function $s(h,T,I){if(u)return Ge(15,1,h,T,I)}var ks,ir,Is=()=>$e(""),Tr=h=>{for(var T="";U()[h>>>0];)T+=ks[U()[h++>>>0]];return T},hs={},zr={};function Ae(h,T,I={}){return function(L,N,ue={}){var Te=N.name;if(!L)throw new ir(`type "${Te}" must have a positive integer typeid pointer`);if(zr.hasOwnProperty(L)){if(ue.Sb)return;throw new ir(`Cannot register type '${Te}' twice`)}zr[L]=N,hs.hasOwnProperty(L)&&(N=hs[L],delete hs[L],N.forEach(Le=>Le()))}(h,T,I)}var Je=(h,T,I)=>{switch(T){case 1:return I?L=>A()[L>>>0]:L=>U()[L>>>0];case 2:return I?L=>ee()[L>>>1>>>0]:L=>_e()[L>>>1>>>0];case 4:return I?L=>le()[L>>>2>>>0]:L=>ye()[L>>>2>>>0];case 8:return I?L=>J[L>>>3]:L=>Q[L>>>3];default:throw new TypeError(`invalid integer width (${T}): ${h}`)}};function it(h,T,I){I>>>=0,Ae(h>>>=0,{name:T=Tr(T>>>0),fromWireType:L=>L,toWireType:function(L,N){if(typeof N!="bigint"&&typeof N!="number")throw N=N===null?"null":(L=typeof N)=="object"||L==="array"||L==="function"?N.toString():""+N,new TypeError(`Cannot convert "${N}" to ${this.name}`);return typeof N=="number"&&(N=BigInt(N)),N},Cb:Rt,readValueFromPointer:Je(T,I,T.indexOf("u")==-1),Db:null})}var Rt=8;function rs(h,T,I,L){Ae(h>>>=0,{name:T=Tr(T>>>0),fromWireType:function(N){return!!N},toWireType:function(N,ue){return ue?I:L},Cb:Rt,readValueFromPointer:function(N){return this.fromWireType(U()[N>>>0])},Db:null})}var ss=[],ur=[];function ns(h){9<(h>>>=0)&&--ur[h+1]==0&&(ur[h]=void 0,ss.push(h))}var cr=h=>{if(!h)throw new ir("Cannot use deleted val. handle = "+h);return ur[h]},hr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let T=ss.pop()||ur.length;return ur[T]=h,ur[T+1]=1,T}};function os(h){return this.fromWireType(ye()[h>>>2>>>0])}var ms={name:"emscripten::val",fromWireType:h=>{var T=cr(h);return ns(h),T},toWireType:(h,T)=>hr(T),Cb:Rt,readValueFromPointer:os,Db:null};function rn(h){return Ae(h>>>0,ms)}var sn=(h,T)=>{switch(T){case 4:return function(I){return this.fromWireType(ze()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ue()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${T}): ${h}`)}};function nn(h,T,I){I>>>=0,Ae(h>>>=0,{name:T=Tr(T>>>0),fromWireType:L=>L,toWireType:(L,N)=>N,Cb:Rt,readValueFromPointer:sn(T,I),Db:null})}function on(h,T,I,L,N){if(h>>>=0,I>>>=0,T=Tr(T>>>0),N===-1&&(N=4294967295),N=Le=>Le,L===0){var ue=32-8*I;N=Le=>Le<>>ue}var Te=T.includes("unsigned")?function(Le,Ke){return Ke>>>0}:function(Le,Ke){return Ke};Ae(h,{name:T,fromWireType:N,toWireType:Te,Cb:Rt,readValueFromPointer:Je(T,I,L!==0),Db:null})}function an(h,T,I){function L(ue){var Te=ye()[ue>>>2>>>0];return ue=ye()[ue+4>>>2>>>0],new N(A().buffer,ue,Te)}var N=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][T];Ae(h>>>=0,{name:I=Tr(I>>>0),fromWireType:L,Cb:Rt,readValueFromPointer:L},{Sb:!0})}function As(h,T){Ae(h>>>=0,{name:T=Tr(T>>>0),fromWireType:function(I){for(var L,N=ye()[I>>>2>>>0],ue=I+4,Te=ue,Le=0;Le<=N;++Le){var Ke=ue+Le;Le!=N&&U()[Ke>>>0]!=0||(Te=lt(Te,Ke-Te),L===void 0?L=Te:(L+="\0",L+=Te),Te=Ke+1)}return Wr(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var N=typeof L=="string";if(!(N||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new ir("Cannot pass non-string to std::string");var ue=N?Ht(L):L.length,Te=fn(4+ue+1),Le=Te+4;if(ye()[Te>>>2>>>0]=ue,N)wr(L,Le,ue+1);else if(N)for(N=0;N>>0]=Ke}else for(N=0;N>>0]=L[N];return I!==null&&I.push(Wr,Te),Te},Cb:Rt,readValueFromPointer:os,Db(I){Wr(I)}})}var Vs=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ln=(h,T)=>{for(var I=h>>1,L=I+T/2;!(I>=L)&&_e()[I>>>0];)++I;if(32<(I<<=1)-h&&Vs)return Vs.decode(U().slice(h,I));for(I="",L=0;!(L>=T/2);++L){var N=ee()[h+2*L>>>1>>>0];if(N==0)break;I+=String.fromCharCode(N)}return I},un=(h,T,I)=>{if(I??(I=2147483647),2>I)return 0;var L=T;I=(I-=2)<2*h.length?I/2:h.length;for(var N=0;N>>1>>>0]=ue,T+=2}return ee()[T>>>1>>>0]=0,T-L},cn=h=>2*h.length,Fs=(h,T)=>{for(var I=0,L="";!(I>=T/4);){var N=le()[h+4*I>>>2>>>0];if(N==0)break;++I,65536<=N?(N-=65536,L+=String.fromCharCode(55296|N>>10,56320|1023&N)):L+=String.fromCharCode(N)}return L},de=(h,T,I)=>{if(T>>>=0,I??(I=2147483647),4>I)return 0;var L=T;I=L+I-4;for(var N=0;N=ue&&(ue=65536+((1023&ue)<<10)|1023&h.charCodeAt(++N)),le()[T>>>2>>>0]=ue,(T+=4)+4>I)break}return le()[T>>>2>>>0]=0,T-L},k=h=>{for(var T=0,I=0;I=L&&++I,T+=4}return T};function j(h,T,I){if(h>>>=0,T>>>=0,I=Tr(I>>>=0),T===2)var L=ln,N=un,ue=cn,Te=Le=>_e()[Le>>>1>>>0];else T===4&&(L=Fs,N=de,ue=k,Te=Le=>ye()[Le>>>2>>>0]);Ae(h,{name:I,fromWireType:Le=>{for(var Ke,et=ye()[Le>>>2>>>0],Mt=Le+4,kt=0;kt<=et;++kt){var Wt=Le+4+kt*T;kt!=et&&Te(Wt)!=0||(Mt=L(Mt,Wt-Mt),Ke===void 0?Ke=Mt:(Ke+="\0",Ke+=Mt),Mt=Wt+T)}return Wr(Le),Ke},toWireType:(Le,Ke)=>{if(typeof Ke!="string")throw new ir(`Cannot pass non-string to C++ string type ${I}`);var et=ue(Ke),Mt=fn(4+et+T);return ye()[Mt>>>2>>>0]=et/T,N(Ke,Mt+4,et+T),Le!==null&&Le.push(Wr,Mt),Mt},Cb:Rt,readValueFromPointer:os,Db(Le){Wr(Le)}})}function X(h,T){Ae(h>>>=0,{Tb:!0,name:T=Tr(T>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){Wn(h>>>0,!l,1,!a,131072,!1),Zr()}var ce=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(le(),h>>>2,h).value.then(Re),h+=128,Atomics.store(le(),h>>>2,1))}var Re=()=>{var h=mn();h&&(xe(h),ce(Io))};function Qe(h,T){(h>>>=0)==T>>>0?setTimeout(Re):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=or[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function Ye(h,T,I,L,N){for(T>>>=0,L/=2,We.length=L,I=N>>>0>>>3,N=0;N>>0];return(T?Be[T]:Ei[h])(...We)}var _t=()=>{at=0};function Ot(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):bt(or[h])}function At(h){}var Jt=(h,T)=>{var I=zr[h];if(I===void 0)throw h=Un(h),I=Tr(h),Wr(h),new ir(`${T} has unknown type ${I}`);return I},Ut=(h,T,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ye()[T>>>2>>>0]=hr(L)),h};function mr(h,T,I){return T>>>=0,I>>>=0,h=cr(h>>>0),T=Jt(T,"emval::as"),Ut(T,I,h)}function br(h,T){return T>>>=0,h=cr(h>>>0),(T=Jt(T,"emval::as")).toWireType(null,h)}var Er=h=>{try{h()}catch(T){$e(T)}},Pr=0,Zt=null,fs=0,Kt=[],fr={},Dr={},Hr=0,qr=null,kr=[];function Lr(h){return function(T){if(!ae){if(Pr===0){var I=!1,L=!1;T((N=0)=>{if(!ae&&(fs=N,I=!0,L)){Pr=2,Er(()=>Oo(Zt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),N=!1;try{var ue=function(){var Ke=le()[Zt+8>>>2>>>0];return Ke=ct[Dr[Ke]],--at,Ke()}()}catch(Ke){ue=Ke,N=!0}var Te=!1;if(!Zt){var Le=qr;Le&&(qr=null,(N?Le.reject:Le.resolve)(ue),Te=!0)}if(N&&!Te)throw ue}}),L=!0,I||(Pr=1,Zt=function(){var N=fn(65548),ue=N+12;ye()[N>>>2>>>0]=ue,ye()[N+4>>>2>>>0]=ue+65536,ue=Kt[0];var Te=fr[ue];return Te===void 0&&(Te=Hr++,fr[ue]=Te,Dr[Te]=ue),ue=Te,le()[N+8>>>2>>>0]=ue,N}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Er(()=>Fo(Zt)))}else Pr===2?(Pr=0,Er(Do),Wr(Zt),Zt=null,kr.forEach(ce)):$e(`invalid state: ${Pr}`);return fs}}(T=>{h().then(T)})}function Mr(h){return h>>>=0,Lr(async()=>{var T=await cr(h);return hr(T)})}var er=[];function dr(h,T,I,L){return I>>>=0,L>>>=0,(h=er[h>>>0])(null,T=cr(T>>>0),I,L)}var pr={},Ir=h=>{var T=pr[h];return T===void 0?Tr(h):T};function is(h,T,I,L,N){return I>>>=0,L>>>=0,N>>>=0,(h=er[h>>>0])(T=cr(T>>>0),T[I=Ir(I)],L,N)}var dn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function ri(h){return(h>>>=0)==0?hr(dn()):(h=Ir(h),hr(dn()[h]))}var si=h=>{var T=er.length;return er.push(h),T},ni=(h,T)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},ao=(h,T)=>Object.defineProperty(T,"name",{value:h});function Us(h,T,I){var L=(T=ni(h,T>>>0)).shift();h--;var N=`return function (obj, func, destructorsRef, args) { +`,ue=0,Te=[];I===0&&Te.push("obj");for(var Le=["retType"],Ke=[L],et=0;etMt.name).join(", ")}) => ${L.name}>`,si(ao(I,h))}function oi(h){return h=Ir(h>>>0),hr(n[h])}function ii(h,T){return T>>>=0,h=cr(h>>>0),T=cr(T),hr(h[T])}function ai(h){9<(h>>>=0)&&(ur[h+1]+=1)}function li(){return hr([])}function ui(h){h=cr(h>>>0);for(var T=Array(h.length),I=0;I>>0))}function ci(){return hr({})}function di(h){for(var T=cr(h>>>=0);T.length;){var I=T.pop();T.pop()(I)}ns(h)}function uo(h,T,I){T>>>=0,I>>>=0,h=cr(h>>>0),T=cr(T),I=cr(I),h[T]=I}function pi(h,T){return T>>>=0,h=(h=Jt(h>>>0,"_emval_take_value")).readValueFromPointer(T),hr(h)}function co(h,T){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),le()[T>>>2>>>0]=h.getUTCSeconds(),le()[T+4>>>2>>>0]=h.getUTCMinutes(),le()[T+8>>>2>>>0]=h.getUTCHours(),le()[T+12>>>2>>>0]=h.getUTCDate(),le()[T+16>>>2>>>0]=h.getUTCMonth(),le()[T+20>>>2>>>0]=h.getUTCFullYear()-1900,le()[T+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,le()[T+28>>>2>>>0]=h}var po=h=>h%4==0&&(h%100!=0||h%400==0),Rn=[0,31,60,91,121,152,182,213,244,274,305,335],hi=[0,31,59,90,120,151,181,212,243,273,304,334];function mi(h,T){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),le()[T>>>2>>>0]=h.getSeconds(),le()[T+4>>>2>>>0]=h.getMinutes(),le()[T+8>>>2>>>0]=h.getHours(),le()[T+12>>>2>>>0]=h.getDate(),le()[T+16>>>2>>>0]=h.getMonth(),le()[T+20>>>2>>>0]=h.getFullYear()-1900,le()[T+24>>>2>>>0]=h.getDay();var I=(po(h.getFullYear())?Rn:hi)[h.getMonth()]+h.getDate()-1|0;le()[T+28>>>2>>>0]=I,le()[T+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),le()[T+32>>>2>>>0]=h}function ho(h){h>>>=0;var T=new Date(le()[h+20>>>2>>>0]+1900,le()[h+16>>>2>>>0],le()[h+12>>>2>>>0],le()[h+8>>>2>>>0],le()[h+4>>>2>>>0],le()[h>>>2>>>0],0),I=le()[h+32>>>2>>>0],L=T.getTimezoneOffset(),N=new Date(T.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(T.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ue,N);return 0>I?le()[h+32>>>2>>>0]=+(N!=ue&&Te==L):0>>2>>>0]=T.getDay(),I=(po(T.getFullYear())?Rn:hi)[T.getMonth()]+T.getDate()-1|0,le()[h+28>>>2>>>0]=I,le()[h>>>2>>>0]=T.getSeconds(),le()[h+4>>>2>>>0]=T.getMinutes(),le()[h+8>>>2>>>0]=T.getHours(),le()[h+12>>>2>>>0]=T.getDate(),le()[h+16>>>2>>>0]=T.getMonth(),le()[h+20>>>2>>>0]=T.getYear(),h=T.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function mo(h,T,I,L,N,ue,Te){return u?Ge(16,1,h,T,I,L,N,ue,Te):-52}function pn(h,T,I,L,N,ue){if(u)return Ge(17,1,h,T,I,L,N,ue)}var Ws={},fi=()=>performance.timeOrigin+performance.now();function fo(h,T){if(u)return Ge(18,1,h,T);if(Ws[h]&&(clearTimeout(Ws[h].id),delete Ws[h]),!T)return 0;var I=setTimeout(()=>{delete Ws[h],ce(()=>ko(h,performance.timeOrigin+performance.now()))},T);return Ws[h]={id:I,qc:T},0}function _i(h,T,I,L){h>>>=0,T>>>=0,I>>>=0,L>>>=0;var N=new Date().getFullYear(),ue=new Date(N,0,1).getTimezoneOffset();N=new Date(N,6,1).getTimezoneOffset();var Te=Math.max(ue,N);ye()[h>>>2>>>0]=60*Te,le()[T>>>2>>>0]=+(ue!=N),h=(T=Le=>{var Ke=Math.abs(Le);return`UTC${0<=Le?"-":"+"}${String(Math.floor(Ke/60)).padStart(2,"0")}${String(Ke%60).padStart(2,"0")}`})(ue),T=T(N),NDate.now();function wi(h,T,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),J[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var jn=[],hn=(h,T)=>{jn.length=0;for(var I;I=U()[h++>>>0];){var L=I!=105;T+=(L&=I!=112)&&T%8?4:0,jn.push(I==112?ye()[T>>>2>>>0]:I==106?J[T>>>3]:I==105?le()[T>>>2>>>0]:Ue()[T>>>3>>>0]),T+=L?8:4}return jn};function _o(h,T,I){return h>>>=0,T=hn(T>>>0,I>>>0),Be[h](...T)}function bi(h,T,I){return h>>>=0,T=hn(T>>>0,I>>>0),Be[h](...T)}var go=()=>{};function Ls(h,T){return x(lt(h>>>0,T>>>0))}var Mi=()=>{throw at+=1,"unwind"};function ba(){return 4294901760}var yi=()=>navigator.hardwareConcurrency;function Ma(){return $e("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function vi(h){h>>>=0;var T=U().length;if(h<=T||4294901760=I;I*=2){var L=T*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-b.buffer.byteLength+65535)/65536|0;try{b.grow(L),re();var N=1;break e}catch{}N=void 0}if(N)return!0}return!1}var Gs=()=>($e("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Ks={},wo=h=>{h.forEach(T=>{Gs()})};function xi(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),wo(h),Ks.Lb=Gs(),Ks.cc=h,Ks.Lb}function Ti(h,T,I){if(h>>>=0,T>>>=0,Ks.Lb==h)var L=Ks.cc;else(L=Error().stack.toString().split(` +`))[0]=="Error"&&L.shift(),wo(L);for(var N=3;L[N]&&Gs()!=h;)++N;for(h=0;h>>2>>>0]=Gs();return h}var Nn,Hs={},bo=()=>{if(!Nn){var h,T={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(h in Hs)Hs[h]===void 0?delete T[h]:T[h]=Hs[h];var I=[];for(h in T)I.push(`${h}=${T[h]}`);Nn=I}return Nn};function Mo(h,T){if(u)return Ge(19,1,h,T);h>>>=0,T>>>=0;var I=0;return bo().forEach((L,N)=>{var ue=T+I;for(N=ye()[h+4*N>>>2>>>0]=ue,ue=0;ue>>0]=L.charCodeAt(ue);A()[N>>>0]=0,I+=L.length+1}),0}function yo(h,T){if(u)return Ge(20,1,h,T);h>>>=0,T>>>=0;var I=bo();ye()[h>>>2>>>0]=I.length;var L=0;return I.forEach(N=>L+=N.length+1),ye()[T>>>2>>>0]=L,0}function Vn(h){return u?Ge(21,1,h):52}function vo(h,T,I,L){return u?Ge(22,1,h,T,I,L):52}function xo(h,T,I,L){return u?Ge(23,1,h,T,I,L):70}var To=[null,[],[]];function Eo(h,T,I,L){if(u)return Ge(24,1,h,T,I,L);T>>>=0,I>>>=0,L>>>=0;for(var N=0,ue=0;ue>>2>>>0],Le=ye()[T+4>>>2>>>0];T+=8;for(var Ke=0;Ke>>0],Mt=To[h];et===0||et===10?((h===1?E:x)(ht(Mt)),Mt.length=0):Mt.push(et)}N+=Le}return ye()[L>>>2>>>0]=N,0}u||function(){for(var h=n.numThreads-1;h--;)oe();Ze.unshift(()=>{we++,function(T){u?T():Promise.all(Vt.map(D)).then(T)}(()=>Pe())})}();for(var Po=Array(256),qs=0;256>qs;++qs)Po[qs]=String.fromCharCode(qs);ks=Po,ir=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},ur.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>ur.length/2-5-ss.length;var ct,Ei=[Ie,pt,ve,rt,Bt,Xt,Or,es,ds,ts,Cs,jr,Ss,Kr,ps,$s,mo,pn,fo,Mo,yo,Vn,vo,xo,Eo];(async function(){function h(L,N){return ct=L.exports,ct=function(){var ue=ct,Te={};for(let[Le,Ke]of Object.entries(ue))Te[Le]=typeof Ke=="function"?(...et)=>{Kt.push(Le);try{return Ke(...et)}finally{ae||(Kt.pop(),Zt&&Pr===1&&Kt.length===0&&(Pr=0,at+=1,Er(qn),typeof Fibers<"u"&&Fibers.rc()))}}:Ke;return Te}(),ct=function(){var ue=ct,Te=Ke=>et=>Ke(et)>>>0,Le=Ke=>()=>Ke()>>>0;return(ue=Object.assign({},ue)).Da=Te(ue.Da),ue.fb=Le(ue.fb),ue.hb=Te(ue.hb),ue.tb=Te(ue.tb),ue.ub=Le(ue.ub),ue.__cxa_get_exception_ptr=Te(ue.__cxa_get_exception_ptr),ue}(),gr.push(ct.ib),y=N,Pe(),ct}we++;var T=Fe();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(T,(N,ue)=>{h(N,ue),L(N.exports)})});if(u)return new Promise(L=>{pe=N=>{var ue=new WebAssembly.Instance(N,Fe());L(h(ue,N))}});be??(be=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",g):g+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href);try{var I=await async function(L){var N=be;if(!fe&&typeof WebAssembly.instantiateStreaming=="function"&&!V(N))try{var ue=fetch(N,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ue,L)}catch(Te){x(`wasm streaming compile failed: ${Te}`),x("falling back to ArrayBuffer instantiation")}return async function(Te,Le){try{var Ke=await async function(et){if(!fe)try{var Mt=await _(et);return new Uint8Array(Mt)}catch{}if(et==be&&fe)et=new Uint8Array(fe);else{if(!f)throw"both async and sync fetching of the wasm failed";et=f(et)}return et}(Te);return await WebAssembly.instantiate(Ke,Le)}catch(et){x(`failed to asynchronously prepare wasm: ${et}`),$e(et)}}(N,L)}(T);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var Un=h=>(Un=ct.Da)(h),Co=()=>(Co=ct.Ea)();n._OrtInit=(h,T)=>(n._OrtInit=ct.Fa)(h,T),n._OrtGetLastError=(h,T)=>(n._OrtGetLastError=ct.Ga)(h,T),n._OrtCreateSessionOptions=(h,T,I,L,N,ue,Te,Le,Ke,et)=>(n._OrtCreateSessionOptions=ct.Ha)(h,T,I,L,N,ue,Te,Le,Ke,et),n._OrtAppendExecutionProvider=(h,T,I,L,N)=>(n._OrtAppendExecutionProvider=ct.Ia)(h,T,I,L,N),n._OrtAddFreeDimensionOverride=(h,T,I)=>(n._OrtAddFreeDimensionOverride=ct.Ja)(h,T,I),n._OrtAddSessionConfigEntry=(h,T,I)=>(n._OrtAddSessionConfigEntry=ct.Ka)(h,T,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=ct.La)(h),n._OrtCreateSession=(h,T,I)=>(n._OrtCreateSession=ct.Ma)(h,T,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=ct.Na)(h),n._OrtGetInputOutputCount=(h,T,I)=>(n._OrtGetInputOutputCount=ct.Oa)(h,T,I),n._OrtGetInputOutputMetadata=(h,T,I,L)=>(n._OrtGetInputOutputMetadata=ct.Pa)(h,T,I,L),n._OrtFree=h=>(n._OrtFree=ct.Qa)(h),n._OrtCreateTensor=(h,T,I,L,N,ue)=>(n._OrtCreateTensor=ct.Ra)(h,T,I,L,N,ue),n._OrtGetTensorData=(h,T,I,L,N)=>(n._OrtGetTensorData=ct.Sa)(h,T,I,L,N),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=ct.Ta)(h),n._OrtCreateRunOptions=(h,T,I,L)=>(n._OrtCreateRunOptions=ct.Ua)(h,T,I,L),n._OrtAddRunConfigEntry=(h,T,I)=>(n._OrtAddRunConfigEntry=ct.Va)(h,T,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=ct.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=ct.Xa)(h),n._OrtBindInput=(h,T,I)=>(n._OrtBindInput=ct.Ya)(h,T,I),n._OrtBindOutput=(h,T,I,L)=>(n._OrtBindOutput=ct.Za)(h,T,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=ct._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=ct.$a)(h),n._OrtRunWithBinding=(h,T,I,L,N)=>(n._OrtRunWithBinding=ct.ab)(h,T,I,L,N),n._OrtRun=(h,T,I,L,N,ue,Te,Le)=>(n._OrtRun=ct.bb)(h,T,I,L,N,ue,Te,Le),n._OrtEndProfiling=h=>(n._OrtEndProfiling=ct.cb)(h),n._JsepOutput=(h,T,I)=>(n._JsepOutput=ct.db)(h,T,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=ct.eb)(h);var mn=()=>(mn=ct.fb)(),Wr=n._free=h=>(Wr=n._free=ct.gb)(h),fn=n._malloc=h=>(fn=n._malloc=ct.hb)(h),Wn=(h,T,I,L,N,ue)=>(Wn=ct.kb)(h,T,I,L,N,ue),Gn=()=>(Gn=ct.lb)(),So=(h,T,I,L,N)=>(So=ct.mb)(h,T,I,L,N),$o=h=>($o=ct.nb)(h),_n=h=>(_n=ct.ob)(h),ko=(h,T)=>(ko=ct.pb)(h,T),Io=()=>(Io=ct.qb)(),Kn=(h,T)=>(Kn=ct.rb)(h,T),gn=h=>(gn=ct.sb)(h),Hn=h=>(Hn=ct.tb)(h),wn=()=>(wn=ct.ub)(),Ao=n.dynCall_ii=(h,T)=>(Ao=n.dynCall_ii=ct.vb)(h,T),Fo=h=>(Fo=ct.wb)(h),qn=()=>(qn=ct.xb)(),Oo=h=>(Oo=ct.yb)(h),Do=()=>(Do=ct.zb)();return n.stackSave=()=>wn(),n.stackRestore=h=>gn(h),n.stackAlloc=h=>Hn(h),n.setValue=function(h,T,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":A()[h>>>0]=T;break;case"i16":ee()[h>>>1>>>0]=T;break;case"i32":le()[h>>>2>>>0]=T;break;case"i64":J[h>>>3]=BigInt(T);break;case"float":ze()[h>>>2>>>0]=T;break;case"double":Ue()[h>>>3>>>0]=T;break;case"*":ye()[h>>>2>>>0]=T;break;default:$e(`invalid type for setValue: ${I}`)}},n.getValue=function(h,T="i8"){switch(T.endsWith("*")&&(T="*"),T){case"i1":case"i8":return A()[h>>>0];case"i16":return ee()[h>>>1>>>0];case"i32":return le()[h>>>2>>>0];case"i64":return J[h>>>3];case"float":return ze()[h>>>2>>>0];case"double":return Ue()[h>>>3>>>0];case"*":return ye()[h>>>2>>>0];default:$e(`invalid type for getValue: ${T}`)}},n.UTF8ToString=lt,n.stringToUTF8=wr,n.lengthBytesUTF8=Ht,function h(){if(0{Zu(),jl=typeof location>"u"?void 0:location.origin,Ou=import.meta.url>"file:"&&import.meta.url<"file;",Ff=()=>{{if(Ou){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,jl).href}return import.meta.url}},Xr=Ff(),zb=()=>{if(Xr&&!Xr.startsWith("blob:"))return Xr.substring(0,Xr.lastIndexOf("/")+1)},Qi=(e,r)=>{try{let t=r??Xr;return(t?new URL(e,t):new URL(e)).origin===jl}catch{return!1}},Of=(e,r)=>{let t=r??Xr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},Df=(e,r)=>`${r??"./"}${e}`,Nl=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Lf=async e=>(await import(e)).default,Vl=(ax(),Zo(Fb)).default,Bb=async()=>{if(!Xr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Qi(Xr))return[void 0,Vl()];let e=await Nl(Xr);return[e,Vl(e)]},Ul=(lx(),Zo(Db)).default,Rb=async(e,r,t)=>{if(!e&&!r&&Ul&&Xr&&Qi(Xr))return[void 0,Ul];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??Of(s,r),n=t&&o&&!Qi(o,r),i=n?await Nl(o):o??Df(s,r);return[n?i:void 0,await Lf(i)]}}}),Wl,Xi,Ro,Gl,zf,Bf,Rf,tc,Qt,zn=je(()=>{ec(),Xi=!1,Ro=!1,Gl=!1,zf=()=>{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}},Bf=()=>{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}},Rf=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},tc=async e=>{if(Xi)return Promise.resolve();if(Ro)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Gl)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ro=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Rf())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Bf())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=zf();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 o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[c,d]=await Rb(a,n,t>1),_=!1,f=[];if(r>0&&f.push(new Promise(v=>{setTimeout(()=>{_=!0,v()},r)})),f.push(new Promise((v,$)=>{let g={numThreads:t};if(p)g.wasmBinary=p;else if(u||n)g.locateFile=w=>u??n+w;else if(a&&a.indexOf("blob:")!==0)g.locateFile=w=>new URL(w,a).href;else if(c){let w=zb();w&&(g.locateFile=C=>w+C)}d(g).then(w=>{Ro=!1,Xi=!0,Wl=w,v(),c&&URL.revokeObjectURL(c)},w=>{Ro=!1,Gl=!0,$(w)})})),await Promise.race(f),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qt=()=>{if(Xi&&Wl)return Wl;throw new Error("WebAssembly is not initialized yet.")}}),vs,pa,Gt,rc=je(()=>{zn(),vs=(e,r)=>{let t=Qt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},pa=(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(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")pa(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Gt=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),jb,ux=je(()=>{zn(),rc(),jb=e=>{let r=Qt(),t=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.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)o.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&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=vs(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&Gt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&pa(e.extra,"",new WeakSet,(i,a)=>{let l=vs(i,s),u=vs(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&Gt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),jf,Nf,Vf,jo,Uf,Nb,cx=je(()=>{zn(),rc(),jf=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}`)}},Nf=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Vf=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)},jo=(e,r,t,s)=>{let o=vs(r,s),n=vs(t,s);Qt()._OrtAddSessionConfigEntry(e,o,n)!==0&&Gt(`Can't set a session config entry: ${r} - ${t}.`)},Uf=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&jo(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);jo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=vs(o,t),a=n.length,l=0,u=0;if(a>0){l=Qt()._malloc(a*Qt().PTR_SIZE),t.push(l),u=Qt()._malloc(a*Qt().PTR_SIZE),t.push(u);for(let p=0;p{let r=Qt(),t=0,s=[],o=e||{};Vf(o);try{let n=jf(o.graphOptimizationLevel??"all"),i=Nf(o.executionMode??"sequential"),a=typeof o.logId=="string"?vs(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?vs(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&Gt("Can't create session options."),o.executionProviders&&await Uf(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);jo(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[c,d]of Object.entries(o.freeDimensionOverrides)){if(typeof c!="string")throw new Error(`free dimension override name must be a string: ${c}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let _=vs(c,s);r._OrtAddFreeDimensionOverride(t,_,d)!==0&&Gt(`Can't set a free dimension override: ${c} - ${d}.`)}return o.extra!==void 0&&pa(o.extra,"",new WeakSet,(c,d)=>{jo(t,c,d,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Gt("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),to,js,An,sc,ha,nc,oc,Du,ft=je(()=>{to=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}`)}},js=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}`)}},An=(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((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},sc=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}`)}},ha=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}`)}},nc=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",oc=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Du=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}`)}}}),ic,Vb=je(()=>{Zu(),ic=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 o=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 i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Wf,Gf,Kf,Hf,ac,qf,It,Ns=je(()=>{ft(),Wf=["V","I","W","E","F"],Gf=(e,r)=>{console.log(`[${Wf[e]},${new Date().toISOString()}]${r}`)},ac=(e,r)=>{Kf=e,Hf=r},qf=(e,r)=>{let t=ha(e),s=ha(Kf);t>=s&&Gf(t,typeof r=="function"?r():r)},It=(...e)=>{Hf&&qf(...e)}}),Qf,no,Me,ma,Ub,Wb,Gb,xt=je(()=>{Qf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},no=class{static calcShape(e,r,t=!1){let s=e.length,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=Qf.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},Me=class ca{static size(r){return ca.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}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 ca.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 ca.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+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((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ma=class Qo{static adjustPoolAttributes(r,t,s,o,n,i){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]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,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(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ft(),lc=(e,r)=>new(sc(r))(e)}),Lu,Kl,Xf,Hl,Jf,ql,Ql,Xl,Yf,Hb,dx=je(()=>{Ns(),Lu=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Kl=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Xf=1,Hl=()=>Xf++,Jf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ql=(e,r)=>{let t=Jf.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Ql=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return ql(this.dataType,this.tensorShape)}destroy(){It("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Kl(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):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,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},Xl=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 o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",It("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==ql(o,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 a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=Lu(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else It("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Kl(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Yf=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=Hl();return this.tensorTrackersById.set(e,new Xl(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,o){It("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){It("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 o=this.getMLContext(e),n=Hl(),i=new Ql({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new Xl(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){It("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let c=this.freeTensors.splice(u,1)[0];return c.sessionId=e,c}It("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Ql({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Hb=(...e)=>new Yf(...e)}),Ji,Zf,qb,px=je(()=>{ft(),zn(),Kb(),dx(),Ns(),Ji=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Zf=(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((o,n)=>o===s[n]&&e[o]===r[o])},qb=class{constructor(e){this.tensorManager=Hb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,ac(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){It("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){It("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)It("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=>Zf(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(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){It("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=Ji.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){It("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Ji.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!Qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");It("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 lc(t,r)}}registerMLTensor(e,r,t,s){let o=Ji.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return It("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=Lu(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return It("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),uc=je(()=>{}),Jl,Yi,Zi,e_,t_,Yl,zu,r_,Qb,hx=je(()=>{Ns(),uc(),Jl=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]]),Yi=[],Zi=e=>Math.ceil(Number(e)/16)*16,e_=e=>{for(let r=0;rt_++,zu=async(e,r,t,s)=>{let o=Zi(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),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()}},r_=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 Jl)Yi.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=Zi(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);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,o)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),It("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 o=Zi(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return It("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=Yl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),It("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),It("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=e_(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?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 i={id:Yl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),It("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}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 It("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 zu(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=Jl.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&&(It("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Qb=(...e)=>new r_(...e)}),s_,Nt,lr=je(()=>{s_=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}},Nt=e=>new s_(e)}),oo,ea,$r,Rr,ut,nr,Bu,so,en,ot,No,Ce,tt,Xb,cc,n_,Jb,Tt=je(()=>{ft(),xt(),oo=64,ea=(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}`)}},$r=(e,r=1)=>{let t=ea(e,r);return typeof t=="string"?t:t[0]},Rr=(e,r=1)=>{let t=ea(e,r);return typeof t=="string"?t:t[1]},ut=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:Me.computeStrides(t)})}),r},nr=e=>e%4===0?4:e%2===0?2:1,Bu=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,so=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,en=(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,ot=(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,No=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=ea(r,o),p=typeof u=="string"?u:u[1],c=typeof u=="string"?u:u[0],d={indices:l,value:p,storage:c,tensor:r},_=V=>typeof V=="string"?V:`${V}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},v=n?"uniforms.":"",$=`${v}${e}_shape`,g=`${v}${e}_strides`,w="";for(let V=0;V ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${w} + return indices; + }`,E=V=>(f.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),x=[];if(i>=2)for(let V=i-1;V>=0;V--)x.push(`${ot(g,V,i)} * (indices[${V}])`);let b=i<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${x.join("+")}; + }`,y=V=>(f.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),S=(...V)=>i===0?"0u":`${d.indices}(${V.map(_).join(",")})`,F=(V,A)=>i<2?`${V}`:`${ot(V,A,i)}`,z=(V,A,U)=>i<2?`${V}=${U};`:`${ot(V,A,i)}=${U};`,K={},q=(V,A)=>{f.broadcastedIndicesToOffset=!0;let U=`${A.name}broadcastedIndicesTo${e}Offset`;if(U in K)return`${U}(${V})`;let ee=[];for(let _e=i-1;_e>=0;_e--){let le=A.indicesGet("outputIndices",_e+A.rank-i);ee.push(`${F(g,_e)} * (${le} % ${F($,_e)})`)}return K[U]=`fn ${U}(outputIndices: ${A.type.indices}) -> u32 { + return ${ee.length>0?ee.join("+"):"0u"}; + }`,`${U}(${V})`},R=(V,A)=>(()=>{if(d.storage===d.value)return`${e}[${V}]=${A};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${V}]=vec2(u32(${A}), select(0u, 0xFFFFFFFFu, ${A} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${V}]=vec2(u32(${A}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${A}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),Z=V=>(()=>{if(d.storage===d.value)return`${e}[${V}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${V}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${V}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${p} { + return ${Z(`i2o_${e}(indices)`)}; + }`,J=i<2?"":(()=>{let V=a.map(U=>`d${U}: u32`).join(", "),A=a.map(U=>`d${U}`).join(", ");return` + fn get_${e}(${V}) -> ${p} { + return get_${e}ByIndices(${S(A)}); + }`})(),Q=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let A=V.map(_).join(",");return i===0?Z("0u"):i===1?Z(A[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${A})`)},se=V=>i<2?Z(V):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${V})`),fe=i<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${p}) { + ${R(`i2o_${e}(indices)`,"value")} + }`,ae=i<2?"":(()=>{let V=a.map(U=>`d${U}: u32`).join(", "),A=a.map(U=>`d${U}`).join(", ");return` + fn set_${e}(${V}, value: ${p}) { + set_${e}ByIndices(${S(A)}, value); + }`})();return{impl:()=>{let V=[],A=!1;return f.offsetToIndices&&(V.push(C),A=!0),f.indicesToOffset&&(V.push(b),A=!0),f.broadcastedIndicesToOffset&&(Object.values(K).forEach(U=>V.push(U)),A=!0),f.set&&(V.push(ae),A=!0),f.setByIndices&&(V.push(fe),A=!0),f.get&&(V.push(J),A=!0),f.getByIndices&&(V.push(H),A=!0),!n&&A&&V.unshift(`const ${$} = ${d.indices}(${t.join(",")});`,`const ${g} = ${d.indices}(${Me.computeStrides(t).join(",")});`),V.join(` +`)},type:d,offsetToIndices:E,indicesToOffset:y,broadcastedIndicesToOffset:q,indices:S,indicesGet:F,indicesSet:z,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let A=V[i];if(typeof A!="string")throw new Error("value must be string");let U=V.slice(0,i).map(_).join(",");return i===0?R("0u",A):i===1?R(U[0],A):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${U}, ${A})`)},setByOffset:R,setByIndices:(V,A)=>i<2?R(V,A):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${A});`),get:Q,getByOffset:Z,getByIndices:se,usage:s,name:e,strides:g,shape:$,rank:i}},Ce=(e,r,t,s=1)=>No(e,r,t,"input",s),tt=(e,r,t,s=1)=>No(e,r,t,"output",s),Xb=(e,r,t)=>No(e,r,t,"atomicOutput",1),cc=(e,r,t,s=1)=>No(e,r,t,"internal",s),n_=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=oo){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 o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@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, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` + 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])}},Jb=(e,r)=>new n_(e,r)}),o_,Zl,i_,a_,l_,u_,Yr,Yb,Zb,tn=je(()=>{ft(),xt(),lr(),Tt(),o_=(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}`)},Zl=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),i_=(e,r)=>Me.sortBasedOnPerm(e,Zl(e.length,r)),a_=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=Zl(s,r),n=i_(e.dims,o),i=e.dims,a=n,l=s<2||u_(o,e.dims),u;if(l)return u=f=>{let v=Ce("input",t,i,4),$=tt("output",t,a,4);return` + ${f.registerUniform("output_size","u32").declareVariables(v,$)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let f=Me.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:u};let{newShape:p,newPerm:c}=l_(e.dims,o),d=Me.areEqual(c,[2,3,1]),_=Me.areEqual(c,[3,1,2]);if(p.length===2||d||_){i=d?[p[0],p[1]*p[2]]:_?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let f=16;return u=v=>{let $=Ce("a",t,i.length),g=tt("output",t,a.length);return` + ${v.registerUniform("output_size","u32").declareVariables($,g)} + var tile : array, ${f}>; + ${v.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 * ${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] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + 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]) { + ${g.setByIndices(`${g.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let v=Me.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:v},...ut(i,a)]}},getShaderSource:u}}return u=f=>{let v=Ce("a",t,i.length),$=tt("output",t,a.length);return` + ${f.registerUniform("output_size","u32").declareVariables(v,$)} + + ${a_(o,s,v,$)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${$.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${$.setByOffset("global_idx",v.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let f=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...ut(i,a)]}},getShaderSource:u}},Yb=(e,r)=>{o_(e.inputs,r.perm),e.compute(Yr(e.inputs[0],r.perm))},Zb=e=>Nt({perm:e.perm})}),c_,d_,p_,h_,m_,f_,__,g_,w_,b_,gs,eM,tM,rM,sM,nM,oM,iM,aM,lM,uM,mx=je(()=>{ft(),xt(),Tt(),dc(),tn(),c_={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"},d_={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"},p_={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},h_={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},m_=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},__=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!g_(e,r)){for(let s=0;st.push(s))}return t},b_=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=Me.size(n),u=Me.size(i),p=Ce("_A",t[0].dataType,a),c=tt("output",o,n),d=64;l===1&&(d=256);let _=` + var aBestValues : array; + `,f=v=>` + ${v.registerUniform("reduceSize","u32").declareVariables(p,c)} + ${_} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${v.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${p_[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${c_[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${d_[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${c.setByOffset("outputIndex",`${s==="mean"?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${h_[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${d}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},gs=(e,r,t,s)=>{let o=e.inputs.length===1?t:Ru(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((_,f)=>f));let i=Me.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=w_(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Yr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=m_(a.length,l.dims.length));let[p,c]=f_(l.dims,a),d=p;o.keepDims&&(d=__(p,i)),e.compute(b_(r,o.cacheKey,[l],s,e.inputs[0].dataType,d,c),{inputs:[l]})},eM=(e,r)=>{gs(e,"ReduceMeanShared",r,"mean")},tM=(e,r)=>{gs(e,"ReduceL1Shared",r,"l1")},rM=(e,r)=>{gs(e,"ReduceL2Shared",r,"l2")},sM=(e,r)=>{gs(e,"ReduceLogSumExpShared",r,"logSumExp")},nM=(e,r)=>{gs(e,"ReduceMaxShared",r,"max")},oM=(e,r)=>{gs(e,"ReduceMinShared",r,"min")},iM=(e,r)=>{gs(e,"ReduceProdShared",r,"prod")},aM=(e,r)=>{gs(e,"ReduceSumShared",r,"sum")},lM=(e,r)=>{gs(e,"ReduceSumSquareShared",r,"sumSquare")},uM=(e,r)=>{gs(e,"ReduceLogSumShared",r,"logSum")}}),ws,M_,fa,Ru,bs,y_,v_,x_,T_,E_,P_,C_,S_,$_,k_,Ms,cM,dM,pM,hM,mM,fM,_M,gM,wM,bM,dc=je(()=>{ft(),xt(),lr(),Tt(),mx(),ws=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.")},M_=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fa=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,c=Me.normalizeAxes(o,p),d=!a&&c.length===0;u.forEach((v,$)=>{d||c.indexOf($)>=0?i&&l.push(1):l.push(v)});let _=l.length,f=Me.size(l);return{name:e,shaderCache:r,getShaderSource:v=>{let $=[],g=Ce("_A",t[0].dataType,p),w=tt("output",n,_),C=s(g,w,c),E=C[2];for(let x=0,b=0;x=0?(i&&b++,E=`for(var j${x}: u32 = 0; j${x} < ${u[x]}; j${x}++) { + ${C[2].includes("last_index")?`let last_index = j${x};`:""} + ${g.indicesSet("input_indices",x,`j${x}`)} + ${E} + }`):($.push(`${g.indicesSet("input_indices",x,w.indicesGet("output_indices",b))};`),b++);return` + + ${v.registerUniform("output_size","u32").declareVariables(g,w)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${g.type.indices}; + let output_indices = ${w.offsetToIndices("global_idx")}; + + ${$.join(` +`)} + ${C[0]} // init ops for reduce max/min + ${C[1]} + ${E} + ${C[3]} + ${C.length===4?w.setByOffset("global_idx","value"):C.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...ut(u,l)]})}},Ru=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Nt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},bs=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:Ru(o,t);e.compute(fa(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?M_:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},y_=(e,r)=>{ws(e.inputs),bs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},v_=(e,r)=>{ws(e.inputs),bs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},x_=(e,r)=>{ws(e.inputs),bs(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);"])},T_=(e,r)=>{ws(e.inputs),bs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},E_=(e,r)=>{ws(e.inputs),bs(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},P_=(e,r)=>{ws(e.inputs),bs(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},C_=(e,r)=>{ws(e.inputs),bs(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},S_=(e,r)=>{ws(e.inputs),bs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},$_=(e,r)=>{ws(e.inputs),bs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},k_=(e,r)=>{ws(e.inputs),bs(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;`,""])},Ms=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},cM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?P_(e,r):eM(e,r)},dM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?v_(e,r):tM(e,r)},pM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?x_(e,r):rM(e,r)},hM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?T_(e,r):sM(e,r)},mM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?E_(e,r):nM(e,r)},fM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?C_(e,r):oM(e,r)},_M=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?S_(e,r):iM(e,r)},gM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?$_(e,r):aM(e,r)},wM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?k_(e,r):lM(e,r)},bM=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?y_(e,r):uM(e,r)}}),eu,MM,yM,ju,fx=je(()=>{ft(),lr(),dc(),eu=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.")},MM=(e,r)=>{eu(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(fa("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},yM=(e,r)=>{eu(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(fa("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},ju=e=>Nt(e)}),I_,ta,A_,F_,O_,ti,D_,vM,pc=je(()=>{ft(),xt(),uc(),Tt(),I_=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&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],u=t.dims[1],p=t.dims[2];if(o.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(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=o.dims[0]/3,d=c,_=d;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let C of r.qkvHiddenSizes)if(C%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");c=r.qkvHiddenSizes[0],d=r.qkvHiddenSizes[1],_=r.qkvHiddenSizes[2]}let f=u;if(c!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==c+d+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let v=0;if(i){if(d!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==d/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(v=i.dims[3])}let $=f+v,g=-1,w=0;if(n)throw new Error("Mask not supported");if(i)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]!==u||a.dims[3]!==$)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:v,kvSequenceLength:f,totalSequenceLength:$,maxSequenceLength:g,inputHiddenSize:p,hiddenSize:c,vHiddenSize:_,headSize:Math.floor(c/r.numHeads),vHeadSize:Math.floor(_/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:w,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ta=(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; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,A_=(e,r,t,s,o,n,i,a)=>{let l=nr(i?1:n),u=64,p=n/l;p{let w=tt("x",e.dataType,e.dims,l),C=[w],E=i?Ce("seq_lens",i.dataType,i.dims):void 0;E&&C.push(E);let x=a?Ce("total_sequence_length_input",a.dataType,a.dims):void 0;x&&C.push(x);let b=Rr(e.dataType),y=[{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; + ${g.registerUniforms(y).declareVariables(...C)} + ${g.mainStart([u,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; + ${ta(E,x,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + 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(${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(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${u}; i++) { + max_value = max(thread_max[i], max_value); + } + + 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(${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(); + + var sum: f32 = 0; + for (var i = 0u; i < ${u}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${w.type.value}(${b}(1.0) / ${b}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${f}(x[offset + i]); + x[offset + i] = ${w.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + 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] = ${w.type.value}(${b}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${_};${l}`,inputDependencies:v},getShaderSource:$,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:d})}},F_=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],c=e>1&&s,d=n.kvNumHeads?n.kvNumHeads:n.numHeads,_=c?[n.batchSize,d,u,n.headSize]:void 0,f=n.nReps?n.nReps:1,v=n.scale===0?1/Math.sqrt(n.headSize):n.scale,$=nr(n.headSize),g=n.headSize/$,w=12,C={x:Math.ceil(u/w),y:Math.ceil(n.sequenceLength/w),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:g},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:v},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:f}],x=c&&s&&Me.size(s.dims)>0,b=["type","type"];x&&b.push("type"),o&&b.push("type"),a&&b.push("type"),l&&b.push("type");let y=[{dims:p,dataType:r.dataType,gpuDataType:0}];c&&y.push({dims:_,dataType:r.dataType,gpuDataType:0});let S=F=>{let z=Ce("q",r.dataType,r.dims,$),K=Ce("key",t.dataType,t.dims,$),q=[z,K];if(x){let fe=Ce("past_key",s.dataType,s.dims,$);q.push(fe)}o&&q.push(Ce("attention_bias",o.dataType,o.dims));let R=a?Ce("seq_lens",a.dataType,a.dims):void 0;R&&q.push(R);let Z=l?Ce("total_sequence_length_input",l.dataType,l.dims):void 0;Z&&q.push(Z);let H=tt("output",r.dataType,p),J=[H];c&&J.push(tt("present_key",r.dataType,_,$));let Q=Rr(1,$),se=[{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 = ${w}u; + + var tileQ: array<${z.type.storage}, ${w*w}>; + var tileK: array<${z.type.storage}, ${w*w}>; + ${F.registerUniforms(se).declareVariables(...q,...J)} + ${F.mainStart([w,w,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + 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; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${ta(R,Z,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${x&&c?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${c?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${Q}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${x&&c?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${c?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${Q}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch($){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: ${$}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${$};${o!==void 0};${s!==void 0};${e}`,inputDependencies:b},getRunData:()=>({outputs:y,dispatchGroup:C,programUniforms:E}),getShaderSource:S}},O_=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,c=e>1&&s,d=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=c?[o.batchSize,d,l,o.headSize]:void 0,f=[o.batchSize,o.sequenceLength,p],v=12,$={x:Math.ceil(o.vHeadSize/v),y:Math.ceil(o.sequenceLength/v),z:o.batchSize*o.numHeads},g=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:u}],w=c&&s&&Me.size(s.dims)>0,C=["type","type"];w&&C.push("type"),i&&C.push("type"),a&&C.push("type");let E=[{dims:f,dataType:r.dataType,gpuDataType:0}];c&&E.push({dims:_,dataType:r.dataType,gpuDataType:0});let x=b=>{let y=Ce("probs",r.dataType,r.dims),S=Ce("v",t.dataType,t.dims),F=[y,S];w&&F.push(Ce("past_value",s.dataType,s.dims));let z=i?Ce("seq_lens",i.dataType,i.dims):void 0;i&&F.push(z);let K=a?Ce("total_sequence_length_input",a.dataType,a.dims):void 0;a&&F.push(K);let q=[tt("output",r.dataType,f)];c&&q.push(tt("present_value",r.dataType,_));let R=[{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 = ${v}u; + var tileQ: array<${y.type.value}, ${v*v}>; + var tileV: array<${y.type.value}, ${v*v}>; + ${b.registerUniforms(R).declareVariables(...F,...q)} + ${b.mainStart([v,v,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${u===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${ta(z,K,!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 + ${w&&c?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${c?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${y.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${w&&c?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${c?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:C},getRunData:()=>({outputs:E,dispatchGroup:$,programUniforms:g}),getShaderSource:x}},ti=(e,r,t,s,o,n,i,a,l,u,p=void 0,c=void 0)=>{let d=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),_=d>1?u.pastSequenceLength:0,f=_+u.kvSequenceLength,v=l&&Me.size(l.dims)>0?l:void 0,$=[r,t];d>1&&i&&Me.size(i.dims)>0&&$.push(i),v&&$.push(v),p&&$.push(p),c&&$.push(c);let g=e.compute(F_(d,r,t,i,v,u,_,p,c),{inputs:$,outputs:d>1?[-1,1]:[-1]})[0];e.compute(A_(g,u.batchSize,u.numHeads,_,u.sequenceLength,f,p,c),{inputs:p&&c?[g,p,c]:[g],outputs:[]});let w=[g,s];d>1&&a&&Me.size(a.dims)>0&&w.push(a),p&&w.push(p),c&&w.push(c),e.compute(O_(d,g,s,a,u,_,p,c),{inputs:w,outputs:d>1?[0,2]:[0]})},D_=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:o},{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=c=>{let d=tt("output_q",l[0].dataType,t),_=tt("output_k",l[0].dataType,t),f=tt("output_v",l[0].dataType,t),v=Ce("input",l[0].dataType,l[0].dims),$=Ce("weight",l[1].dataType,l[1].dims),g=Ce("bias",l[2].dataType,l[2].dims),w=v.type.storage,C=[{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 = ${i}u; + var tileInput: array<${w}, ${i*i}>; + var tileWeightQ: array<${w}, ${i*i}>; + var tileWeightK: array<${w}, ${i*i}>; + var tileWeightV: array<${w}, ${i*i}>; + ${c.registerUniforms(C).declareVariables(v,$,g,d,_,f)} + ${c.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${w}(0); + var valueK = ${w}(0); + var valueV = ${w}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({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:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},vM=(e,r)=>{let t=I_(e.inputs,r),[s,o,n]=D_(e,t);return ti(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),L_,z_,B_,xM,_x=je(()=>{Ps(),ft(),xt(),lr(),Tt(),L_=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.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")},z_=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?nr(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=Me.size(n)/i,u=s,p=u?n.length:n,c=Ce("x",e[0].dataType,e[0].dims,i),d=Ce("scale",e[1].dataType,e[1].dims,a),_=Ce("bias",e[2].dataType,e[2].dims,a),f=Ce("inputMean",e[3].dataType,e[3].dims,a),v=Ce("inputVar",e[4].dataType,e[4].dims,a),$=tt("y",e[0].dataType,p,i),g=()=>{let C="";if(s)C=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")C=` + ${$.indicesSet("outputIndices","0","0")} + let cOffset = ${$.indicesToOffset("outputIndices")};`;else{C=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` + const epsilon = ${t}; + ${C.registerUniform("outputSize","u32").declareVariables(c,d,_,f,v,$)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${$.offsetToIndices(`global_idx * ${i}`)}; + ${g()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${_.getByOffset("cOffset")}; + let inputMean = ${f.getByOffset("cOffset")}; + let inputVar = ${v.getByOffset("cOffset")}; + let x = ${c.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${$.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:w,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...ut(n)]:[{type:12,data:l}]})}},B_=e=>Nt(e),xM=(e,r)=>{let{inputs:t,outputCount:s}=e,o=B_({...r,outputCount:s});if(Yt.webgpu.validateInputContent&&L_(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(z_(t,o))}}),R_,j_,TM,gx=je(()=>{xt(),Tt(),R_=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")},j_=e=>{let r=e[0].dims,t=e[0].dims[2],s=Me.size(r)/4,o=e[0].dataType,n=Ce("input",o,r,4),i=Ce("bias",o,[t],4),a=Ce("residual",o,r,4),l=tt("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` + const channels = ${t}u / 4; + ${u.declareVariables(n,i,a,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},TM=e=>{R_(e.inputs),e.compute(j_(e.inputs))}}),N_,Lt,EM,PM,CM,SM,$M,kM,IM,AM,FM,V_,OM,DM,LM,zM,Xo,BM,da,RM,jM,NM,VM,UM,WM,GM,KM,HM,qM,QM,XM,JM,YM,ZM,ey,tu,ty,Nu,Vu,ry,sy,ny,U_,W_,oy,hc=je(()=>{ft(),xt(),lr(),Tt(),N_=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Ce("inputData",t,[a],4),p=tt("outputData",s,[a],4),c=[{name:"vec_size",type:"u32"}];return i&&c.push(...i),` + ${e.registerUniforms(c).declareVariables(u,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Lt=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(Me.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:u=>N_(u,Me.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Me.size(u[0].dims)/64/4)},programUniforms:l})}},EM=e=>{e.compute(Lt(e.inputs[0],"Abs","abs"))},PM=e=>{e.compute(Lt(e.inputs[0],"Acos","acos"))},CM=e=>{e.compute(Lt(e.inputs[0],"Acosh","acosh"))},SM=e=>{e.compute(Lt(e.inputs[0],"Asin","asin"))},$M=e=>{e.compute(Lt(e.inputs[0],"Asinh","asinh"))},kM=e=>{e.compute(Lt(e.inputs[0],"Atan","atan"))},IM=e=>{e.compute(Lt(e.inputs[0],"Atanh","atanh"))},AM=e=>Nt(e),FM=(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(Lt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},V_=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Nt({min:r,max:t})},OM=(e,r)=>{let t=r||V_(e.inputs),s=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"Clip",o=>`clamp(${o}, 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]})},DM=e=>{e.compute(Lt(e.inputs[0],"Ceil","ceil"))},LM=e=>{e.compute(Lt(e.inputs[0],"Cos","cos"))},zM=e=>{e.compute(Lt(e.inputs[0],"Cosh","cosh"))},Xo=e=>Nt(e),BM=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},da=(e="f32")=>` +const r0: ${e} = 0.3275911; +const r1: ${e} = 0.254829592; +const r2: ${e} = -0.284496736; +const r3: ${e} = 1.421413741; +const r4: ${e} = -1.453152027; +const r5: ${e} = 1.061405429; + +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)); +}`,RM=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,da(r)))},jM=e=>{e.compute(Lt(e.inputs[0],"Exp","exp"))},NM=e=>{e.compute(Lt(e.inputs[0],"Floor","floor"))},VM=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,da(r)))},UM=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Lt(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))},WM=e=>{e.compute(Lt(e.inputs[0],"Not",r=>`!${r}`))},GM=e=>{e.compute(Lt(e.inputs[0],"Neg",r=>`-${r}`))},KM=e=>{e.compute(Lt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},HM=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},qM=e=>{e.compute(Lt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},QM=e=>Nt(e),XM=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Lt(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))},JM=e=>{e.compute(Lt(e.inputs[0],"Sin","sin"))},YM=e=>{e.compute(Lt(e.inputs[0],"Sinh","sinh"))},ZM=e=>{e.compute(Lt(e.inputs[0],"Sqrt","sqrt"))},ey=e=>{e.compute(Lt(e.inputs[0],"Tan","tan"))},tu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ty=e=>{e.compute(Lt(e.inputs[0],"Tanh",tu))},Nu=(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 ${tu("v")}; +} +`,Vu=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,ry=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"FastGelu",Vu,Nu(r),void 0,e.inputs[0].dataType))},sy=(e,r)=>{let t=Rr(e.inputs[0].dataType);return e.compute(Lt(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},ny=e=>{e.compute(Lt(e.inputs[0],"Log","log"))},U_=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,W_=e=>`quick_gelu_impl(${e})`,oy=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Lt(e.inputs[0],"QuickGelu",W_,U_(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),G_,K_,iy,wx=je(()=>{xt(),Tt(),hc(),G_=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")},K_=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Ce("input",e[0].dataType,e[0].dims,4),s=Ce("bias",e[0].dataType,[e[0].dims[2]],4),o=tt("output",e[0].dataType,r,4),n=Me.size(r)/4,i=$r(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; + + ${a.declareVariables(t,s,o)} + + ${da(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},iy=e=>{G_(e.inputs),e.compute(K_(e.inputs))}}),H_,q_,ys,ay,ly,uy,cy,dy,py,hy,my,fy,_y,bx=je(()=>{ft(),xt(),Tt(),H_=(e,r,t,s,o,n,i,a,l,u,p,c)=>{let d,_;typeof a=="string"?d=_=(w,C)=>`${a}((${w}),(${C}))`:typeof a=="function"?d=_=a:(d=a.scalar,_=a.vector);let f=tt("outputData",p,s.length,4),v=Ce("aData",l,r.length,4),$=Ce("bData",u,t.length,4),g;if(o)if(n){let w=Me.size(r)===1,C=Me.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,x=t.length>0&&t[t.length-1]%4===0;w||C?g=f.setByOffset("global_idx",_(w?`${v.type.value}(${v.getByOffset("0")}.x)`:v.getByOffset("global_idx"),C?`${$.type.value}(${$.getByOffset("0")}.x)`:$.getByOffset("global_idx"))):g=` + let outputIndices = ${f.offsetToIndices("global_idx * 4u")}; + let offsetA = ${v.broadcastedIndicesToOffset("outputIndices",f)}; + let offsetB = ${$.broadcastedIndicesToOffset("outputIndices",f)}; + ${f.setByOffset("global_idx",_(i||E?v.getByOffset("offsetA / 4u"):`${v.type.value}(${v.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||x?$.getByOffset("offsetB / 4u"):`${$.type.value}(${$.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else g=f.setByOffset("global_idx",_(v.getByOffset("global_idx"),$.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let w=(C,E,x="")=>{let b=`aData[indexA${E}][componentA${E}]`,y=`bData[indexB${E}][componentB${E}]`;return` + let outputIndices${E} = ${f.offsetToIndices(`global_idx * 4u + ${E}u`)}; + let offsetA${E} = ${v.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let offsetB${E} = ${$.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let indexA${E} = offsetA${E} / 4u; + let indexB${E} = offsetB${E} / 4u; + let componentA${E} = offsetA${E} % 4u; + let componentB${E} = offsetB${E} % 4u; + ${C}[${E}] = ${x}(${d(b,y)}); + `};p===9?g=` + var data = vec4(0); + ${w("data",0,"u32")} + ${w("data",1,"u32")} + ${w("data",2,"u32")} + ${w("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:g=` + ${w("outputData[global_idx]",0)} + ${w("outputData[global_idx]",1)} + ${w("outputData[global_idx]",2)} + ${w("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(v,$,f)} + + ${c??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${g} + }`},q_=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(v=>Number(v)??1),l=s.dims.map(v=>Number(v)??1),u=!Me.areEqual(a,l),p=a,c=Me.size(a),d=!1,_=!1,f=[u];if(u){let v=no.calcShape(a,l,!1);if(!v)throw new Error("Can't perform binary op on the given tensors");p=v.slice(),c=Me.size(p);let $=Me.size(a)===1,g=Me.size(l)===1,w=a.length>0&&a[a.length-1]%4===0,C=l.length>0&&l[l.length-1]%4===0;f.push($),f.push(g),f.push(w),f.push(C);let E=1;for(let x=1;xv.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:v=>H_(v,a,l,p,d,u,_,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Me.size(p)/4)},...ut(a,l,p)]})}},ys=(e,r,t,s,o,n)=>{e.compute(q_(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},ay=e=>{ys(e,"Add",(r,t)=>`${r}+${t}`)},ly=e=>{ys(e,"Div",(r,t)=>`${r}/${t}`)},uy=e=>{ys(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},cy=e=>{ys(e,"Mul",(r,t)=>`${r}*${t}`)},dy=e=>{let r=Ce("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ys(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); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // 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)); + } + `)},py=e=>{ys(e,"Sub",(r,t)=>`${r}-${t}`)},hy=e=>{ys(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},my=e=>{ys(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},fy=e=>{ys(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},_y=e=>{ys(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Q_,X_,J_,Y_,gy,wy,Mx=je(()=>{ft(),xt(),lr(),Tt(),Q_=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},X_=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,J_=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=Me.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:o}];for(let v=0;v`uniforms.sizeInConcatAxis${v}`).join(","),f=v=>` + + ${(()=>{v.registerUniform("outputSize","u32");for(let $=0;$(${_}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${J_(i,c)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:f}},gy=(e,r)=>{let t=e.inputs,s=t[0].dims,o=Me.normalizeAxis(r.axis,s.length);Q_(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>Me.size(a.dims)>0);e.compute(Y_(i,o,n,t[0].dataType),{inputs:i})},wy=e=>Nt({axis:e.axis})}),On,Dn,Ln,mc,Bn=je(()=>{ft(),xt(),On=(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}`)}},Dn=(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})},Ln=(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"})},mc=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)||[Wb,Gb];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}}}),Fr,by,fc=je(()=>{Fr=(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.`)}},by=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),My,yx=je(()=>{My=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)); +} +fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); +} +`}),Yo,_c,gc=je(()=>{ft(),xt(),Tt(),Bn(),Yo=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${ot(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,ot(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},_c=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],c=nr(u),d=nr(p),_=nr(l),f=Me.size(t)/c/_,v=e.length>2,$=s?s.slice(0,-2):t.slice(0,-2),g=[Me.size($),l,u],w=[{type:12,data:f},{type:12,data:l},{type:12,data:u},{type:12,data:p}];Dn(r,w),w.push(...ut($,i,a)),v&&w.push(...ut(e[2].dims)),w.push(...ut(g));let C=E=>{let x=cc("batch_dims",e[0].dataType,$.length),b=Ce("a",e[0].dataType,i.length,d),y=Ce("b",e[1].dataType,a.length,c),S=tt("output",e[0].dataType,g.length,c),F=$r(S.type.tensor),z=On(r,S.type.value,F),K=[b,y],q="";if(v){let H=o?c:1;K.push(Ce("bias",e[2].dataType,e[2].dims.length,H)),q=`${o?`value += bias[col / ${H}];`:`value += ${S.type.value}(bias[row + i]);`}`}let R=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ln(r,R);let Z=()=>{let H=`var a_data: ${b.type.value};`;for(let J=0;J; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${Z()} + } + for (var i = 0u; i < ${_}u; i++) { + var value = values[i]; + ${q} + ${z} + let cur_indices = ${S.type.indices}(batch, row + i, col); + let offset = ${S.indicesToOffset("cur_indices")}; + ${S.setByOffset(`offset / ${c}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${c};${d};${_};${o}`,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:w}),getShaderSource:C}}}),Z_,eg,Uu,ru,tg,Wu,rg,_a,wc=je(()=>{ft(),xt(),Tt(),Bn(),gc(),fc(),Z_=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,eg=(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]; + ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Uu=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,c=o?n:l,d=p/r[0],_=n/r[1];if(!((o&&d===4&&e[1]===4||!o&&(d===3||d===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${d} 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/d}>, ${c}>; +var mm_Bsub: array, ${u/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${_}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${Z_(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${eg(o,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},ru=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,tg=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Wu=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],c=o?u:n,d=o?n:u;if(!(d%r[1]===0&&c%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let _=d/r[1],f=c/r[0],v=n/r[1],$=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + let globalColStart = i32(workgroupId.x) * ${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 inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${r[0]}) { + ${ru(o,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${u}; + +let tileRowA = i32(localId.y) * ${_}; +let tileColA = i32(localId.x) * ${f}; +let tileRowB = i32(localId.y) * ${v}; +// 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 < ${_}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${ru(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${v}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${tg(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${d}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${$} + } +`},rg=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=$r(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Fr(e,u)} { + var value = ${Fr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${Yo("aIndices",i,i.rank-2,n.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Fr(e,u)} { + var value = ${Fr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${Yo("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Fr(e,u)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${o?"bias[colIn]":`${Fr(e,u)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},_a=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),c=Me.size(p),d=i[i.length-2],_=i[i.length-1],f=a[a.length-1],v=_%4===0&&f%4===0,$=d<=8?[4,1,1]:[4,4,1],g=[8,8,1],w=[Math.ceil(f/g[0]/$[0]),Math.ceil(d/g[1]/$[1]),Math.ceil(c/g[2]/$[2])],C=v?4:1,E=[...l,d,_/C],x=E.length,b=[...u,_,f/C],y=b.length,S=[c,d,f/C],F=[{type:6,data:d},{type:6,data:f},{type:6,data:_}];Dn(r,F),F.push(...ut(p,E,b));let z=["rank","rank"],K=e.length>2;K&&(F.push(...ut(e[2].dims)),z.push("rank")),F.push(...ut(S));let q=R=>{let Z=p.length,H=cc("batchDims",e[0].dataType,Z,1),J=$r(e[0].dataType),Q=Ce("a",e[0].dataType,x,C),se=Ce("b",e[1].dataType,y,C),fe=tt("result",e[0].dataType,S.length,C),ae=[Q,se];if(K){let _e=o?C:1;ae.push(Ce("bias",e[2].dataType,e[2].dims.length,_e))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ln(r,V);let A=$r(fe.type.tensor),U=On(r,fe.type.value,A),ee=rg(C,K,U,[H,Q,se,fe],o);return` + ${R.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,fe)} + ${ee} + ${v?Uu($,g,J,H):Wu($,g,J,H)} + `};return{name:"MatMul",shaderCache:{hint:`${$};${r.activation};${v};${o}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:w[0],y:w[1],z:w[2]},programUniforms:F}),getShaderSource:q}}}),sg,yy,vx=je(()=>{ft(),Ns(),Tt(),Bn(),fc(),yx(),wc(),sg=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=F=>{switch(F){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${F} is not supported.`)}},c=F=>{switch(F){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 ${F} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,_=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",v=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",$=e?"row":"col",g=e?"col":"row",w=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${$} / outWidth; + let outCol = ${$} % outWidth; + + let WRow = ${g} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${g} / 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 = ${g} % inChannels; + var resData = ${Fr(i,u)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${v}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,C=e?r&&s?` + let col = colIn * ${i}; + ${w}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${w} + } + return ${Fr(i,u)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${w}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${w} + } + return ${Fr(i,u)}(0.0);`,E=e?s&&t?c(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${c(a)} + } + return ${Fr(a,u)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${c(a)} + } + return ${Fr(a,u)}(0.0);`,x=Fr(l,u),b=Fr(e?i:a,u),y=Fr(e?a:i,u),S=On(n,x,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${b} { + ${e?C:E} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${y} { + ${e?E:C} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${x}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${_} + ${by(o)} + ${S} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},yy=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],c=t[0],d=u?t[2]:t[3],_=u?t[1]:t[2],f=u?t[3]:t[1],v=u&&(p%4===0||p%3===0)&&f%4===0,$=u?f:d*_,g=u?d*_:f,w=[8,8,1],C=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil($/w[0]/C[0]),Math.ceil(g/w[1]/C[1]),Math.ceil(c/w[2]/C[2])];It("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let x=v?u&&p%4!==0?3:4:1,b=w[1]*C[1],y=w[0]*C[0],S=Math.max(w[0]*x,w[1]),F=s%b===0,z=o%y===0,K=n%S===0,q=v?[x,4,4]:[1,1,1],R=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];Dn(r,R),R.push(...ut(e[0].dims,e[1].dims));let Z=["rank","rank"];i&&(R.push(...ut(e[2].dims)),Z.push("rank")),R.push(...ut(t));let H=J=>{let Q=[{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}];Ln(r,Q);let se=v?4:1,fe=$r(e[0].dataType),ae=` + fn setOutputAtIndex(flatIndex : i32, value : ${v?`vec4<${fe}>`:fe}) { + result[flatIndex] = ${v?`vec4<${fe}>`:fe}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${v?`vec4<${fe}>`:fe}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${v?"/ 4":""}, value); + }`,V=Ce("x",e[0].dataType,e[0].dims.length,x===3?1:x),A=Ce("w",e[1].dataType,e[1].dims.length,se),U=[V,A],ee=tt("result",e[0].dataType,t.length,se);if(i){let _e=Ce("bias",e[2].dataType,e[2].dims.length,se);U.push(_e),ae+=` + fn getBiasByOutputCoords(coords : vec4) -> ${v?`vec4<${fe}>`:fe} { + return bias[coords.${u?"w":"y"}${v?"/ 4":""}]; + }`}return` + ${My("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 }; + ${J.registerUniforms(Q).declareVariables(...U,ee)} + ${ae} + ${sg(u,F,z,K,i,r,q[0],q[1],q[2],fe)} + ${v?Uu(C,w,fe,void 0,!u,S):Wu(C,w,fe,void 0,!u,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${x};${v};${F};${z};${K};${b};${y};${S}`,inputDependencies:Z},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:R}),getShaderSource:H}}}),ng,su,Vo,og,nu,ig,vy,xy,xx=je(()=>{ft(),Ns(),xt(),Tt(),Bn(),fc(),ng=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Vo=(e,r)=>r<=1?e:e+(e-1)*(r-1),og=(e,r,t,s=1)=>{let o=Vo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},nu=(e,r,t,s,o)=>{o==null&&(o=og(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},ig=(e,r,t,s,o,n,i,a,l,u)=>{let p,c,d,_;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=nu([r,t,s,1],[a,l,u],1,[o,n,i],e);c=f[0],d=f[1],_=f[2]}else if(Array.isArray(e)){if(!e.every((v,$,g)=>v===g[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=nu([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);c=f[0],d=f[1],_=f[2]}else if(e==="SAME_UPPER"){c=Math.ceil(r/o),d=Math.ceil(t/n),_=Math.ceil(s/i);let f=(c-1)*o+a-r,v=(d-1)*n+l-t,$=(_-1)*i+u-s,g=Math.floor(f/2),w=f-g,C=Math.floor(v/2),E=v-C,x=Math.floor($/2),b=$-x;p={top:C,bottom:E,left:x,right:b,front:g,back:w}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:c,outHeight:d,outWidth:_}},vy=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,c;if(i==="channelsLast")[a,l,u,p,c]=e;else if(i==="channelsFirst")[a,c,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,,_,f,v]=r,[$,g,w]=su(t),[C,E,x]=su(s),b=Vo(_,C),y=Vo(f,E),S=Vo(v,x),{padInfo:F,outDepth:z,outHeight:K,outWidth:q}=ig(o,l,u,p,$,g,w,b,y,S),R=n?d*c:d,Z=[0,0,0,0,0];return i==="channelsFirst"?Z=[a,R,z,K,q]:i==="channelsLast"&&(Z=[a,z,K,q,R]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:c,outDepth:z,outHeight:K,outWidth:q,outChannels:R,padInfo:F,strideDepth:$,strideHeight:g,strideWidth:w,filterDepth:_,filterHeight:f,filterWidth:v,effectiveFilterDepth:b,effectiveFilterHeight:y,effectiveFilterWidth:S,dilationDepth:C,dilationHeight:E,dilationWidth:x,inShape:e,outShape:Z,filterShape:r}},xy=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map(($,g)=>g)},u=[Math.ceil(ng(l.x.map($=>t[$]))/a[0]),1,1];It("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,c=Me.size(t),d=[{type:12,data:c},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];Dn(r,d),d.push(...ut(e[0].dims,e[1].dims));let _=["rank","rank"],f=e.length===3;f&&(d.push(...ut(e[2].dims)),_.push("rank")),d.push(...ut(t));let v=$=>{let g=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];Ln(r,g);let w=1,C=$r(e[0].dataType),E=Ce("x",e[0].dataType,e[0].dims.length,p),x=Ce("W",e[1].dataType,e[1].dims.length,w),b=[E,x],y=tt("result",e[0].dataType,t.length,w),S="";if(f){let K=Ce("bias",e[2].dataType,e[2].dims.length,w);b.push(K),S+=` + fn getBiasByOutputCoords(coords : array) -> ${C} { + return bias[${i?ot("coords",4,5):ot("coords",1,5)}]; + }`}let F=Fr(p,C),z=On(r,F,C);return` + ${S} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${E.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${x.getByIndices("aIndices")}; + } + ${$.registerUniforms(g).declareVariables(...b,y)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${y.offsetToIndices("global_idx")}; + let batch = ${ot("coords",0,E.rank)}; + let d2 = ${i?ot("coords",E.rank-1,E.rank):ot("coords",1,E.rank)}; + let xFRCCorner = vec3(${i?ot("coords",1,E.rank):ot("coords",2,E.rank)}, + ${i?ot("coords",2,E.rank):ot("coords",3,E.rank)}, + ${i?ot("coords",3,E.rank):ot("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?ot("uniforms.x_shape",1,E.rank):ot("uniforms.x_shape",2,E.rank)}; + let xShapeZ = ${i?ot("uniforms.x_shape",2,E.rank):ot("uniforms.x_shape",3,E.rank)}; + let xShapeW = ${i?ot("uniforms.x_shape",3,E.rank):ot("uniforms.x_shape",4,E.rank)}; + let xShapeU = ${i?ot("uniforms.x_shape",4,E.rank):ot("uniforms.x_shape",1,E.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${f?"value = value + getBiasByOutputCoords(coords)":""}; + ${z} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:d}),getShaderSource:v}}}),Ty,Ey,Tx=je(()=>{ft(),xt(),Tt(),Bn(),Ty=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,c=l&&p>=4?nr(u):1,d=Me.size(t)/c,_=[{type:12,data:d},{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}];Dn(r,_),_.push(...ut(i,[a[0],a[1],a[2],a[3]/c]));let f=o?["rank","rank","rank"]:["rank","rank"];_.push(...ut([t[0],t[1],t[2],t[3]/c]));let v=$=>{let g=tt("output",e[0].dataType,t.length,c),w=$r(g.type.tensor),C=On(r,g.type.value,w),E=Ce("x",e[0].dataType,i.length),x=Ce("w",e[1].dataType,a.length,c),b=[E,x];o&&b.push(Ce("b",e[2].dataType,e[2].dims,c));let y=[{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"}];Ln(r,y);let S=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${x.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${x.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${$.registerUniforms(y).declareVariables(...b,g)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${g.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 * ${c} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${g.type.value} = ${g.type.value}(0); + ${S} + ${n} + ${C} + ${g.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${c}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:v}},Ey=(e,r,t,s)=>{let o=e.length>2,n=nr(t[3]),i=nr(t[2]),a=Me.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],u=[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],c=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];Dn(r,c),c.push(...ut(l,u,p));let d=(i-1)*r.strides[1]+u[1],_=f=>{let v=tt("output",e[0].dataType,p.length,n),$=$r(v.type.tensor),g=On(r,v.type.value,$),w=Ce("x",e[0].dataType,l.length,n),C=Ce("w",e[1].dataType,u.length,n),E=[w,C];o&&E.push(Ce("b",e[2].dataType,e[2].dims,n));let x=o?"value += b[output_channel];":"",b=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ln(r,b),` + ${f.registerUniforms(b).declareVariables(...E,v)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${w.type.value}, ${d}>; + var values: array<${v.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${d}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${w.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${w.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${C.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${x} + ${g} + ${v.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${d};${u[0]};${u[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:_}}}),ag,ra,lg,sa,Gu,ou,ug,cg,Ku,Ex=je(()=>{xt(),vx(),xx(),wc(),Tx(),Bn(),gc(),tn(),ag=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((d,_)=>d+(d-1)*(t[_]-1)),c=a.map((d,_)=>d+s[_]+s[_+l]).map((d,_)=>Math.floor((d-p[_]+o[_])/o[_]));return c.splice(0,0,i),c.splice(n?3:1,0,u),c},ra=[2,3,1,0],lg=(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 o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},sa=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=mc(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},ou=(e,r,t,s)=>{let o=t.format==="NHWC",n=ag(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let b=[r[0]];if(o){let y=e.kernelCustomData.wT??e.compute(Yr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=y),b.push(y)}else b.push(r[1]);r.length===3&&b.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(Ey(b,t,n,s),{inputs:b}):e.compute(Ty(b,t,n,s),{inputs:b});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],c=r[1].dims[3],d=n[o?1:2],_=n[o?2:3],f=n[o?3:1],v=o&&p===a&&c===l&&t.pads[0]===0&&t.pads[1]===0;if(v||p===1&&c===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 b=n[0],y,S,F,z=[];if(o){let R=e.kernelCustomData.wT??e.compute(Yr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=R),v){let Z=a*l*u;y=r[0].reshape([1,b,Z]),S=R.reshape([1,Z,f]),F=[1,b,f]}else y=r[0].reshape([b,a*l,u]),S=R.reshape([1,u,f]),F=[b,d*_,f];z.push(y),z.push(S)}else y=r[0].reshape([b,u,a*l]),S=r[1].reshape([1,f,u]),F=[b,f,d*_],z.push(S),z.push(y);i&&z.push(r[2]);let K=F[2],q=z[0].dims[z[0].dims.length-1];K<8&&q<8?e.compute(_c(z,t,n,F,o,s),{inputs:z}):e.compute(_a(z,t,n,F,o,s),{inputs:z});return}let $=!0,g=e.kernelCustomData.wT??e.compute(Yr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let w=[r[0],g];i&&w.push(r[2]);let C=o?d*_:f,E=o?f:d*_,x=p*c*u;e.compute(yy(w,t,n,C,E,x,i,$,s),{inputs:w})},ug=(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 o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=sa({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);ou(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},cg=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=sa(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=vy(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(xy(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Ku=(e,r)=>{if(lg(e.inputs,r),e.inputs[0].dims.length===3)ug(e,r);else if(e.inputs[0].dims.length===5)cg(e,e.inputs,r);else{let t=sa(r,e.inputs);ou(e,e.inputs,t)}}}),Py,Px=je(()=>{ft(),Ns(),xt(),Tt(),Py=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,u=a[3],p=n?nr(l):1,c=n&&u===1&&l>=4,d=c?Math.floor(l/4)*4:Math.floor(l/p)*p,_=l-d,f=n?nr(u):1,v=n?u===1?p:f:1,$=Me.size(o)/f,g=[Math.ceil($/64),1,1];It("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${g}`);let w=["rank","rank"],C=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],x=[r.dilations[0],r.dilations[1]],b=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],y=[b[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),b[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:$},{type:12,data:C},{type:12,data:E},{type:12,data:x},{type:12,data:b},{type:6,data:y},{type:12,data:d},{type:12,data:l},{type:12,data:u},...ut(e[0].dims,e[1].dims)];s&&(S.push(...ut(e[2].dims)),w.push("rank")),S.push(...ut(o));let F=z=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:C.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:b.length},{name:"pads",type:"i32",length:y.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=$r(e[0].dataType),R=n?1:2,Z=n?2:3,H=n?3:1,J=Ce("W",e[1].dataType,e[1].dims.length,v),Q=Ce("Dy",e[0].dataType,e[0].dims.length,p),se=[Q,J];s&&se.push(Ce("bias",e[2].dataType,[o[H]].length,f));let fe=tt("result",e[0].dataType,o.length,f),ae=()=>{let U="";if(c)p===4?U+=` + let xValue = ${Q.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?U+=` + dotProd = dotProd + dot(vec4<${q}>(${Q.getByOffset("x_offset")}, ${Q.getByOffset("x_offset + 1u")}), vec4<${q}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(U+=` + dotProd = dotProd + dot(vec4<${q}>(${Q.getByOffset("x_offset")}, ${Q.getByOffset("x_offset + 1u")}, ${Q.getByOffset("x_offset + 2u")}, ${Q.getByOffset("x_offset + 3u")}), vec4<${q}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")}, ${J.getByOffset("w_offset + 2u")}, ${J.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(U+=` + let xValue = ${n?Q.getByOffset(`${Q.indicesToOffset(`${Q.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Q.get("batch","inputChannel","idyR","idyC")}; + `,p===1)U+=` + let w_offset = ${J.indicesToOffset(`${J.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${J.getByOffset(`w_offset / ${v}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let ee=0;ee{if(_===0)return"";if(!c)throw new Error(`packInputAs4 ${c} is not true.`);let U="";if(p===1){U+="dotProd = dotProd";for(let ee=0;ee<_;ee++)U+=` + + ${Q.getByOffset(`x_offset + ${ee}`)} * ${J.getByOffset(`w_offset + ${ee}`)}`;U+=";"}else if(p===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);U+=` + let xValue = ${Q.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue);`}return U},A=` + let outputIndices = ${fe.offsetToIndices(`global_idx * ${f}`)}; + let batch = ${fe.indicesGet("outputIndices",0)}; + let d1 = ${fe.indicesGet("outputIndices",H)}; + let r = ${fe.indicesGet("outputIndices",R)}; + let c = ${fe.indicesGet("outputIndices",Z)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${fe.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${q}(dyRCorner) + ${q}(wR)) / ${q}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${q}(uniforms.Dy_shape[${R}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${q}(dyCCorner) + ${q}(wC)) / ${q}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${q}(uniforms.Dy_shape[${Z}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${c?` + var x_offset = ${Q.indicesToOffset(`${Q.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${J.indicesToOffset(`${J.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${v}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${c?4:p}) { + ${ae()} + inputChannel = inputChannel + ${c?4:p}; + } + ${V()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${f}]`:""}; + ${fe.setByOffset("global_idx","value")}; + `;return` + ${z.registerUniforms(K).declareVariables(...se,fe)} + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${A}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${v}${f}${c}${_}`,inputDependencies:w},getRunData:()=>({dispatchGroup:{x:g[0],y:g[1],z:g[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:F}}}),dg,pg,hg,iu,Cy,mg,au,fg,Sy,Cx=je(()=>{Px(),Bn(),tn(),dg=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,pg=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},hg=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,c=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((c,d)=>c*d,1)===0){t.length=0;for(let c=2;cc+d,0)===0){let c=r[0].dims.length-2;l=new Array(c).fill(1)}let u=e.strides.slice();if(u.reduce((c,d)=>c+d,0)===0){let c=r[0].dims.length-2;u=new Array(c).fill(1)}hg(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},Cy=e=>{let r=mc(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,c=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:c,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},mg=(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 o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+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((i,a)=>i+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")},au=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(Yr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(Py(n,t,s),{inputs:n})},fg=(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 o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let u=iu({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);au(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Sy=(e,r)=>{if(mg(e.inputs,r),e.inputs[0].dims.length===3)fg(e,r);else{let t=iu(r,e.inputs);au(e,e.inputs,t)}}}),_g,$y,ky,Sx=je(()=>{ft(),xt(),lr(),Tt(),_g=(e,r,t,s)=>{let o=Me.size(r),n=r.length,i=Ce("input",e,n),a=tt("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Me.normalizeAxis(l,n),p=c=>{let d=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,_=ot("uniforms.input_shape","uniforms.axis",n),f=s.reverse?d+(s.exclusive?" + 1":""):"0",v=s.reverse?_:d+(s.exclusive?"":" + 1");return` + ${c.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${f}; + let last : i32 = ${v}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.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(o/64)},programUniforms:[{type:12,data:o},{type:12,data:u},...ut(r,r)]}),getShaderSource:p}},$y=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(_g(s,t,o,r),{inputs:[0]})},ky=e=>{let r=e.exclusive===1,t=e.reverse===1;return Nt({exclusive:r,reverse:t})}}),gg,wg,bg,Iy,Ay,$x=je(()=>{ft(),xt(),lr(),Tt(),gg=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.")},wg=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let c=e.reshape(i),d=c.dims.length,_=e.dataType,f=Ce("a",_,d),v=tt("output",_,d),$=g=>` + ${g.registerUniform("output_size","u32").declareVariables(f,v)} + + ${wg(a,d,f,v)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${v.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${v.setByOffset("global_idx",f.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:g=>{let w=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],C=Me.size(w),E=c.dims,x=Me.sortBasedOnPerm(E,a);return{outputs:[{dims:w,dataType:g[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...ut(E,x)]}},getShaderSource:$}},Iy=(e,r)=>{gg(e.inputs),e.compute(bg(e.inputs[0],r))},Ay=e=>Nt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),na,Uo,lu,Mg,yg,vg,xg,uu,Tg,Fy,Oy,kx=je(()=>{ft(),xt(),lr(),Tt(),na="[a-zA-Z]|\\.\\.\\.",Uo="("+na+")+",lu="^"+Uo+"$",Mg="("+Uo+",)*"+Uo,yg="^"+Mg+"$",vg=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)}},xg=class{constructor(e,r){var o;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(yg)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(lu)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(Uo)))throw new Error("Invalid RHS");(o=s.match(RegExp(na,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.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 o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(lu))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(na,"g")),u=new vg(s);return l==null||l.forEach((p,c)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let d=o-l.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+d),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let _=0;_e+"_max",Tg=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Ce(`input${p}`,r,u)),n=Me.size(s),i=tt("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],c="var prod = 1.0;",d="var sum = 0.0;",_="sum += prod;",f=[],v=[],$=[],g=[],w=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,x)=>{var b;if(t.rhs.symbolToIndices.has(x)){let y=(b=t.rhs.symbolToIndices.get(x))==null?void 0:b[0];y!==void 0&&t.lhs.forEach((S,F)=>{if(E.inputIndices.includes(F)){let z=S.symbolToIndices.get(x);if(z===void 0)throw new Error("Invalid symbol error");z.forEach(K=>{p.push(`${o[F].indicesSet(`input${F}Indices`,K,i.indicesGet("outputIndices",y))}`)})}})}else t.lhs.forEach((y,S)=>{if(E.inputIndices.includes(S)){let F=y.symbolToIndices.get(x);if(F===void 0)throw new Error("Invalid symbol error");F.forEach(z=>{f.push(`${o[S].indicesSet(`input${S}Indices`,z,`${x}`)}`)}),g.push(`prod *= ${o[S].getByIndices(`input${S}Indices`)};`)}}),v.push(`for(var ${x}: u32 = 0; ${x} < uniforms.${uu(x)}; ${x}++) {`),$.push("}")});let C=w?[...p,`let sum = ${o.map((E,x)=>E.getByIndices(`input${x}Indices`)).join(" * ")};`]:[...p,d,...v,...f,c,...g,_,...$];return` + ${u.registerUniforms(a.map(E=>({name:`${uu(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((E,x)=>`var input${x}Indices: ${o[x].type.indices};`).join(` +`)} + ${C.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(c=>t.symbolToInfo.has(c)).map(c=>{var d;return{type:12,data:((d=t.symbolToInfo.get(c))==null?void 0:d.dimValue)||0}});u.push({type:12,data:n});let p=e.map((c,d)=>[...ut(c)]).reduce((c,d)=>c.concat(d),u);return p.push(...ut(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Fy=(e,r)=>{let t=new xg(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(Tg(o,e.inputs[0].dataType,t,s))},Oy=e=>{let r=e.equation.replace(/\s+/g,"");return Nt({equation:r})}}),Eg,cu,Pg,Cg,Dy,Ix=je(()=>{ft(),xt(),Tt(),Eg=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 o=0;oe.length>r.length?cu(e,r):cu(r,e),Cg=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Pg(r,t),o=e[0].dataType,n=o===9||Me.size(r)===1,i=o===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(Me.size(s)/a),u=c=>{let d=Ce("input",o,r.length,i),_=tt("output",o,s.length,a),f;if(o===9){let v=($,g,w="")=>` + let outputIndices${g} = ${_.offsetToIndices(`outputOffset + ${g}u`)}; + let offset${g} = ${d.broadcastedIndicesToOffset(`outputIndices${g}`,_)}; + let index${g} = offset${g} / 4u; + let component${g} = offset${g} % 4u; + ${$}[${g}] = ${w}(${d.getByOffset(`index${g}`)}[component${g}]); + `;f=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${v("data",0,"u32")} + ${v("data",1,"u32")} + ${v("data",2,"u32")} + ${v("data",3,"u32")} + ${_.setByOffset("global_idx","data")} + }`}else f=` + let outputIndices = ${_.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",_)}; + let data = ${_.type.value}(${d.getByOffset(`inputOffset / ${i}`)}); + ${_.setByOffset("global_idx","data")} + }`;return` + ${c.registerUniform("vec_size","u32").declareVariables(d,_)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${f}`},p=[{type:12,data:l},...ut(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Dy=e=>{Eg(e.inputs),e.compute(Cg(e.inputs),{inputs:[0]})}}),Sg,Ly,Ax=je(()=>{ft(),xt(),Tt(),hc(),Sg=e=>{let r=e[0].dataType,t=Me.size(e[0].dims),s=Me.size(e[1].dims),o=s%4===0,n=i=>{let a=Ce("x",r,[1],4),l=Ce("bias",r,[1],4),u=tt("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],c=_=>` + let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size; + let bias${_} = ${l.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,d=o?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${c(0)}${c(1)}${c(2)}${c(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,u)} + + ${Nu(Rr(r))} + + ${i.mainStart(oo)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${u.setByOffset("global_idx",Vu("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/oo/4)}})}},Ly=e=>{e.inputs.length<2||Me.size(e.inputs[1].dims)===0?ry(e):e.compute(Sg(e.inputs))}}),$g,kg,zy,By,Fx=je(()=>{ft(),xt(),lr(),Tt(),$g=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},kg=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(Me.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...ut(e[0].dims,e[1].dims,i)],c=d=>{let _=Ce("data",e[0].dataType,e[0].dims.length,l),f=Ce("inputIndices",e[1].dataType,e[1].dims.length),v=tt("output",e[0].dataType,i.length,l),$=w=>{let C=s.length,E=`var indicesIndices${w} = ${f.type.indices}(0);`;for(let x=0;x1?`indicesIndices${w}[${x}]`:`indicesIndices${w}`} = ${i.length>1?`outputIndices${w}[uniforms.axis + ${x}]`:`outputIndices${w}`};`;E+=` + var idx${w} = ${f.getByIndices(`indicesIndices${w}`)}; + if (idx${w} < 0) { + idx${w} = idx${w} + uniforms.axisDimLimit; + } + var dataIndices${w} : ${_.type.indices}; + `;for(let x=0,b=0;x1?`dataIndices${w}[${x}]`:`dataIndices${w}`} = u32(idx${w});`,b+=C):(E+=`${o>1?`dataIndices${w}[${x}]`:`dataIndices${w}`} = ${i.length>1?`outputIndices${w}[${b}]`:`outputIndices${w}`};`,b++);return E},g;if(e[0].dataType===9){let w=(C,E,x="")=>` + let outputIndices${E} = ${v.offsetToIndices(`outputOffset + ${E}u`)}; + ${$(E)}; + let offset${E} = ${_.indicesToOffset(`dataIndices${E}`)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${C}[${E}] = ${x}(${_.getByOffset(`index${E}`)}[component${E}]); + `;g=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${w("value",0,"u32")} + ${w("value",1,"u32")} + ${w("value",2,"u32")} + ${w("value",3,"u32")} + ${v.setByOffset("global_idx","value")} + `}else g=` + let outputIndices = ${v.offsetToIndices("global_idx")}; + ${$("")}; + let value = ${_.getByIndices("dataIndices")}; + ${v.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,f,v)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${g} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:c}},zy=e=>Nt({axis:e.axis}),By=(e,r)=>{let t=e.inputs;$g(t),e.compute(kg(e.inputs,r))}}),Ig,Ry,jy,Ox=je(()=>{ft(),xt(),Tt(),Ig=(e,r,t,s,o,n,i,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...ut(r.dims,p));let c=d=>{let _=Ce("indices_data",r.dataType,r.dims.length),f=tt("input_slice_offsets_data",12,1,1),v=[_,f],$=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.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` + ${d.registerUniforms($).declareVariables(...v)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:c},{inputs:[r],outputs:[-1]})[0]},Ry=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=Me.sizeToDimension(n,n.length-1),l=Me.sizeFromDimension(s,r.batchDims+i),u=Me.sizeToDimension(s,r.batchDims),p=Me.sizeFromDimension(s,r.batchDims),c=a/u,d=new Array(i),_=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let $=n.slice(0,-1).concat(s.slice(v)),g=Me.size($),w=[{type:12,data:g},{type:12,data:l},...ut(t[0].dims,f.dims,$)],C=E=>{let x=Ce("data",t[0].dataType,t[0].dims.length),b=Ce("slice_offsets",12,f.dims.length),y=tt("output",t[0].dataType,$.length);return` + ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(x,b,y)} + ${E.mainStart()} + ${E.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:$,dataType:o}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:w}),getShaderSource:C},{inputs:[t[0],f]})},jy=e=>({batchDims:e.batch_dims,cacheKey:""})}),Ag,Fg,Ny,Vy,Dx=je(()=>{ft(),xt(),lr(),Tt(),Ag=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Me.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.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(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.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.")}},Fg=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.gatherAxis,o),i=Me.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=Me.size(a),u=e[2].dataType,p=e[0].dataType===22,c=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...ut(...e.map((_,f)=>_.dims),a)],d=_=>{let f=Ce("data",e[0].dataType,e[0].dims.length),v=Ce("inputIndices",e[1].dataType,e[1].dims.length),$=Ce("scales",e[2].dataType,e[2].dims.length),g=e.length>3?Ce("zeroPoint",e[3].dataType,e[3].dims.length):void 0,w=tt("output",u,a.length),C=[f,v,$];g&&C.push(g);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${_.registerUniforms(E).declareVariables(...C,w)} + ${_.mainStart()} + let output_indices = ${w.offsetToIndices("global_idx")}; + var indices_indices = ${v.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${w.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${v.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${w.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${f.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${w.indicesGet("output_indices","i")}; + ${f.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${v.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${w.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${f.indicesSet("data_indices","i","index")}; + } + 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 = ${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]; + var scale_indices = data_indices; + let quantize_axis_index = ${$.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${$.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${$.getByIndices("scale_indices")}; + ${g?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${g.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${g.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 = ${Rr(u)}(quantized_data - zero_point) * scale; + ${w.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((_,f)=>f!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,f)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:d}},Ny=(e,r)=>{let t=e.inputs;Ag(t,r),e.compute(Fg(e.inputs,r))},Vy=e=>Nt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Og,Dg,Uy,Wy,Lx=je(()=>{ft(),xt(),lr(),Tt(),Og=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.`)},Dg=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=Me.normalizeAxis(r.axis,o),l=t[a],u=n.slice(0),p=Me.size(u),c=Ce("input",s,o),d=Ce("indicesInput",i,n.length),_=tt("output",s,u.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return f.push(...ut(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:v=>` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,d,_)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${_.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${c.type.indices}(outputIndices); + ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${c.getByIndices("inputIndices")}; + + ${_.setByOffset("global_idx","value")}; + }`}},Uy=e=>Nt({axis:e.axis}),Wy=(e,r)=>{let t=e.inputs;Og(t),e.compute(Dg(e.inputs,r))}}),Lg,zg,Gy,Ky,zx=je(()=>{ft(),xt(),Tt(),Lg=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")},zg=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=Ub.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(n/l),p=Math.ceil(o/l),c=!0,d=Me.size(a),_=[{type:12,data:c?u:d},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(_.push(...ut(e[2].dims)),f.push("rank")),_.push(...ut(a));let v=g=>{let w="";r.transA&&r.transB?w="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?w="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?w="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(w="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=r.alpha===1?"":"value *= uniforms.alpha;",E=Ce("a",e[0].dataType,e[0].dims),x=Ce("b",e[1].dataType,e[1].dims),b=E.type.value,y=null,S=[E,x];e.length===3&&(y=Ce("c",e[2].dataType,e[2].dims.length),S.push(y));let F=tt("output",e[0].dataType,a.length);S.push(F);let z=[{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` + ${g.registerUniforms(z).declareVariables(...S)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${b}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${w} + } + + ${C} + ${y!=null?`let cOffset = ${y.broadcastedIndicesToOffset("vec2(m, n)",F)}; value += ${b}(uniforms.beta) * ${y.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},$=g=>{let w=Ce("a",e[0].dataType,e[0].dims),C=Ce("b",e[1].dataType,e[1].dims),E=null,x=[w,C];e.length===3&&(E=Ce("c",e[2].dataType,e[2].dims.length),x.push(E));let b=tt("output",e[0].dataType,a.length);x.push(b);let y=[{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"}],S="",F="";r.transA&&r.transB?(F=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${w.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + 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] = ${C.type.value}(0); + } + `,S="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(F=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${w.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + 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] = ${C.type.value}(0); + } + `,S="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(F=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${w.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + 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] = ${C.type.value}(0); + } + `,S="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(F=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${w.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + 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] = ${C.type.value}(0); + } + `,S="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let z=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${g.registerUniforms(y).declareVariables(...x)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${g.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; + var k_start = 0u; + var value = ${b.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${F} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${S} + } + workgroupBarrier(); + } + + ${z} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",b)}; value += ${b.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return c?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:_}),getShaderSource:$}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:v}},Gy=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Ky=(e,r)=>{Lg(e.inputs),e.compute(zg(e.inputs,r))}}),Ds,Bs,Pn,Cn,Bg,Rg,jg,Ng,Vg,Ug,Wg,Gg,Hy,qy,Bx=je(()=>{ft(),xt(),lr(),Tt(),[Ds,Bs,Pn,Cn]=[0,1,2,3],Bg=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")},Rg=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,jg=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,Ng=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,Vg=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,Ug=(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); + indices[${Ds}] = batch; + indices[${Bs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Pn}] = u32(r); + indices[${Cn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${Pn}] = u32(clamp(r, 0, H - 1)); + indices[${Cn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Pn}] = gs_reflect(r, border[1], border[3]); + indices[${Cn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,Wg=(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[${Ds}], indices[${Bs}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Ds}], indices[${Bs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Ds}], indices[${Bs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Ds}], indices[${Bs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Ds}], indices[${Bs}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Ds}], indices[${Bs}], border); + } + } + + 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")}`,Gg=(e,r)=>{let t=Ce("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Ce("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]],[Ds,Bs,Pn,Cn]=[0,3,1,2]);let i=tt("output",e[0].dataType,n.length),a=t.type.value,l=Me.size(n),u=[{type:12,data:l},...ut(e[0].dims,s,n)],p=c=>` + ${c.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${Rg} + ${jg(a)} + ${Ng(r)} + ${Vg(r)} + ${Ug(t,a,r)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Pn}]); + let W_in = i32(uniforms.x_shape[${Cn}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Ds}], indices[${Pn}], indices[${Cn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${Wg(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:c=>{let d=Me.size(n);return{outputs:[{dims:n,dataType:c[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:u}},getShaderSource:p}},Hy=(e,r)=>{Bg(e.inputs),e.compute(Gg(e.inputs,r))},qy=e=>Nt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Ur,Kg,Qy,du,Hg,Jo,Xy,Jy=je(()=>{ft(),xt(),lr(),uc(),pc(),Tt(),tn(),Ur=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Kg=(e,r)=>{let t=e[0],s=Ur(e,1),o=Ur(e,2),n=Ur(e,3),i=Ur(e,4),a=Ur(e,5),l=Ur(e,6),u=Ur(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],c=t.dims[1],d=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],_=c,f=0,v=0,$=Math.floor(d/r.numHeads);if(l&&u&&Me.size(l.dims)&&Me.size(u.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]!==$)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==$)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],v=l.dims[2]}else if(l&&Me.size(l.dims)||u&&Me.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g;if(s&&Me.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)');g=2,_=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');g=5,_=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');g=0,_=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');g=3}if(n&&Me.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 w=f+_,C=0;if(i&&Me.size(i.dims)>0){C=8;let y=i.dims;throw y.length===1?y[0]===p?C=1:y[0]===3*p+2&&(C=3):y.length===2&&y[0]===p&&y[1]===w&&(C=5),C===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let E=!1,x=d;if(o&&Me.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');x=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');x=o.dims[1]*o.dims[3],E=!0}}let b=!1;if(i&&Me.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&Me.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]!==c||a.dims[3]!==w)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:c,pastSequenceLength:f,kvSequenceLength:_,totalSequenceLength:w,maxSequenceLength:v,inputHiddenSize:0,hiddenSize:d,vHiddenSize:x,headSize:$,vHeadSize:Math.floor(x/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:C,scale:r.scale,broadcastResPosBias:b,passPastInKv:E,qkvFormat:g}},Qy=e=>Nt({...e}),du=Nt({perm:[0,2,1,3]}),Hg=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=Me.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=c=>{let d=tt("qkv_with_bias",r.dataType,a),_=Ce("qkv",r.dataType,a),f=Ce("bias",t.dataType,a),v=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${c.registerUniforms(v).declareVariables(_,f,d)} + ${c.mainStart()} + ${c.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:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Jo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&Me.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Hg(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(Yr(l,du.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(Yr(l,du.perm),{inputs:[l],outputs:[-1]})[0]},Xy=(e,r)=>{let t=Kg(e.inputs,r),s=e.inputs[0],o=Ur(e.inputs,1),n=Ur(e.inputs,2),i=Ur(e.inputs,3),a=Ur(e.inputs,4),l=Ur(e.inputs,5),u=Ur(e.inputs,6),p=Ur(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let c=o&&n&&o.dims.length===4&&n.dims.length===4,d=Jo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(c)return ti(e,d,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let _=Jo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),f=Jo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);ti(e,d,_,f,a,void 0,u,p,l,t)}}),qg,Qg,Xg,Jg,Hu,Yy,Zy,e0=je(()=>{ft(),xt(),lr(),Tt(),qg=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Qg=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),Nt({numOutputs:s,axis:r.axis,splitSizes:t})},Xg=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${ot("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Jg=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Me.size(t),o=e[0].dataType,n=Me.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Ce("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],c=0,d=[{type:12,data:s}];for(let f=0;f` + ${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${Xg(l.length)} + ${Jg(i)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${ot("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d})}},Yy=(e,r)=>{qg(e.inputs);let t=e.inputs.length===1?r:Qg(e.inputs,r);e.compute(Hu(e.inputs,t),{inputs:[0]})},Zy=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 Nt({axis:r,numOutputs:s,splitSizes:t})}}),Yg,ga,t0,r0=je(()=>{ft(),xt(),lr(),Tt(),Yg=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,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(!Me.areEqual(s.dims,[])&&!Me.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(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Me.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],p=o.dims[0],c=Me.sizeFromDimension(t.dims,1)/u,d=a===0?o.dims[1]*2:c/i;if(a>d)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(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(d/2!==o.dims[1]&&a/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ga=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=Me.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],c=o===0?p*2:u/s,d=new Array(i,l,u/c,c-p),_=Me.computeStrides(d),f=[{type:1,data:n},{type:12,data:d},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[a,u,c,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,c,l*c,1]}):[],...ut(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],v=$=>{let g=Ce("input",e[0].dataType,e[0].dims.length),w=Ce("position_ids",e[1].dataType,e[1].dims.length),C=Ce("cos_cache",e[2].dataType,e[2].dims.length),E=Ce("sin_cache",e[3].dataType,e[3].dims.length),x=tt("output",e[0].dataType,e[0].dims.length);return $.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),` + ${$.declareVariables(g,w,C,E,x)} + + ${$.mainStart(oo)} + let half_rotary_emb_dim = uniforms.${C.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${$.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${w.broadcastedIndicesToOffset("bsnh.xy",tt("",w.type.tensor,2))}; + let position_id = + u32(${w.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 = ${g.getByOffset("i")} * ${C.get("position_id","bsnh[3]")} - + ${g.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; + ${x.setByOffset("i","re")} + let im = ${g.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + + ${g.getByOffset("j")} * ${C.get("position_id","bsnh[3]")}; + ${x.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${x.setByOffset("k",g.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Nt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(d)/oo)},programUniforms:f})}},t0=(e,r)=>{Yg(e.inputs,r),e.compute(ga(e.inputs,r))}}),Zg,ew,pu,tw,s0,Rx=je(()=>{lr(),ft(),pc(),Jy(),e0(),tn(),r0(),Tt(),Zg=(e,r)=>{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],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");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],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],c=u,d=0,_=!s||s.dims.length===0,f=Math.floor(_?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);_&&(p=f*r.numHeads);let v=n&&n.dims.length!==0,$=i&&i.dims.length!==0;if(v&&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(v&&$){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=n.dims[2]}else if(v||$)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=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"');c=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');c=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');c=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');g=3}let w=0,C=!1,E=r.kvNumHeads?f*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(c!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(c!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],C=!0}}let x=e.length>4?e[5]:void 0;if(x&&x.dims.length!==1&&x.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:u,pastSequenceLength:d,kvSequenceLength:c,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:f,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:w,scale:r.scale,broadcastResPosBias:!1,passPastInKv:C,qkvFormat:g}},ew=Nt({perm:[0,2,1,3]}),pu=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(Yr(s,ew.perm),{inputs:[s],outputs:[-1]})[0]),s},tw=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],u=p=>{let c=Ce("seq_lens",t.dataType,t.dims),d=Ce("total_seq_lens",s.dataType,s.dims),_=tt("pos_ids",o,i),f=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(f).declareVariables(c,d,_)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${d.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${c.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${_.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:u}},s0=(e,r)=>{var E;let t=Zg(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=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,i=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,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,c=Nt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[d,_,f]=!o&&!n?e.compute(Hu([s],c),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],v,$;if(r.doRotary){let x=e.compute(tw(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],b=e.inputs[7],y=e.inputs[8],S=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),F=[d,x,b,y],z=[-1];v=e.compute(ga(F,S),{inputs:F,outputs:z})[0],F.splice(0,1,_);let K=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});$=e.compute(ga(F,K),{inputs:F,outputs:z})[0]}let g=Jo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?v:d,void 0,0),w=pu(e,r.doRotary?$:_,t),C=pu(e,f,t);ti(e,g,w,C,void 0,void 0,i,a,void 0,t,l,u)}}),hu,rw,sw,n0,jx=je(()=>{ft(),xt(),tn(),Tt(),hu=(e,r,t,s,o,n,i,a)=>{let l=nr(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,c=o*i,d=64;c===1&&(d=256);let _=[o,i,n/l],f=[o,i,2],v=["rank","type","type"],$=[];$.push(...ut(_,f));let g=w=>{let C=Ce("x",r.dataType,3,l),E=Ce("scale",t.dataType,t.dims),x=Ce("bias",s.dataType,s.dims),b=tt("output",1,3,2),y=[C,E,x,b];return` + var workgroup_shared : array<${p}, ${d}>; + const workgroup_size = ${d}u; + ${w.declareVariables(...y)} + ${w.mainStart(d)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${u}(0); + var squared_sum = ${u}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${u}(${C.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${en("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${en("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + 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};${d}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:c},programUniforms:$}),getShaderSource:g},{inputs:[r,t,s],outputs:[-1]})[0]},rw=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=Me.sizeFromDimension(s,n),u=nr(l),p=Me.size(o)/u,c=hu(e,r[0],r[1],r[2],i,l,a,t.epsilon),d=[i,a,l/u],_=[i,a],f=["type","none"],v=$=>{let g=Ce("x",r[0].dataType,d.length,u),w=Ce("scale_shift",1,_.length,2),C=tt("output",r[0].dataType,d.length,u),E=[g,w,C];return` + ${$.registerUniform("output_size","u32").declareVariables(...E)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${C.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${w.getByIndices("vec2(batch, channel)")}; + let value = ${g.getByOffset("global_idx")} * ${C.type.value}(scale_shift.x) + ${C.type.value}(scale_shift.y); + ${C.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ut(d,_,d)]}),getShaderSource:v},{inputs:[r[0],c]})},sw=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=Me.sizeFromDimension(s,1)/i,l=nr(i),u=Me.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],c=["type","type"],d=!1,_=[0,s.length-1];for(let g=0;gs[_[w]])),v=hu(e,f,r[1],r[2],n,a,i,t.epsilon),$=g=>{let w=$r(r[0].dataType),C=l===1?"vec2f":`mat${l}x2f`,E=y=>{let S=y===0?"x":"y",F=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${w}(${F}(scale.${S}))`;case 2:return`vec2<${w}>(${F}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${w}>(${F}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},x=Ce("input",r[0].dataType,r[0].dims,l),b=tt("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${x.type.storage}>; + @group(0) @binding(1) var scale_input : array<${C}>; + @group(0) @binding(2) var output : array<${b.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${g.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], ${E(0)}, ${E(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:$},{inputs:[r[0],v]})},n0=(e,r)=>{r.format==="NHWC"?sw(e,e.inputs,r):rw(e,e.inputs,r)}}),nw,ow,o0,Nx=je(()=>{ft(),xt(),Tt(),nw=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},ow=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=Me.normalizeAxis(r.axis,o.length),u=Me.sizeToDimension(o,l),p=Me.sizeFromDimension(o,l),c=Me.size(n.dims),d=i?Me.size(i.dims):0;if(c!==p||i&&d!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${c} and bias size of ${d}`);let _=[];for(let x=0;x1,w=t>2,C=x=>{let b=$r(e[0].dataType),y=[Ce("x",e[0].dataType,e[0].dims,f),Ce("scale",n.dataType,n.dims,f)];i&&y.push(Ce("bias",i.dataType,i.dims,f)),y.push(tt("output",e[0].dataType,a,f)),g&&y.push(tt("mean_data_output",1,_)),w&&y.push(tt("inv_std_output",1,_));let S=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${x.registerUniforms(S).declareVariables(...y)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Bu("f32",f)}; + var mean_square_vector = ${Bu("f32",f)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${so(b,f,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${en("mean_vector",f)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${en("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 = ${so(b,f,"x[j + offset]")}; + let f32scale = ${so(b,f,"scale[j]")}; + output[j + offset] = ${y[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${so(b,f,"bias[j]")}`:""} + ); + } + + ${g?"mean_data_output[global_idx] = mean":""}; + ${w?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:a,dataType:e[0].dataType}];return g&&E.push({dims:_,dataType:1}),w&&E.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:v},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:$}),getShaderSource:C}},o0=(e,r)=>{nw(e.inputs),e.compute(ow(e.inputs,r,e.outputCount))}}),iw,i0,Vx=je(()=>{xt(),gc(),wc(),iw=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.")},i0=e=>{iw(e.inputs);let r=no.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(_c(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=Me.size(e.inputs[0].dims.slice(0,-2)),i=Me.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),u=[1,n,t],p=[a,l];e.compute(_a(p,{activation:""},r,u),{inputs:p})}else e.compute(_a(e.inputs,{activation:""},r))}}}),aw,lw,uw,a0,l0,Ux=je(()=>{ft(),xt(),lr(),Tt(),aw=(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 o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!Me.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(Me.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(Me.size(l)!==u)throw new Error("zeroPoints input size error.")}},lw=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=nr(r.k),d=nr(u),_=nr(i),f=a.concat([o,i]),v=o>1&&i/_%2===0?2:1,$=Me.size(f)/_/v,g=64,w=[],C=[l,o,n/c],E=Me.convertShape(e[1].dims).slice();E.splice(-1,1,u/d),w.push(...ut(C)),w.push(...ut(E)),w.push(...ut(e[2].dims)),e.length===4&&w.push(...ut(Me.convertShape(e[3].dims)));let x=[l,o,i/_];w.push(...ut(x));let b=y=>{let S=C.length,F=Ce("a",e[0].dataType,S,c),z=Ce("b",12,E.length,d),K=Ce("scales",e[2].dataType,e[2].dims.length),q=[F,z,K],R=e.length===4?Ce("zero_points",12,e[3].dims.length):void 0;R&&q.push(R);let Z=x.length,H=tt("output",e[0].dataType,Z,_),J=$r(e[0].dataType),Q=(()=>{switch(c){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${c}-component is not supported.`)}})(),se=()=>{let V=` + // reuse a data + var input_offset = ${F.indicesToOffset(`${F.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Q}; + for (var j: u32 = 0; j < ${8/c}; j++) { + a_data[j] = ${F.getByOffset("input_offset")}; + input_offset++; + } + `;for(let A=0;A<_*v;A++)V+=` + b_value = ${d===1?`b${A}_data`:`b${A}_data[i]`}; + b_value_lower = unpack4xU8(b_value & b_mask); + b_value_upper = unpack4xU8((b_value >> 4) & b_mask); + b_quantized_values = ${Q}(${Array.from({length:4},(U,ee)=>`${J}(b_value_lower[${ee}]), ${J}(b_value_upper[${ee}])`).join(", ")}); + b_dequantized_values = ${c===1?`${Q}(${Array.from({length:8},(U,ee)=>`(b_quantized_values[${ee}] - ${R?`zero_point${A}`:"zero_point"}) * scale${A}`).join(", ")});`:`(b_quantized_values - ${Q}(${Array(8).fill(`${R?`zero_point${A}`:"zero_point"}`).join(",")})) * scale${A};`}; + workgroup_shared[local_id.x * ${v} + ${Math.floor(A/_)}]${_>1?`[${A%_}]`:""} += ${Array.from({length:8/c},(U,ee)=>`${c===1?`a_data[${ee}] * b_dequantized_values[${ee}]`:`dot(a_data[${ee}], b_dequantized_values[${ee}])`}`).join(" + ")}; + `;return V},fe=()=>{let V=` + var col_index = col * ${_}; + ${R?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${J}(8);`} + `;for(let A=0;A<_*v;A++)V+=` + let scale${A} = ${K.getByOffset("col_index * nBlocksPerCol + block")}; + ${R?` + zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${R.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${A} = ${J}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${_};`;for(let A=0;A<_*v;A++)V+=` + let b${A}_data = ${z.getByIndices(`${z.type.indices}(col_index, block, word)`)}; + col_index += 1;`;return V+=` + var b_value: u32; + let b_mask: u32 = 0x0F0F0F0Fu; + var b_value_lower: vec4; + var b_value_upper: vec4; + var b_quantized_values: ${Q}; + var b_dequantized_values: ${Q};`,V};return` + var workgroup_shared: array<${H.type.value}, ${v*g}>; + ${y.declareVariables(...q,H)} + ${y.mainStart([g,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${g}) * ${v}`)}; + 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 += ${g}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/c}; + ${fe()} + for (var word: u32 = 0; word < ${u}; word += ${d}) { + ${ae()} + for (var i: u32 = 0; i < ${d}; i++) { + ${se()} + word_offset += ${8/c}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${v}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${g}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${v}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${c};${d};${_};${v};${g}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:$},programUniforms:w}),getShaderSource:b}},uw=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=nr(r.k),d=nr(u),_=a.concat([o,i]),f=128,v=i%8===0?8:i%4===0?4:1,$=f/v,g=$*d*8,w=g/c,C=g/r.blockSize,E=Me.size(_)/v,x=[],b=[l,o,n/c],y=Me.convertShape(e[1].dims).slice();y.splice(-1,1,u/d),x.push(...ut(b)),x.push(...ut(y)),x.push(...ut(e[2].dims)),e.length===4&&x.push(...ut(Me.convertShape(e[3].dims)));let S=[l,o,i];x.push(...ut(S));let F=z=>{let K=b.length,q=Ce("a",e[0].dataType,K,c),R=Ce("b",12,y.length,d),Z=Ce("scales",e[2].dataType,e[2].dims.length),H=[q,R,Z],J=e.length===4?Ce("zero_points",12,e[3].dims.length):void 0;J&&H.push(J);let Q=S.length,se=tt("output",e[0].dataType,Q),fe=$r(e[0].dataType),ae=()=>{switch(c){case 1:return` + let a_data0 = vec4<${fe}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${fe}>(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<${fe}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${fe}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${c}-component is not supported.`)}};return` + var sub_a: array<${q.type.value}, ${w}>; + var inter_results: array, ${v}>; + ${z.declareVariables(...H,se)} + ${z.mainStart([$,v,1])} + let output_indices = ${se.offsetToIndices(`workgroup_index * ${v}`)}; + 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) / ${C} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${w}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${w}; a_offset += ${f}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${q.getByIndices(`${q.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${q.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${C} + local_id.x; + ${J?` + 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); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${fe}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${fe}(8);`} + let scale = ${Z.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${R.getByIndices(`${R.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/c}; + for (var i: u32 = 0; i < ${d}; i++) { + ${ae()} + let b_value = ${d===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<${fe}>(${Array.from({length:4},(V,A)=>`${fe}(b_value_lower[${A}]), ${fe}(b_value_upper[${A}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${fe}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,A)=>`${`dot(a_data${A}, b_dequantized_values[${A}])`}`).join(" + ")}; + word_offset += ${8/c}; + } + workgroupBarrier(); + } + + if (local_idx < ${v}) { + var output_value: ${se.type.value} = ${se.type.value}(0); + for (var b = 0u; b < ${$}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${se.setByIndices(`${se.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${c};${d};${$};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:E},programUniforms:x}),getShaderSource:F}},a0=(e,r)=>{aw(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(uw(e.inputs,r)):e.compute(lw(e.inputs,r))},l0=e=>Nt(e)}),cw,dw,pw,hw,mw,fw,_w,gw,u0,Wx=je(()=>{ft(),xt(),Tt(),cw=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].")}},dw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${ot("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + } + `},pw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${ot("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${ot("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},hw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${ot("uniforms.x_shape",o,r)})) { + k = i32(${ot("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},mw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${ot("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${ot("uniforms.x_shape",o,r)})) { + k -= i32(${ot("uniforms.x_shape",o,r)}); + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},fw=(e,r,t)=>{switch(t.mode){case 0:return dw(e,r,t.pads.length);case 1:return pw(e,r,t.pads.length);case 2:return hw(e,r,t.pads.length);case 3:return mw(e,r,t.pads.length);default:throw new Error("Invalid mode")}},_w=(e,r)=>{let t=Me.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=Me.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...ut(e[0].dims,t));let a=["rank"],l=u=>{let p=tt("output",e[0].dataType,t.length),c=Ce("x",e[0].dataType,s.length),d=c.type.value,_=fw(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:i?d:"f32"}),` + ${u.registerUniforms(f).declareVariables(c,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${_} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(t)/64)},programUniforms:n}),getShaderSource:l}},gw=(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,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},u0=(e,r)=>{cw(e.inputs);let t=gw(e.inputs,r);e.compute(_w(e.inputs,t),{inputs:[0]})}}),Wo,mu,fu,_u,gu,ww,bw,wu,bu,c0,d0,Mu,p0,h0,yu,m0,f0,_0,g0,Gx=je(()=>{Ps(),ft(),xt(),Tt(),Wo=e=>{if(Yt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},mu=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();ma.adjustPoolAttributes(t,o,i,a,l,u);let p=ma.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),c=Object.assign({},r);n?Object.assign(c,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(c,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let d=p.slice();return d.push(d.splice(1,1)[0]),[c,s?d:p]},fu=(e,r)=>{let t=r.format==="NHWC",s=Me.size(e),o=Me.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{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],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],c=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(r.kernelShape.length===2){let _=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],v=r.pads[r.pads.length/2-2],$=r.pads[r.pads.length-2];d=!!(v+$),n.push({type:12,data:_},{type:12,data:f},{type:12,data:v},{type:12,data:$}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,c,d]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=Me.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.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((u,p)=>u+p);return[n,i,!!l,!1,!1]}},_u=(e,r,t,s,o,n,i,a,l,u,p,c)=>{let d=o.format==="NHWC",_=r.type.value,f=tt("output",r.type.tensor,s);if(o.kernelShape.length<=2){let v="",$="",g="",w=t-(d?2:1);if(p?v=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${w}] = indices[${w}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${w}] < 0 || xIndices[${w}] + >= uniforms.x_shape[${w}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:v=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${w}] = indices[${w}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let C=t-(d?3:2);c?$=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${C}] < 0 || xIndices[${C}] >= uniforms.x_shape[${C}]) { + pad += i32(uniforms.kw); + continue; + } + `:$=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j; + `,g=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var value = ${_}(${a}); + var pad = 0; + ${$} + ${v} + ${g} + ${i} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let v=o.kernelShape.length,$=o.pads.length,g="";return u?g=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:g=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${_}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${v-1}u; j++) { + offsets[j] = offset / ${ot("uniforms.kernelStrides","j",v)}; + offset -= offsets[j] * ${ot("uniforms.kernelStrides","j",v)}; + } + offsets[${v-1}] = offset; + + isPad = false; + for (var j = ${t-v}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${ot("uniforms.strides",`j - ${t-v}u`,v)} + + offsets[j - ${t-v}u] - ${ot("uniforms.pads","j - 2u",$)}; + ${g} + } + ${i} + + output[global_idx] = value; + }`}},gu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,ww=e=>`${gu(e)};${e.countIncludePad}`,bw=e=>`${gu(e)};${e.storageOrder};${e.dilations}`,wu=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}),bu=(e,r,t,s)=>{let[o,n]=mu(r,s,t),i=Ce("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,c,d,_,f]=fu(n,o);p.push(...ut(r.dims,n));let v=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${d};${_};${f}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:$=>_u($,i,r.dims.length,n.length,o,l,u,0,c,d,_,f)}},c0=e=>{let r=e.count_include_pad!==0,t=wu(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:ww(s)}},d0=(e,r)=>{Wo(e.inputs),e.compute(bu("AveragePool",e.inputs[0],!1,r))},Mu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},p0=e=>{let r=e.format;return{format:r,...Mu,cacheKey:r}},h0=(e,r)=>{Wo(e.inputs),e.compute(bu("GlobalAveragePool",e.inputs[0],!0,r))},yu=(e,r,t,s)=>{let[o,n]=mu(r,s,t),i=` + value = max(x_val, value); + `,a="",l=Ce("x",r.dataType,r.dims.length),u=["rank"],[p,c,d,_,f]=fu(n,o);return p.push(...ut(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${d};${_};${f}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:v=>_u(v,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,c,d,_,f)}},m0=(e,r)=>{Wo(e.inputs),e.compute(yu("MaxPool",e.inputs[0],!1,r))},f0=e=>{let r=e.storage_order,t=e.dilations,s=wu(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 o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:bw(o)}},_0=e=>{let r=e.format;return{format:r,...Mu,cacheKey:r}},g0=(e,r)=>{Wo(e.inputs),e.compute(yu("GlobalMaxPool",e.inputs[0],!0,r))}}),Mw,yw,w0,b0,Kx=je(()=>{ft(),xt(),lr(),Tt(),Mw=(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((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&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)].")}},yw=(e,r)=>{let t=Me.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=Me.size(n),l=s===3||s===2,u=l?[Math.ceil(Me.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,c=e.length>2?e[2]:void 0,d=c?l?[Math.ceil(Me.size(c.dims)/4)]:c.dims:void 0,_=p.length===0||p.length===1&&p[0]===1,f=_===!1&&p.length===1,v=nr(a),$=_&&(!l||v===4),g=$?v:1,w=$&&!l?v:1,C=Ce("input",l?12:s,u.length,w),E=Ce("scale",i,p.length),x=c?Ce("zero_point",l?12:s,d.length):void 0,b=tt("output",i,n.length,g),y=[C,E];x&&y.push(x);let S=[u,p];c&&S.push(d);let F=[{type:12,data:a/g},{type:12,data:t},{type:12,data:r.blockSize},...ut(...S,n)],z=K=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(q).declareVariables(...y,b)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${b.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${C.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${g===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${C.getByOffset("global_idx")};`}; + + // Set scale input + ${_?`let scale_value= ${E.getByOffset("0")}`:f?` + let scale_index = ${b.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${E.getByOffset("scale_index")};`:` + var scale_indices: ${E.type.indices} = output_indices; + let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${E.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${E.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${x?_?l?` + let zero_point_input = ${x.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${x.getByOffset("0")}`:f?l?` + let zero_point_index = ${b.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${x.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${b.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${x.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${E.indicesToOffset("scale_indices")}; + let zero_point_input = ${x.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${x.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":C.type.value}(0);`}; + // Compute and write output + ${b.setByOffset("global_idx",`${b.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/g/64),y:1,z:1},programUniforms:F})}},w0=(e,r)=>{Mw(e.inputs,r),e.compute(yw(e.inputs,r))},b0=e=>Nt({axis:e.axis,blockSize:e.blockSize})}),vw,xw,M0,Hx=je(()=>{Ps(),ft(),Tt(),vw=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},xw=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ut(n)],l=u=>{let p=tt("output",s,n.length),c=p.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:c},{name:"delta",type:c}];return` + ${u.registerUniforms(d).declareVariables(p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${c}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},M0=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]),Yt.webgpu.validateInputContent&&vw(r,t,s),e.compute(xw(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Tw,vu,xu,Ew,y0,v0,qx=je(()=>{ft(),xt(),lr(),Tt(),Tw=(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 o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},vu=(e,r)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,xu=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${Tw(e.reduction,"output[data_offset + i]","value",r)} + }`,Ew=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(Me.size(s)/n),a=s[s.length-1],l=Me.sizeFromDimension(t,a),u=Me.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ut(e[1].dims,e[2].dims,o)],c=d=>{let _=Ce("indices",e[1].dataType,e[1].dims.length),f=Ce("updates",e[2].dataType,e[2].dims.length,n),v=r.reduction!=="none"&&r.reduction!==""?Xb("output",e[0].dataType,o.length):tt("output",e[0].dataType,o.length,n);return` + ${d.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(_,f,v)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${u}; i = i + 1) { + for (var j = i + 1; j < ${u}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${u}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${vu(t.length,!1)} + } + ${xu(r,v.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${vu(t.length,!0)} + } + ${xu(r,v.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:c}},y0=e=>Nt({reduction:e.reduction}),v0=(e,r)=>{e.compute(Ew(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Pw,Cw,Sw,Tu,$w,kw,Iw,Aw,Fw,Ow,Dw,Lw,Eu,zw,Bw,Rw,jw,Nw,x0,T0,Qx=je(()=>{ft(),xt(),lr(),Tt(),Pw=(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")}},Cw=(e,r,t)=>{r.every(o=>o>=0&&o{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((o,n)=>s[o]=e[n]),s},Sw=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].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!==u&&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");Pw(s,r),r.axes.length>0&&Cw(s,r.axes,u).forEach((p,c)=>s[c]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==u&&t>=18&&o.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(o.length!==0&&o.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 o<"u"&&s.length>0&&o.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},Tu=(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(). + let big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,$w=(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 { + ${Tu("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;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 { + ${Tu("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)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + 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`)}})()+"}",kw=(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`)}})()+"}",Iw=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},Aw=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},Fw=(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 o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},Ow=(e,r,t,s,o)=>` + 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++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${ot("uniforms.scales","i",s)}; + var roi_low = ${ot("uniforms.roi","i",o)}; + var roi_hi = ${ot("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${ot("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${ot("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Dw=(e,r,t,s,o,n,i)=>` + 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++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${ot("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${ot("uniforms.roi","i",n)}; + var roi_hi = ${ot("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${ot("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${ot("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,Lw=(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")}; + if (input_index < 0 || input_index >= ${ot("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Eu=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",zw=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Eu(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${i}]; + var col:${u} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${u} = getInputValue(batch, channel, row1, col1); + var x12: ${u} = getInputValue(batch, channel, row1, col2); + var x21: ${u} = getInputValue(batch, channel, row2, col1); + var x22: ${u} = getInputValue(batch, channel, row2, col2); + var dx1: ${u} = abs(row - ${u}(row1)); + var dx2: ${u} = abs(${u}(row2) - row); + var dy1: ${u} = abs(col - ${u}(col1)); + var dy2: ${u} = abs(${u}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},Bw=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[c,d]=p?[0,1]:[2,3],_=e.type.value,f=v=>{let $=v===c?"row":"col";return` + fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${_} { + var output_index = ${r.indicesGet("output_indices",v)}; + var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[v]}, + ${s[v]}, ${t[v]}, ${n[v]}, ${n[v]} + ${t.length}); + var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[v]} - 1))) { + return ${l}; + } + var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${$}: ${_} = originalIdx + ${_}(i); + if (${$} < 0 || ${$} >= ${t[v]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${$} = max(0, min(${$}, ${t[v]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",v,`u32(${$})`)}; + data[i + 1] = ${v===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${f(c)}; + ${f(d)}; + fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> { + var absS = abs(s); + var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${_} = 1.0 - absS; + var twoMinusAbsS: ${_} = 2.0 - absS; + var onePlusAbsS: ${_} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} { + var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${_} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Rw=(e,r,t,s,o)=>{let[n,i,a,l,u]=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",i,`max(0, min(depth, ${t[i]} - 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))`)}; + ${Eu(e,u,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + 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); + }`},jw=(e,r,t,s,o,n)=>{let i=e.dims,a=Iw(n,r.axes,i.length),l=Aw(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((w,C)=>w===0?1:l[C]/w),r.keepAspectRatioPolicy!=="stretch"&&(l=Fw(i,u,r)));let p=tt("output",e.dataType,l.length),c=Ce("input",e.dataType,i.length),d=Me.size(l),_=i.length===l.length&&i.every((w,C)=>w===l[C]),f=r.coordinateTransformMode==="tf_crop_and_resize",v=r.extrapolationValue,$=c.type.value,g=w=>` + ${_?"":` + ${$w(r.coordinateTransformMode,$)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${Lw(c,i)}; + ${kw(r.nearestMode,t,$)}; + ${Dw(c,p,i,l,u.length,a.length,f)}; + `;case"linear":return` + ${Ow(p,i,l,u.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${zw(c,p,i,f,v)}`;if(i.length===3||i.length===5)return`${Rw(c,p,i,f,v)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${Bw(c,p,i,l,u,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")}})()}; + `} + ${w.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(c,p)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${_?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${c.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${c.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.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}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${_}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:u},{type:1,data:a},...ut(i,l)]})}},Nw=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},x0=(e,r)=>{let t=[],s=[],o=[],n=Nw(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Sw(e.inputs,r,n,t,s,o),e.compute(jw(e.inputs[0],r,n,t,s,o),{inputs:[0]})},T0=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return Nt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),Vw,Uw,E0,Xx=je(()=>{ft(),xt(),Tt(),Vw=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 o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)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]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Uw=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=Me.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],c=!o&&e.length>3,d=e.length>4,_=s&&t>1,f=s&&t>2,v=t>3,$=64,g=nr(u),w=[{type:12,data:l},{type:12,data:g},{type:12,data:u},{type:1,data:r.epsilon}],C=x=>{let b=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],y=[Ce("x",e[0].dataType,e[0].dims,g),Ce("skip",e[1].dataType,e[1].dims,g),Ce("gamma",e[2].dataType,e[2].dims,g)];c&&y.push(Ce("beta",e[3].dataType,e[3].dims,g)),d&&y.push(Ce("bias",e[4].dataType,e[4].dims,g)),y.push(tt("output",e[0].dataType,a,g)),_&&y.push(tt("mean_output",1,p)),f&&y.push(tt("inv_std_output",1,p)),v&&y.push(tt("input_skip_bias_sum",e[0].dataType,a,g));let S=$r(e[0].dataType),F=$r(1,g);return` + + ${x.registerUniforms(b).declareVariables(...y)} + var sum_shared : array<${F}, ${$}>; + var sum_squared_shared : array<${F}, ${$}>; + + ${x.mainStart([$,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${$}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${$}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${$-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":S+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${v?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${so(S,g,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${$}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${en("sum",g)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${en("square_sum",g)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${_?"mean_output[global_idx] = mean;":""} + ${f?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${S}(mean)`}) * + ${S}(inv_std_dev) * gamma[offset1d + i] + ${c?"+ beta[offset1d + i]":""}; + } + }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${g};${_};${f};${v}`,inputDependencies:e.map((x,b)=>"type")},getShaderSource:C,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:w})}},E0=(e,r)=>{Vw(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(Uw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),Ww,Go,Gw,Pu,Kw,Hw,P0,C0,Jx=je(()=>{ft(),xt(),lr(),Tt(),Ww=(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`)})},Go=(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},Gw=(e,r)=>{if(e.length>1){let t=Go(e,1),s=Go(e,2),o=Go(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Nt({starts:t,ends:s,axes:o})}else return r},Pu=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},Kw=(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--) { + let input_shape_i = ${ot("uniforms.input_shape","i",t.length)}; + let steps_i = ${ot("uniforms.steps","i",t.length)}; + let signs_i = ${ot("uniforms.signs","i",t.length)}; + let starts_i = ${ot("uniforms.starts","i",t.length)}; + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,Hw=(e,r)=>{let t=e[0].dims,s=Me.size(t),o=r.axes.length>0?Me.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=Go(e,4);n.forEach(g=>g!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((g,w)=>Pu(g,w,t,o,n)),a=r.ends.map((g,w)=>Pu(g,w,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let g=0;gMath.sign(g));n.forEach((g,w,C)=>{if(g<0){let E=(a[w]-i[w])/g,x=i[w],b=x+E*n[w];i[w]=b,a[w]=x,C[w]=-g}});let u=t.slice(0);o.forEach((g,w)=>{u[g]=Math.ceil((a[g]-i[g])/n[g])});let p={dims:u,dataType:e[0].dataType},c=tt("output",e[0].dataType,u.length),d=Ce("input",e[0].dataType,e[0].dims.length),_=Me.size(u),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],v=[{type:12,data:_},{type:12,data:i},{type:6,data:l},{type:12,data:n},...ut(e[0].dims,u)],$=g=>` + ${g.registerUniforms(f).declareVariables(d,c)} + ${Kw(d,c,t)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${c.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${c.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:v})}},P0=(e,r)=>{Ww(e.inputs,r);let t=Gw(e.inputs,r);e.compute(Hw(e.inputs,t),{inputs:[0]})},C0=e=>{let r=e.starts,t=e.ends,s=e.axes;return Nt({starts:r,ends:t,axes:s})}}),qw,Qw,S0,$0,Yx=je(()=>{ft(),xt(),lr(),tn(),Tt(),qw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Qw=(e,r)=>{let t=e.inputs[0],s=t.dims,o=Me.size(s),n=s.length,i=Me.normalizeAxis(r.axis,n),a=iS),u[i]=n-1,u[n-1]=i,l=e.compute(Yr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,c=p[n-1],d=o/c,_=nr(c),f=c/_,v=64;d===1&&(v=256);let $=(y,S)=>S===4?`max(max(${y}.x, ${y}.y), max(${y}.z, ${y}.w))`:S===2?`max(${y}.x, ${y}.y)`:S===3?`max(max(${y}.x, ${y}.y), ${y}.z)`:y,g=Ce("x",l.dataType,l.dims,_),w=tt("result",l.dataType,l.dims,_),C=g.type.value,E=$r(l.dataType)==="f32"?`var threadMax = ${C}(-3.402823e+38f);`:`var threadMax = ${C}(-65504.0h);`,x=y=>` + var rowMaxShared : ${C}; + var rowSumShared : ${C}; + var threadShared : array<${C}, ${v}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${C} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${C}) { + let index = row * row_stride + col; + result[index] = value; + } + ${y.registerUniform("packedCols","i32").declareVariables(g,w)} + ${y.mainStart(v)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${v}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${E} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${C}(${$("threadShared[0]",_)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${C}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${C}(${en("threadShared[0]",_)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,b=e.compute({name:"Softmax",shaderCache:{hint:`${_};${v}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:f}]}),getShaderSource:x},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Yr(b,u),{inputs:[b]})},S0=(e,r)=>{qw(e.inputs),Qw(e,r)},$0=e=>Nt({axis:e.axis})}),Cu,Xw,Jw,Yw,k0,Zx=je(()=>{ft(),xt(),Tt(),Cu=e=>Array.from(e.getBigInt64Array(),Number),Xw=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(Cu(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")},Jw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Cu(e[1]),o=Jw(t,s),n=Me.size(o),i=e[0].dataType,a=Ce("input",i,t.length),l=tt("output",i,o.length),u=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${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:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...ut(e[0].dims,o)]}),getShaderSource:u}},k0=e=>{Xw(e.inputs),e.compute(Yw(e.inputs),{inputs:[0]})}}),Zw,eb,I0,eT=je(()=>{ft(),xt(),Tt(),Zw=(e,r,t,s,o)=>{let n=tt("output_data",o,t.length,4),i=Ce("a_data",r[1].dataType,r[1].dims.length,4),a=Ce("b_data",r[2].dataType,r[2].dims.length,4),l=Ce("c_data",r[0].dataType,r[0].dims.length,4),u,p=(c,d,_)=>`select(${d}, ${c}, ${_})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let c=(d,_,f="")=>{let v=`a_data[index_a${_}][component_a${_}]`,$=`b_data[index_b${_}][component_b${_}]`,g=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return` + let output_indices${_} = ${n.offsetToIndices(`global_idx * 4u + ${_}u`)}; + let offset_a${_} = ${i.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_b${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_c${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let index_a${_} = offset_a${_} / 4u; + let index_b${_} = offset_b${_} / 4u; + let index_c${_} = offset_c${_} / 4u; + let component_a${_} = offset_a${_} % 4u; + let component_b${_} = offset_b${_} % 4u; + let component_c${_} = offset_c${_} % 4u; + ${d}[${_}] = ${f}(${p(v,$,g)}); + `};o===9?u=` + var data = vec4(0); + ${c("data",0,"u32")} + ${c("data",1,"u32")} + ${c("data",2,"u32")} + ${c("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${c("output_data[global_idx]",0)} + ${c("output_data[global_idx]",1)} + ${c("output_data[global_idx]",2)} + ${c("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},eb=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(Me.areEqual(r,t)&&Me.areEqual(t,s)),i=r,a=Me.size(r);if(n){let u=no.calcShape(no.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=Me.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>Zw(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ut(s,r,t,i)]})}},I0=e=>{e.compute(eb(e.inputs))}}),A0,tT=je(()=>{fx(),pc(),_x(),gx(),wx(),bx(),Mx(),Ex(),Cx(),Sx(),$x(),kx(),Ix(),Ax(),Fx(),Ox(),Dx(),Lx(),zx(),Bx(),Rx(),jx(),Nx(),Vx(),Ux(),Jy(),Wx(),Gx(),Kx(),Hx(),qx(),dc(),Qx(),r0(),Xx(),Jx(),Yx(),e0(),Zx(),tn(),hc(),eT(),A0=new Map([["Abs",[EM]],["Acos",[PM]],["Acosh",[CM]],["Add",[ay]],["ArgMax",[yM,ju]],["ArgMin",[MM,ju]],["Asin",[SM]],["Asinh",[$M]],["Atan",[kM]],["Atanh",[IM]],["Attention",[vM]],["AveragePool",[d0,c0]],["BatchNormalization",[xM]],["BiasAdd",[TM]],["BiasSplitGelu",[iy]],["Cast",[FM,AM]],["Ceil",[DM]],["Clip",[OM]],["Concat",[gy,wy]],["Conv",[Ku,Gu]],["ConvTranspose",[Sy,Cy]],["Cos",[LM]],["Cosh",[zM]],["CumSum",[$y,ky]],["DepthToSpace",[Iy,Ay]],["DequantizeLinear",[w0,b0]],["Div",[ly]],["Einsum",[Fy,Oy]],["Elu",[BM,Xo]],["Equal",[uy]],["Erf",[RM]],["Exp",[jM]],["Expand",[Dy]],["FastGelu",[Ly]],["Floor",[NM]],["FusedConv",[Ku,Gu]],["Gather",[By,zy]],["GatherElements",[Wy,Uy]],["GatherBlockQuantized",[Ny,Vy]],["GatherND",[Ry,jy]],["Gelu",[VM]],["Gemm",[Ky,Gy]],["GlobalAveragePool",[h0,p0]],["GlobalMaxPool",[g0,_0]],["Greater",[hy]],["GreaterOrEqual",[fy]],["GridSample",[Hy,qy]],["GroupQueryAttention",[s0]],["HardSigmoid",[XM,QM]],["InstanceNormalization",[n0]],["LayerNormalization",[o0]],["LeakyRelu",[UM,Xo]],["Less",[my]],["LessOrEqual",[_y]],["Log",[ny]],["MatMul",[i0]],["MatMulNBits",[a0,l0]],["MaxPool",[m0,f0]],["Mul",[cy]],["MultiHeadAttention",[Xy,Qy]],["Neg",[GM]],["Not",[WM]],["Pad",[u0]],["Pow",[dy]],["QuickGelu",[oy,Xo]],["Range",[M0]],["Reciprocal",[KM]],["ReduceMin",[fM]],["ReduceMean",[cM]],["ReduceMax",[mM]],["ReduceSum",[gM]],["ReduceProd",[_M]],["ReduceL1",[dM]],["ReduceL2",[pM]],["ReduceLogSum",[bM]],["ReduceLogSumExp",[hM]],["ReduceSumSquare",[wM]],["Relu",[HM]],["Resize",[x0,T0]],["RotaryEmbedding",[t0]],["ScatterND",[v0,y0]],["Sigmoid",[qM]],["Sin",[JM]],["Sinh",[YM]],["Slice",[P0,C0]],["SkipLayerNormalization",[E0]],["Split",[Yy,Zy]],["Sqrt",[ZM]],["Softmax",[S0,$0]],["Sub",[py]],["Tan",[ey]],["Tanh",[ty]],["ThresholdedRelu",[sy,Xo]],["Tile",[k0]],["Transpose",[Yb,Zb]],["Where",[I0]]])}),F0,rT=je(()=>{Ps(),Ns(),Tt(),F0=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,o){Es(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.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(),cs(e.programInfo.name)}dispose(){}build(e,r){Es(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=Jb(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});It("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return cs(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.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,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),O0={};io(O0,{WebGpuBackend:()=>D0});var tb,rb,sb,D0,sT=je(()=>{Ps(),ft(),Ns(),Kb(),hx(),tT(),rT(),tb=(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 o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${tb(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},sb=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},D0=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},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new sb(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Qb(this),this.programManager=new F0(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ac(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;Es(),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 o=0;o"u"&&(this.queryTimeBase=_);let v=Number(_-this.queryTimeBase),$=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(v)||!Number.isSafeInteger($))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:c.map(g=>({dims:g.dims,dataType:js(g.dataType)})),outputsMetadata:d.map(g=>({dims:g.dims,dataType:js(g.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:v,endTime:$});else{let g="";c.forEach((C,E)=>{g+=`input[${E}]: [${C.dims}] | ${js(C.dataType)}, `});let w="";d.forEach((C,E)=>{w+=`output[${E}]: [${C.dims}] | ${js(C.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${g}${w}execution time: ${$-v} ns`)}ei("GPU",`${p}::${_}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),cs()}run(e,r,t,s,o,n){Es(e.name);let i=[];for(let w=0;wC):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let c=[],d=[];for(let w=0;w=n)throw new Error(`Invalid output index: ${p[w]}`);if(p[w]===-3)continue;let C=p[w]===-1,E=p[w]===-2,x=C||E?o(a[w].dataType,a[w].dims):s(p[w],a[w].dataType,a[w].dims);if(c.push(x),x.data===0)continue;let b=this.gpuDataManager.get(x.data);if(!b)throw new Error(`no GPU data for output: ${x.data}`);if(C&&this.temporaryData.push(b),E){let y=this.kernelPersistentData.get(this.currentKernelId);y||(y=[],this.kernelPersistentData.set(this.currentKernelId,y)),y.push(b)}d.push(b)}if(i.length!==r.length||d.length!==c.length){if(d.length===0)return cs(e.name),c;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(u){let w=0,C=[];u.forEach(y=>{let S=typeof y.data=="number"?[y.data]:y.data;if(S.length===0)return;let F=y.type===10?2:4,z,K;y.type===10?(K=S.length>4?16:S.length>2?8:S.length*F,z=S.length>4?16:F*S.length):(K=S.length<=2?S.length*F:16,z=16),w=Math.ceil(w/K)*K,C.push(w);let q=y.type===10?8:4;w+=S.length>4?Math.ceil(S.length/q)*z:S.length*F});let E=16;w=Math.ceil(w/E)*E;let x=new ArrayBuffer(w);u.forEach((y,S)=>{let F=C[S],z=typeof y.data=="number"?[y.data]:y.data;if(y.type===6)new Int32Array(x,F,z.length).set(z);else if(y.type===12)new Uint32Array(x,F,z.length).set(z);else if(y.type===10)new Uint16Array(x,F,z.length).set(z);else if(y.type===1)new Float32Array(x,F,z.length).set(z);else throw new Error(`Unsupported uniform type: ${js(y.type)}`)});let b=this.gpuDataManager.create(w,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(b.buffer,0,x,0,w),this.gpuDataManager.release(b.id),_={offset:0,size:w,buffer:b.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),v=f[1]===1&&f[2]===1,$=rb(e,r,v),g=this.programManager.getArtifact($);if(g||(g=this.programManager.build(e,f),this.programManager.setArtifact($,g),It("info",()=>`[artifact] key: ${$}, programName: ${e.name}`)),u&&g.uniformVariablesInfo){if(u.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${u.length} in program "${g.programInfo.name}".`);for(let w=0;w`[ProgramManager] run "${e.name}" (key=${$}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let w={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:r,outputTensorViews:c};this.pendingKernels.push(w),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(w)}return this.programManager.run(g,i,d,f,_),cs(e.name),c}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 o=A0.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[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 o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),It("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}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 zu(this,e,r);return lc(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(){It("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(){It("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){It("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()}}}),L0={};io(L0,{init:()=>z0});var oa,nb,z0,nT=je(()=>{ft(),Ns(),xt(),px(),oa=class B0{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Me.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=Me.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=Me.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=Me.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Me.size(r)!==Me.size(this.dims))throw new Error("Invalid new shape");return new B0(this.module,this.dataType,this.data,r)}},nb=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,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,u)=>new oa(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=An(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new oa(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(sT(),Zo(O0)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)It("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{It("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let c=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),c)}},async(a,l,u)=>{It("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{It("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let c=new nb(r,i,Number(l));return i.computeKernel(Number(a),c,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new qb(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),ob,bc,Mc,Ys,ib,Su,wa,yc,vc,$u,xc,Tc,Ec,R0=je(()=>{ux(),cx(),ft(),zn(),rc(),Vb(),ob=(e,r)=>{Qt()._OrtInit(e,r)!==0&&Gt("Can't initialize onnxruntime.")},bc=async e=>{ob(e.wasm.numThreads,ha(e.logLevel))},Mc=async(e,r)=>{var t,s;(s=(t=Qt()).asyncInit)==null||s.call(t);{let o=(nT(),Zo(L0)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",Qt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",Qt(),e)}}},Ys=new Map,ib=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&Gt("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},Su=(e,r)=>{let t=Qt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&Gt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let u=t.HEAPU32[o/4+1],p=[];for(let c=0;c{let r=Qt(),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]},yc=async(e,r)=>{var c,d,_,f;let t,s,o=Qt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=wa(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await Nb(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let S=[];for(let F of r.externalData){let z=typeof F=="string"?F:F.path;S.push(ic(typeof F=="string"?F:F.data).then(K=>{o.mountExternalData(z,K)}))}await Promise.all(S)}for(let S of(r==null?void 0:r.executionProviders)??[])if((typeof S=="string"?S:S.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof S!="string"){let F=S,z=F==null?void 0:F.context,K=F==null?void 0:F.gpuDevice,q=F==null?void 0:F.deviceType,R=F==null?void 0:F.powerPreference;z?o.currentContext=z:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:q,powerPreference:R})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(c=o.webgpuOnCreateSession)==null||c.call(o,n),n===0&&Gt("Can't create a session."),(d=o.jsepOnCreateSession)==null||d.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[v,$]=ib(n),g=!!(r!=null&&r.enableGraphCapture),w=[],C=[],E=[],x=[],b=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&Gt("Can't create IO binding."),y={handle:a,outputPreferredLocations:b,outputPreferredLocationsEncoded:b.map(S=>Du(S))}),Ys.set(n,[n,u,p,y,g,!1]),[n,w,C,E,x]}catch(v){throw u.forEach($=>o._OrtFree($)),p.forEach($=>o._OrtFree($)),a!==0&&o._OrtReleaseBinding(a)!==0&&Gt("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&Gt("Can't release session."),v}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&Gt("Can't release session options."),l.forEach(v=>o._free(v)),(f=o.unmountExternalData)==null||f.call(o)}},vc=e=>{var l,u,p;let r=Qt(),t=Ys.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Gt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Gt("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(c=>r._OrtFree(c)),n.forEach(c=>r._OrtFree(c)),r._OrtReleaseSession(s)!==0&&Gt("Can't release session."),Ys.delete(e)},$u=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=Qt(),l=a.PTR_SIZE,u=e[0],p=e[1],c=e[3],d=c,_,f;if(u==="string"&&(c==="gpu-buffer"||c==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let g=e[2].gpuBuffer;f=An(to(u),p);{let w=a.jsepRegisterBuffer;if(!w)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=w(s,n,g,f)}}else if(c==="ml-tensor"){let g=e[2].mlTensor;f=An(to(u),p);let w=a.webnnRegisterMLTensor;if(!w)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=w(s,g,to(u),p)}else{let g=e[2];if(Array.isArray(g)){f=l*g.length,_=a._malloc(f),t.push(_);for(let w=0;wa.setValue($+C*l,w,l===4?"i32":"i64"));let g=a._OrtCreateTensor(to(u),_,f,$,p.length,Du(d));g===0&&Gt(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(g)}finally{a.stackRestore(v)}},xc=async(e,r,t,s,o,n)=>{var K,q,R,Z;let i=Qt(),a=i.PTR_SIZE,l=Ys.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],c=l[2],d=l[3],_=l[4],f=l[5],v=r.length,$=s.length,g=0,w=[],C=[],E=[],x=[],b=i.stackSave(),y=i.stackAlloc(v*a),S=i.stackAlloc(v*a),F=i.stackAlloc($*a),z=i.stackAlloc($*a);try{[g,w]=jb(n);for(let Q=0;QW*re,1);A=js(_e);let pe=d==null?void 0:d.outputPreferredLocations[s[Q]];if(A==="string"){if(pe==="gpu-buffer"||pe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let W=[];for(let re=0;re0){let W=i.jsepGetBuffer;if(!W)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let re=W(U),G=An(_e,Ue);if(G===void 0||!nc(A))throw new Error(`Unsupported data type: ${A}`);V=!0,J.push([A,ze,{gpuBuffer:re,download:i.jsepCreateDownloader(re,G,A),dispose:()=>{i._OrtReleaseTensor(se)!==0&&Gt("Can't release tensor.")}},"gpu-buffer"])}else if(pe==="ml-tensor"&&Ue>0){let W=i.webnnEnsureTensor,re=i.webnnIsInt64Supported;if(!W||!re)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(An(_e,Ue)===void 0||!oc(A))throw new Error(`Unsupported data type: ${A}`);if(A==="int64"&&!re(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let G=await W(e,U,_e,ze,!1);V=!0,J.push([A,ze,{mlTensor:G,download:i.webnnCreateMLTensorDownloader(U,A),dispose:()=>{i.webnnReleaseTensorId(U),i._OrtReleaseTensor(se)}},"ml-tensor"])}else{let W=sc(A),re=new W(Ue);new Uint8Array(re.buffer,re.byteOffset,re.byteLength).set(i.HEAPU8.subarray(U,U+re.byteLength)),J.push([A,ze,re,"cpu"])}}finally{i.stackRestore(fe),A==="string"&&U&&i._free(U),V||i._OrtReleaseTensor(se),(Z=i.webnnOnRunEnd)==null||Z.call(i,u)}}return d&&!_&&(i._OrtClearBoundOutputs(d.handle)!==0&&Gt("Can't clear bound outputs."),Ys.set(e,[u,p,c,d,_,!1])),J}finally{i.stackRestore(b),C.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),x.forEach(H=>i._free(H)),g!==0&&i._OrtReleaseRunOptions(g),w.forEach(H=>i._free(H))}},Tc=e=>{let r=Qt(),t=Ys.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&Gt("Can't get an profile file name."),r._OrtFree(o)},Ec=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Zs,Gr,Zn,Ko,Ho,ia,ku,aa,Sn,$n,ab,j0,N0,V0,U0,W0,G0,K0,H0=je(()=>{Ps(),R0(),zn(),ec(),Zs=()=>!!Yt.wasm.proxy&&typeof document<"u",Zn=!1,Ko=!1,Ho=!1,aa=new Map,Sn=(e,r)=>{let t=aa.get(e);t?t.push(r):aa.set(e,[r])},$n=()=>{if(Zn||!Ko||Ho||!Gr)throw new Error("worker not ready")},ab=e=>{switch(e.data.type){case"init-wasm":Zn=!1,e.data.err?(Ho=!0,ku[1](e.data.err)):(Ko=!0,ku[0]()),ia&&(URL.revokeObjectURL(ia),ia=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=aa.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},j0=async()=>{if(!Ko){if(Zn)throw new Error("multiple calls to 'initWasm()' detected.");if(Ho)throw new Error("previous call to 'initWasm()' failed.");if(Zn=!0,Zs())return new Promise((e,r)=>{Gr==null||Gr.terminate(),Bb().then(([t,s])=>{try{Gr=s,Gr.onerror=n=>r(n),Gr.onmessage=ab,ku=[e,r];let o={type:"init-wasm",in:Yt};!o.in.wasm.wasmPaths&&(t||Ou)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href}),Gr.postMessage(o),ia=t}catch(o){r(o)}},r)});try{await tc(Yt.wasm),await bc(Yt),Ko=!0}catch(e){throw Ho=!0,e}finally{Zn=!1}}},N0=async e=>{if(Zs())return $n(),new Promise((r,t)=>{Sn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Yt}};Gr.postMessage(s)});await Mc(Yt,e)},V0=async e=>Zs()?($n(),new Promise((r,t)=>{Sn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Gr.postMessage(s,[e.buffer])})):wa(e),U0=async(e,r)=>{if(Zs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $n(),new Promise((t,s)=>{Sn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Gr.postMessage(o,n)})}else return yc(e,r)},W0=async e=>{if(Zs())return $n(),new Promise((r,t)=>{Sn("release",[r,t]);let s={type:"release",in:e};Gr.postMessage(s)});vc(e)},G0=async(e,r,t,s,o,n)=>{if(Zs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return $n(),new Promise((i,a)=>{Sn("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Gr.postMessage(u,Ec(l))})}else return xc(e,r,t,s,o,n)},K0=async e=>{if(Zs())return $n(),new Promise((r,t)=>{Sn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Gr.postMessage(s)});Tc(e)}}),Iu,lb,q0,oT=je(()=>{Ps(),H0(),ft(),Zu(),Vb(),Iu=(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()}`)}},lb=e=>{switch(e[3]){case"cpu":return new xs(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!nc(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return xs.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!oc(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return xs.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},q0=class{async fetchModelAndCopyToWasmMemory(e){return V0(await ic(e))}async loadModel(e,r){Es();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await U0(t,r),cs()}async dispose(){return W0(this.sessionId)}async run(e,r,t){Es();let s=[],o=[];Object.entries(e).forEach(c=>{let d=c[0],_=c[1],f=this.inputNames.indexOf(d);if(f===-1)throw new Error(`invalid input '${d}'`);s.push(_),o.push(f)});let n=[],i=[];Object.entries(r).forEach(c=>{let d=c[0],_=c[1],f=this.outputNames.indexOf(d);if(f===-1)throw new Error(`invalid output '${d}'`);n.push(_),i.push(f)});let a=s.map((c,d)=>Iu(c,()=>`input "${this.inputNames[o[d]]}"`)),l=n.map((c,d)=>c?Iu(c,()=>`output "${this.outputNames[i[d]]}"`):null),u=await G0(this.sessionId,o,a,i,l,t),p={};for(let c=0;cQu,initializeFlags:()=>qu,wasmBackend:()=>X0});var qu,Qu,X0,iT=je(()=>{Ps(),H0(),oT(),qu=()=>{(typeof Yt.wasm.initTimeout!="number"||Yt.wasm.initTimeout<0)&&(Yt.wasm.initTimeout=0);let e=Yt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Yt.wasm.simd=!1),typeof Yt.wasm.proxy!="boolean"&&(Yt.wasm.proxy=!1),typeof Yt.wasm.trace!="boolean"&&(Yt.wasm.trace=!1),typeof Yt.wasm.numThreads!="number"||!Number.isInteger(Yt.wasm.numThreads)||Yt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Yt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Kv("node:os").cpus().length:navigator.hardwareConcurrency;Yt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},Qu=class{async init(e){qu(),await j0(),await N0(e)}async createInferenceSessionHandler(e,r){let t=new q0;return await t.loadModel(e,r),t}},X0=new Qu});Ps();Ps();Ps();var aT="1.22.0-dev.20250409-89f8206ba4",lT=Ab;{let e=(iT(),Zo(Q0)).wasmBackend;Fn("webgpu",e,5),Fn("webnn",e,5),Fn("cpu",e,10),Fn("wasm",e,10)}Object.defineProperty(Yt.versions,"web",{value:aT,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const uT=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Yu},get TRACE(){return ei},get TRACE_FUNC_BEGIN(){return Es},get TRACE_FUNC_END(){return cs},get Tensor(){return xs},default:lT,get env(){return Yt},get registerBackend(){return Fn}},Symbol.toStringTag,{value:"Module"}));var Rs={},cT={"onnxruntime-common":e=>{e.exports=Vv},"onnxruntime-web":e=>{e.exports=uT},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Be,Interpreter:()=>He,Template:()=>Zr,parse:()=>U,tokenize:()=>c});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",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro",Break:"Break",Continue:"Continue"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,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,break:s.Break,continue:s.Continue,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(D,oe){this.value=D,this.type=oe}};function i(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]],u=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(D,oe={}){return D.endsWith(` +`)&&(D=D.slice(0,-1)),D=D.replace(/{#.*?#}/gs,"{##}"),oe.lstrip_blocks&&(D=D.replace(/^[ \t]*({[#%])/gm,"$1")),oe.trim_blocks&&(D=D.replace(/([#%]})\n/g,"$1")),D.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function c(D,oe={}){var ve,yt,Ft;const B=[],te=p(D,oe);let me=0;const Oe=ht=>{let lt="";for(;ht(te[me]);){if(te[me]==="\\"){if(++me,me>=te.length)throw new SyntaxError("Unexpected end of input");const rt=te[me++],Bt=u.get(rt);if(Bt===void 0)throw new SyntaxError(`Unexpected escaped character: ${rt}`);lt+=Bt;continue}if(lt+=te[me++],me>=te.length)throw new SyntaxError("Unexpected end of input")}return lt};e:for(;me0){B.push(new n(rt,s.Text));continue}}Oe(rt=>/\s/.test(rt));const lt=te[me];if(lt==="-"||lt==="+"){const rt=(yt=B.at(-1))==null?void 0:yt.type;if(rt===s.Text||rt===void 0)throw new SyntaxError(`Unexpected character: ${lt}`);switch(rt){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++me;const Bt=Oe(a);B.push(new n(`${lt}${Bt}`,Bt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[rt,Bt]of l)if(te.slice(me,me+rt.length)===rt){B.push(new n(rt,Bt)),me+=rt.length;continue e}if(lt==="'"||lt==='"'){++me;const rt=Oe(Bt=>Bt!==lt);B.push(new n(rt,s.StringLiteral)),++me;continue}if(a(lt)){const rt=Oe(a);B.push(new n(rt,s.NumericLiteral));continue}if(i(lt)){const rt=Oe(i),Bt=Object.hasOwn(o,rt)?o[rt]:s.Identifier;Bt===s.In&&((Ft=B.at(-1))==null?void 0:Ft.type)===s.Not?(B.pop(),B.push(new n("not in",s.NotIn))):B.push(new n(rt,Bt));continue}throw new SyntaxError(`Unexpected character: ${lt}`)}return B}var d=class{constructor(){Y(this,"type","Statement")}},_=class extends d{constructor(oe){super();Y(this,"type","Program");this.body=oe}},f=class extends d{constructor(oe,B,te){super();Y(this,"type","If");this.test=oe,this.body=B,this.alternate=te}},v=class extends d{constructor(oe,B,te,me){super();Y(this,"type","For");this.loopvar=oe,this.iterable=B,this.body=te,this.defaultBlock=me}},$=class extends d{constructor(){super(...arguments);Y(this,"type","Break")}},g=class extends d{constructor(){super(...arguments);Y(this,"type","Continue")}},w=class extends d{constructor(oe,B,te){super();Y(this,"type","Set");this.assignee=oe,this.value=B,this.body=te}},C=class extends d{constructor(oe,B,te){super();Y(this,"type","Macro");this.name=oe,this.args=B,this.body=te}},E=class extends d{constructor(){super(...arguments);Y(this,"type","Expression")}},x=class extends E{constructor(oe,B,te){super();Y(this,"type","MemberExpression");this.object=oe,this.property=B,this.computed=te}},b=class extends E{constructor(oe,B){super();Y(this,"type","CallExpression");this.callee=oe,this.args=B}},y=class extends E{constructor(oe){super();Y(this,"type","Identifier");this.value=oe}},S=class extends E{constructor(oe){super();Y(this,"type","Literal");this.value=oe}},F=class extends S{constructor(){super(...arguments);Y(this,"type","NumericLiteral")}},z=class extends S{constructor(){super(...arguments);Y(this,"type","StringLiteral")}},K=class extends S{constructor(){super(...arguments);Y(this,"type","BooleanLiteral")}},q=class extends S{constructor(){super(...arguments);Y(this,"type","NullLiteral")}},R=class extends S{constructor(){super(...arguments);Y(this,"type","ArrayLiteral")}},Z=class extends S{constructor(){super(...arguments);Y(this,"type","TupleLiteral")}},H=class extends S{constructor(){super(...arguments);Y(this,"type","ObjectLiteral")}},J=class extends E{constructor(oe,B,te){super();Y(this,"type","BinaryExpression");this.operator=oe,this.left=B,this.right=te}},Q=class extends E{constructor(oe,B){super();Y(this,"type","FilterExpression");this.operand=oe,this.filter=B}},se=class extends E{constructor(oe,B){super();Y(this,"type","SelectExpression");this.iterable=oe,this.test=B}},fe=class extends E{constructor(oe,B,te){super();Y(this,"type","TestExpression");this.operand=oe,this.negate=B,this.test=te}},ae=class extends E{constructor(oe,B){super();Y(this,"type","UnaryExpression");this.operator=oe,this.argument=B}},V=class extends E{constructor(oe=void 0,B=void 0,te=void 0){super();Y(this,"type","SliceExpression");this.start=oe,this.stop=B,this.step=te}},A=class extends E{constructor(oe,B){super();Y(this,"type","KeywordArgumentExpression");this.key=oe,this.value=B}};function U(D){const oe=new _([]);let B=0;function te(Ae,Je){const it=D[B++];if(!it||it.type!==Ae)throw new Error(`Parser Error: ${Je}. ${it.type} !== ${Ae}.`);return it}function me(){switch(D[B].type){case s.Text:return yt();case s.OpenStatement:return Ft();case s.OpenExpression:return ht();default:throw new SyntaxError(`Unexpected token type: ${D[B].type}`)}}function Oe(...Ae){return B+Ae.length<=D.length&&Ae.some((Je,it)=>Je!==D[B+it].type)}function ve(...Ae){return B+Ae.length<=D.length&&Ae.every((Je,it)=>Je===D[B+it].type)}function yt(){return new z(te(s.Text,"Expected text token").value)}function Ft(){te(s.OpenStatement,"Expected opening statement token");let Ae;switch(D[B].type){case s.Set:++B,Ae=lt(),te(s.CloseStatement,"Expected closing statement token");break;case s.If:++B,Ae=rt(),te(s.OpenStatement,"Expected {% token"),te(s.EndIf,"Expected endif token"),te(s.CloseStatement,"Expected %} token");break;case s.Macro:++B,Ae=Bt(),te(s.OpenStatement,"Expected {% token"),te(s.EndMacro,"Expected endmacro token"),te(s.CloseStatement,"Expected %} token");break;case s.For:++B,Ae=wr(),te(s.OpenStatement,"Expected {% token"),te(s.EndFor,"Expected endfor token"),te(s.CloseStatement,"Expected %} token");break;case s.Break:++B,te(s.CloseStatement,"Expected closing statement token"),Ae=new $;break;case s.Continue:++B,te(s.CloseStatement,"Expected closing statement token"),Ae=new g;break;default:throw new SyntaxError(`Unknown statement type: ${D[B].type}`)}return Ae}function ht(){te(s.OpenExpression,"Expected opening expression token");const Ae=Xt();return te(s.CloseExpression,"Expected closing expression token"),Ae}function lt(){var Je,it;const Ae=Xt();if(ve(s.Equals)){++B;const Rt=Xt();return new w(Ae,Rt,[])}else{const Rt=[];for(te(s.CloseStatement,"Expected %} token");!(((Je=D[B])==null?void 0:Je.type)===s.OpenStatement&&((it=D[B+1])==null?void 0:it.type)===s.EndSet);){const rs=me();Rt.push(rs)}return te(s.OpenStatement,"Expected {% token"),te(s.EndSet,"Expected endset token"),new w(Ae,null,Rt)}}function rt(){var Rt,rs,ss,ur,ns,cr,hr,os;const Ae=Xt();te(s.CloseStatement,"Expected closing statement token");const Je=[],it=[];for(;!(((Rt=D[B])==null?void 0:Rt.type)===s.OpenStatement&&(((rs=D[B+1])==null?void 0:rs.type)===s.ElseIf||((ss=D[B+1])==null?void 0:ss.type)===s.Else||((ur=D[B+1])==null?void 0:ur.type)===s.EndIf));)Je.push(me());if(((ns=D[B])==null?void 0:ns.type)===s.OpenStatement&&((cr=D[B+1])==null?void 0:cr.type)!==s.EndIf)if(++B,ve(s.ElseIf))te(s.ElseIf,"Expected elseif token"),it.push(rt());else for(te(s.Else,"Expected else token"),te(s.CloseStatement,"Expected closing statement token");!(((hr=D[B])==null?void 0:hr.type)===s.OpenStatement&&((os=D[B+1])==null?void 0:os.type)===s.EndIf);)it.push(me());return new f(Ae,Je,it)}function Bt(){const Ae=zr();if(Ae.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Je=ps();te(s.CloseStatement,"Expected closing statement token");const it=[];for(;Oe(s.OpenStatement,s.EndMacro);)it.push(me());return new C(Ae,Je,it)}function Ht(Ae=!1){const Je=Ae?zr:Xt,it=[Je()],Rt=ve(s.Comma);for(;Rt&&(++B,it.push(Je()),!!ve(s.Comma)););return Rt?new Z(it):it[0]}function wr(){const Ae=Ht(!0);if(!(Ae instanceof y||Ae instanceof Z))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Ae.type} instead`);te(s.In,"Expected `in` keyword following loop variable");const Je=Xt();te(s.CloseStatement,"Expected closing statement token");const it=[];for(;Oe(s.OpenStatement,s.EndFor)&&Oe(s.OpenStatement,s.Else);)it.push(me());const Rt=[];if(ve(s.OpenStatement,s.Else))for(++B,++B,te(s.CloseStatement,"Expected closing statement token");Oe(s.OpenStatement,s.EndFor);)Rt.push(me());return new v(Ae,Je,it,Rt)}function Xt(){return Or()}function Or(){const Ae=es();if(ve(s.If)){++B;const Je=es();if(ve(s.Else)){++B;const it=es();return new f(Je,[Ae],[it])}else return new se(Ae,Je)}return Ae}function es(){let Ae=ds();for(;ve(s.Or);){const Je=D[B];++B;const it=ds();Ae=new J(Je,Ae,it)}return Ae}function ds(){let Ae=ts();for(;ve(s.And);){const Je=D[B];++B;const it=ts();Ae=new J(Je,Ae,it)}return Ae}function ts(){let Ae;for(;ve(s.Not);){const Je=D[B];++B;const it=ts();Ae=new ae(Je,it)}return Ae??Cs()}function Cs(){let Ae=jr();for(;ve(s.ComparisonBinaryOperator)||ve(s.In)||ve(s.NotIn);){const Je=D[B];++B;const it=jr();Ae=new J(Je,Ae,it)}return Ae}function jr(){let Ae=Is();for(;ve(s.AdditiveBinaryOperator);){const Je=D[B];++B;const it=Is();Ae=new J(Je,Ae,it)}return Ae}function Ss(){const Ae=ir(zr());return ve(s.OpenParen)?Kr(Ae):Ae}function Kr(Ae){let Je=new b(Ae,ps());return Je=ir(Je),ve(s.OpenParen)&&(Je=Kr(Je)),Je}function ps(){te(s.OpenParen,"Expected opening parenthesis for arguments list");const Ae=$s();return te(s.CloseParen,"Expected closing parenthesis for arguments list"),Ae}function $s(){const Ae=[];for(;!ve(s.CloseParen);){let Je=Xt();if(ve(s.Equals)){if(++B,!(Je instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const it=Xt();Je=new A(Je,it)}Ae.push(Je),ve(s.Comma)&&++B}return Ae}function ks(){const Ae=[];let Je=!1;for(;!ve(s.CloseSquareBracket);)ve(s.Colon)?(Ae.push(void 0),++B,Je=!0):(Ae.push(Xt()),ve(s.Colon)&&(++B,Je=!0));if(Ae.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Je){if(Ae.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new V(...Ae)}return Ae[0]}function ir(Ae){for(;ve(s.Dot)||ve(s.OpenSquareBracket);){const Je=D[B];++B;let it;const Rt=Je.type!==s.Dot;if(Rt)it=ks(),te(s.CloseSquareBracket,"Expected closing square bracket");else if(it=zr(),it.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Ae=new x(Ae,it,Rt)}return Ae}function Is(){let Ae=Tr();for(;ve(s.MultiplicativeBinaryOperator);){const Je=D[B];++B;const it=Tr();Ae=new J(Je,Ae,it)}return Ae}function Tr(){let Ae=hs();for(;ve(s.Is);){++B;const Je=ve(s.Not);Je&&++B;let it=zr();if(it instanceof K?it=new y(it.value.toString()):it instanceof q&&(it=new y("none")),!(it instanceof y))throw new SyntaxError("Expected identifier for the test");Ae=new fe(Ae,Je,it)}return Ae}function hs(){let Ae=Ss();for(;ve(s.Pipe);){++B;let Je=zr();if(!(Je instanceof y))throw new SyntaxError("Expected identifier for the filter");ve(s.OpenParen)&&(Je=Kr(Je)),Ae=new Q(Ae,Je)}return Ae}function zr(){const Ae=D[B];switch(Ae.type){case s.NumericLiteral:return++B,new F(Number(Ae.value));case s.StringLiteral:return++B,new z(Ae.value);case s.BooleanLiteral:return++B,new K(Ae.value.toLowerCase()==="true");case s.NullLiteral:return++B,new q(null);case s.Identifier:return++B,new y(Ae.value);case s.OpenParen:{++B;const Je=Ht();if(D[B].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${D[B].type} instead`);return++B,Je}case s.OpenSquareBracket:{++B;const Je=[];for(;!ve(s.CloseSquareBracket);)Je.push(Xt()),ve(s.Comma)&&++B;return++B,new R(Je)}case s.OpenCurlyBracket:{++B;const Je=new Map;for(;!ve(s.CloseCurlyBracket);){const it=Xt();te(s.Colon,"Expected colon between key and value in object literal");const Rt=Xt();Je.set(it,Rt),ve(s.Comma)&&++B}return++B,new H(Je)}default:throw new SyntaxError(`Unexpected token: ${Ae.type}`)}}for(;B=0?(oe=(oe??(oe=0))<0?Math.max(D.length+oe,0):Math.min(oe,D.length),B=(B??(B=D.length))<0?Math.max(D.length+B,0):Math.min(B,D.length)):(oe=(oe??(oe=D.length-1))<0?Math.max(D.length+oe,-1):Math.min(oe,D.length-1),B=(B??(B=-1))<-1?Math.max(D.length+B,-1):Math.min(B,D.length-1));const Oe=[];for(let ve=oe;me*veoe.toUpperCase())}var ye=class extends Error{},ze=class extends Error{},Ue=class{constructor(D=void 0){Y(this,"type","RuntimeValue");Y(this,"value");Y(this,"builtins",new Map);this.value=D}__bool__(){return new re(!!this.value)}},pe=class extends Ue{constructor(){super(...arguments);Y(this,"type","NumericValue")}},W=class extends Ue{constructor(){super(...arguments);Y(this,"type","StringValue");Y(this,"builtins",new Map([["upper",new Pe(()=>new W(this.value.toUpperCase()))],["lower",new Pe(()=>new W(this.value.toLowerCase()))],["strip",new Pe(()=>new W(this.value.trim()))],["title",new Pe(()=>new W(le(this.value)))],["length",new pe(this.value.length)],["rstrip",new Pe(()=>new W(this.value.trimEnd()))],["lstrip",new Pe(()=>new W(this.value.trimStart()))],["startswith",new Pe(oe=>{if(oe.length===0)throw new Error("startswith() requires at least one argument");const B=oe[0];if(!(B instanceof W))throw new Error("startswith() argument must be a string");return new re(this.value.startsWith(B.value))})],["endswith",new Pe(oe=>{if(oe.length===0)throw new Error("endswith() requires at least one argument");const B=oe[0];if(!(B instanceof W))throw new Error("endswith() argument must be a string");return new re(this.value.endsWith(B.value))})],["split",new Pe(oe=>{const B=oe[0]??new $e;if(!(B instanceof W||B instanceof $e))throw new Error("sep argument must be a string or null");const te=oe[1]??new pe(-1);if(!(te instanceof pe))throw new Error("maxsplit argument must be a number");let me=[];if(B instanceof $e){const Oe=this.value.trimStart();for(const{0:ve,index:yt}of Oe.matchAll(/\S+/g)){if(te.value!==-1&&me.length>=te.value&&yt!==void 0){me.push(ve+Oe.slice(yt+ve.length));break}me.push(ve)}}else{if(B.value==="")throw new Error("empty separator");me=this.value.split(B.value),te.value!==-1&&me.length>te.value&&me.push(me.splice(te.value).join(B.value))}return new we(me.map(Oe=>new W(Oe)))})]]))}},re=class extends Ue{constructor(){super(...arguments);Y(this,"type","BooleanValue")}},G=class extends Ue{constructor(){super(...arguments);Y(this,"type","ObjectValue");Y(this,"builtins",new Map([["get",new Pe(([oe,B])=>{if(!(oe instanceof W))throw new Error(`Object key must be a string: got ${oe.type}`);return this.value.get(oe.value)??B??new $e})],["items",new Pe(()=>new we(Array.from(this.value.entries()).map(([oe,B])=>new we([new W(oe),B]))))]]))}__bool__(){return new re(this.value.size>0)}},be=class extends G{constructor(){super(...arguments);Y(this,"type","KeywordArgumentsValue")}},we=class extends Ue{constructor(){super(...arguments);Y(this,"type","ArrayValue");Y(this,"builtins",new Map([["length",new pe(this.value.length)]]))}__bool__(){return new re(this.value.length>0)}},Se=class extends we{constructor(){super(...arguments);Y(this,"type","TupleValue")}},Pe=class extends Ue{constructor(){super(...arguments);Y(this,"type","FunctionValue")}},$e=class extends Ue{constructor(){super(...arguments);Y(this,"type","NullValue")}},Fe=class extends Ue{constructor(){super(...arguments);Y(this,"type","UndefinedValue")}},Be=class{constructor(D){Y(this,"variables",new Map([["namespace",new Pe(D=>{if(D.length===0)return new G(new Map);if(D.length!==1||!(D[0]instanceof G))throw new Error("`namespace` expects either zero arguments or a single object argument");return D[0]})]]));Y(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 oe=D.value;return D.type==="StringValue"&&oe===oe.toLowerCase()}],["upper",D=>{const oe=D.value;return D.type==="StringValue"&&oe===oe.toUpperCase()}],["none",D=>D.type==="NullValue"],["defined",D=>D.type!=="UndefinedValue"],["undefined",D=>D.type==="UndefinedValue"],["equalto",(D,oe)=>D.value===oe.value],["eq",(D,oe)=>D.value===oe.value]]));this.parent=D}set(D,oe){return this.declareVariable(D,qe(oe))}declareVariable(D,oe){if(this.variables.has(D))throw new SyntaxError(`Variable already declared: ${D}`);return this.variables.set(D,oe),oe}setVariable(D,oe){return this.variables.set(D,oe),oe}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 Fe}catch{return new Fe}}},He=class{constructor(D){Y(this,"global");this.global=D??new Be}run(D){return this.evaluate(D,this.global)}evaluateBinaryExpression(D,oe){const B=this.evaluate(D.left,oe);switch(D.operator.value){case"and":return B.__bool__().value?this.evaluate(D.right,oe):B;case"or":return B.__bool__().value?B:this.evaluate(D.right,oe)}const te=this.evaluate(D.right,oe);switch(D.operator.value){case"==":return new re(B.value==te.value);case"!=":return new re(B.value!=te.value)}if(B instanceof Fe||te instanceof Fe)throw new Error("Cannot perform operation on undefined values");if(B instanceof $e||te instanceof $e)throw new Error("Cannot perform operation on null values");if(B instanceof pe&&te instanceof pe)switch(D.operator.value){case"+":return new pe(B.value+te.value);case"-":return new pe(B.value-te.value);case"*":return new pe(B.value*te.value);case"/":return new pe(B.value/te.value);case"%":return new pe(B.value%te.value);case"<":return new re(B.value":return new re(B.value>te.value);case">=":return new re(B.value>=te.value);case"<=":return new re(B.value<=te.value)}else if(B instanceof we&&te instanceof we)switch(D.operator.value){case"+":return new we(B.value.concat(te.value))}else if(te instanceof we){const me=te.value.find(Oe=>Oe.value===B.value)!==void 0;switch(D.operator.value){case"in":return new re(me);case"not in":return new re(!me)}}if(B instanceof W||te instanceof W)switch(D.operator.value){case"+":return new W(B.value.toString()+te.value.toString())}if(B instanceof W&&te instanceof W)switch(D.operator.value){case"in":return new re(te.value.includes(B.value));case"not in":return new re(!te.value.includes(B.value))}if(B instanceof W&&te instanceof G)switch(D.operator.value){case"in":return new re(te.value.has(B.value));case"not in":return new re(!te.value.has(B.value))}throw new SyntaxError(`Unknown operator "${D.operator.value}" between ${B.type} and ${te.type}`)}evaluateArguments(D,oe){const B=[],te=new Map;for(const me of D)if(me.type==="KeywordArgumentExpression"){const Oe=me;te.set(Oe.key.value,this.evaluate(Oe.value,oe))}else{if(te.size>0)throw new Error("Positional arguments must come before keyword arguments");B.push(this.evaluate(me,oe))}return[B,te]}evaluateFilterExpression(D,oe){const B=this.evaluate(D.operand,oe);if(D.filter.type==="Identifier"){const te=D.filter;if(te.value==="tojson")return new W(ke(B));if(B instanceof we)switch(te.value){case"list":return B;case"first":return B.value[0];case"last":return B.value[B.value.length-1];case"length":return new pe(B.value.length);case"reverse":return new we(B.value.reverse());case"sort":return new we(B.value.sort((me,Oe)=>{if(me.type!==Oe.type)throw new Error(`Cannot compare different types: ${me.type} and ${Oe.type}`);switch(me.type){case"NumericValue":return me.value-Oe.value;case"StringValue":return me.value.localeCompare(Oe.value);default:throw new Error(`Cannot compare type: ${me.type}`)}}));case"join":return new W(B.value.map(me=>me.value).join(""));case"string":return new W(ke(B));default:throw new Error(`Unknown ArrayValue filter: ${te.value}`)}else if(B instanceof W)switch(te.value){case"length":return new pe(B.value.length);case"upper":return new W(B.value.toUpperCase());case"lower":return new W(B.value.toLowerCase());case"title":return new W(le(B.value));case"capitalize":return new W(B.value.charAt(0).toUpperCase()+B.value.slice(1));case"trim":return new W(B.value.trim());case"indent":return new W(B.value.split(` +`).map((me,Oe)=>Oe===0||me.length===0?me:" "+me).join(` +`));case"join":case"string":return B;default:throw new Error(`Unknown StringValue filter: ${te.value}`)}else if(B instanceof pe)switch(te.value){case"abs":return new pe(Math.abs(B.value));default:throw new Error(`Unknown NumericValue filter: ${te.value}`)}else if(B instanceof G)switch(te.value){case"items":return new we(Array.from(B.value.entries()).map(([me,Oe])=>new we([new W(me),Oe])));case"length":return new pe(B.value.size);default:throw new Error(`Unknown ObjectValue filter: ${te.value}`)}throw new Error(`Cannot apply filter "${te.value}" to type: ${B.type}`)}else if(D.filter.type==="CallExpression"){const te=D.filter;if(te.callee.type!=="Identifier")throw new Error(`Unknown filter: ${te.callee.type}`);const me=te.callee.value;if(me==="tojson"){const[,Oe]=this.evaluateArguments(te.args,oe),ve=Oe.get("indent")??new $e;if(!(ve instanceof pe||ve instanceof $e))throw new Error("If set, indent must be a number");return new W(ke(B,ve.value))}else if(me==="join"){let Oe;if(B instanceof W)Oe=Array.from(B.value);else if(B instanceof we)Oe=B.value.map(ht=>ht.value);else throw new Error(`Cannot apply filter "${me}" to type: ${B.type}`);const[ve,yt]=this.evaluateArguments(te.args,oe),Ft=ve.at(0)??yt.get("separator")??new W("");if(!(Ft instanceof W))throw new Error("separator must be a string");return new W(Oe.join(Ft.value))}if(B instanceof we){switch(me){case"selectattr":case"rejectattr":{const Oe=me==="selectattr";if(B.value.some(rt=>!(rt instanceof G)))throw new Error(`\`${me}\` can only be applied to array of objects`);if(te.args.some(rt=>rt.type!=="StringLiteral"))throw new Error(`arguments of \`${me}\` must be strings`);const[ve,yt,Ft]=te.args.map(rt=>this.evaluate(rt,oe));let ht;if(yt){const rt=oe.tests.get(yt.value);if(!rt)throw new Error(`Unknown test: ${yt.value}`);ht=rt}else ht=(...rt)=>rt[0].__bool__().value;const lt=B.value.filter(rt=>{const Bt=rt.value.get(ve.value),Ht=Bt?ht(Bt,Ft):!1;return Oe?Ht:!Ht});return new we(lt)}case"map":{const[,Oe]=this.evaluateArguments(te.args,oe);if(Oe.has("attribute")){const ve=Oe.get("attribute");if(!(ve instanceof W))throw new Error("attribute must be a string");const yt=Oe.get("default"),Ft=B.value.map(ht=>{if(!(ht instanceof G))throw new Error("items in map must be an object");return ht.value.get(ve.value)??yt??new Fe});return new we(Ft)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${me}`)}else if(B instanceof W){switch(me){case"indent":{const[Oe,ve]=this.evaluateArguments(te.args,oe),yt=Oe.at(0)??ve.get("width")??new pe(4);if(!(yt instanceof pe))throw new Error("width must be a number");const Ft=Oe.at(1)??ve.get("first")??new re(!1),ht=Oe.at(2)??ve.get("blank")??new re(!1),lt=B.value.split(` +`),rt=" ".repeat(yt.value),Bt=lt.map((Ht,wr)=>!Ft.value&&wr===0||!ht.value&&Ht.length===0?Ht:rt+Ht);return new W(Bt.join(` +`))}}throw new Error(`Unknown StringValue filter: ${me}`)}else throw new Error(`Cannot apply filter "${me}" to type: ${B.type}`)}throw new Error(`Unknown filter: ${D.filter.type}`)}evaluateTestExpression(D,oe){const B=this.evaluate(D.operand,oe),te=oe.tests.get(D.test.value);if(!te)throw new Error(`Unknown test: ${D.test.value}`);const me=te(B);return new re(D.negate?!me:me)}evaluateUnaryExpression(D,oe){const B=this.evaluate(D.argument,oe);switch(D.operator.value){case"not":return new re(!B.value);default:throw new SyntaxError(`Unknown operator: ${D.operator.value}`)}}evalProgram(D,oe){return this.evaluateBlock(D.body,oe)}evaluateBlock(D,oe){let B="";for(const te of D){const me=this.evaluate(te,oe);me.type!=="NullValue"&&me.type!=="UndefinedValue"&&(B+=me.value)}return new W(B)}evaluateIdentifier(D,oe){return oe.lookupVariable(D.value)}evaluateCallExpression(D,oe){const[B,te]=this.evaluateArguments(D.args,oe);te.size>0&&B.push(new be(te));const me=this.evaluate(D.callee,oe);if(me.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${me.type}`);return me.value(B,oe)}evaluateSliceExpression(D,oe,B){if(!(D instanceof we||D instanceof W))throw new Error("Slice object must be an array or string");const te=this.evaluate(oe.start,B),me=this.evaluate(oe.stop,B),Oe=this.evaluate(oe.step,B);if(!(te instanceof pe||te instanceof Fe))throw new Error("Slice start must be numeric or undefined");if(!(me instanceof pe||me instanceof Fe))throw new Error("Slice stop must be numeric or undefined");if(!(Oe instanceof pe||Oe instanceof Fe))throw new Error("Slice step must be numeric or undefined");return D instanceof we?new we(_e(D.value,te.value,me.value,Oe.value)):new W(_e(Array.from(D.value),te.value,me.value,Oe.value).join(""))}evaluateMemberExpression(D,oe){const B=this.evaluate(D.object,oe);let te;if(D.computed){if(D.property.type==="SliceExpression")return this.evaluateSliceExpression(B,D.property,oe);te=this.evaluate(D.property,oe)}else te=new W(D.property.value);let me;if(B instanceof G){if(!(te instanceof W))throw new Error(`Cannot access property with non-string: got ${te.type}`);me=B.value.get(te.value)??B.builtins.get(te.value)}else if(B instanceof we||B instanceof W)if(te instanceof pe)me=B.value.at(te.value),B instanceof W&&(me=new W(B.value.at(te.value)));else if(te instanceof W)me=B.builtins.get(te.value);else throw new Error(`Cannot access property with non-string/non-number: got ${te.type}`);else{if(!(te instanceof W))throw new Error(`Cannot access property with non-string: got ${te.type}`);me=B.builtins.get(te.value)}return me instanceof Ue?me:new Fe}evaluateSet(D,oe){const B=D.value?this.evaluate(D.value,oe):this.evaluateBlock(D.body,oe);if(D.assignee.type==="Identifier"){const te=D.assignee.value;oe.setVariable(te,B)}else if(D.assignee.type==="MemberExpression"){const te=D.assignee,me=this.evaluate(te.object,oe);if(!(me instanceof G))throw new Error("Cannot assign to member of non-object");if(te.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");me.value.set(te.property.value,B)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(D.assignee)}`);return new $e}evaluateIf(D,oe){const B=this.evaluate(D.test,oe);return this.evaluateBlock(B.__bool__().value?D.body:D.alternate,oe)}evaluateFor(D,oe){const B=new Be(oe);let te,me;if(D.iterable.type==="SelectExpression"){const ht=D.iterable;me=this.evaluate(ht.iterable,B),te=ht.test}else me=this.evaluate(D.iterable,B);if(!(me instanceof we))throw new Error(`Expected iterable type in for loop: got ${me.type}`);const Oe=[],ve=[];for(let ht=0;htHt.setVariable(D.loopvar.value,rt);else if(D.loopvar.type==="TupleLiteral"){const Ht=D.loopvar;if(rt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${rt.type}`);const wr=rt;if(Ht.value.length!==wr.value.length)throw new Error(`Too ${Ht.value.length>wr.value.length?"few":"many"} items to unpack`);Bt=Xt=>{for(let Or=0;Or0?Oe[ht-1]:new Fe],["nextitem",ht{var ve;const me=new Be(te);B=B.slice();let Oe;((ve=B.at(-1))==null?void 0:ve.type)==="KeywordArgumentsValue"&&(Oe=B.pop());for(let yt=0;ytthis.evaluate(B,oe)));case"TupleLiteral":return new Se(D.value.map(B=>this.evaluate(B,oe)));case"ObjectLiteral":{const B=new Map;for(const[te,me]of D.value){const Oe=this.evaluate(te,oe);if(!(Oe instanceof W))throw new Error(`Object keys must be strings: got ${Oe.type}`);B.set(Oe.value,this.evaluate(me,oe))}return new G(B)}case"Identifier":return this.evaluateIdentifier(D,oe);case"CallExpression":return this.evaluateCallExpression(D,oe);case"MemberExpression":return this.evaluateMemberExpression(D,oe);case"UnaryExpression":return this.evaluateUnaryExpression(D,oe);case"BinaryExpression":return this.evaluateBinaryExpression(D,oe);case"FilterExpression":return this.evaluateFilterExpression(D,oe);case"TestExpression":return this.evaluateTestExpression(D,oe);default:throw new SyntaxError(`Unknown node type: ${D.type}`)}}};function qe(D){switch(typeof D){case"number":return new pe(D);case"string":return new W(D);case"boolean":return new re(D);case"undefined":return new Fe;case"object":return D===null?new $e:Array.isArray(D)?new we(D.map(qe)):new G(new Map(Object.entries(D).map(([oe,B])=>[oe,qe(B)])));case"function":return new Pe((oe,B)=>{const te=D(...oe.map(me=>me.value))??null;return qe(te)});default:throw new Error(`Cannot convert to runtime value: ${D}`)}}function ke(D,oe,B){const te=B??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 me=oe?" ".repeat(oe):"",Oe=` +`+me.repeat(te),ve=Oe+me;if(D.type==="ArrayValue"){const yt=D.value.map(Ft=>ke(Ft,oe,te+1));return oe?`[${ve}${yt.join(`,${ve}`)}${Oe}]`:`[${yt.join(", ")}]`}else{const yt=Array.from(D.value.entries()).map(([Ft,ht])=>{const lt=`"${Ft}": ${ke(ht,oe,te+1)}`;return oe?`${ve}${lt}`:lt});return oe?`{${yt.join(",")}${Oe}}`:`{${yt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${D.type}`)}}var Ve=` +`,Ze="{%- ",st=" -%}",at={MultiplicativeBinaryOperator:2,AdditiveBinaryOperator:1,ComparisonBinaryOperator:0};function Ge(D,oe=" "){const B=typeof oe=="number"?" ".repeat(oe):oe;return pt(D.body,0,B).replace(/\n$/,"")}function Ie(...D){return Ze+D.join(" ")+st}function pt(D,oe,B){return D.map(te=>St(te,oe,B)).join(Ve)}function St(D,oe,B){const te=B.repeat(oe);switch(D.type){case"Program":return pt(D.body,oe,B);case"If":return Vt(D,oe,B);case"For":return zt(D,oe,B);case"Set":return gr(D,oe,B);case"Macro":return or(D,oe,B);case"Break":return te+Ie("break");case"Continue":return te+Ie("continue");default:return te+"{{- "+bt(D)+" -}}"}}function Vt(D,oe,B){const te=B.repeat(oe),me=[];let Oe=D;for(;Oe&&(me.push({test:Oe.test,body:Oe.body}),Oe.alternate.length===1&&Oe.alternate[0].type==="If");)Oe=Oe.alternate[0];let ve=te+Ie("if",bt(me[0].test))+Ve+pt(me[0].body,oe+1,B);for(let yt=1;yt0&&(ve+=Ve+te+Ie("else")+Ve+pt(Oe.alternate,oe+1,B)),ve+=Ve+te+Ie("endif"),ve}function zt(D,oe,B){const te=B.repeat(oe);let me="";if(D.iterable.type==="SelectExpression"){const ve=D.iterable;me=`${bt(ve.iterable)} if ${bt(ve.test)}`}else me=bt(D.iterable);let Oe=te+Ie("for",bt(D.loopvar),"in",me)+Ve+pt(D.body,oe+1,B);return D.defaultBlock.length>0&&(Oe+=Ve+te+Ie("else")+Ve+pt(D.defaultBlock,oe+1,B)),Oe+=Ve+te+Ie("endfor"),Oe}function gr(D,oe,B){const te=B.repeat(oe),me=bt(D.assignee),Oe=D.value?bt(D.value):"",ve=te+Ie("set",`${me}${D.value?" = "+Oe:""}`);return D.body.length===0?ve:ve+Ve+pt(D.body,oe+1,B)+Ve+te+Ie("endset")}function or(D,oe,B){const te=B.repeat(oe),me=D.args.map(bt).join(", ");return te+Ie("macro",`${D.name.value}(${me})`)+Ve+pt(D.body,oe+1,B)+Ve+te+Ie("endmacro")}function bt(D,oe=-1){switch(D.type){case"Identifier":return D.value;case"NullLiteral":return"none";case"NumericLiteral":case"BooleanLiteral":return`${D.value}`;case"StringLiteral":return JSON.stringify(D.value);case"BinaryExpression":{const B=D,te=at[B.operator.type]??0,me=bt(B.left,te),Oe=bt(B.right,te+1),ve=`${me} ${B.operator.value} ${Oe}`;return tebt(me,-1)).join(", ");return`${bt(B.callee,-1)}(${te})`}case"MemberExpression":{const B=D;let te=bt(B.object,-1);B.object.type!=="Identifier"&&(te=`(${te})`);let me=bt(B.property,-1);return!B.computed&&B.property.type!=="Identifier"&&(me=`(${me})`),B.computed?`${te}[${me}]`:`${te}.${me}`}case"FilterExpression":{const B=D,te=bt(B.operand,1/0);return B.filter.type==="CallExpression"?`${te} | ${bt(B.filter,-1)}`:`${te} | ${B.filter.value}`}case"SelectExpression":{const B=D;return`${bt(B.iterable,-1)} | select(${bt(B.test,-1)})`}case"TestExpression":{const B=D;return`${bt(B.operand,-1)} is${B.negate?" not":""} ${B.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const B=D.value.map(me=>bt(me,-1)),te=D.type==="ArrayLiteral"?"[]":"()";return`${te[0]}${B.join(", ")}${te[1]}`}case"ObjectLiteral":return`{ ${Array.from(D.value.entries()).map(([te,me])=>`${bt(te,-1)}: ${bt(me,-1)}`).join(", ")} }`;case"SliceExpression":{const B=D,te=B.start?bt(B.start,-1):"",me=B.stop?bt(B.stop,-1):"",Oe=B.step?`:${bt(B.step,-1)}`:"";return`${te}:${me}${Oe}`}case"KeywordArgumentExpression":{const B=D;return`${B.key.value}=${bt(B.value,-1)}`}case"If":{const B=D,te=bt(B.test,-1),me=bt(B.body[0],0),Oe=bt(B.alternate[0],-1);return`${me} if ${te} else ${Oe}`}default:throw new Error(`Unknown expression type: ${D.type}`)}}var Zr=class{constructor(D){Y(this,"parsed");const oe=c(D,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=U(oe)}render(D){const oe=new Be;if(oe.set("false",!1),oe.set("true",!0),oe.set("raise_exception",me=>{throw new Error(me)}),oe.set("range",ee),D)for(const[me,Oe]of Object.entries(D))oe.set(me,Oe);return new He(oe).run(this.parsed).value}format(D){return Ge(this.parsed,(D==null?void 0:D.indent)||" ")}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>$,deviceToExecutionProviders:()=>f,isONNXProxy:()=>C,isONNXTensor:()=>g});var o=t("./src/env.js"),n=t("?2ce3"),i=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"}}),u=[];let p,c;const d=Symbol.for("onnxruntime");if(d in globalThis)c=globalThis[d];else if(o.apis.IS_NODE_ENV){switch(c=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else c=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const _=c.InferenceSession;function f(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(x=>["webgpu","cuda","dml","webnn-gpu"].includes(x))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let v=null;async function $(E,x,b){v&&await v;const y=_.create(E,x);v??(v=y);const S=await y;return S.config=b,S}function g(E){return E instanceof c.Tensor}const w=c==null?void 0:c.env;w!=null&&w.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!w.wasm.wasmPaths&&(w.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),w.wasm.proxy=!1),w!=null&&w.webgpu&&(w.webgpu.powerPreference="high-performance");function C(){var E;return(E=w==null?void 0:w.wasm)==null?void 0:E.proxy}o.env.backends.onnx=w},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const c=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(c)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} 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:()=>E,center_to_corners_format:()=>c,post_process_instance_segmentation:()=>C,post_process_object_detection:()=>d,post_process_panoptic_segmentation:()=>w,post_process_semantic_segmentation:()=>_});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(x,b,y=0,S=null){const F=x/b;let z=(0,n.bankers_round)(F)*b;return S!==null&&z>S&&(z=Math.floor(F)*b),zb&&A.push(ee)}else{let ee=(0,n.max)(V.data)[1];if(ee===R-1||(U=(0,n.softmax)(V.data),U[ee]le*J[(ye+1)%2])),Q.boxes.push(_e),Q.classes.push(ee),Q.scores.push(U[ee])}}Z.push(Q)}return Z}function _(x,b=null){const y=x.logits,S=y.dims[0];if(b!==null&&b.length!==S)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const F=[];for(let z=0;zJ[A]&&(J[A]=V[A],Q[A]=ae)}const se=new Array(q.dims[0]);for(let ae=0;aeae!==void 0);F.push({segmentation:H,labels:fe})}return F}function f(x,b,y,S){const F=[],z=[],K=[];for(let q=0;qy&&(F.push(Z),z.push(Q),K.push(H))}return[F,z,K]}function v(x,b,y,S=.5,F=.8){const z=[];let K=0,q=0;const R=b[y].data;for(let H=0;H=S&&++q;let Z=K>0&&q>0;return Z&&(Z=K/q>F),[Z,z]}function $(x,b,y,S,F,z=null,K=null){const[q,R]=K??x[0].dims,Z=new o.Tensor("int32",new Int32Array(q*R),[q,R]),H=[];if(K!==null)for(let ae=0;aeQ[U]&&(J[U]=ae,Q[U]=A[U])}let se=0;const fe=Z.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(x,b)/Math.min(x,b)}`);let z=Math.round(x/y)*y,K=Math.round(b/y)*y;if(z*K>F){const q=Math.sqrt(x*b/F);z=Math.floor(x/q/y)*y,K=Math.floor(b/q/y)*y}else if(z*Kz?Z=Math.floor(z*R/F):z>F&&(R=Math.floor(F*Z/z)),await b.resize(Z,R,{resample:S}))}async crop_margin(b,y=200){const S=b.clone().grayscale(),F=(0,n.min)(S.data)[0],K=(0,n.max)(S.data)[0]-F;if(K===0)return b;const q=y/255;let R=S.width,Z=S.height,H=0,J=0;const Q=S.data;for(let se=0;sethis.preprocess(z)));return{pixel_values:(0,o.stack)(S.map(z=>z.pixel_values),0),original_sizes:S.map(z=>z.original_size),reshaped_input_sizes:S.map(z=>z.reshaped_input_size)}}static async from_pretrained(b,y){const S=await(0,a.getModelJSON)(b,l.IMAGE_PROCESSOR_NAME,!0,y);return new this(S)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,u){super(),this.config=l,this.components=u}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,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}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,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,c]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(d=>d in this).map(async d=>{const _=await this[d].from_pretrained(l,u);return[d.replace(/_class$/,""),_]})).then(Object.fromEntries)]);return new this(p,c)}}Y(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),Y(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,c){return await(0,o.getModelJSON)(p,"config.json",!0,c)}function i(p){const c={};let d={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":d=i(p.text_config);break;case"moondream1":d=i(p.phi_config);break;case"musicgen":d=i(p.decoder);break;case"multi_modality":d=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":c.num_heads="num_attention_heads",c.num_layers="num_hidden_layers",c.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":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.hidden_size="hidden_size",c.num_attention_heads="num_attention_heads";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.dim_kv="head_dim";break;case"openelm":c.num_heads="num_kv_heads",c.num_layers="num_transformer_layers",c.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":c.num_heads="num_heads",c.num_layers="num_layers",c.hidden_size="hidden_size";break;case"bloom":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="hidden_size";break;case"mpt":c.num_heads="n_heads",c.num_layers="n_layers",c.hidden_size="d_model";break;case"exaone":c.num_heads="num_key_value_heads",c.num_layers="num_layers",c.dim_kv="head_dim",c.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":c.num_decoder_layers="num_decoder_layers",c.num_decoder_heads="num_heads",c.decoder_dim_kv="d_kv",c.num_encoder_layers="num_layers",c.num_encoder_heads="num_heads",c.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":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="d_model",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="d_model";break;case"speecht5":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="hidden_size",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="hidden_size";break;case"trocr":c.num_encoder_layers=c.num_decoder_layers="decoder_layers",c.num_encoder_heads=c.num_decoder_heads="decoder_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="d_model";break;case"musicgen_decoder":c.num_encoder_layers=c.num_decoder_layers="num_hidden_layers",c.num_encoder_heads=c.num_decoder_heads="num_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"moonshine":c.num_decoder_layers="decoder_num_hidden_layers",c.num_decoder_heads="decoder_num_key_value_heads",c.num_encoder_layers="encoder_num_hidden_layers",c.num_encoder_heads="encoder_num_key_value_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const f=i(p.decoder),v="num_decoder_layers"in f,$=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return v?($.num_decoder_layers=f.num_decoder_layers,$.num_decoder_heads=f.num_decoder_heads,$.decoder_hidden_size=f.decoder_hidden_size,$.num_encoder_layers=f.num_encoder_layers,$.num_encoder_heads=f.num_encoder_heads,$.encoder_hidden_size=f.encoder_hidden_size):($.num_layers=f.num_layers,$.num_heads=f.num_heads,$.hidden_size=f.hidden_size),$}const _={...d,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const f in c)_[f]=p[c[f]];return _}function a(p,{prefix:c="past_key_values",batch_size:d=1}={}){const _={},f=p.normalized_config;if(f.is_encoder_decoder&&"num_encoder_heads"in f&&"num_decoder_heads"in f){const v=f.encoder_dim_kv??f.encoder_hidden_size/f.num_encoder_heads,$=f.decoder_dim_kv??f.decoder_hidden_size/f.num_decoder_heads,g=[d,f.num_encoder_heads,0,v],w=[d,f.num_decoder_heads,0,$];for(let C=0;C{var S,F;t.r(r),t.d(r,{apis:()=>$,env:()=>b});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((S=self.constructor)==null?void 0:S.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,c=typeof navigator<"u"&&"ml"in navigator,d=typeof process<"u",_=d&&((F=process==null?void 0:process.release)==null?void 0:F.name)==="node",f=!y(s),v=!y(o),$=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:c,IS_PROCESS_AVAILABLE:d,IS_NODE_ENV:_,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:v}),g=f&&v;let w="./";if(g){const z=Object(import.meta).url;z?w=o.dirname(o.dirname(n.fileURLToPath(z))):typeof __dirname<"u"&&(w=o.dirname(__dirname))}const C=g?o.join(w,"/.cache/"):null,E="/models/",x=g?o.join(w,E):E,b={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:x,useFS:f,useBrowserCache:u,useFSCache:f,cacheDir:C,useCustomCache:!1,customCache:null};function y(z){return Object.keys(z).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){Y(this,"max_length",20);Y(this,"max_new_tokens",null);Y(this,"min_length",0);Y(this,"min_new_tokens",null);Y(this,"early_stopping",!1);Y(this,"max_time",null);Y(this,"do_sample",!1);Y(this,"num_beams",1);Y(this,"num_beam_groups",1);Y(this,"penalty_alpha",null);Y(this,"use_cache",!0);Y(this,"temperature",1);Y(this,"top_k",50);Y(this,"top_p",1);Y(this,"typical_p",1);Y(this,"epsilon_cutoff",0);Y(this,"eta_cutoff",0);Y(this,"diversity_penalty",0);Y(this,"repetition_penalty",1);Y(this,"encoder_repetition_penalty",1);Y(this,"length_penalty",1);Y(this,"no_repeat_ngram_size",0);Y(this,"bad_words_ids",null);Y(this,"force_words_ids",null);Y(this,"renormalize_logits",!1);Y(this,"constraints",null);Y(this,"forced_bos_token_id",null);Y(this,"forced_eos_token_id",null);Y(this,"remove_invalid_values",!1);Y(this,"exponential_decay_length_penalty",null);Y(this,"suppress_tokens",null);Y(this,"streamer",null);Y(this,"begin_suppress_tokens",null);Y(this,"forced_decoder_ids",null);Y(this,"guidance_scale",null);Y(this,"num_return_sequences",1);Y(this,"output_attentions",!1);Y(this,"output_hidden_states",!1);Y(this,"output_scores",!1);Y(this,"return_dict_in_generate",!1);Y(this,"pad_token_id",null);Y(this,"bos_token_id",null);Y(this,"eos_token_id",null);Y(this,"encoder_no_repeat_ngram_size",0);Y(this,"decoder_start_token_id",null);Y(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>g,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>v,NoBadWordsLogitsProcessor:()=>$,NoRepeatNGramLogitsProcessor:()=>d,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>w,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>C,WhisperTimeStampLogitsProcessor:()=>c});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(b,y){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(b,y){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(b){this.processors.push(b)}extend(b){this.processors.push(...b)}_call(b,y){let S=y;for(const F of this.processors)S=F(b,S);return S}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(b){super(),this.bos_token_id=b}_call(b,y){for(let S=0;S=1&&z[z.length-1]>=this.timestamp_begin,q=z.length<2||z[z.length-2]>=this.timestamp_begin;if(K&&(q?F.subarray(this.timestamp_begin).fill(-1/0):F.subarray(0,this.eos_token_id).fill(-1/0)),b[S].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;F.subarray(J+1).fill(-1/0)}const R=(0,o.log_softmax)(F),Z=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((J,Q)=>J+Q)),H=(0,o.max)(R.subarray(0,this.timestamp_begin))[0];Z>H&&F.subarray(0,this.timestamp_begin).fill(-1/0)}return y}}class d extends n{constructor(b){super(),this.no_repeat_ngram_size=b}getNgrams(b){const y=b.length,S=[];for(let z=0;z1 to use the classifier free guidance processor, got guidance scale ${b}.`);this.guidance_scale=b}_call(b,y){if(y.dims[0]!==2*b.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 ${y.dims[0]} for the logits and ${b.length} for the input ids.`);const S=b.length,F=y.slice([0,S],null),z=y.slice([S,y.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${b}`);if(!Number.isInteger(S)||S<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${S}`);this.top_p=b,this.filter_value=y,this.min_tokens_to_keep=S}}class E extends i{constructor(b,{filter_value:y=-1/0,min_tokens_to_keep:S=1}={}){if(super(),!Number.isInteger(b)||b<0)throw new Error(`\`top_k\` must be a positive integer, but is ${b}`);this.top_k=Math.max(b,S),this.filter_value=y}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(c){super(),this.generation_config=c}async _call(c){return this.sample(c)}async sample(c){throw Error("sample should be implemented in subclasses.")}getLogits(c,d){let _=c.dims.at(-1),f=c.data;if(d===-1)f=f.slice(-_);else{let v=d*_;f=f.slice(v,v+_)}return f}randomSelect(c){let d=0;for(let f=0;f1)return new u(c);if(c.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${c.num_return_sequences}.`);return new a(c)}}class a extends i{async sample(c){const d=(0,n.max)(c.data)[1];return[[BigInt(d),0]]}}class l extends i{async sample(c){let d=c.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[_,f]=await(0,o.topk)(c,d),v=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},()=>{const $=this.randomSelect(v);return[f.data[$],Math.log(v[$])]})}}class u extends i{async sample(c){let d=c.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[_,f]=await(0,o.topk)(c,d),v=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},($,g)=>[f.data[g],Math.log(v[g])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,c){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 o&&(p=[p]),this.criteria.push(...p)}_call(p,c){const d=new Array(p.length).fill(!1);for(const _ of this.criteria){const f=_(p,c);for(let v=0;vc.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,c){return p.map(d=>{const _=d.at(-1);return this.eos_token_id.some(f=>_==f)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,c){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(c){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 i{constructor(c,{skip_prompt:d=!1,callback_function:_=null,token_callback_function:f=null,skip_special_tokens:v=!0,decode_kwargs:$={},...g}={}){super(),this.tokenizer=c,this.skip_prompt=d,this.callback_function=_??a,this.token_callback_function=f,this.decode_kwargs={skip_special_tokens:v,...$,...g},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(c){var $;if(c.length>1)throw Error("TextStreamer only supports batch size of 1");const d=this.next_tokens_are_prompt;if(d&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const _=c[0];($=this.token_callback_function)==null||$.call(this,_),this.token_cache=(0,s.mergeArrays)(this.token_cache,_);const f=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let v;d||f.endsWith(` +`)?(v=f.slice(this.print_len),this.token_cache=[],this.print_len=0):f.length>0&&(0,o.is_chinese_char)(f.charCodeAt(f.length-1))?(v=f.slice(this.print_len),this.print_len+=v.length):(v=f.slice(this.print_len,f.lastIndexOf(" ")+1),this.print_len+=v.length),this.on_finalized_text(v,!1)}end(){let c;this.token_cache.length>0?(c=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):c="",this.next_tokens_are_prompt=!0,this.on_finalized_text(c,!0)}on_finalized_text(c,d){var _,f;c.length>0&&((_=this.callback_function)==null||_.call(this,c)),d&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((f=this.callback_function)==null||f.call(this,` +`))}}class u extends l{constructor(c,{skip_prompt:d=!1,callback_function:_=null,token_callback_function:f=null,on_chunk_start:v=null,on_chunk_end:$=null,on_finalize:g=null,time_precision:w=.02,skip_special_tokens:C=!0,decode_kwargs:E={}}={}){super(c,{skip_prompt:d,skip_special_tokens:C,callback_function:_,token_callback_function:f,decode_kwargs:E}),this.timestamp_begin=c.timestamp_begin,this.on_chunk_start=v,this.on_chunk_end=$,this.on_finalize=g,this.time_precision=w,this.waiting_for_timestamp=!1}put(c){var _,f;if(c.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const d=c[0];if(d.length===1){const v=Number(d[0])-this.timestamp_begin;if(v>=0){const $=v*this.time_precision;this.waiting_for_timestamp?(_=this.on_chunk_end)==null||_.call(this,$):(f=this.on_chunk_start)==null||f.call(this,$),this.waiting_for_timestamp=!this.waiting_for_timestamp,c=[[]]}}return super.put(c)}end(){var c;super.end(),(c=this.on_finalize)==null||c.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>di,ASTModel:()=>ci,ASTPreTrainedModel:()=>lo,AlbertForMaskedLM:()=>X,AlbertForQuestionAnswering:()=>j,AlbertForSequenceClassification:()=>k,AlbertModel:()=>de,AlbertPreTrainedModel:()=>Fs,AutoModel:()=>El,AutoModelForAudioClassification:()=>uf,AutoModelForAudioFrameClassification:()=>df,AutoModelForAudioTextToText:()=>Mf,AutoModelForCTC:()=>lf,AutoModelForCausalLM:()=>Xm,AutoModelForDepthEstimation:()=>ff,AutoModelForDocumentQuestionAnswering:()=>pf,AutoModelForImageClassification:()=>ef,AutoModelForImageFeatureExtraction:()=>wf,AutoModelForImageMatting:()=>hf,AutoModelForImageSegmentation:()=>tf,AutoModelForImageTextToText:()=>bf,AutoModelForImageToImage:()=>mf,AutoModelForMaskGeneration:()=>af,AutoModelForMaskedLM:()=>Jm,AutoModelForNormalEstimation:()=>_f,AutoModelForObjectDetection:()=>nf,AutoModelForPoseEstimation:()=>gf,AutoModelForQuestionAnswering:()=>Ym,AutoModelForSemanticSegmentation:()=>rf,AutoModelForSeq2SeqLM:()=>Km,AutoModelForSequenceClassification:()=>Wm,AutoModelForSpeechSeq2Seq:()=>Hm,AutoModelForTextToSpectrogram:()=>qm,AutoModelForTextToWaveform:()=>Qm,AutoModelForTokenClassification:()=>Gm,AutoModelForUniversalSegmentation:()=>sf,AutoModelForVision2Seq:()=>Zm,AutoModelForXVector:()=>cf,AutoModelForZeroShotObjectDetection:()=>of,BartForConditionalGeneration:()=>Ut,BartForSequenceClassification:()=>mr,BartModel:()=>Jt,BartPretrainedModel:()=>At,BaseModelOutput:()=>we,BeitForImageClassification:()=>Pd,BeitModel:()=>Ed,BeitPreTrainedModel:()=>Va,BertForMaskedLM:()=>$e,BertForQuestionAnswering:()=>He,BertForSequenceClassification:()=>Fe,BertForTokenClassification:()=>Be,BertModel:()=>Pe,BertPreTrainedModel:()=>Se,BlenderbotForConditionalGeneration:()=>Dr,BlenderbotModel:()=>fr,BlenderbotPreTrainedModel:()=>Kt,BlenderbotSmallForConditionalGeneration:()=>kr,BlenderbotSmallModel:()=>qr,BlenderbotSmallPreTrainedModel:()=>Hr,BloomForCausalLM:()=>qc,BloomModel:()=>Hc,BloomPreTrainedModel:()=>ka,CLIPModel:()=>Mi,CLIPPreTrainedModel:()=>Ls,CLIPSegForImageSegmentation:()=>xo,CLIPSegModel:()=>vo,CLIPSegPreTrainedModel:()=>Vn,CLIPTextModel:()=>ba,CLIPTextModelWithProjection:()=>yi,CLIPVisionModel:()=>Ma,CLIPVisionModelWithProjection:()=>vi,CamembertForMaskedLM:()=>rt,CamembertForQuestionAnswering:()=>wr,CamembertForSequenceClassification:()=>Bt,CamembertForTokenClassification:()=>Ht,CamembertModel:()=>lt,CamembertPreTrainedModel:()=>ht,CausalLMOutput:()=>bn,CausalLMOutputWithPast:()=>dv,ChineseCLIPModel:()=>Nn,ChineseCLIPPreTrainedModel:()=>Ti,ClapAudioModelWithProjection:()=>Ph,ClapModel:()=>Th,ClapPreTrainedModel:()=>Fi,ClapTextModelWithProjection:()=>Eh,CodeGenForCausalLM:()=>Hn,CodeGenModel:()=>gn,CodeGenPreTrainedModel:()=>Kn,CohereForCausalLM:()=>Sc,CohereModel:()=>Cc,CoherePreTrainedModel:()=>ya,ConvBertForMaskedLM:()=>Zr,ConvBertForQuestionAnswering:()=>B,ConvBertForSequenceClassification:()=>D,ConvBertForTokenClassification:()=>oe,ConvBertModel:()=>bt,ConvBertPreTrainedModel:()=>or,ConvNextForImageClassification:()=>Mp,ConvNextModel:()=>bp,ConvNextPreTrainedModel:()=>sl,ConvNextV2ForImageClassification:()=>vp,ConvNextV2Model:()=>yp,ConvNextV2PreTrainedModel:()=>nl,DFineForObjectDetection:()=>Rd,DFineModel:()=>Bd,DFinePreTrainedModel:()=>qa,DPTForDepthEstimation:()=>tp,DPTModel:()=>ep,DPTPreTrainedModel:()=>el,DacDecoderModel:()=>mm,DacDecoderOutput:()=>dm,DacEncoderModel:()=>hm,DacEncoderOutput:()=>cm,DacModel:()=>pm,DacPreTrainedModel:()=>ji,DebertaForMaskedLM:()=>es,DebertaForQuestionAnswering:()=>Cs,DebertaForSequenceClassification:()=>ds,DebertaForTokenClassification:()=>ts,DebertaModel:()=>Or,DebertaPreTrainedModel:()=>Xt,DebertaV2ForMaskedLM:()=>Kr,DebertaV2ForQuestionAnswering:()=>ks,DebertaV2ForSequenceClassification:()=>ps,DebertaV2ForTokenClassification:()=>$s,DebertaV2Model:()=>Ss,DebertaV2PreTrainedModel:()=>jr,DecisionTransformerModel:()=>Hh,DecisionTransformerPreTrainedModel:()=>Kh,DeiTForImageClassification:()=>Wd,DeiTModel:()=>Ud,DeiTPreTrainedModel:()=>Xa,DepthAnythingForDepthEstimation:()=>sp,DepthAnythingPreTrainedModel:()=>rp,DepthProForDepthEstimation:()=>lp,DepthProPreTrainedModel:()=>ap,DetrForObjectDetection:()=>Sd,DetrForSegmentation:()=>Ua,DetrModel:()=>Cd,DetrObjectDetectionOutput:()=>Wa,DetrPreTrainedModel:()=>Ci,DetrSegmentationOutput:()=>$d,Dinov2ForImageClassification:()=>Tp,Dinov2Model:()=>xp,Dinov2PreTrainedModel:()=>ol,Dinov2WithRegistersForImageClassification:()=>Pp,Dinov2WithRegistersModel:()=>Ep,Dinov2WithRegistersPreTrainedModel:()=>il,DistilBertForMaskedLM:()=>Ae,DistilBertForQuestionAnswering:()=>zr,DistilBertForSequenceClassification:()=>Tr,DistilBertForTokenClassification:()=>hs,DistilBertModel:()=>Is,DistilBertPreTrainedModel:()=>ir,DonutSwinModel:()=>wp,DonutSwinPreTrainedModel:()=>gp,EfficientNetForImageClassification:()=>Fh,EfficientNetModel:()=>Ah,EfficientNetPreTrainedModel:()=>_l,ElectraForMaskedLM:()=>Oe,ElectraForQuestionAnswering:()=>Ft,ElectraForSequenceClassification:()=>ve,ElectraForTokenClassification:()=>yt,ElectraModel:()=>me,ElectraPreTrainedModel:()=>te,EsmForMaskedLM:()=>Rt,EsmForSequenceClassification:()=>rs,EsmForTokenClassification:()=>ss,EsmModel:()=>it,EsmPreTrainedModel:()=>Je,ExaoneForCausalLM:()=>N,ExaoneModel:()=>L,ExaonePreTrainedModel:()=>I,FalconForCausalLM:()=>xh,FalconModel:()=>vh,FalconPreTrainedModel:()=>hl,FastViTForImageClassification:()=>md,FastViTModel:()=>hd,FastViTPreTrainedModel:()=>za,Florence2ForConditionalGeneration:()=>_i,Florence2PreTrainedModel:()=>fo,GLPNForDepthEstimation:()=>_p,GLPNModel:()=>fp,GLPNPreTrainedModel:()=>rl,GPT2LMHeadModel:()=>Po,GPT2Model:()=>Eo,GPT2PreTrainedModel:()=>To,GPTBigCodeForCausalLM:()=>Io,GPTBigCodeModel:()=>ko,GPTBigCodePreTrainedModel:()=>_n,GPTJForCausalLM:()=>$o,GPTJModel:()=>So,GPTJPreTrainedModel:()=>Gn,GPTNeoForCausalLM:()=>mn,GPTNeoModel:()=>Co,GPTNeoPreTrainedModel:()=>Un,GPTNeoXForCausalLM:()=>Wn,GPTNeoXModel:()=>fn,GPTNeoXPreTrainedModel:()=>Wr,Gemma2ForCausalLM:()=>Ac,Gemma2Model:()=>Ic,Gemma2PreTrainedModel:()=>xa,Gemma3ForCausalLM:()=>Oc,Gemma3Model:()=>Fc,Gemma3PreTrainedModel:()=>Ta,GemmaForCausalLM:()=>kc,GemmaModel:()=>$c,GemmaPreTrainedModel:()=>va,GlmForCausalLM:()=>T,GlmModel:()=>h,GlmPreTrainedModel:()=>Qn,GraniteForCausalLM:()=>Pc,GraniteModel:()=>Pi,GranitePreTrainedModel:()=>Os,GroundingDinoForObjectDetection:()=>Sp,GroundingDinoPreTrainedModel:()=>Cp,GroupViTModel:()=>pd,GroupViTPreTrainedModel:()=>dd,HeliumForCausalLM:()=>Do,HeliumModel:()=>Oo,HeliumPreTrainedModel:()=>qn,HieraForImageClassification:()=>Kd,HieraModel:()=>Gd,HieraPreTrainedModel:()=>Ja,HubertForCTC:()=>nh,HubertForSequenceClassification:()=>oh,HubertModel:()=>sh,HubertPreTrainedModel:()=>J0,IJepaForImageClassification:()=>rd,IJepaModel:()=>td,IJepaPreTrainedModel:()=>Oa,Idefics3ForConditionalGeneration:()=>hn,Idefics3PreTrainedModel:()=>jn,ImageMattingOutput:()=>vf,JAISLMHeadModel:()=>Ei,JAISModel:()=>ct,JAISPreTrainedModel:()=>qs,JinaCLIPModel:()=>bo,JinaCLIPPreTrainedModel:()=>Hs,JinaCLIPTextModel:()=>Mo,JinaCLIPVisionModel:()=>yo,LiteWhisperForConditionalGeneration:()=>po,LlamaForCausalLM:()=>Fo,LlamaModel:()=>Ao,LlamaPreTrainedModel:()=>wn,LlavaForConditionalGeneration:()=>pn,LlavaOnevisionForConditionalGeneration:()=>Ws,LlavaPreTrainedModel:()=>mo,LongT5ForConditionalGeneration:()=>We,LongT5Model:()=>Qe,LongT5PreTrainedModel:()=>Re,M2M100ForConditionalGeneration:()=>Bp,M2M100Model:()=>zp,M2M100PreTrainedModel:()=>ul,MBartForCausalLM:()=>fs,MBartForConditionalGeneration:()=>Pr,MBartForSequenceClassification:()=>Zt,MBartModel:()=>Er,MBartPreTrainedModel:()=>br,MPNetForMaskedLM:()=>sn,MPNetForQuestionAnswering:()=>an,MPNetForSequenceClassification:()=>nn,MPNetForTokenClassification:()=>on,MPNetModel:()=>rn,MPNetPreTrainedModel:()=>ms,MT5ForConditionalGeneration:()=>Ot,MT5Model:()=>_t,MT5PreTrainedModel:()=>Ye,MarianMTModel:()=>Lp,MarianModel:()=>Dp,MarianPreTrainedModel:()=>ll,MaskFormerForInstanceSegmentation:()=>mp,MaskFormerModel:()=>hp,MaskFormerPreTrainedModel:()=>tl,MaskedLMOutput:()=>Ar,Metric3DForDepthEstimation:()=>cp,Metric3DPreTrainedModel:()=>up,Metric3Dv2ForDepthEstimation:()=>pp,Metric3Dv2PreTrainedModel:()=>dp,MgpstrForSceneTextRecognition:()=>Yh,MgpstrModelOutput:()=>Xh,MgpstrPreTrainedModel:()=>Jh,MimiDecoderModel:()=>um,MimiDecoderOutput:()=>im,MimiEncoderModel:()=>lm,MimiEncoderOutput:()=>om,MimiModel:()=>am,MimiPreTrainedModel:()=>Ri,MistralForCausalLM:()=>bh,MistralModel:()=>wh,MistralPreTrainedModel:()=>dl,MobileBertForMaskedLM:()=>cr,MobileBertForQuestionAnswering:()=>os,MobileBertForSequenceClassification:()=>hr,MobileBertModel:()=>ns,MobileBertPreTrainedModel:()=>ur,MobileLLMForCausalLM:()=>Le,MobileLLMModel:()=>Te,MobileLLMPreTrainedModel:()=>ue,MobileNetV1ForImageClassification:()=>Dh,MobileNetV1ForSemanticSegmentation:()=>Lh,MobileNetV1Model:()=>Oh,MobileNetV1PreTrainedModel:()=>Di,MobileNetV2ForImageClassification:()=>Bh,MobileNetV2ForSemanticSegmentation:()=>Rh,MobileNetV2Model:()=>zh,MobileNetV2PreTrainedModel:()=>Li,MobileNetV3ForImageClassification:()=>Nh,MobileNetV3ForSemanticSegmentation:()=>Vh,MobileNetV3Model:()=>jh,MobileNetV3PreTrainedModel:()=>zi,MobileNetV4ForImageClassification:()=>Wh,MobileNetV4ForSemanticSegmentation:()=>Gh,MobileNetV4Model:()=>Uh,MobileNetV4PreTrainedModel:()=>Bi,MobileViTForImageClassification:()=>wd,MobileViTModel:()=>gd,MobileViTPreTrainedModel:()=>Ba,MobileViTV2ForImageClassification:()=>Md,MobileViTV2Model:()=>bd,MobileViTV2PreTrainedModel:()=>Ra,ModelOutput:()=>be,ModernBertForMaskedLM:()=>Ve,ModernBertForSequenceClassification:()=>Ze,ModernBertForTokenClassification:()=>st,ModernBertModel:()=>ke,ModernBertPreTrainedModel:()=>qe,Moondream1ForConditionalGeneration:()=>fi,MoonshineForConditionalGeneration:()=>mi,MoonshineModel:()=>hi,MoonshinePreTrainedModel:()=>Rn,MptForCausalLM:()=>Xc,MptModel:()=>Qc,MptPreTrainedModel:()=>Ia,MultiModalityCausalLM:()=>Qh,MultiModalityPreTrainedModel:()=>qh,MusicgenForCausalLM:()=>tv,MusicgenForConditionalGeneration:()=>wl,MusicgenModel:()=>ev,MusicgenPreTrainedModel:()=>gl,NomicBertModel:()=>Ge,NomicBertPreTrainedModel:()=>at,OPTForCausalLM:()=>Yc,OPTModel:()=>Jc,OPTPreTrainedModel:()=>Aa,Olmo2ForCausalLM:()=>yr,Olmo2Model:()=>Wt,Olmo2PreTrainedModel:()=>kt,OlmoForCausalLM:()=>Mt,OlmoModel:()=>et,OlmoPreTrainedModel:()=>Ke,OpenELMForCausalLM:()=>Lc,OpenELMModel:()=>Dc,OpenELMPreTrainedModel:()=>Ea,OwlViTForObjectDetection:()=>vd,OwlViTModel:()=>yd,OwlViTPreTrainedModel:()=>ja,Owlv2ForObjectDetection:()=>Td,Owlv2Model:()=>xd,Owlv2PreTrainedModel:()=>Na,PaliGemmaForConditionalGeneration:()=>wi,PaliGemmaPreTrainedModel:()=>gi,PatchTSMixerForPrediction:()=>rm,PatchTSMixerModel:()=>tm,PatchTSMixerPreTrainedModel:()=>Ml,PatchTSTForPrediction:()=>em,PatchTSTModel:()=>Zh,PatchTSTPreTrainedModel:()=>bl,Phi3ForCausalLM:()=>Kc,Phi3Model:()=>Gc,Phi3PreTrainedModel:()=>$a,Phi3VForCausalLM:()=>go,Phi3VPreTrainedModel:()=>bi,PhiForCausalLM:()=>Wc,PhiModel:()=>Uc,PhiPreTrainedModel:()=>Sa,PreTrainedModel:()=>G,PretrainedMixin:()=>Dt,PvtForImageClassification:()=>id,PvtModel:()=>od,PvtPreTrainedModel:()=>Da,PyAnnoteForAudioFrameClassification:()=>Wp,PyAnnoteModel:()=>Up,PyAnnotePreTrainedModel:()=>cl,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>Bc,Qwen2Model:()=>zc,Qwen2PreTrainedModel:()=>Pa,Qwen2VLForConditionalGeneration:()=>Vc,Qwen2VLPreTrainedModel:()=>Nc,Qwen3ForCausalLM:()=>jc,Qwen3Model:()=>Rc,Qwen3PreTrainedModel:()=>Ca,RFDetrForObjectDetection:()=>Ld,RFDetrModel:()=>Dd,RFDetrObjectDetectionOutput:()=>zd,RFDetrPreTrainedModel:()=>Ha,RTDetrForObjectDetection:()=>Id,RTDetrModel:()=>kd,RTDetrObjectDetectionOutput:()=>Lo,RTDetrPreTrainedModel:()=>Ga,RTDetrV2ForObjectDetection:()=>Fd,RTDetrV2Model:()=>Ad,RTDetrV2ObjectDetectionOutput:()=>Od,RTDetrV2PreTrainedModel:()=>Ka,ResNetForImageClassification:()=>qd,ResNetModel:()=>Hd,ResNetPreTrainedModel:()=>Ya,RoFormerForMaskedLM:()=>St,RoFormerForQuestionAnswering:()=>gr,RoFormerForSequenceClassification:()=>Vt,RoFormerForTokenClassification:()=>zt,RoFormerModel:()=>pt,RoFormerPreTrainedModel:()=>Ie,RobertaForMaskedLM:()=>er,RobertaForQuestionAnswering:()=>Ir,RobertaForSequenceClassification:()=>dr,RobertaForTokenClassification:()=>pr,RobertaModel:()=>Mr,RobertaPreTrainedModel:()=>Lr,SamImageSegmentationOutput:()=>Op,SamModel:()=>Fp,SamPreTrainedModel:()=>Ap,SapiensForDepthEstimation:()=>op,SapiensForNormalEstimation:()=>ip,SapiensForSemanticSegmentation:()=>np,SapiensPreTrainedModel:()=>$i,SegformerForImageClassification:()=>Sh,SegformerForSemanticSegmentation:()=>$h,SegformerModel:()=>Z0,SegformerPreTrainedModel:()=>Oi,Seq2SeqLMOutput:()=>cv,SequenceClassifierOutput:()=>vt,SiglipModel:()=>Ks,SiglipPreTrainedModel:()=>Gs,SiglipTextModel:()=>wo,SiglipVisionModel:()=>xi,SmolVLMForConditionalGeneration:()=>_o,SnacDecoderModel:()=>gm,SnacEncoderModel:()=>_m,SnacModel:()=>fm,SnacPreTrainedModel:()=>Ni,SpeechT5ForSpeechToText:()=>hh,SpeechT5ForTextToSpeech:()=>mh,SpeechT5HifiGan:()=>fh,SpeechT5Model:()=>Y0,SpeechT5PreTrainedModel:()=>Ai,SqueezeBertForMaskedLM:()=>ln,SqueezeBertForQuestionAnswering:()=>cn,SqueezeBertForSequenceClassification:()=>un,SqueezeBertModel:()=>Vs,SqueezeBertPreTrainedModel:()=>As,StableLmForCausalLM:()=>Ih,StableLmModel:()=>kh,StableLmPreTrainedModel:()=>fl,Starcoder2ForCausalLM:()=>yh,Starcoder2Model:()=>Mh,Starcoder2PreTrainedModel:()=>pl,StyleTextToSpeech2Model:()=>ph,StyleTextToSpeech2PreTrainedModel:()=>dh,Swin2SRForImageSuperResolution:()=>Zd,Swin2SRModel:()=>Yd,Swin2SRPreTrainedModel:()=>Za,SwinForImageClassification:()=>Xd,SwinForSemanticSegmentation:()=>Jd,SwinModel:()=>Qd,SwinPreTrainedModel:()=>Si,T5ForConditionalGeneration:()=>xe,T5Model:()=>ce,T5PreTrainedModel:()=>ie,TableTransformerForObjectDetection:()=>Nd,TableTransformerModel:()=>jd,TableTransformerObjectDetectionOutput:()=>Vd,TableTransformerPreTrainedModel:()=>Qa,TokenClassifierOutput:()=>Cr,TrOCRForCausalLM:()=>gh,TrOCRPreTrainedModel:()=>_h,UltravoxModel:()=>nm,UltravoxPreTrainedModel:()=>sm,UniSpeechForCTC:()=>qp,UniSpeechForSequenceClassification:()=>Qp,UniSpeechModel:()=>Hp,UniSpeechPreTrainedModel:()=>ki,UniSpeechSatForAudioFrameClassification:()=>Zp,UniSpeechSatForCTC:()=>Jp,UniSpeechSatForSequenceClassification:()=>Yp,UniSpeechSatModel:()=>Xp,UniSpeechSatPreTrainedModel:()=>zo,ViTForImageClassification:()=>ed,ViTMAEModel:()=>ld,ViTMAEPreTrainedModel:()=>ad,ViTMSNForImageClassification:()=>cd,ViTMSNModel:()=>ud,ViTMSNPreTrainedModel:()=>La,ViTModel:()=>Zc,ViTPreTrainedModel:()=>Fa,VisionEncoderDecoderModel:()=>ho,VitMatteForImageMatting:()=>_d,VitMattePreTrainedModel:()=>fd,VitPoseForPoseEstimation:()=>nd,VitPosePreTrainedModel:()=>sd,VitsModel:()=>ml,VitsModelOutput:()=>xf,VitsPreTrainedModel:()=>Ch,Wav2Vec2BertForCTC:()=>th,Wav2Vec2BertForSequenceClassification:()=>rh,Wav2Vec2BertModel:()=>eh,Wav2Vec2BertPreTrainedModel:()=>Ii,Wav2Vec2ForAudioFrameClassification:()=>Vp,Wav2Vec2ForCTC:()=>jp,Wav2Vec2ForSequenceClassification:()=>Np,Wav2Vec2Model:()=>Rp,Wav2Vec2PreTrainedModel:()=>Qs,WavLMForAudioFrameClassification:()=>ch,WavLMForCTC:()=>ah,WavLMForSequenceClassification:()=>lh,WavLMForXVector:()=>uh,WavLMModel:()=>ih,WavLMPreTrainedModel:()=>Xn,WeSpeakerResNetModel:()=>Kp,WeSpeakerResNetPreTrainedModel:()=>Gp,WhisperForConditionalGeneration:()=>co,WhisperModel:()=>pi,WhisperPreTrainedModel:()=>uo,XLMForQuestionAnswering:()=>ao,XLMForSequenceClassification:()=>si,XLMForTokenClassification:()=>ni,XLMModel:()=>dn,XLMPreTrainedModel:()=>is,XLMRobertaForMaskedLM:()=>ii,XLMRobertaForQuestionAnswering:()=>ui,XLMRobertaForSequenceClassification:()=>ai,XLMRobertaForTokenClassification:()=>li,XLMRobertaModel:()=>oi,XLMRobertaPreTrainedModel:()=>Us,XLMWithLMHeadModel:()=>ri,XVectorOutput:()=>yf,YolosForObjectDetection:()=>kp,YolosModel:()=>$p,YolosObjectDetectionOutput:()=>Ip,YolosPreTrainedModel:()=>al});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),c=t("./src/generation/configuration_utils.js"),d=t("./src/utils/tensor.js"),_=t("./src/utils/image.js"),f=t("./src/utils/maths.js"),v=t("./src/generation/stopping_criteria.js"),$=t("./src/generation/logits_sampler.js"),g=t("./src/env.js"),w=t("./src/models/whisper/generation_whisper.js"),C=t("./src/models/whisper/common_whisper.js");const E={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},x=new Map,b=new Map,y=new Map;async function S(M,P,O){var Sr;let ne=((Sr=O.config)==null?void 0:Sr["transformers.js_config"])??{},ge=O.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const he=ge??(g.apis.IS_NODE_ENV?"cpu":"wasm"),Ee=(0,o.deviceToExecutionProviders)(he),De=ne.device_config??{};De.hasOwnProperty(he)&&(ne={...ne,...De[he]});let Ne=O.dtype??ne.dtype;if(typeof Ne!="string"&&(Ne&&Ne.hasOwnProperty(P)?Ne=Ne[P]:(Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${Ne}) for this device (${he}).`))),Ne===n.DATA_TYPES.auto){let Ct=ne.dtype;typeof Ct!="string"&&(Ct=Ct==null?void 0:Ct[P]),Ct&&Ct!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Ct)?Ne=Ct:Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32}const Xe=Ne;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Xe)){if(Xe===n.DATA_TYPES.fp16&&he==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${he}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Xe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const mt=ne.kv_cache_dtype,wt=mt?typeof mt=="string"?mt:mt[Xe]??"float32":void 0;if(wt&&!["float32","float16"].includes(wt))throw new Error(`Invalid kv_cache_dtype: ${wt}. Should be one of: float32, float16`);const dt={dtype:Xe,kv_cache_dtype:wt,device:he},Pt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Xe],gt=`${P}${Pt}.onnx`,Et=`${O.subfolder??""}/${gt}`,nt={...O.session_options};nt.executionProviders??(nt.executionProviders=Ee);const $t=ne.free_dimension_overrides;$t?nt.freeDimensionOverrides??(nt.freeDimensionOverrides=$t):he.startsWith("webnn")&&!nt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${he}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const qt=g.apis.IS_NODE_ENV&&g.env.useFSCache,tr=(0,l.getModelFile)(M,Et,!0,O,qt),ar=O.use_external_data_format??ne.use_external_data_format;let sr=[];if(ar){let Ct;typeof ar=="object"?ar.hasOwnProperty(gt)?Ct=ar[gt]:ar.hasOwnProperty(P)?Ct=ar[P]:Ct=!1:Ct=ar;const vr=+Ct;if(vr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${vr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Qr=0;Qr{const yn=await(0,l.getModelFile)(M,Nr,!0,O,qt);as(yn instanceof Uint8Array?{path:Mn,data:yn}:Mn)}))}}else nt.externalData!==void 0&&(sr=nt.externalData.map(async Ct=>{if(typeof Ct.data=="string"){const vr=await(0,l.getModelFile)(M,Ct.data,!0,O);return{...Ct,data:vr}}return Ct}));if(sr.length>0){const Ct=await Promise.all(sr);g.apis.IS_NODE_ENV||(nt.externalData=Ct)}if(he==="webgpu"){const Ct=(0,s.getKeyValueShapes)(O.config,{prefix:"present"});if(Object.keys(Ct).length>0&&!(0,o.isONNXProxy)()){const vr={};for(const Qr in Ct)vr[Qr]="gpu-buffer";nt.preferredOutputLocation=vr}}return{buffer_or_path:await tr,session_options:nt,session_config:dt}}async function F(M,P,O){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:he,session_config:Ee}=await S(M,P[ne],O),De=await(0,o.createInferenceSession)(ge,he,Ee);return[ne,De]})))}async function z(M,P,O){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(M,P[ne],!1,O);return[ne,ge]})))}function K(M,P){const O=Object.create(null),ne=[];for(const Ee of M.inputNames){const De=P[Ee];if(!(De instanceof d.Tensor)){ne.push(Ee);continue}O[Ee]=(0,o.isONNXProxy)()?De.clone():De}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,he=M.inputNames.length;if(ge>he){let Ee=Object.keys(P).filter(De=>!M.inputNames.includes(De));console.warn(`WARNING: Too many inputs were provided (${ge} > ${he}). The following inputs will be ignored: "${Ee.join(", ")}".`)}return O}let q=Promise.resolve();async function R(M,P){const O=K(M,P);try{const ne=Object.fromEntries(Object.entries(O).map(([Ee,De])=>[Ee,De.ort_tensor])),ge=()=>M.run(ne),he=await(g.apis.IS_BROWSER_ENV||g.apis.IS_WEBWORKER_ENV?q=q.then(ge):ge());return Z(he)}catch(ne){const ge=Object.fromEntries(Object.entries(O).map(([he,Ee])=>{const De={type:Ee.type,dims:Ee.dims,location:Ee.location};return De.location!=="gpu-buffer"&&(De.data=Ee.data),[he,De]}));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function Z(M){for(let P in M)(0,o.isONNXTensor)(M[P])?M[P]=new d.Tensor(M[P]):typeof M[P]=="object"&&Z(M[P]);return M}function H(M){if(M instanceof d.Tensor)return M;if(M.length===0)throw Error("items must be non-empty");if(Array.isArray(M[0])){if(M.some(P=>P.length!==M[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 d.Tensor("int64",BigInt64Array.from(M.flat().map(P=>BigInt(P))),[M.length,M[0].length])}else return new d.Tensor("int64",BigInt64Array.from(M.map(P=>BigInt(P))),[1,M.length])}function J(M){return new d.Tensor("bool",[M],[1])}async function Q(M,P){let{encoder_outputs:O,input_ids:ne,decoder_input_ids:ge,...he}=P;if(!O){const De=(0,a.pick)(P,M.sessions.model.inputNames);O=(await se(M,De)).last_hidden_state}return he.input_ids=ge,he.encoder_hidden_states=O,M.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(he.encoder_attention_mask=P.attention_mask),await ae(M,he,!0)}async function se(M,P){const O=M.sessions.model,ne=(0,a.pick)(P,O.inputNames);if(O.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await M.encode_text({input_ids:P.input_ids})}if(O.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,d.zeros_like)(ne.input_ids)}if(O.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=ne.pixel_values.dims;ne.pixel_mask=(0,d.ones)([ge[0],ge[2],ge[3]])}return await R(O,ne)}async function fe(M,P){const O=await M.encode(P);return await M.decode(O)}async function ae(M,P,O=!1){const ne=M.sessions[O?"decoder_model_merged":"model"],{past_key_values:ge,...he}=P;if(ne.inputNames.includes("use_cache_branch")&&(he.use_cache_branch=J(!!ge)),ne.inputNames.includes("position_ids")&&he.attention_mask&&!he.position_ids){const De=["paligemma","gemma3_text","gemma3"].includes(M.config.model_type)?1:0;he.position_ids=ze(he,ge,De)}M.addPastKeyValues(he,ge);const Ee=(0,a.pick)(he,ne.inputNames);return await R(ne,Ee)}function V({modality_token_id:M,inputs_embeds:P,modality_features:O,input_ids:ne,attention_mask:ge}){const he=ne.tolist().map(Xe=>Xe.reduce((mt,wt,dt)=>(wt==M&&mt.push(dt),mt),[])),Ee=he.reduce((Xe,mt)=>Xe+mt.length,0),De=O.dims[0];if(Ee!==De)throw new Error(`Number of tokens and features do not match: tokens: ${Ee}, features ${De}`);let Ne=0;for(let Xe=0;Xehe.dims[1])){if(geDe==M.config.image_token_index)){const De=M.config.num_image_tokens;if(!De)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ne=he.dims[1]-(ge-De);O.input_ids=he.slice(null,[-Ne,null]),O.attention_mask=(0,d.ones)([1,ge+Ne])}}}return O}function pe(M,P,O,ne){return O.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...O,decoder_input_ids:H(P)}}function W(M,...P){return M.config.is_encoder_decoder?pe(M,...P):Ue(M,...P)}function re(M,P,O,ne){const ge=!!O.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?O.input_ids=(0,d.cat)([O.input_ids,O.input_ids],0):(O.input_ids=(0,d.cat)([O.input_ids,(0,d.full_like)(O.input_ids,BigInt(ne.pad_token_id))],0),O.attention_mask=(0,d.cat)([O.attention_mask,(0,d.full_like)(O.attention_mask,0n)],0))),(ge||!O.pixel_values)&&(O.pixel_values=(0,d.full)([0,0,3,384,384],1)),ge&&(O.images_seq_mask=new d.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),O.images_emb_mask=new d.Tensor("bool",new Array(0).fill(!1),[1,1,0])),O}class G extends i.Callable{constructor(O,ne,ge){super();Y(this,"main_input_name","input_ids");Y(this,"forward_params",["input_ids","attention_mask"]);this.config=O,this.sessions=ne,this.configs=ge;const he=y.get(this.constructor),Ee=x.get(he);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ee){case E.DecoderOnly:this.can_generate=!0,this._forward=ae,this._prepare_inputs_for_generation=Ue;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Q,this._prepare_inputs_for_generation=pe;break;case E.EncoderDecoder:this._forward=Q;break;case E.ImageTextToText:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=W;break;case E.AudioTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=W;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=W;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=re;break;case E.AutoEncoder:this._forward=fe;break;default:this._forward=se;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const O=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&O.push(ge.handler.dispose());return await Promise.all(O)}static async from_pretrained(O,{progress_callback:ne=null,config:ge=null,cache_dir:he=null,local_files_only:Ee=!1,revision:De="main",model_file_name:Ne=null,subfolder:Xe="onnx",device:mt=null,dtype:wt=null,use_external_data_format:dt=null,session_options:Pt={}}={}){let gt={progress_callback:ne,config:ge,cache_dir:he,local_files_only:Ee,revision:De,model_file_name:Ne,subfolder:Xe,device:mt,dtype:wt,use_external_data_format:dt,session_options:Pt};const Et=y.get(this),nt=x.get(Et);ge=gt.config=await s.AutoConfig.from_pretrained(O,gt);let $t;if(nt===E.DecoderOnly)$t=await Promise.all([F(O,{model:gt.model_file_name??"model"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(nt===E.Seq2Seq||nt===E.Vision2Seq)$t=await Promise.all([F(O,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(nt===E.MaskGeneration)$t=await Promise.all([F(O,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},gt)]);else if(nt===E.EncoderDecoder)$t=await Promise.all([F(O,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},gt)]);else if(nt===E.ImageTextToText){const qt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(qt.model="encoder_model"),$t=await Promise.all([F(O,qt,gt),z(O,{generation_config:"generation_config.json"},gt)])}else if(nt===E.AudioTextToText){const qt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};$t=await Promise.all([F(O,qt,gt),z(O,{generation_config:"generation_config.json"},gt)])}else if(nt===E.Musicgen)$t=await Promise.all([F(O,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(nt===E.MultiModality)$t=await Promise.all([F(O,{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"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(nt===E.Phi3V)$t=await Promise.all([F(O,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(nt===E.AutoEncoder)$t=await Promise.all([F(O,{encoder_model:"encoder_model",decoder_model:"decoder_model"},gt)]);else{if(nt!==E.EncoderOnly){const qt=Et??(ge==null?void 0:ge.model_type);qt!=="custom"&&console.warn(`Model type for '${qt}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}$t=await Promise.all([F(O,{model:gt.model_file_name??"model"},gt)])}return new this(ge,...$t)}async _call(O){return await this.forward(O)}async forward(O){return await this._forward(this,O)}get generation_config(){var O;return((O=this.configs)==null?void 0:O.generation_config)??null}_get_logits_warper(O){const ne=new p.LogitsProcessorList;return O.temperature!==null&&O.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(O.temperature)),O.top_k!==null&&O.top_k!==0&&ne.push(new p.TopKLogitsWarper(O.top_k)),O.top_p!==null&&O.top_p<1&&ne.push(new p.TopPLogitsWarper(O.top_p)),ne}_get_logits_processor(O,ne,ge=null){const he=new p.LogitsProcessorList;if(O.repetition_penalty!==null&&O.repetition_penalty!==1&&he.push(new p.RepetitionPenaltyLogitsProcessor(O.repetition_penalty)),O.no_repeat_ngram_size!==null&&O.no_repeat_ngram_size>0&&he.push(new p.NoRepeatNGramLogitsProcessor(O.no_repeat_ngram_size)),O.bad_words_ids!==null&&he.push(new p.NoBadWordsLogitsProcessor(O.bad_words_ids,O.eos_token_id)),O.min_length!==null&&O.eos_token_id!==null&&O.min_length>0&&he.push(new p.MinLengthLogitsProcessor(O.min_length,O.eos_token_id)),O.min_new_tokens!==null&&O.eos_token_id!==null&&O.min_new_tokens>0&&he.push(new p.MinNewTokensLengthLogitsProcessor(ne,O.min_new_tokens,O.eos_token_id)),O.forced_bos_token_id!==null&&he.push(new p.ForcedBOSTokenLogitsProcessor(O.forced_bos_token_id)),O.forced_eos_token_id!==null&&he.push(new p.ForcedEOSTokenLogitsProcessor(O.max_length,O.forced_eos_token_id)),O.begin_suppress_tokens!==null){const Ee=ne>1||O.forced_bos_token_id===null?ne:ne+1;he.push(new p.SuppressTokensAtBeginLogitsProcessor(O.begin_suppress_tokens,Ee))}return O.guidance_scale!==null&&O.guidance_scale>1&&he.push(new p.ClassifierFreeGuidanceLogitsProcessor(O.guidance_scale)),ge!==null&&he.extend(ge),he}_prepare_generation_config(O,ne,ge=c.GenerationConfig){const he={...this.config};for(const De of["decoder","generator","text_config"])De in he&&Object.assign(he,he[De]);const Ee=new ge(he);return Object.assign(Ee,this.generation_config??{}),O&&Object.assign(Ee,O),ne&&Object.assign(Ee,(0,a.pick)(ne,Object.getOwnPropertyNames(Ee))),Ee}_get_stopping_criteria(O,ne=null){const ge=new v.StoppingCriteriaList;return O.max_length!==null&&ge.push(new v.MaxLengthCriteria(O.max_length,this.config.max_position_embeddings??null)),O.eos_token_id!==null&&ge.push(new v.EosTokenCriteria(O.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const O=[xl,Tl,vl,yl],ne=y.get(this.constructor),ge=new Set,he=this.config.model_type;for(const De of O){const Ne=De.get(he);Ne&&ge.add(Ne[0])}let Ee=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ee+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ee)}}prepare_inputs_for_generation(...O){return this._prepare_inputs_for_generation(this,...O)}_update_model_kwargs_for_generation({generated_input_ids:O,outputs:ne,model_inputs:ge,is_encoder_decoder:he}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new d.Tensor("int64",O.flat(),[O.length,1]),he||(ge.attention_mask=(0,d.cat)([ge.attention_mask,(0,d.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:O,bos_token_id:ne,model_kwargs:ge}){const he=(0,a.pick)(ge,this.forward_params),Ee=this.main_input_name;if(Ee in he){if(O)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else he[Ee]=O;return{inputs_tensor:he[Ee],model_inputs:he,model_input_name:Ee}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:O,model_inputs:ne,model_input_name:ge,generation_config:he}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:De,pixel_values:Ne,attention_mask:Xe,...mt}=ne,wt=await this._prepare_inputs_embeds(ne);ne={...mt,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ee}=await se(this,ne);if(he.guidance_scale!==null&&he.guidance_scale>1)Ee=(0,d.cat)([Ee,(0,d.full_like)(Ee,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,d.cat)([ne.attention_mask,(0,d.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const De=H(ne.decoder_input_ids).dims[0];if(De!==Ee.dims[0]){if(Ee.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ee.dims[0]}) than the decoder inputs (${De}).`);Ee=(0,d.cat)(Array.from({length:De},()=>Ee),0)}}return ne.encoder_outputs=Ee,ne}_prepare_decoder_input_ids_for_generation({batch_size:O,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:he,bos_token_id:Ee,generation_config:De}){let{decoder_input_ids:Ne,...Xe}=ge;if(!(Ne instanceof d.Tensor)){if(Ne)Array.isArray(Ne[0])||(Ne=Array.from({length:O},()=>Ne));else if(he??(he=Ee),this.config.model_type==="musicgen")Ne=Array.from({length:O*this.config.decoder.num_codebooks},()=>[he]);else if(Array.isArray(he)){if(he.length!==O)throw new Error(`\`decoder_start_token_id\` expcted to have length ${O} but got ${he.length}`);Ne=he}else Ne=Array.from({length:O},()=>[he]);Ne=H(Ne)}return ge.decoder_attention_mask=(0,d.ones_like)(Ne),{input_ids:Ne,model_inputs:Xe}}async generate({inputs:O=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:he=null,streamer:Ee=null,...De}){this._validate_model_class(),ne=this._prepare_generation_config(ne,De);let{inputs_tensor:Ne,model_inputs:Xe,model_input_name:mt}=this._prepare_model_inputs({inputs:O,model_kwargs:De});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Xe||(Xe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ne,model_inputs:Xe,model_input_name:mt,generation_config:ne})));let dt;wt?{input_ids:dt,model_inputs:Xe}=this._prepare_decoder_input_ids_for_generation({batch_size:Xe[mt].dims.at(0),model_input_name:mt,model_kwargs:Xe,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):dt=Xe[mt];let Pt=dt.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=Pt+ne.max_new_tokens);const gt=this._get_logits_processor(ne,Pt,ge),Et=this._get_stopping_criteria(ne,he),nt=Xe[mt].dims.at(0),$t=$.LogitsSampler.getSampler(ne),qt=new Array(nt).fill(0),tr=dt.tolist();Ee&&Ee.put(tr);let ar,sr={};for(;;){if(Xe=this.prepare_inputs_for_generation(tr,Xe,ne),ar=await this.forward(Xe),ne.output_attentions&&ne.return_dict_in_generate){const Nr=this.getAttentions(ar);for(const as in Nr)as in sr||(sr[as]=[]),sr[as].push(Nr[as])}const Ct=ar.logits.slice(null,-1,null),vr=gt(tr,Ct),Qr=[];for(let Nr=0;NrNr))break;Xe=this._update_model_kwargs_for_generation({generated_input_ids:Qr,outputs:ar,model_inputs:Xe,is_encoder_decoder:wt})}Ee&&Ee.end();const _r=this.getPastKeyValues(ar,Xe.past_key_values,!0),Sr=new d.Tensor("int64",tr.flat(),[tr.length,tr[0].length]);if(ne.return_dict_in_generate)return{sequences:Sr,past_key_values:_r,...sr};for(const Ct of Object.values(ar))Ct.location==="gpu-buffer"&&Ct.dispose();return Sr}getPastKeyValues(O,ne,ge=!1){const he=Object.create(null);for(const Ee in O)if(Ee.startsWith("present")){const De=Ee.replace("present","past_key_values"),Ne=Ee.includes("encoder");if(Ne&&ne?he[De]=ne[De]:he[De]=O[Ee],ne&&(!Ne||ge)){const Xe=ne[De];Xe.location==="gpu-buffer"&&Xe.dispose()}}return he}getAttentions(O){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const he in O)he.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(O[he]));return ne}addPastKeyValues(O,ne){var ge,he,Ee;if(ne)Object.assign(O,ne);else{const De=this.sessions.decoder_model_merged??this.sessions.model,Ne=((ge=De==null?void 0:De.config)==null?void 0:ge.kv_cache_dtype)??"float32",Xe=Ne==="float16"?new d.DataTypeMap.float16:[],mt=((Ee=(he=O[this.main_input_name]??O.attention_mask)==null?void 0:he.dims)==null?void 0:Ee[0])??1,wt=(0,s.getKeyValueShapes)(this.config,{batch_size:mt});for(const dt in wt)O[dt]=new d.Tensor(Ne,Xe,wt[dt])}}async encode_image({pixel_values:O}){const ne=(await R(this.sessions.vision_encoder,{pixel_values:O})).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 (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:O}){return(await R(this.sessions.embed_tokens,{input_ids:O})).inputs_embeds}async encode_audio({audio_values:O}){return(await R(this.sessions.audio_encoder,{audio_values:O})).audio_features}}class be{}class we extends be{constructor({last_hidden_state:P,hidden_states:O=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=O,this.attentions=ne}}class Se extends G{}class Pe extends Se{}class $e extends Se{async _call(P){return new Ar(await super._call(P))}}class Fe extends Se{async _call(P){return new vt(await super._call(P))}}class Be extends Se{async _call(P){return new Cr(await super._call(P))}}class He extends Se{async _call(P){return new Br(await super._call(P))}}class qe extends G{}class ke extends qe{}class Ve extends qe{async _call(P){return new Ar(await super._call(P))}}class Ze extends qe{async _call(P){return new vt(await super._call(P))}}class st extends qe{async _call(P){return new Cr(await super._call(P))}}class at extends G{}class Ge extends at{}class Ie extends G{}class pt extends Ie{}class St extends Ie{async _call(P){return new Ar(await super._call(P))}}class Vt extends Ie{async _call(P){return new vt(await super._call(P))}}class zt extends Ie{async _call(P){return new Cr(await super._call(P))}}class gr extends Ie{async _call(P){return new Br(await super._call(P))}}class or extends G{}class bt extends or{}class Zr extends or{async _call(P){return new Ar(await super._call(P))}}class D extends or{async _call(P){return new vt(await super._call(P))}}class oe extends or{async _call(P){return new Cr(await super._call(P))}}class B extends or{async _call(P){return new Br(await super._call(P))}}class te extends G{}class me extends te{}class Oe extends te{async _call(P){return new Ar(await super._call(P))}}class ve extends te{async _call(P){return new vt(await super._call(P))}}class yt extends te{async _call(P){return new Cr(await super._call(P))}}class Ft extends te{async _call(P){return new Br(await super._call(P))}}class ht extends G{}class lt extends ht{}class rt extends ht{async _call(P){return new Ar(await super._call(P))}}class Bt extends ht{async _call(P){return new vt(await super._call(P))}}class Ht extends ht{async _call(P){return new Cr(await super._call(P))}}class wr extends ht{async _call(P){return new Br(await super._call(P))}}class Xt extends G{}class Or extends Xt{}class es extends Xt{async _call(P){return new Ar(await super._call(P))}}class ds extends Xt{async _call(P){return new vt(await super._call(P))}}class ts extends Xt{async _call(P){return new Cr(await super._call(P))}}class Cs extends Xt{async _call(P){return new Br(await super._call(P))}}class jr extends G{}class Ss extends jr{}class Kr extends jr{async _call(P){return new Ar(await super._call(P))}}class ps extends jr{async _call(P){return new vt(await super._call(P))}}class $s extends jr{async _call(P){return new Cr(await super._call(P))}}class ks extends jr{async _call(P){return new Br(await super._call(P))}}class ir extends G{}class Is extends ir{}class Tr extends ir{async _call(P){return new vt(await super._call(P))}}class hs extends ir{async _call(P){return new Cr(await super._call(P))}}class zr extends ir{async _call(P){return new Br(await super._call(P))}}class Ae extends ir{async _call(P){return new Ar(await super._call(P))}}class Je extends G{}class it extends Je{}class Rt extends Je{async _call(P){return new Ar(await super._call(P))}}class rs extends Je{async _call(P){return new vt(await super._call(P))}}class ss extends Je{async _call(P){return new Cr(await super._call(P))}}class ur extends G{}class ns extends ur{}class cr extends ur{async _call(P){return new Ar(await super._call(P))}}class hr extends ur{async _call(P){return new vt(await super._call(P))}}class os extends ur{async _call(P){return new Br(await super._call(P))}}class ms extends G{}class rn extends ms{}class sn extends ms{async _call(P){return new Ar(await super._call(P))}}class nn extends ms{async _call(P){return new vt(await super._call(P))}}class on extends ms{async _call(P){return new Cr(await super._call(P))}}class an extends ms{async _call(P){return new Br(await super._call(P))}}class As extends G{}class Vs extends As{}class ln extends As{async _call(P){return new Ar(await super._call(P))}}class un extends As{async _call(P){return new vt(await super._call(P))}}class cn extends As{async _call(P){return new Br(await super._call(P))}}class Fs extends G{}class de extends Fs{}class k extends Fs{async _call(P){return new vt(await super._call(P))}}class j extends Fs{async _call(P){return new Br(await super._call(P))}}class X extends Fs{async _call(P){return new Ar(await super._call(P))}}class ie extends G{constructor(){super(...arguments);Y(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ce extends ie{}class xe extends ie{}class Re extends G{}class Qe extends Re{}class We extends Re{}class Ye extends G{}class _t extends Ye{}class Ot extends Ye{}class At extends G{}class Jt extends At{}class Ut extends At{}class mr extends At{async _call(P){return new vt(await super._call(P))}}class br extends G{}class Er extends br{}class Pr extends br{}class Zt extends br{async _call(P){return new vt(await super._call(P))}}class fs extends br{}class Kt extends G{}class fr extends Kt{}class Dr extends Kt{}class Hr extends G{}class qr extends Hr{}class kr extends Hr{}class Lr extends G{}class Mr extends Lr{}class er extends Lr{async _call(P){return new Ar(await super._call(P))}}class dr extends Lr{async _call(P){return new vt(await super._call(P))}}class pr extends Lr{async _call(P){return new Cr(await super._call(P))}}class Ir extends Lr{async _call(P){return new Br(await super._call(P))}}class is extends G{}class dn extends is{}class ri extends is{async _call(P){return new Ar(await super._call(P))}}class si extends is{async _call(P){return new vt(await super._call(P))}}class ni extends is{async _call(P){return new Cr(await super._call(P))}}class ao extends is{async _call(P){return new Br(await super._call(P))}}class Us extends G{}class oi extends Us{}class ii extends Us{async _call(P){return new Ar(await super._call(P))}}class ai extends Us{async _call(P){return new vt(await super._call(P))}}class li extends Us{async _call(P){return new Cr(await super._call(P))}}class ui extends Us{async _call(P){return new Br(await super._call(P))}}class lo extends G{}class ci extends lo{}class di extends lo{}class uo extends G{constructor(){super(...arguments);Y(this,"requires_attention_mask",!1);Y(this,"main_input_name","input_features");Y(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class pi extends uo{}class co extends uo{_prepare_generation_config(P,O){return super._prepare_generation_config(P,O,w.WhisperGenerationConfig)}_retrieve_init_tokens(P){const O=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ee=`<|${(0,C.whisper_language_to_code)(ne)}|>`;O.push(P.lang_to_id[Ee]),O.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)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!P.return_timestamps&&P.no_timestamps_token_id&&O.at(-1)!==P.no_timestamps_token_id?O.push(P.no_timestamps_token_id):P.return_timestamps&&O.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),O.pop()),O.filter(he=>he!=null)}async generate({inputs:P=null,generation_config:O=null,logits_processor:ne=null,stopping_criteria:ge=null,...he}){O=this._prepare_generation_config(O,he);const Ee=he.decoder_input_ids??this._retrieve_init_tokens(O);if(O.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(O,Ee))),O.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(O.begin_suppress_tokens,Ee.length))),O.return_token_timestamps){if(!O.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.");O.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),O.output_attentions=!0,O.return_dict_in_generate=!0}const De=await super.generate({inputs:P,generation_config:O,logits_processor:ne,decoder_input_ids:Ee,...he});return O.return_token_timestamps&&(De.token_timestamps=this._extract_token_timestamps(De,O.alignment_heads,O.num_frames)),De}_extract_token_timestamps(P,O,ne=null,ge=.02){if(!P.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`.");ne==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 he=this.config.median_filter_width;he===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),he=7);const Ee=P.cross_attentions,De=Array.from({length:this.config.decoder_layers},(Et,nt)=>(0,d.cat)(Ee.map($t=>$t[nt]),2)),Ne=(0,d.stack)(O.map(([Et,nt])=>{if(Et>=De.length)throw new Error(`Layer index ${Et} is out of bounds for cross attentions (length ${De.length}).`);return ne?De[Et].slice(null,nt,null,[0,ne]):De[Et].slice(null,nt)})).transpose(1,0,2,3),[Xe,mt]=(0,d.std_mean)(Ne,-2,0,!0),wt=Ne.clone();for(let Et=0;Et$t[Sr+1]-$t[Sr]),ar=(0,a.mergeArrays)([1],tr).map(_r=>!!_r),sr=[];for(let _r=0;_rdt.findIndex(Pt=>Pt==he)),Ne=De.every(dt=>dt===-1),Xe=De.every(dt=>dt!==-1);if(!Ne&&!Xe)throw new Error("Every input should contain either 0 or 1 image token.");if(Ne)return{inputs_embeds:P,attention_mask:ge};const mt=[],wt=[];for(let dt=0;dtArray.from({length:P.dims[0]},tr=>Array.from({length:P.dims[1]},ar=>1))),gt=O?O.tolist():[],Et=ne?ne.tolist():[];let nt=0,$t=0;for(let qt=0;qtdt[qt][xr]==1),sr=tr.reduce((rr,xr,Xs)=>(xr==Ne&&rr.push(Xs),rr),[]).map(rr=>tr[rr+1]),_r=sr.filter(rr=>rr==Ee).length,Sr=sr.filter(rr=>rr==De).length;let Ct=[],vr=0,Qr=_r,Mn=Sr;for(let rr=0;rr_s>vr&&xn==Ee),Xs=tr.findIndex((xn,_s)=>_s>vr&&xn==De),vn=Qr>0&&xr!==-1?xr:tr.length+1,Yn=Mn>0&&Xs!==-1?Xs:tr.length+1;let Gi,Pl,Cl,Sl;vn0?(0,f.max)(Ct.at(-1))[0]+1:0;Ct.push(Array.from({length:3*kl},(xn,_s)=>Tf+_s%kl));const Il=kl+Tf,Hi=pv*$l*Ki,hv=Array.from({length:Hi},(xn,_s)=>Il+Math.floor(_s/($l*Ki))),mv=Array.from({length:Hi},(xn,_s)=>Il+Math.floor(_s/Ki)%$l),fv=Array.from({length:Hi},(xn,_s)=>Il+_s%Ki);Ct.push([hv,mv,fv].flat()),vr=Gi+Hi}if(vr0?(0,f.max)(Ct.at(-1))[0]+1:0,xr=tr.length-vr;Ct.push(Array.from({length:3*xr},(Xs,vn)=>rr+vn%xr))}const Nr=Ct.reduce((rr,xr)=>rr+xr.length,0),as=new Array(Nr);let Vi=0;for(let rr=0;rr<3;++rr)for(let xr=0;xrwt[nt%wt.length]),gt=Array.from({length:dt[0]},(Et,nt)=>(0,f.max)(wt.subarray(dt[1]*nt,dt[1]*(nt+1)))[0]+1n+BigInt(dt[1]));return[new d.Tensor("int64",Pt,[3,...dt]),new d.Tensor("int64",gt,[gt.length,1])]}else{const[wt,dt]=P.dims,Pt=BigInt64Array.from({length:3*wt*dt},(gt,Et)=>BigInt(Math.floor(Et%dt/wt)));return[new d.Tensor("int64",Pt,[3,...P.dims]),(0,d.zeros)([wt,1])]}}async encode_image({pixel_values:P,image_grid_thw:O}){return(await R(this.sessions.vision_encoder,{pixel_values:P,grid_thw:O})).image_features}_merge_input_ids_with_image_features(P){return A({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,O,ne){if(O.attention_mask&&!O.position_ids)if(!O.past_key_values)[O.position_ids,O.rope_deltas]=this.get_rope_index(O.input_ids,O.image_grid_thw,O.video_grid_thw,O.attention_mask);else{O.pixel_values=null;const ge=BigInt(Object.values(O.past_key_values)[0].dims.at(-2)),he=O.rope_deltas.map(Ee=>ge+Ee);O.position_ids=(0,d.stack)([he,he,he],0)}return O}}class Sa extends G{}class Uc extends Sa{}class Wc extends Sa{}class $a extends G{}class Gc extends $a{}class Kc extends $a{}class ka extends G{}class Hc extends ka{}class qc extends ka{}class Ia extends G{}class Qc extends Ia{}class Xc extends Ia{}class Aa extends G{}class Jc extends Aa{}class Yc extends Aa{}class Fa extends G{}class Zc extends Fa{}class ed extends Fa{async _call(P){return new vt(await super._call(P))}}class Oa extends G{}class td extends Oa{}class rd extends Oa{async _call(P){return new vt(await super._call(P))}}class sd extends G{}class nd extends sd{}class Da extends G{}class od extends Da{}class id extends Da{async _call(P){return new vt(await super._call(P))}}class ad extends G{}class ld extends ad{}class La extends G{}class ud extends La{}class cd extends La{async _call(P){return new vt(await super._call(P))}}class dd extends G{}class pd extends dd{}class za extends G{}class hd extends za{}class md extends za{async _call(P){return new vt(await super._call(P))}}class fd extends G{}class _d extends fd{async _call(P){return new vf(await super._call(P))}}class Ba extends G{}class gd extends Ba{}class wd extends Ba{async _call(P){return new vt(await super._call(P))}}class Ra extends G{}class bd extends Ra{}class Md extends Ra{async _call(P){return new vt(await super._call(P))}}class ja extends G{}class yd extends ja{}class vd extends ja{}class Na extends G{}class xd extends Na{}class Td extends Na{}class Va extends G{}class Ed extends Va{}class Pd extends Va{async _call(P){return new vt(await super._call(P))}}class Ci extends G{}class Cd extends Ci{}class Sd extends Ci{async _call(P){return new Wa(await super._call(P))}}class Ua extends Ci{async _call(P){return new $d(await super._call(P))}}class Wa extends be{constructor({logits:P,pred_boxes:O}){super(),this.logits=P,this.pred_boxes=O}}class $d extends be{constructor({logits:P,pred_boxes:O,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=O,this.pred_masks=ne}}class Ga extends G{}class kd extends Ga{}class Id extends Ga{async _call(P){return new Lo(await super._call(P))}}class Lo extends be{constructor({logits:P,pred_boxes:O}){super(),this.logits=P,this.pred_boxes=O}}class Ka extends G{}class Ad extends Ka{}class Fd extends Ka{async _call(P){return new Od(await super._call(P))}}class Od extends Lo{}class Ha extends G{}class Dd extends Ha{}class Ld extends Ha{async _call(P){return new zd(await super._call(P))}}class zd extends Lo{}class qa extends G{}class Bd extends qa{}class Rd extends qa{async _call(P){return new Lo(await super._call(P))}}class Qa extends G{}class jd extends Qa{}class Nd extends Qa{async _call(P){return new Vd(await super._call(P))}}class Vd extends Wa{}class Xa extends G{}class Ud extends Xa{}class Wd extends Xa{async _call(P){return new vt(await super._call(P))}}class Ja extends G{}class Gd extends Ja{}class Kd extends Ja{async _call(P){return new vt(await super._call(P))}}class Ya extends G{}class Hd extends Ya{}class qd extends Ya{async _call(P){return new vt(await super._call(P))}}class Si extends G{}class Qd extends Si{}class Xd extends Si{async _call(P){return new vt(await super._call(P))}}class Jd extends Si{}class Za extends G{}class Yd extends Za{}class Zd extends Za{}class el extends G{}class ep extends el{}class tp extends el{}class rp extends G{}class sp extends rp{}class $i extends G{}class np extends $i{}class op extends $i{}class ip extends $i{}class ap extends G{}class lp extends ap{}class up extends G{}class cp extends up{}class dp extends G{}class pp extends dp{}class tl extends G{}class hp extends tl{}class mp extends tl{}class rl extends G{}class fp extends rl{}class _p extends rl{}class gp extends G{}class wp extends gp{}class sl extends G{}class bp extends sl{}class Mp extends sl{async _call(P){return new vt(await super._call(P))}}class nl extends G{}class yp extends nl{}class vp extends nl{async _call(P){return new vt(await super._call(P))}}class ol extends G{}class xp extends ol{}class Tp extends ol{async _call(P){return new vt(await super._call(P))}}class il extends G{}class Ep extends il{}class Pp extends il{async _call(P){return new vt(await super._call(P))}}class Cp extends G{}class Sp extends Cp{}class al extends G{}class $p extends al{}class kp extends al{async _call(P){return new Ip(await super._call(P))}}class Ip extends be{constructor({logits:P,pred_boxes:O}){super(),this.logits=P,this.pred_boxes=O}}class Ap extends G{}class Fp extends Ap{async get_image_embeddings({pixel_values:P}){return await se(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((he,Ee)=>he*Ee,1);P.input_labels=new d.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const O={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(O.input_points=P.input_points),P.input_labels&&(O.input_labels=P.input_labels),P.input_boxes&&(O.input_boxes=P.input_boxes),await R(this.sessions.prompt_encoder_mask_decoder,O)}async _call(P){return new Op(await super._call(P))}}class Op extends be{constructor({iou_scores:P,pred_masks:O}){super(),this.iou_scores=P,this.pred_masks=O}}class ll extends G{}class Dp extends ll{}class Lp extends ll{}class ul extends G{}class zp extends ul{}class Bp extends ul{}class Qs extends G{}class Rp extends Qs{}class jp extends Qs{async _call(P){return new bn(await super._call(P))}}class Np extends Qs{async _call(P){return new vt(await super._call(P))}}class Vp extends Qs{async _call(P){return new Cr(await super._call(P))}}class cl extends G{}class Up extends cl{}class Wp extends cl{async _call(P){return new Cr(await super._call(P))}}class Gp extends G{}class Kp extends Gp{}class ki extends G{}class Hp extends ki{}class qp extends ki{async _call(P){return new bn(await super._call(P))}}class Qp extends ki{async _call(P){return new vt(await super._call(P))}}class zo extends G{}class Xp extends zo{}class Jp extends zo{async _call(P){return new bn(await super._call(P))}}class Yp extends zo{async _call(P){return new vt(await super._call(P))}}class Zp extends zo{async _call(P){return new Cr(await super._call(P))}}class Ii extends G{}class eh extends Ii{}class th extends Ii{async _call(P){return new bn(await super._call(P))}}class rh extends Ii{async _call(P){return new vt(await super._call(P))}}class J0 extends G{}class sh extends Qs{}class nh extends Qs{async _call(P){return new bn(await super._call(P))}}class oh extends Qs{async _call(P){return new vt(await super._call(P))}}class Xn extends G{}class ih extends Xn{}class ah extends Xn{async _call(P){return new bn(await super._call(P))}}class lh extends Xn{async _call(P){return new vt(await super._call(P))}}class uh extends Xn{async _call(P){return new yf(await super._call(P))}}class ch extends Xn{async _call(P){return new Cr(await super._call(P))}}class dh extends G{}class ph extends dh{}class Ai extends G{}class Y0 extends Ai{}class hh extends Ai{}class mh extends Ai{async generate_speech(P,O,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:he=20,vocoder:Ee=null}={}){const De={input_ids:P},{encoder_outputs:Ne,encoder_attention_mask:Xe}=await se(this,De),mt=Ne.dims[1]/this.config.reduction_factor,wt=Math.floor(mt*he),dt=Math.floor(mt*ge),Pt=this.config.num_mel_bins;let gt=[],Et=null,nt=null,$t=0;for(;;){++$t;const ar=J(!!nt);let sr;nt?sr=nt.output_sequence_out:sr=new d.Tensor("float32",new Float32Array(Pt),[1,1,Pt]);let _r={use_cache_branch:ar,output_sequence:sr,encoder_attention_mask:Xe,speaker_embeddings:O,encoder_hidden_states:Ne};this.addPastKeyValues(_r,Et),nt=await R(this.sessions.decoder_model_merged,_r),Et=this.getPastKeyValues(nt,Et);const{prob:Sr,spectrum:Ct}=nt;if(gt.push(Ct),$t>=dt&&(Array.from(Sr.data).filter(vr=>vr>=ne).length>0||$t>=wt))break}const qt=(0,d.cat)(gt),{waveform:tr}=await R(Ee.sessions.model,{spectrogram:qt});return{spectrogram:qt,waveform:tr}}}class fh extends G{constructor(){super(...arguments);Y(this,"main_input_name","spectrogram")}}class _h extends G{}class gh extends _h{}class dl extends G{}class wh extends dl{}class bh extends dl{}class pl extends G{}class Mh extends pl{}class yh extends pl{}class hl extends G{}class vh extends hl{}class xh extends hl{}class Fi extends G{}class Th extends Fi{}class Eh extends Fi{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"text_model"})}}class Ph extends Fi{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"audio_model"})}}class Ch extends G{}class ml extends Ch{async _call(P){return new xf(await super._call(P))}}class Oi extends G{}class Z0 extends Oi{}class Sh extends Oi{}class $h extends Oi{}class fl extends G{}class kh extends fl{}class Ih extends fl{}class _l extends G{}class Ah extends _l{}class Fh extends _l{async _call(P){return new vt(await super._call(P))}}class gl extends G{}class ev extends gl{}class tv extends gl{}class wl extends G{constructor(){super(...arguments);Y(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(O){const[ne,ge]=O.dims,he=this.config.decoder.num_codebooks,Ee=ge-he;let De=0;for(let mt=0;mt0&&Pt<=Ee&&(O.data[De++]=O.data[mt])}const Ne=Math.floor(ne/he),Xe=De/(Ne*he);return new d.Tensor(O.type,O.data.slice(0,De),[Ne,he,Xe])}prepare_inputs_for_generation(O,ne,ge){let he=structuredClone(O);for(let De=0;De=Ne&&(he[De][Ne]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(he=he.concat(he)),super.prepare_inputs_for_generation(he,ne,ge)}async generate(O){const ne=await super.generate(O),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:he}=await R(this.sessions.encodec_decode,{audio_codes:ge});return he}}class Di extends G{}class Oh extends Di{}class Dh extends Di{async _call(P){return new vt(await super._call(P))}}class Lh extends Di{}class Li extends G{}class zh extends Li{}class Bh extends Li{async _call(P){return new vt(await super._call(P))}}class Rh extends Li{}class zi extends G{}class jh extends zi{}class Nh extends zi{async _call(P){return new vt(await super._call(P))}}class Vh extends zi{}class Bi extends G{}class Uh extends Bi{}class Wh extends Bi{async _call(P){return new vt(await super._call(P))}}class Gh extends Bi{}class Kh extends G{}class Hh extends Kh{}class qh extends G{}class Qh extends qh{constructor(...O){super(...O);Y(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(O){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!O.past_key_values){const Xe=this.sessions.prepare_inputs_embeds,mt=(0,a.pick)(O,Xe.inputNames);ge=await R(Xe,mt)}else{const Xe=this.sessions.gen_img_embeds,mt=(0,a.pick)({image_ids:O.input_ids},Xe.inputNames);ge=await R(Xe,mt)}const he={...O,...ge},Ee=await ae(this,he),De=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!De)throw new Error(`Unable to find "${De}" generation head`);const Ne=await R(De,(0,a.pick)(Ee,De.inputNames));return{...ge,...Ee,...Ne}}async generate(O){return this._generation_mode="text",super.generate(O)}async generate_images(O){this._generation_mode="image";const ne=(O.inputs??O[this.main_input_name]).dims[1],he=(await super.generate(O)).slice(null,[ne,null]),Ee=this.sessions.image_decode,{decoded_image:De}=await R(Ee,{generated_tokens:he}),Ne=De.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Xe=[];for(const mt of Ne){const wt=_.RawImage.fromTensor(mt);Xe.push(wt)}return Xe}}class Xh extends be{constructor({char_logits:P,bpe_logits:O,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=O,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Jh extends G{}class Yh extends Jh{async _call(P){return new Xh(await super._call(P))}}class bl extends G{}class Zh extends bl{}class em extends bl{}class Ml extends G{}class tm extends Ml{}class rm extends Ml{}class sm extends G{constructor(){super(...arguments);Y(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class nm extends sm{_merge_input_ids_with_audio_features(P){const O=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,O);return U({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class Ri extends G{constructor(){super(...arguments);Y(this,"main_input_name","input_values");Y(this,"forward_params",["input_values"])}}class om extends be{constructor({audio_codes:P}){super(),this.audio_codes=P}}class im extends be{constructor({audio_values:P}){super(),this.audio_values=P}}class am extends Ri{async encode(P){return new om(await R(this.sessions.encoder_model,P))}async decode(P){return new im(await R(this.sessions.decoder_model,P))}}class lm extends Ri{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"encoder_model"})}}class um extends Ri{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"decoder_model"})}}class ji extends G{constructor(){super(...arguments);Y(this,"main_input_name","input_values");Y(this,"forward_params",["input_values"])}}class cm extends be{constructor({audio_codes:P}){super(),this.audio_codes=P}}class dm extends be{constructor({audio_values:P}){super(),this.audio_values=P}}class pm extends ji{async encode(P){return new cm(await R(this.sessions.encoder_model,P))}async decode(P){return new dm(await R(this.sessions.decoder_model,P))}}class hm extends ji{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"encoder_model"})}}class mm extends ji{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"decoder_model"})}}class Ni extends G{constructor(){super(...arguments);Y(this,"main_input_name","input_values");Y(this,"forward_params",["input_values"])}}class fm extends Ni{async encode(P){return await R(this.sessions.encoder_model,P)}async decode(P){return await R(this.sessions.decoder_model,P)}}class _m extends Ni{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"encoder_model"})}}class gm extends Ni{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"decoder_model"})}}class Dt{static async from_pretrained(P,{progress_callback:O=null,config:ne=null,cache_dir:ge=null,local_files_only:he=!1,revision:Ee="main",model_file_name:De=null,subfolder:Ne="onnx",device:Xe=null,dtype:mt=null,use_external_data_format:wt=null,session_options:dt={}}={}){const Pt={progress_callback:O,config:ne,cache_dir:ge,local_files_only:he,revision:Ee,model_file_name:De,subfolder:Ne,device:Xe,dtype:mt,use_external_data_format:wt,session_options:dt};if(Pt.config=await s.AutoConfig.from_pretrained(P,Pt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const gt=Pt.config.model_type;for(const Et of this.MODEL_CLASS_MAPPINGS){let nt=Et.get(gt);if(!nt){for(const $t of Et.values())if($t[0]===gt){nt=$t;break}if(!nt)continue}return await nt[1].from_pretrained(P,Pt)}if(this.BASE_IF_FAIL)return Um.has(gt)||console.warn(`Unknown model class "${gt}", attempting to construct from base class.`),await G.from_pretrained(P,Pt);throw Error(`Unsupported model type: ${gt}`)}}Y(Dt,"MODEL_CLASS_MAPPINGS",null),Y(Dt,"BASE_IF_FAIL",!1);const rv=new Map([["bert",["BertModel",Pe]],["modernbert",["ModernBertModel",ke]],["nomic_bert",["NomicBertModel",Ge]],["roformer",["RoFormerModel",pt]],["electra",["ElectraModel",me]],["esm",["EsmModel",it]],["convbert",["ConvBertModel",bt]],["camembert",["CamembertModel",lt]],["deberta",["DebertaModel",Or]],["deberta-v2",["DebertaV2Model",Ss]],["mpnet",["MPNetModel",rn]],["albert",["AlbertModel",de]],["distilbert",["DistilBertModel",Is]],["roberta",["RobertaModel",Mr]],["xlm",["XLMModel",dn]],["xlm-roberta",["XLMRobertaModel",oi]],["clap",["ClapModel",Th]],["clip",["CLIPModel",Mi]],["clipseg",["CLIPSegModel",vo]],["chinese_clip",["ChineseCLIPModel",Nn]],["siglip",["SiglipModel",Ks]],["jina_clip",["JinaCLIPModel",bo]],["mobilebert",["MobileBertModel",ns]],["squeezebert",["SqueezeBertModel",Vs]],["wav2vec2",["Wav2Vec2Model",Rp]],["wav2vec2-bert",["Wav2Vec2BertModel",eh]],["unispeech",["UniSpeechModel",Hp]],["unispeech-sat",["UniSpeechSatModel",Xp]],["hubert",["HubertModel",sh]],["wavlm",["WavLMModel",ih]],["audio-spectrogram-transformer",["ASTModel",ci]],["vits",["VitsModel",ml]],["pyannote",["PyAnnoteModel",Up]],["wespeaker-resnet",["WeSpeakerResNetModel",Kp]],["detr",["DetrModel",Cd]],["rt_detr",["RTDetrModel",kd]],["rt_detr_v2",["RTDetrV2Model",Ad]],["rf_detr",["RFDetrModel",Dd]],["d_fine",["DFineModel",Bd]],["table-transformer",["TableTransformerModel",jd]],["vit",["ViTModel",Zc]],["ijepa",["IJepaModel",td]],["pvt",["PvtModel",od]],["vit_msn",["ViTMSNModel",ud]],["vit_mae",["ViTMAEModel",ld]],["groupvit",["GroupViTModel",pd]],["fastvit",["FastViTModel",hd]],["mobilevit",["MobileViTModel",gd]],["mobilevitv2",["MobileViTV2Model",bd]],["owlvit",["OwlViTModel",yd]],["owlv2",["Owlv2Model",xd]],["beit",["BeitModel",Ed]],["deit",["DeiTModel",Ud]],["hiera",["HieraModel",Gd]],["convnext",["ConvNextModel",bp]],["convnextv2",["ConvNextV2Model",yp]],["dinov2",["Dinov2Model",xp]],["dinov2_with_registers",["Dinov2WithRegistersModel",Ep]],["resnet",["ResNetModel",Hd]],["swin",["SwinModel",Qd]],["swin2sr",["Swin2SRModel",Yd]],["donut-swin",["DonutSwinModel",wp]],["yolos",["YolosModel",$p]],["dpt",["DPTModel",ep]],["glpn",["GLPNModel",fp]],["hifigan",["SpeechT5HifiGan",fh]],["efficientnet",["EfficientNetModel",Ah]],["decision_transformer",["DecisionTransformerModel",Hh]],["patchtst",["PatchTSTForPrediction",Zh]],["patchtsmixer",["PatchTSMixerForPrediction",tm]],["mobilenet_v1",["MobileNetV1Model",Oh]],["mobilenet_v2",["MobileNetV2Model",zh]],["mobilenet_v3",["MobileNetV3Model",jh]],["mobilenet_v4",["MobileNetV4Model",Uh]],["maskformer",["MaskFormerModel",hp]],["mgp-str",["MgpstrForSceneTextRecognition",Yh]],["style_text_to_speech_2",["StyleTextToSpeech2Model",ph]]]),sv=new Map([["t5",["T5Model",ce]],["longt5",["LongT5Model",Qe]],["mt5",["MT5Model",_t]],["bart",["BartModel",Jt]],["mbart",["MBartModel",Er]],["marian",["MarianModel",Dp]],["whisper",["WhisperModel",pi]],["m2m_100",["M2M100Model",zp]],["blenderbot",["BlenderbotModel",fr]],["blenderbot-small",["BlenderbotSmallModel",qr]]]),nv=new Map([["mimi",["MimiModel",am]],["dac",["DacModel",pm]],["snac",["SnacModel",fm]]]),ov=new Map([["bloom",["BloomModel",Hc]],["jais",["JAISModel",ct]],["gpt2",["GPT2Model",Eo]],["gptj",["GPTJModel",So]],["gpt_bigcode",["GPTBigCodeModel",ko]],["gpt_neo",["GPTNeoModel",Co]],["gpt_neox",["GPTNeoXModel",fn]],["codegen",["CodeGenModel",gn]],["llama",["LlamaModel",Ao]],["exaone",["ExaoneModel",L]],["olmo",["OlmoModel",et]],["olmo2",["Olmo2Model",Wt]],["mobilellm",["MobileLLMModel",Te]],["granite",["GraniteModel",Pi]],["cohere",["CohereModel",Cc]],["gemma",["GemmaModel",$c]],["gemma2",["Gemma2Model",Ic]],["gemma3_text",["Gemma3Model",Fc]],["helium",["HeliumModel",Oo]],["glm",["GlmModel",h]],["openelm",["OpenELMModel",Dc]],["qwen2",["Qwen2Model",zc]],["qwen3",["Qwen3Model",Rc]],["phi",["PhiModel",Uc]],["phi3",["Phi3Model",Gc]],["mpt",["MptModel",Qc]],["opt",["OPTModel",Jc]],["mistral",["MistralModel",wh]],["starcoder2",["Starcoder2Model",Mh]],["falcon",["FalconModel",vh]],["stablelm",["StableLmModel",kh]]]),yl=new Map([["speecht5",["SpeechT5ForSpeechToText",hh]],["whisper",["WhisperForConditionalGeneration",co]],["lite-whisper",["LiteWhisperForConditionalGeneration",po]],["moonshine",["MoonshineForConditionalGeneration",mi]]]),wm=new Map([["speecht5",["SpeechT5ForTextToSpeech",mh]]]),bm=new Map([["vits",["VitsModel",ml]],["musicgen",["MusicgenForConditionalGeneration",wl]]]),Mm=new Map([["bert",["BertForSequenceClassification",Fe]],["modernbert",["ModernBertForSequenceClassification",Ze]],["roformer",["RoFormerForSequenceClassification",Vt]],["electra",["ElectraForSequenceClassification",ve]],["esm",["EsmForSequenceClassification",rs]],["convbert",["ConvBertForSequenceClassification",D]],["camembert",["CamembertForSequenceClassification",Bt]],["deberta",["DebertaForSequenceClassification",ds]],["deberta-v2",["DebertaV2ForSequenceClassification",ps]],["mpnet",["MPNetForSequenceClassification",nn]],["albert",["AlbertForSequenceClassification",k]],["distilbert",["DistilBertForSequenceClassification",Tr]],["roberta",["RobertaForSequenceClassification",dr]],["xlm",["XLMForSequenceClassification",si]],["xlm-roberta",["XLMRobertaForSequenceClassification",ai]],["bart",["BartForSequenceClassification",mr]],["mbart",["MBartForSequenceClassification",Zt]],["mobilebert",["MobileBertForSequenceClassification",hr]],["squeezebert",["SqueezeBertForSequenceClassification",un]]]),ym=new Map([["bert",["BertForTokenClassification",Be]],["modernbert",["ModernBertForTokenClassification",st]],["roformer",["RoFormerForTokenClassification",zt]],["electra",["ElectraForTokenClassification",yt]],["esm",["EsmForTokenClassification",ss]],["convbert",["ConvBertForTokenClassification",oe]],["camembert",["CamembertForTokenClassification",Ht]],["deberta",["DebertaForTokenClassification",ts]],["deberta-v2",["DebertaV2ForTokenClassification",$s]],["mpnet",["MPNetForTokenClassification",on]],["distilbert",["DistilBertForTokenClassification",hs]],["roberta",["RobertaForTokenClassification",pr]],["xlm",["XLMForTokenClassification",ni]],["xlm-roberta",["XLMRobertaForTokenClassification",li]]]),vl=new Map([["t5",["T5ForConditionalGeneration",xe]],["longt5",["LongT5ForConditionalGeneration",We]],["mt5",["MT5ForConditionalGeneration",Ot]],["bart",["BartForConditionalGeneration",Ut]],["mbart",["MBartForConditionalGeneration",Pr]],["marian",["MarianMTModel",Lp]],["m2m_100",["M2M100ForConditionalGeneration",Bp]],["blenderbot",["BlenderbotForConditionalGeneration",Dr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",kr]]]),xl=new Map([["bloom",["BloomForCausalLM",qc]],["gpt2",["GPT2LMHeadModel",Po]],["jais",["JAISLMHeadModel",Ei]],["gptj",["GPTJForCausalLM",$o]],["gpt_bigcode",["GPTBigCodeForCausalLM",Io]],["gpt_neo",["GPTNeoForCausalLM",mn]],["gpt_neox",["GPTNeoXForCausalLM",Wn]],["codegen",["CodeGenForCausalLM",Hn]],["llama",["LlamaForCausalLM",Fo]],["exaone",["ExaoneForCausalLM",N]],["olmo",["OlmoForCausalLM",Mt]],["olmo2",["Olmo2ForCausalLM",yr]],["mobilellm",["MobileLLMForCausalLM",Le]],["granite",["GraniteForCausalLM",Pc]],["cohere",["CohereForCausalLM",Sc]],["gemma",["GemmaForCausalLM",kc]],["gemma2",["Gemma2ForCausalLM",Ac]],["gemma3_text",["Gemma3ForCausalLM",Oc]],["helium",["HeliumForCausalLM",Do]],["glm",["GlmForCausalLM",T]],["openelm",["OpenELMForCausalLM",Lc]],["qwen2",["Qwen2ForCausalLM",Bc]],["qwen3",["Qwen3ForCausalLM",jc]],["phi",["PhiForCausalLM",Wc]],["phi3",["Phi3ForCausalLM",Kc]],["mpt",["MptForCausalLM",Xc]],["opt",["OPTForCausalLM",Yc]],["mbart",["MBartForCausalLM",fs]],["mistral",["MistralForCausalLM",bh]],["starcoder2",["Starcoder2ForCausalLM",yh]],["falcon",["FalconForCausalLM",xh]],["trocr",["TrOCRForCausalLM",gh]],["stablelm",["StableLmForCausalLM",Ih]],["phi3_v",["Phi3VForCausalLM",go]]]),iv=new Map([["multi_modality",["MultiModalityCausalLM",Qh]]]),vm=new Map([["bert",["BertForMaskedLM",$e]],["modernbert",["ModernBertForMaskedLM",Ve]],["roformer",["RoFormerForMaskedLM",St]],["electra",["ElectraForMaskedLM",Oe]],["esm",["EsmForMaskedLM",Rt]],["convbert",["ConvBertForMaskedLM",Zr]],["camembert",["CamembertForMaskedLM",rt]],["deberta",["DebertaForMaskedLM",es]],["deberta-v2",["DebertaV2ForMaskedLM",Kr]],["mpnet",["MPNetForMaskedLM",sn]],["albert",["AlbertForMaskedLM",X]],["distilbert",["DistilBertForMaskedLM",Ae]],["roberta",["RobertaForMaskedLM",er]],["xlm",["XLMWithLMHeadModel",ri]],["xlm-roberta",["XLMRobertaForMaskedLM",ii]],["mobilebert",["MobileBertForMaskedLM",cr]],["squeezebert",["SqueezeBertForMaskedLM",ln]]]),xm=new Map([["bert",["BertForQuestionAnswering",He]],["roformer",["RoFormerForQuestionAnswering",gr]],["electra",["ElectraForQuestionAnswering",Ft]],["convbert",["ConvBertForQuestionAnswering",B]],["camembert",["CamembertForQuestionAnswering",wr]],["deberta",["DebertaForQuestionAnswering",Cs]],["deberta-v2",["DebertaV2ForQuestionAnswering",ks]],["mpnet",["MPNetForQuestionAnswering",an]],["albert",["AlbertForQuestionAnswering",j]],["distilbert",["DistilBertForQuestionAnswering",zr]],["roberta",["RobertaForQuestionAnswering",Ir]],["xlm",["XLMForQuestionAnswering",ao]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ui]],["mobilebert",["MobileBertForQuestionAnswering",os]],["squeezebert",["SqueezeBertForQuestionAnswering",cn]]]),Tl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ho]],["idefics3",["Idefics3ForConditionalGeneration",hn]],["smolvlm",["SmolVLMForConditionalGeneration",_o]]]),Tm=new Map([["llava",["LlavaForConditionalGeneration",pn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Ws]],["moondream1",["Moondream1ForConditionalGeneration",fi]],["florence2",["Florence2ForConditionalGeneration",_i]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Vc]],["idefics3",["Idefics3ForConditionalGeneration",hn]],["smolvlm",["SmolVLMForConditionalGeneration",_o]],["paligemma",["PaliGemmaForConditionalGeneration",wi]]]),Em=new Map([["ultravox",["UltravoxModel",nm]]]),av=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ho]]]),Pm=new Map([["vit",["ViTForImageClassification",ed]],["ijepa",["IJepaForImageClassification",rd]],["pvt",["PvtForImageClassification",id]],["vit_msn",["ViTMSNForImageClassification",cd]],["fastvit",["FastViTForImageClassification",md]],["mobilevit",["MobileViTForImageClassification",wd]],["mobilevitv2",["MobileViTV2ForImageClassification",Md]],["beit",["BeitForImageClassification",Pd]],["deit",["DeiTForImageClassification",Wd]],["hiera",["HieraForImageClassification",Kd]],["convnext",["ConvNextForImageClassification",Mp]],["convnextv2",["ConvNextV2ForImageClassification",vp]],["dinov2",["Dinov2ForImageClassification",Tp]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Pp]],["resnet",["ResNetForImageClassification",qd]],["swin",["SwinForImageClassification",Xd]],["segformer",["SegformerForImageClassification",Sh]],["efficientnet",["EfficientNetForImageClassification",Fh]],["mobilenet_v1",["MobileNetV1ForImageClassification",Dh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Bh]],["mobilenet_v3",["MobileNetV3ForImageClassification",Nh]],["mobilenet_v4",["MobileNetV4ForImageClassification",Wh]]]),Cm=new Map([["detr",["DetrForObjectDetection",Sd]],["rt_detr",["RTDetrForObjectDetection",Id]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Fd]],["rf_detr",["RFDetrForObjectDetection",Ld]],["d_fine",["DFineForObjectDetection",Rd]],["table-transformer",["TableTransformerForObjectDetection",Nd]],["yolos",["YolosForObjectDetection",kp]]]),Sm=new Map([["owlvit",["OwlViTForObjectDetection",vd]],["owlv2",["Owlv2ForObjectDetection",Td]],["grounding-dino",["GroundingDinoForObjectDetection",Sp]]]),Jn=new Map([["detr",["DetrForSegmentation",Ua]],["clipseg",["CLIPSegForImageSegmentation",xo]]]),$m=new Map([["segformer",["SegformerForSemanticSegmentation",$h]],["sapiens",["SapiensForSemanticSegmentation",np]],["swin",["SwinForSemanticSegmentation",Jd]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Lh]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Rh]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Vh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Gh]]]),km=new Map([["detr",["DetrForSegmentation",Ua]],["maskformer",["MaskFormerForInstanceSegmentation",mp]]]),Im=new Map([["sam",["SamModel",Fp]]]),Am=new Map([["wav2vec2",["Wav2Vec2ForCTC",jp]],["wav2vec2-bert",["Wav2Vec2BertForCTC",th]],["unispeech",["UniSpeechForCTC",qp]],["unispeech-sat",["UniSpeechSatForCTC",Jp]],["wavlm",["WavLMForCTC",ah]],["hubert",["HubertForCTC",nh]]]),Fm=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Np]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",rh]],["unispeech",["UniSpeechForSequenceClassification",Qp]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Yp]],["wavlm",["WavLMForSequenceClassification",lh]],["hubert",["HubertForSequenceClassification",oh]],["audio-spectrogram-transformer",["ASTForAudioClassification",di]]]),Om=new Map([["wavlm",["WavLMForXVector",uh]]]),Dm=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Zp]],["wavlm",["WavLMForAudioFrameClassification",ch]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Vp]],["pyannote",["PyAnnoteForAudioFrameClassification",Wp]]]),Lm=new Map([["vitmatte",["VitMatteForImageMatting",_d]]]),lv=new Map([["patchtst",["PatchTSTForPrediction",em]],["patchtsmixer",["PatchTSMixerForPrediction",rm]]]),zm=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Zd]]]),Bm=new Map([["dpt",["DPTForDepthEstimation",tp]],["depth_anything",["DepthAnythingForDepthEstimation",sp]],["glpn",["GLPNForDepthEstimation",_p]],["sapiens",["SapiensForDepthEstimation",op]],["depth_pro",["DepthProForDepthEstimation",lp]],["metric3d",["Metric3DForDepthEstimation",cp]],["metric3dv2",["Metric3Dv2ForDepthEstimation",pp]]]),Rm=new Map([["sapiens",["SapiensForNormalEstimation",ip]]]),jm=new Map([["vitpose",["VitPoseForPoseEstimation",nd]]]),Nm=new Map([["clip",["CLIPVisionModelWithProjection",vi]],["siglip",["SiglipVisionModel",xi]],["jina_clip",["JinaCLIPVisionModel",yo]]]),Vm=[[rv,E.EncoderOnly],[sv,E.EncoderDecoder],[ov,E.DecoderOnly],[nv,E.AutoEncoder],[Mm,E.EncoderOnly],[ym,E.EncoderOnly],[vl,E.Seq2Seq],[yl,E.Seq2Seq],[xl,E.DecoderOnly],[iv,E.MultiModality],[vm,E.EncoderOnly],[xm,E.EncoderOnly],[Tl,E.Vision2Seq],[Tm,E.ImageTextToText],[Em,E.AudioTextToText],[Pm,E.EncoderOnly],[Jn,E.EncoderOnly],[km,E.EncoderOnly],[$m,E.EncoderOnly],[Lm,E.EncoderOnly],[lv,E.EncoderOnly],[zm,E.EncoderOnly],[Bm,E.EncoderOnly],[Rm,E.EncoderOnly],[jm,E.EncoderOnly],[Cm,E.EncoderOnly],[Sm,E.EncoderOnly],[Im,E.MaskGeneration],[Am,E.EncoderOnly],[Fm,E.EncoderOnly],[wm,E.Seq2Seq],[bm,E.EncoderOnly],[Om,E.EncoderOnly],[Dm,E.EncoderOnly],[Nm,E.EncoderOnly]];for(const[M,P]of Vm)for(const[O,ne]of M.values())x.set(O,P),y.set(ne,O),b.set(O,ne);const uv=[["MusicgenForConditionalGeneration",wl,E.Musicgen],["Phi3VForCausalLM",go,E.Phi3V],["CLIPTextModelWithProjection",yi,E.EncoderOnly],["SiglipTextModel",wo,E.EncoderOnly],["JinaCLIPTextModel",Mo,E.EncoderOnly],["ClapTextModelWithProjection",Eh,E.EncoderOnly],["ClapAudioModelWithProjection",Ph,E.EncoderOnly],["DacEncoderModel",hm,E.EncoderOnly],["DacDecoderModel",mm,E.EncoderOnly],["MimiEncoderModel",lm,E.EncoderOnly],["MimiDecoderModel",um,E.EncoderOnly],["SnacEncoderModel",_m,E.EncoderOnly],["SnacDecoderModel",gm,E.EncoderOnly]];for(const[M,P,O]of uv)x.set(M,O),y.set(P,M),b.set(M,P);const Um=new Map([["modnet",Jn],["birefnet",Jn],["isnet",Jn],["ben",Jn]]);for(const[M,P]of Um.entries())P.set(M,["PreTrainedModel",G]),x.set(M,E.EncoderOnly),y.set(G,M),b.set(M,G);class El extends Dt{}Y(El,"MODEL_CLASS_MAPPINGS",Vm.map(P=>P[0])),Y(El,"BASE_IF_FAIL",!0);class Wm extends Dt{}Y(Wm,"MODEL_CLASS_MAPPINGS",[Mm]);class Gm extends Dt{}Y(Gm,"MODEL_CLASS_MAPPINGS",[ym]);class Km extends Dt{}Y(Km,"MODEL_CLASS_MAPPINGS",[vl]);class Hm extends Dt{}Y(Hm,"MODEL_CLASS_MAPPINGS",[yl]);class qm extends Dt{}Y(qm,"MODEL_CLASS_MAPPINGS",[wm]);class Qm extends Dt{}Y(Qm,"MODEL_CLASS_MAPPINGS",[bm]);class Xm extends Dt{}Y(Xm,"MODEL_CLASS_MAPPINGS",[xl]);class Jm extends Dt{}Y(Jm,"MODEL_CLASS_MAPPINGS",[vm]);class Ym extends Dt{}Y(Ym,"MODEL_CLASS_MAPPINGS",[xm]);class Zm extends Dt{}Y(Zm,"MODEL_CLASS_MAPPINGS",[Tl]);class ef extends Dt{}Y(ef,"MODEL_CLASS_MAPPINGS",[Pm]);class tf extends Dt{}Y(tf,"MODEL_CLASS_MAPPINGS",[Jn]);class rf extends Dt{}Y(rf,"MODEL_CLASS_MAPPINGS",[$m]);class sf extends Dt{}Y(sf,"MODEL_CLASS_MAPPINGS",[km]);class nf extends Dt{}Y(nf,"MODEL_CLASS_MAPPINGS",[Cm]);class of extends Dt{}Y(of,"MODEL_CLASS_MAPPINGS",[Sm]);class af extends Dt{}Y(af,"MODEL_CLASS_MAPPINGS",[Im]);class lf extends Dt{}Y(lf,"MODEL_CLASS_MAPPINGS",[Am]);class uf extends Dt{}Y(uf,"MODEL_CLASS_MAPPINGS",[Fm]);class cf extends Dt{}Y(cf,"MODEL_CLASS_MAPPINGS",[Om]);class df extends Dt{}Y(df,"MODEL_CLASS_MAPPINGS",[Dm]);class pf extends Dt{}Y(pf,"MODEL_CLASS_MAPPINGS",[av]);class hf extends Dt{}Y(hf,"MODEL_CLASS_MAPPINGS",[Lm]);class mf extends Dt{}Y(mf,"MODEL_CLASS_MAPPINGS",[zm]);class ff extends Dt{}Y(ff,"MODEL_CLASS_MAPPINGS",[Bm]);class _f extends Dt{}Y(_f,"MODEL_CLASS_MAPPINGS",[Rm]);class gf extends Dt{}Y(gf,"MODEL_CLASS_MAPPINGS",[jm]);class wf extends Dt{}Y(wf,"MODEL_CLASS_MAPPINGS",[Nm]);class bf extends Dt{}Y(bf,"MODEL_CLASS_MAPPINGS",[Tm]);class Mf extends Dt{}Y(Mf,"MODEL_CLASS_MAPPINGS",[Em]);class cv extends be{constructor({logits:P,past_key_values:O,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:he=null}){super(),this.logits=P,this.past_key_values=O,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=he}}class vt extends be{constructor({logits:P,...O}){super(),this.logits=P;const ne=Object.values(O);ne.length>0&&(this.attentions=ne)}}class yf extends be{constructor({logits:P,embeddings:O}){super(),this.logits=P,this.embeddings=O}}class Cr extends be{constructor({logits:P}){super(),this.logits=P}}class Ar extends be{constructor({logits:P}){super(),this.logits=P}}class Br extends be{constructor({start_logits:P,end_logits:O}){super(),this.start_logits=P,this.end_logits=O}}class bn extends be{constructor({logits:P}){super(),this.logits=P}}class dv extends be{constructor({logits:P,past_key_values:O}){super(),this.logits=P,this.past_key_values=O}}class vf extends be{constructor({alphas:P}){super(),this.alphas=P}}class xf extends be{constructor({waveform:P,spectrogram:O}){super(),this.waveform=P,this.spectrogram=O}}},"./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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.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,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const u=this.std*2,p=l.data;for(let c=0;c{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),c=p.feature_extractor_type,d=n[c];if(!d)throw new Error(`Unknown feature_extractor_type: '${c}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new d(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"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const c=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),d=c.image_processor_type??c.feature_extractor_type;let _=i[d];return _||(d!==void 0&&console.warn(`Image processor type '${d}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),_=n.ImageProcessor),new _(c)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class u{static async from_pretrained(c,d={}){const _=await(0,o.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,d),{image_processor_type:f,feature_extractor_type:v,processor_class:$}=_;if($&&i[$])return i[$].from_pretrained(c,d);if(!f&&!v)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const g={};if(f){const C=a[f];if(!C)throw new Error(`Unknown image_processor_type: '${f}'.`);g.image_processor=new C(_)}if(v){const C=a[v];if(C)g.image_processor=new C(_);else{const E=l[v];if(!E)throw new Error(`Unknown feature_extractor_type: '${v}'.`);g.feature_extractor=new E(_)}}const w={};return new n.Processor(w,g)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.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,o.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,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let c;const d=a.length-l;if(d>0)if(u==="rand_trunc"){const _=Math.floor(Math.random()*(d+1));a=a.subarray(_,_+l),c=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(d<0){let _=new Float64Array(l);if(_.set(a),p==="repeat")for(let f=a.length;f{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var u;const l=(u=this.size)==null?void 0:u.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),[c,d]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(c,d,{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 o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const u=await super._call(l),p=[u.pixel_values.dims[0],64,64],c=(0,o.full)(p,1n);return{...u,pixel_mask:c}}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 i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[c,d,_]=l;let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(_).fill(f));let v=this.image_std;Array.isArray(v)||(v=new Array(_).fill(f));const $=f.map((g,w)=>-g/v[w]);return super.pad_image(a,l,u,{center:!0,constant_values:$,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),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"),o=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 u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>f.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=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"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),c=t("./src/models/speecht5/feature_extraction_speecht5.js"),d=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),f=t("./src/models/whisper/feature_extraction_whisper.js"),v=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:c,task_prompts_with_input:d}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(c??{})),this.task_prompts_with_input=new Map(Object.entries(d??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[c,d]of this.task_prompts_with_input)if(p.includes(c)){u.push(d.replaceAll("{input}",p).replaceAll(c,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const c=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let d;switch(c){case"pure_text":d=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const _=c==="ocr"?"quad_boxes":"bboxes",f=l.matchAll(this.regexes[_]),v=[],$=[];for(const[g,w,...C]of f)v.push(w?w.trim():v.at(-1)??""),$.push(C.map((E,x)=>(Number(E)+.5)/this.size_per_bin*p[x%2]));d={labels:v,[_]:$};break;default:throw new Error(`Task "${u}" (of type "${c}") not yet implemented.`)}return{[u]:d}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=await this.image_processor(l,p),d=u?this.tokenizer(u,p):{};return{...c,...d}}}Y(i,"tokenizer_class",n.AutoTokenizer),Y(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(u,p){const d=u.dims.at(-1)-1,_=u.tolist();_.fill(!1,0,1),_.fill(!1,d);const f=p.tolist();return _.map((v,$)=>v?$:null).filter(v=>v!==null).map(v=>f[v])}class l extends s.Processor{async _call(p,c,d={}){const _=p?await this.image_processor(p,d):{};return{...c?this.tokenizer(c,d):{},..._}}post_process_grounded_object_detection(p,c,{box_threshold:d=.25,text_threshold:_=.25,target_sizes:f=null}={}){const{logits:v,pred_boxes:$}=p,g=v.dims[0];if(f!==null&&f.length!==g)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const w=v.dims.at(1),C=v.sigmoid(),E=C.max(-1).tolist(),x=$.tolist().map(y=>y.map(S=>(0,i.center_to_corners_format)(S))),b=[];for(let y=0;yR.map((Z,H)=>Z*S[(H+1)%2])));const F=E[y],z=[],K=[],q=[];for(let R=0;R{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=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[u,p]=a.dims.slice(-2);const c=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/c),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*c),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!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 c=[],d=[],_=[];const f=[],v=[];for(const y of p){let S=await Promise.all(y.map(K=>this.preprocess(K)));f.push(...S.map(K=>K.original_size)),v.push(...S.map(K=>K.reshaped_input_size)),S.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:F}=this.max_image_size;let z;if(l??this.do_image_splitting){let K=new Array(S.length),q=new Array(S.length);z=await Promise.all(S.map(async(R,Z)=>{const H=this.get_resize_for_vision_encoder(R.pixel_values,F),J=await(0,o.interpolate_4d)(R.pixel_values,{size:[H.height,H.width]}),{frames:Q,num_splits_h:se,num_splits_w:fe}=await this.split_image(J,this.max_image_size);return K[Z]=se,q[Z]=fe,(0,o.cat)(Q,0)})),d.push(K),_.push(q)}else{const K=[F,F];z=await Promise.all(S.map(q=>(0,o.interpolate_4d)(q.pixel_values,{size:K}))),d.push(new Array(S.length).fill(0)),_.push(new Array(S.length).fill(0))}c.push((0,o.cat)(z,0))}const $=c.length,[g,w,C,E]=c[0].dims;let x,b;if($===1)x=c[0].unsqueeze_(0),b=(0,o.full)([$,g,C,E],!0);else{const y=Math.max(...c.map(z=>z.dims.at(0)));b=(0,o.full)([$,y,C,E],!0);const S=b.data,F=y*C*E;for(let z=0;z<$;++z){const K=c[z].dims[0];if(Ku||_>p){f=Math.ceil(d/u),v=Math.ceil(_/p);const $=Math.ceil(d/f),g=Math.ceil(_/v);for(let E=0;E{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(c,d,_,f,v,$){let g="";for(let w=0;w`+v.repeat(c);g+=` +`}return g+=` +${f}${$}`+v.repeat(c)+`${f}`,g}function l(c,d,_,f){return`${d}${f}`+_.repeat(c)+`${d}`}function u(c,d,_,f,v,$){return c===0&&d===0?l(_,f,v,$):a(_,c,d,f,v,$)}class p extends s.Processor{constructor(){super(...arguments);Y(this,"fake_image_token","");Y(this,"image_token","");Y(this,"global_img_token","")}async _call(_,f=null,v={}){v.return_row_col_info??(v.return_row_col_info=!0);let $;f&&($=await this.image_processor(f,v)),Array.isArray(_)||(_=[_]);const g=$.rows??[new Array(_.length).fill(0)],w=$.cols??[new Array(_.length).fill(0)],C=this.config.image_seq_len,E=[],x=[];for(let y=0;y<_.length;++y){const S=_[y],F=g[y],z=w[y];E.push((0,i.count)(S,this.image_token));const K=F.map((Z,H)=>u(Z,z[H],C,this.fake_image_token,this.image_token,this.global_img_token)),q=S.split(this.image_token);if(q.length===0)throw new Error("The image token should be present in the text.");let R=q[0];for(let Z=0;Z{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>c.DPTFeatureExtractor,DPTImageProcessor:()=>c.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>d.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>v.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>g.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>w.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>C.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>x.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>x.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>b.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>b.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>y.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>y.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>S.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>S.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>F.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>F.MobileViTImageProcessor,NougatImageProcessor:()=>z.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>R.Phi3VImageProcessor,PvtImageProcessor:()=>Z.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>J.RTDetrImageProcessor,SamImageProcessor:()=>Q.SamImageProcessor,SegformerFeatureExtractor:()=>se.SegformerFeatureExtractor,SegformerImageProcessor:()=>se.SegformerImageProcessor,SiglipImageProcessor:()=>fe.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>$.VLMImageProcessor,ViTFeatureExtractor:()=>A.ViTFeatureExtractor,ViTImageProcessor:()=>A.ViTImageProcessor,VitMatteImageProcessor:()=>U.VitMatteImageProcessor,VitPoseImageProcessor:()=>ee.VitPoseImageProcessor,YolosFeatureExtractor:()=>_e.YolosFeatureExtractor,YolosImageProcessor:()=>_e.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=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"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),c=t("./src/models/dpt/image_processing_dpt.js"),d=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),f=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),v=t("./src/models/idefics3/image_processing_idefics3.js"),$=t("./src/models/janus/image_processing_janus.js"),g=t("./src/models/jina_clip/image_processing_jina_clip.js"),w=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),C=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),x=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),b=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),y=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),S=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),F=t("./src/models/mobilevit/image_processing_mobilevit.js"),z=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),R=t("./src/models/phi3_v/image_processing_phi3_v.js"),Z=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),J=t("./src/models/rt_detr/image_processing_rt_detr.js"),Q=t("./src/models/sam/image_processing_sam.js"),se=t("./src/models/segformer/image_processing_segformer.js"),fe=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),A=t("./src/models/vit/image_processing_vit.js"),U=t("./src/models/vitmatte/image_processing_vitmatte.js"),ee=t("./src/models/vitpose/image_processing_vitpose.js"),_e=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:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(c,d){super(c,d),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(c,{images:d=null,chat_template:_="default"}={}){d?Array.isArray(d)||(d=[d]):d=await Promise.all(c.filter(z=>z.images).flatMap(z=>z.images).map(z=>l.RawImage.read(z)));const f=this.tokenizer,v=f.apply_chat_template(c,{tokenize:!1,add_generation_prompt:!0,chat_template:_}),$=z=>f.encode(z,{add_special_tokens:!1}),g=v.split(this.image_tag),w=g.length-1;if(d.length!==w)throw new Error(`Number of images provided (${d.length}) does not match number of "${this.image_tag}" image tags (${w})`);const[C,E,x]=f.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let b=$(g[0]),y=new Array(b.length).fill(!1);for(let z=1;z0){const z=await this.image_processor(d);return z.pixel_values.unsqueeze_(0),{...F,...z}}return F}}Y(u,"image_processor_class",o.AutoImageProcessor),Y(u,"tokenizer_class",n.AutoTokenizer),Y(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...c}=i,d=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},_=u==="bicubic"?3:2;super({...c,size:d,resample:_,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:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=l?this.tokenizer(l,p):{},d=u?await this.image_processor(u,p):{};return{...c,...d}}}Y(i,"tokenizer_class",n.AutoTokenizer),Y(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o{}},"./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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=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,c){if(!a.hasOwnProperty(c))throw new Error(`Format ${c} is not supported.`);const[d,_]=a[c],f=this[d].bind(this),[v,$]=p.dims,g=[],w=[],C=p.tolist();for(let x=0;x0?S.reduce((z,K)=>z*K,1):0;w.push(y),g.push(F)}return[f(w),g]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}batch_decode([p,c,d]){const[_,f]=this._decode_helper(p,"char"),[v,$]=this._decode_helper(c,"bpe"),[g,w]=this._decode_helper(d,"wp"),C=[],E=[];for(let x=0;x<_.length;++x){const[b,y]=(0,i.max)([f[x],$[x],w[x]]);C.push([_[x],v[x],g[x]][y]),E.push(b)}return{generated_text:C,scores:E,char_preds:_,bpe_preds:v,wp_preds:g}}static async from_pretrained(...p){const c=await super.from_pretrained(...p),d=await n.AutoTokenizer.from_pretrained("Xenova/gpt2"),_=await n.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return c.components={image_processor:c.image_processor,char_tokenizer:c.tokenizer,bpe_tokenizer:d,wp_tokenizer:_},c}async _call(p,c=null){const d=await this.image_processor(p);return c&&(d.labels=this.tokenizer(c).input_ids),d}}Y(l,"tokenizer_class",n.AutoTokenizer),Y(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}Y(i,"tokenizer_class",n.AutoTokenizer),Y(i,"image_processor_class",o.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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(u,p,c,d,_){return`${d.repeat(c*_)}${p}${u} +`}class l extends s.Processor{async _call(p,c=null,d={}){c||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),c=""),Array.isArray(p)||(p=[p]),Array.isArray(c)||(c=[c]);const _=this.tokenizer.bos_token,f=this.image_processor.config.image_seq_length;let v;c.some(w=>w.includes(i))?v=c.map(w=>{const C=w.replaceAll(i,i.repeat(f)),E=C.lastIndexOf(i),x=E===-1?0:E+i.length;return C.slice(0,x)+_+C.slice(x)+` +`}):(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."),v=c.map(w=>a(w,_,f,i,p.length)));const $=this.tokenizer(v,d);return{...await this.image_processor(p,d),...$}}}Y(l,"tokenizer_class",n.AutoTokenizer),Y(l,"image_processor_class",o.AutoImageProcessor),Y(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"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(d){super({...d,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=d.num_crops}calc_num_image_tokens_from_image_size(d,_){const{num_img_tokens:f}=this.config;return l((l(_/n)*l(d/n)+1)*f+1+(l(_/n)+1)*u(f))}get_resize_output_image_size(d,_){const f=this._num_crops,[v,$]=d.size;let g=v/$,w=1;for(;w*Math.ceil(w/g)<=f;)w+=1;w-=1;const C=Math.floor(w*336),E=Math.floor(C/g);return[C,E]}pad_image(d,_,f,v={}){const[$,g]=_,w=n*a($/n),C=n*a(g/n),E=[1,1,1].map((x,b)=>(x-this.image_mean[b])/this.image_std[b]);return super.pad_image(d,_,{width:C,height:w},{center:!0,constant_values:E,...v})}async _call(d,{num_crops:_=null}={}){if(this._num_crops=_??(_=this.config.num_crops),_<4||u(_)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(d)||(d=[d]);const f=d.length,v=await Promise.all(d.map(y=>this.preprocess(y))),$=v.map(y=>y.original_size),g=v.map(y=>y.reshaped_input_size),w=[];for(const{pixel_values:y}of v){y.unsqueeze_(0);const[S,F]=y.dims.slice(-2),z=await(0,o.interpolate_4d)(y,{size:[n,n],mode:"bicubic"});if(_>0){const K=[],q=u(_),R=l(F/q),Z=l(S/q);for(let J=0;Jy.map(S=>n*a(S/n))),x=new o.Tensor("int64",E.flat(),[f,2]),b=E.map(([y,S])=>this.calc_num_image_tokens_from_image_size(S,y));return{pixel_values:C,original_sizes:$,reshaped_input_sizes:g,image_sizes:x,num_img_tokens:b}}}},"./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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,c=null,{padding:d=!0,truncation:_=!0,num_crops:f=null}={}){Array.isArray(p)||(p=[p]);let v,$;if(c){$=await this.image_processor(c,{num_crops:f});const{num_img_tokens:g}=$,w=p.map((E,x)=>E.split(a).join(i.repeat(g[x])));v=this.tokenizer(w,{padding:d,truncation:_});const C=this.tokenizer.model.convert_tokens_to_ids([i])[0];v.input_ids.map_(E=>E==C?-E:E)}else v=this.tokenizer(p);return{...v,...$}}}Y(l,"image_processor_class",o.AutoImageProcessor),Y(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>d.PaliGemmaProcessor,Phi3VProcessor:()=>c.Phi3VProcessor,PyAnnoteProcessor:()=>_.PyAnnoteProcessor,Qwen2VLProcessor:()=>f.Qwen2VLProcessor,SamProcessor:()=>v.SamProcessor,SmolVLMProcessor:()=>$.SmolVLMProcessor,SpeechT5Processor:()=>g.SpeechT5Processor,UltravoxProcessor:()=>w.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>C.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>x.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=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"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),c=t("./src/models/phi3_v/processing_phi3_v.js"),d=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/pyannote/processing_pyannote.js"),f=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),v=t("./src/models/sam/processing_sam.js"),$=t("./src/models/smolvlm/processing_smolvlm.js"),g=t("./src/models/speecht5/processing_speecht5.js"),w=t("./src/models/ultravox/processing_ultravox.js"),C=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),x=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,c=[];for(const d of l.tolist()){const _=[];let f=-1;for(let v=0;v({id:v,start:$*p,end:g*p,confidence:w/(g-$)})))}return c}}},"./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"),o=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}}Y(n,"feature_extractor_class",o.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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:c}=await super._call(a,...l);let d=u;const{temporal_patch_size:_,merge_size:f,patch_size:v}=this.config;d.dims[0]===1&&(d=(0,o.cat)(Array.from({length:_},()=>d),0));const $=d.dims[0]/_,g=d.dims[1],w=Math.floor(d.dims[2]/v),C=Math.floor(d.dims[3]/v),E=d.view($,_,g,Math.floor(w/f),f,v,Math.floor(C/f),f,v).permute(0,3,6,4,7,2,1,5,8).view($*w*C,g*_*v*v),x=new o.Tensor("int64",[$,w,C],[1,3]);return{pixel_values:E,image_grid_thw:x,original_sizes:p,reshaped_input_sizes:c}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let c,d;if(u&&(c=await this.image_processor(u),d=c.image_grid_thw),d){let f=this.image_processor.config.merge_size**2,v=0;const $=d.tolist();l=l.map(g=>{for(;g.includes("<|image_pad|>");){const w=Number($[v++].reduce((C,E)=>C*E,1n));g=g.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(w/f)))}return g.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...c}}}Y(i,"image_processor_class",o.AutoImageProcessor),Y(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,u,p,c=!1){l=structuredClone(l);let d=(0,o.calculateDimensions)(l);if(d.length===3)c||(d=[1,...d]),l=[l];else if(d.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 _=0;_c!==u.dims[d]))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:u=null,input_labels:p=null,input_boxes:c=null}={}){const d=await super._call(l);if(u&&(d.input_points=this.reshape_input_points(u,d.original_sizes,d.reshaped_input_sizes)),p){if(!d.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");d.input_labels=this.add_input_labels(p,d.input_points)}return c&&(d.input_boxes=this.reshape_input_points(c,d.original_sizes,d.reshaped_input_sizes,!0)),d}async post_process_masks(l,u,p,{mask_threshold:c=0,binarize:d=!0,pad_size:_=null}={}){const f=[];_=_??this.pad_size;const v=[_.height,_.width];for(let $=0;$c&&(x[b]=1);C=new n.Tensor("bool",x,C.dims)}f.push(C)}return f}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:c=512/1500,points_per_crop:d=32,crop_n_points_downscale_factor:_=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"),o=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)}}Y(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){return l=l.map(p=>p*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:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:c=!0,return_attention_mask:d=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let _=await this._extract_fbank_features(l,this.config.max_length);if(c){const[x,b]=_.dims,y=_.data;for(let S=0;S0){const F=new Float32Array(b*(x+S));F.set(y),F.fill(this.config.padding_value,y.length);const z=x+S;_=new o.Tensor(_.type,F,[z,b]),d&&(f=new o.Tensor("int64",new BigInt64Array(z),[1,z]),f.data.fill(1n,0,x))}}const[v,$]=_.dims,g=this.config.stride;if(v%g!==0)throw new Error(`The number of frames (${v}) must be a multiple of the stride (${g}).`);const C=_.view(1,Math.floor(v/g),$*g),E={input_features:C};if(d){const x=C.dims[1],b=new BigInt64Array(x);if(f){const y=f.data;for(let S=1,F=0;S{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,u={}){const[p,c,d]=a;return super.pad_image(i,a,{width:c+(l-c%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...u})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let c={};if(u){const _=u.length,{input_features:f}=await this.feature_extractor(u,{...p,max_length:_}),v=Math.round(_/this.config.encoder_ds_factor+1e-4),$=1+Math.ceil(v/this.config.stack_factor);c.audio_token_len=[$],c.audio_values=f;const g=this.config.audio_placeholder;if(!l.includes(g))throw new Error(`The input text does not contain the image token ${g}.`);l=l.replaceAll(g,g.repeat($))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...c}}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",s.AutoFeatureExtractor),Y(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 u=await Promise.all(a.map(d=>this.preprocess(d))),p=await Promise.all(l.map(d=>this.preprocess(d,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(u.map((d,_)=>(0,o.cat)([d.pixel_values,p[_].pixel_values],0)),0),original_sizes:u.map(d=>d.original_size),reshaped_input_sizes:u.map(d=>d.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const u=i.tolist(),[p,c,d,_]=i.dims,f=[];for(let v=0;v{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((c,d)=>c+d,0)/a.length,p=a.reduce((c,d)=>c+(d-u)**2,0)/a.length;return a.map(c=>(c-u)/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 u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",s.AutoTokenizer),Y(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",s.AutoTokenizer),Y(i,"feature_extractor_class",o.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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.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 u=l.mean(1).data,p=l.data,[c,d,_]=l.dims;for(let f=0;f{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});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"]],o=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 i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[1]),o.has(a))l=a;else{const c=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(c))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,o.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,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,o.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=u.data,c=(0,n.max)(p)[0];for(let d=0;dc?(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,c)):(p=new Float32Array(c),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:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);Y(this,"return_timestamps",null);Y(this,"return_token_timestamps",null);Y(this,"num_frames",null);Y(this,"alignment_heads",null);Y(this,"task",null);Y(this,"language",null);Y(this,"no_timestamps_token_id",null);Y(this,"prompt_ids",null);Y(this,"is_multilingual",null);Y(this,"lang_to_id",null);Y(this,"task_to_id",null);Y(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,c)=>{const d=await(0,s.createInferenceSession)(new Uint8Array(u),p);let _=Promise.resolve();return async f=>{const v=(0,s.isONNXProxy)(),$=Object.fromEntries(Object.entries(f).map(([w,C])=>[w,(v?C.clone():C).ort_tensor])),g=await(_=i?_.then(()=>d.run($)):d.run($));return Array.isArray(c)?c.map(w=>new o.Tensor(g[w])):new o.Tensor(g[c])}};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}}Y(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>q,AutomaticSpeechRecognitionPipeline:()=>Z,BackgroundRemovalPipeline:()=>se,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>A,FeatureExtractionPipeline:()=>z,FillMaskPipeline:()=>C,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>Q,ImageToImagePipeline:()=>ee,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>v,QuestionAnsweringPipeline:()=>w,SummarizationPipeline:()=>x,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>$,TextGenerationPipeline:()=>S,TextToAudioPipeline:()=>U,TokenClassificationPipeline:()=>g,TranslationPipeline:()=>b,ZeroShotAudioClassificationPipeline:()=>R,ZeroShotClassificationPipeline:()=>F,ZeroShotImageClassificationPipeline:()=>fe,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>ze});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),c=t("./src/utils/image.js");async function d(pe){return Array.isArray(pe)||(pe=[pe]),await Promise.all(pe.map(W=>c.RawImage.read(W)))}async function _(pe,W){return Array.isArray(pe)||(pe=[pe]),await Promise.all(pe.map(re=>typeof re=="string"||re instanceof URL?(0,u.read_audio)(re,W):re instanceof Float64Array?new Float32Array(re):re))}function f(pe,W){W&&(pe=pe.map(Se=>Se|0));const[re,G,be,we]=pe;return{xmin:re,ymin:G,xmax:be,ymax:we}}class v extends i.Callable{constructor({task:W,model:re,tokenizer:G=null,processor:be=null}){super(),this.task=W,this.model=re,this.tokenizer=G,this.processor=be}async dispose(){await this.model.dispose()}}class $ extends v{constructor(W){super(W)}async _call(W,{top_k:re=1}={}){const G=this.tokenizer(W,{padding:!0,truncation:!0}),be=await this.model(G),we=this.model.config.problem_type==="multi_label_classification"?$e=>$e.sigmoid():$e=>new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),Se=this.model.config.id2label,Pe=[];for(const $e of be.logits){const Fe=we($e),Be=await(0,p.topk)(Fe,re),He=Be[0].tolist(),ke=Be[1].tolist().map((Ve,Ze)=>({label:Se?Se[Ve]:`LABEL_${Ve}`,score:He[Ze]}));re===1?Pe.push(...ke):Pe.push(ke)}return Array.isArray(W)||re===1?Pe:Pe[0]}}class g extends v{constructor(W){super(W)}async _call(W,{ignore_labels:re=["O"]}={}){const G=Array.isArray(W),be=this.tokenizer(G?W:[W],{padding:!0,truncation:!0}),Se=(await this.model(be)).logits,Pe=this.model.config.id2label,$e=[];for(let Fe=0;FeIe==this.tokenizer.sep_token_id);$e[He].map((Ie,pt)=>Ie==1&&(pt===0||pt>ke&&Fe.findIndex(St=>St==qe[pt])===-1));const Ve=we[He].tolist(),Ze=Se[He].tolist();for(let Ie=1;Iept==qe[Ie])!==-1)&&(Ve[Ie]=-1/0,Ze[Ie]=-1/0);const st=(0,l.softmax)(Ve).map((Ie,pt)=>[Ie,pt]),at=(0,l.softmax)(Ze).map((Ie,pt)=>[Ie,pt]);st[0][0]=0,at[0][0]=0;const Ge=(0,a.product)(st,at).filter(Ie=>Ie[0][1]<=Ie[1][1]).map(Ie=>[Ie[0][1],Ie[1][1],Ie[0][0]*Ie[1][0]]).sort((Ie,pt)=>pt[2]-Ie[2]);for(let Ie=0;IeVe==this.tokenizer.mask_token_id);if(Fe===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Be=be[Pe][Fe],He=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Be.data),Be.dims),re),qe=He[0].tolist(),ke=He[1].tolist();we.push(ke.map((Ve,Ze)=>{const st=$e.slice();return st[Fe]=Ve,{score:qe[Ze],token:Number(Ve),token_str:this.tokenizer.decode([Ve]),sequence:this.tokenizer.decode(st,{skip_special_tokens:!0})}}))}return Array.isArray(W)?we:we[0]}}class E extends v{constructor(re){super(re);Y(this,"_key","generated_text")}async _call(re,G={}){Array.isArray(re)||(re=[re]),this.model.config.prefix&&(re=re.map(Fe=>this.model.config.prefix+Fe));const be=this.model.config.task_specific_params;be&&be[this.task]&&be[this.task].prefix&&(re=re.map(Fe=>be[this.task].prefix+Fe));const we=this.tokenizer,Se={padding:!0,truncation:!0};let Pe;this instanceof b&&"_build_translation_inputs"in we?Pe=we._build_translation_inputs(re,Se,G):Pe=we(re,Se);const $e=await this.model.generate({...Pe,...G});return we.batch_decode($e,{skip_special_tokens:!0}).map(Fe=>({[this._key]:Fe}))}}class x extends E{constructor(re){super(re);Y(this,"_key","summary_text")}}class b extends E{constructor(re){super(re);Y(this,"_key","translation_text")}}function y(pe){return Array.isArray(pe)&&pe.every(W=>"role"in W&&"content"in W)}class S extends v{constructor(W){super(W)}async _call(W,re={}){let G=!1,be=!1,we;if(typeof W=="string")we=W=[W];else if(Array.isArray(W)&&W.every(ke=>typeof ke=="string"))G=!0,we=W;else{if(y(W))W=[W];else if(Array.isArray(W)&&W.every(y))G=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,we=W.map(ke=>this.tokenizer.apply_chat_template(ke,{tokenize:!1,add_generation_prompt:!0}))}const Se=re.add_special_tokens??!1,Pe=be?!1:re.return_full_text??!0;this.tokenizer.padding_side="left";const $e=this.tokenizer(we,{add_special_tokens:Se,padding:!0,truncation:!0}),Fe=await this.model.generate({...$e,...re}),Be=this.tokenizer.batch_decode(Fe,{skip_special_tokens:!0});let He;!Pe&&$e.input_ids.dims.at(-1)>0&&(He=this.tokenizer.batch_decode($e.input_ids,{skip_special_tokens:!0}).map(ke=>ke.length));const qe=Array.from({length:W.length},ke=>[]);for(let ke=0;ke[re.toLowerCase(),G])),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(W,re,{hypothesis_template:G="This example is {}.",multi_label:be=!1}={}){const we=Array.isArray(W);we||(W=[W]),Array.isArray(re)||(re=[re]);const Se=re.map(Fe=>G.replace("{}",Fe)),Pe=be||re.length===1,$e=[];for(const Fe of W){const Be=[];for(const ke of Se){const Ve=this.tokenizer(Fe,{text_pair:ke,padding:!0,truncation:!0}),Ze=await this.model(Ve);Pe?Be.push([Ze.logits.data[this.contradiction_id],Ze.logits.data[this.entailment_id]]):Be.push(Ze.logits.data[this.entailment_id])}const qe=(Pe?Be.map(ke=>(0,l.softmax)(ke)[1]):(0,l.softmax)(Be)).map((ke,Ve)=>[ke,Ve]).sort((ke,Ve)=>Ve[0]-ke[0]);$e.push({sequence:Fe,labels:qe.map(ke=>re[ke[1]]),scores:qe.map(ke=>ke[0])})}return we?$e:$e[0]}}class z extends v{constructor(W){super(W)}async _call(W,{pooling:re="none",normalize:G=!1,quantize:be=!1,precision:we="binary"}={}){const Se=this.tokenizer(W,{padding:!0,truncation:!0}),Pe=await this.model(Se);let $e=Pe.last_hidden_state??Pe.logits??Pe.token_embeddings;if(re!=="none")if(re==="mean")$e=(0,p.mean_pooling)($e,Se.attention_mask);else if(re==="cls")$e=$e.slice(null,0);else throw Error(`Pooling method '${re}' not supported.`);return G&&($e=$e.normalize(2,-1)),be&&($e=(0,p.quantize_embeddings)($e,we)),$e}}class K extends v{constructor(W){super(W)}async _call(W,{pool:re=null}={}){const G=await d(W),{pixel_values:be}=await this.processor(G),we=await this.model({pixel_values:be});let Se;if(re){if(!("pooler_output"in we))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=we.pooler_output}else Se=we.last_hidden_state??we.logits??we.image_embeds;return Se}}class q extends v{constructor(W){super(W)}async _call(W,{top_k:re=5}={}){const G=this.processor.feature_extractor.config.sampling_rate,be=await _(W,G),we=this.model.config.id2label,Se=[];for(const Pe of be){const $e=await this.processor(Pe),Be=(await this.model($e)).logits[0],He=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Be.data),Be.dims),re),qe=He[0].tolist(),Ve=He[1].tolist().map((Ze,st)=>({label:we?we[Ze]:`LABEL_${Ze}`,score:qe[st]}));Se.push(Ve)}return Array.isArray(W)?Se:Se[0]}}class R extends v{constructor(W){super(W)}async _call(W,re,{hypothesis_template:G="This is a sound of {}."}={}){const be=!Array.isArray(W);be&&(W=[W]);const we=re.map(Be=>G.replace("{}",Be)),Se=this.tokenizer(we,{padding:!0,truncation:!0}),Pe=this.processor.feature_extractor.config.sampling_rate,$e=await _(W,Pe),Fe=[];for(const Be of $e){const He=await this.processor(Be),qe=await this.model({...Se,...He}),ke=(0,l.softmax)(qe.logits_per_audio.data);Fe.push([...ke].map((Ve,Ze)=>({score:Ve,label:re[Ze]})))}return be?Fe[0]:Fe}}class Z extends v{constructor(W){super(W)}async _call(W,re={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(W,re);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(W,re);case"moonshine":return this._call_moonshine(W,re);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(W,re){re.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),re.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const G=!Array.isArray(W);G&&(W=[W]);const be=this.processor.feature_extractor.config.sampling_rate,we=await _(W,be),Se=[];for(const Pe of we){const $e=await this.processor(Pe),Be=(await this.model($e)).logits[0],He=[];for(const ke of Be)He.push((0,l.max)(ke.data)[1]);const qe=this.tokenizer.decode(He);Se.push({text:qe})}return G?Se[0]:Se}async _call_whisper(W,re){const G=re.return_timestamps??!1,be=re.chunk_length_s??0,we=re.force_full_sequences??!1;let Se=re.stride_length_s??null;const Pe={...re};G==="word"&&(Pe.return_token_timestamps=!0,Pe.return_timestamps=!1);const $e=!Array.isArray(W);$e&&(W=[W]);const Fe=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Be=this.processor.feature_extractor.config.hop_length,He=this.processor.feature_extractor.config.sampling_rate,qe=await _(W,He),ke=[];for(const Ve of qe){let Ze=[];if(be>0){if(Se===null)Se=be/6;else if(be<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ge=He*be,Ie=He*Se,pt=Ge-2*Ie;let St=0;for(;;){const Vt=St+Ge,zt=Ve.subarray(St,Vt),gr=await this.processor(zt),or=St===0,bt=Vt>=Ve.length;if(Ze.push({stride:[zt.length,or?0:Ie,bt?0:Ie],input_features:gr.input_features,is_last:bt}),bt)break;St+=pt}}else Ze=[{stride:[Ve.length,0,0],input_features:(await this.processor(Ve)).input_features,is_last:!0}];for(const Ge of Ze){Pe.num_frames=Math.floor(Ge.stride[0]/Be);const Ie=await this.model.generate({inputs:Ge.input_features,...Pe});G==="word"?(Ge.tokens=Ie.sequences.tolist()[0],Ge.token_timestamps=Ie.token_timestamps.tolist()[0].map(pt=>(0,l.round)(pt,2))):Ge.tokens=Ie[0].tolist(),Ge.stride=Ge.stride.map(pt=>pt/He)}const[st,at]=this.tokenizer._decode_asr(Ze,{time_precision:Fe,return_timestamps:G,force_full_sequences:we});ke.push({text:st,...at})}return $e?ke[0]:ke}async _call_moonshine(W,re){const G=!Array.isArray(W);G&&(W=[W]);const be=this.processor.feature_extractor.config.sampling_rate,we=await _(W,be),Se=[];for(const Pe of we){const $e=await this.processor(Pe),Fe=Math.floor(Pe.length/be)*6,Be=await this.model.generate({max_new_tokens:Fe,...re,...$e}),He=this.processor.batch_decode(Be,{skip_special_tokens:!0})[0];Se.push({text:He})}return G?Se[0]:Se}}class H extends v{constructor(W){super(W)}async _call(W,re={}){const G=Array.isArray(W),be=await d(W),{pixel_values:we}=await this.processor(be),Se=[];for(const Pe of we){Pe.dims=[1,...Pe.dims];const $e=await this.model.generate({inputs:Pe,...re}),Fe=this.tokenizer.batch_decode($e,{skip_special_tokens:!0}).map(Be=>({generated_text:Be.trim()}));Se.push(Fe)}return G?Se:Se[0]}}class J extends v{constructor(W){super(W)}async _call(W,{top_k:re=5}={}){const G=await d(W),{pixel_values:be}=await this.processor(G),we=await this.model({pixel_values:be}),Se=this.model.config.id2label,Pe=[];for(const $e of we.logits){const Fe=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),re),Be=Fe[0].tolist(),qe=Fe[1].tolist().map((ke,Ve)=>({label:Se?Se[ke]:`LABEL_${ke}`,score:Be[Ve]}));Pe.push(qe)}return Array.isArray(W)?Pe:Pe[0]}}class Q extends v{constructor(W){super(W),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(W,{threshold:re=.5,mask_threshold:G=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:we=null,target_sizes:Se=null,subtask:Pe=null}={}){if(Array.isArray(W)&&W.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Fe=await d(W),Be=Fe.map(Ge=>[Ge.height,Ge.width]),He=await this.processor(Fe),{inputNames:qe,outputNames:ke}=this.model.sessions.model;if(!qe.includes("pixel_values")){if(qe.length!==1)throw Error(`Expected a single input name, but got ${qe.length} inputs: ${qe}.`);const Ge=qe[0];if(Ge in He)throw Error(`Input name ${Ge} already exists in the inputs.`);He[Ge]=He.pixel_values}const Ve=await this.model(He);let Ze=null;if(Pe!==null)Ze=this.subtasks_mapping[Pe];else if(this.processor.image_processor){for(const[Ge,Ie]of Object.entries(this.subtasks_mapping))if(Ie in this.processor.image_processor){Ze=this.processor.image_processor[Ie].bind(this.processor.image_processor),Pe=Ge;break}}const st=this.model.config.id2label,at=[];if(Pe)if(Pe==="panoptic"||Pe==="instance"){const Ge=Ze(Ve,re,G,be,we,Se??Be)[0],Ie=Ge.segmentation;for(const pt of Ge.segments_info){const St=new Uint8ClampedArray(Ie.data.length);for(let zt=0;ztgr<-1e-5||gr>1+1e-5)&&Vt.sigmoid_();const zt=await c.RawImage.fromTensor(Vt.mul_(255).to("uint8")).resize(St[1],St[0]);at.push({label:null,score:null,mask:zt})}}return at}}class se extends Q{constructor(W){super(W)}async _call(W,re={}){if(Array.isArray(W)&&W.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await d(W),we=await super._call(W,re);return be.map((Pe,$e)=>{const Fe=Pe.clone();return Fe.putAlpha(we[$e].mask),Fe})}}class fe extends v{constructor(W){super(W)}async _call(W,re,{hypothesis_template:G="This is a photo of {}"}={}){const be=Array.isArray(W),we=await d(W),Se=re.map(qe=>G.replace("{}",qe)),Pe=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:$e}=await this.processor(we),Fe=await this.model({...Pe,pixel_values:$e}),Be=this.model.config.model_type==="siglip"?qe=>qe.sigmoid().data:qe=>(0,l.softmax)(qe.data),He=[];for(const qe of Fe.logits_per_image){const Ve=[...Be(qe)].map((Ze,st)=>({score:Ze,label:re[st]}));Ve.sort((Ze,st)=>st.score-Ze.score),He.push(Ve)}return be?He:He[0]}}class ae extends v{constructor(W){super(W)}async _call(W,{threshold:re=.9,percentage:G=!1}={}){const be=Array.isArray(W);if(be&&W.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const we=await d(W),Se=G?null:we.map(ke=>[ke.height,ke.width]),{pixel_values:Pe,pixel_mask:$e}=await this.processor(we),Fe=await this.model({pixel_values:Pe,pixel_mask:$e}),Be=this.processor.image_processor.post_process_object_detection(Fe,re,Se),He=this.model.config.id2label,qe=Be.map(ke=>ke.boxes.map((Ve,Ze)=>({score:ke.scores[Ze],label:He[ke.classes[Ze]],box:f(Ve,!G)})));return be?qe:qe[0]}}class V extends v{constructor(W){super(W)}async _call(W,re,{threshold:G=.1,top_k:be=null,percentage:we=!1}={}){const Se=Array.isArray(W),Pe=await d(W),$e=this.tokenizer(re,{padding:!0,truncation:!0}),Fe=await this.processor(Pe),Be=[];for(let He=0;He({score:at.scores[Ie],label:at.labels[Ie],box:f(Ge,!we)}))}else{const at=this.processor.image_processor.post_process_object_detection(Ze,G,ke,!0)[0];st=at.boxes.map((Ge,Ie)=>({score:at.scores[Ie],label:re[at.classes[Ie]],box:f(Ge,!we)}))}st.sort((at,Ge)=>Ge.score-at.score),be!==null&&(st=st.slice(0,be)),Be.push(st)}return Se?Be:Be[0]}}class A extends v{constructor(W){super(W)}async _call(W,re,G={}){const be=(await d(W))[0],{pixel_values:we}=await this.processor(be),Se=`${re}`,Pe=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,$e=await this.model.generate({inputs:we,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Pe,...G}),Be=this.tokenizer.batch_decode($e)[0].match(/(.*?)<\/s_answer>/);let He=null;return Be&&Be.length>=2&&(He=Be[1].trim()),[{answer:He}]}}class U extends v{constructor(re){super(re);Y(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=re.vocoder??null}async _call(re,{speaker_embeddings:G=null}={}){return this.processor?this._call_text_to_spectrogram(re,{speaker_embeddings:G}):this._call_text_to_waveform(re)}async _call_text_to_waveform(re){const G=this.tokenizer(re,{padding:!0,truncation:!0}),{waveform:be}=await this.model(G),we=this.model.config.sampling_rate;return new u.RawAudio(be.data,we)}async _call_text_to_spectrogram(re,{speaker_embeddings:G}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof G=="string"||G instanceof URL)&&(G=new Float32Array(await(await fetch(G)).arrayBuffer())),G instanceof Float32Array)G=new p.Tensor("float32",G,[1,G.length]);else if(!(G instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:be}=this.tokenizer(re,{padding:!0,truncation:!0}),{waveform:we}=await this.model.generate_speech(be,G,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(we.data,Se)}}class ee extends v{constructor(W){super(W)}async _call(W){const re=await d(W),G=await this.processor(re),be=await this.model(G),we=[];for(const Se of be.reconstruction){const Pe=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");we.push(c.RawImage.fromTensor(Pe))}return we.length>1?we:we[0]}}class _e extends v{constructor(W){super(W)}async _call(W){const re=await d(W),G=await this.processor(re),{predicted_depth:be}=await this.model(G),we=[];for(let Se=0;Se1?we:we[0]}}const le=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:$,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:w,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:x,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:b,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:S,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:q,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:R,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Z,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:U,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Q,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:se,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:fe,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:A,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ee,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_e,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:z,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ye=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ze(pe,W=null,{progress_callback:re=null,config:G=null,cache_dir:be=null,local_files_only:we=!1,revision:Se="main",device:Pe=null,dtype:$e=null,subfolder:Fe="onnx",use_external_data_format:Be=null,model_file_name:He=null,session_options:qe={}}={}){pe=ye[pe]??pe;const ke=le[pe.split("_",1)[0]];if(!ke)throw Error(`Unsupported pipeline: ${pe}. Must be one of [${Object.keys(le)}]`);W||(W=ke.default.model,console.log(`No model specified. Using default model: "${W}".`));const Ve={progress_callback:re,config:G,cache_dir:be,local_files_only:we,revision:Se,device:Pe,dtype:$e,subfolder:Fe,use_external_data_format:Be,model_file_name:He,session_options:qe},Ze=new Map([["tokenizer",ke.tokenizer],["model",ke.model],["processor",ke.processor]]),st=await Ue(Ze,W,Ve);st.task=pe,(0,a.dispatchCallback)(re,{status:"ready",task:pe,model:W});const at=ke.pipeline;return new at(st)}async function Ue(pe,W,re){const G=Object.create(null),be=[];for(const[we,Se]of pe.entries()){if(!Se)continue;let Pe;Array.isArray(Se)?Pe=new Promise(async($e,Fe)=>{var He,qe;let Be;for(const ke of Se){if(ke===null){$e(null);return}try{$e(await ke.from_pretrained(W,re));return}catch(Ve){if((He=Ve.message)!=null&&He.includes("Unsupported model type"))Be=Ve;else if((qe=Ve.message)!=null&&qe.includes("Could not locate file"))Be=Ve;else{Fe(Ve);return}}}Fe(Be)}):Pe=Se.from_pretrained(W,re),G[we]=Pe,be.push(Pe)}await Promise.all(be);for(const[we,Se]of Object.entries(G))G[we]=await Se;return G}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ft,AutoTokenizer:()=>Fs,BartTokenizer:()=>Ss,BertTokenizer:()=>yt,BlenderbotSmallTokenizer:()=>an,BlenderbotTokenizer:()=>on,BloomTokenizer:()=>ks,CLIPTokenizer:()=>ms,CamembertTokenizer:()=>es,CodeGenTokenizer:()=>os,CodeLlamaTokenizer:()=>Tr,CohereTokenizer:()=>un,ConvBertTokenizer:()=>wr,DebertaTokenizer:()=>rt,DebertaV2Tokenizer:()=>Bt,DistilBertTokenizer:()=>Or,ElectraTokenizer:()=>ts,EsmTokenizer:()=>it,FalconTokenizer:()=>Ae,GPT2Tokenizer:()=>jr,GPTNeoXTokenizer:()=>Je,GemmaTokenizer:()=>rs,Grok1Tokenizer:()=>ss,HerbertTokenizer:()=>Ht,LlamaTokenizer:()=>Is,M2M100Tokenizer:()=>cr,MBart50Tokenizer:()=>ps,MBartTokenizer:()=>Kr,MPNetTokenizer:()=>zr,MarianTokenizer:()=>sn,MgpstrTokenizer:()=>cn,MobileBertTokenizer:()=>ht,NllbTokenizer:()=>ns,NougatTokenizer:()=>Vs,PreTrainedTokenizer:()=>ve,Qwen2Tokenizer:()=>Rt,RoFormerTokenizer:()=>Xt,RobertaTokenizer:()=>$s,SiglipTokenizer:()=>rn,SpeechT5Tokenizer:()=>As,SqueezeBertTokenizer:()=>lt,T5Tokenizer:()=>Cs,TokenizerModel:()=>K,VitsTokenizer:()=>ln,Wav2Vec2CTCTokenizer:()=>nn,WhisperTokenizer:()=>hr,XLMRobertaTokenizer:()=>hs,XLMTokenizer:()=>ds,is_chinese_char:()=>C});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function c(de,k){const j=await Promise.all([(0,n.getModelJSON)(de,"tokenizer.json",!0,k),(0,n.getModelJSON)(de,"tokenizer_config.json",!0,k)]);return k.legacy!==null&&(j[1].legacy=k.legacy),j}function d(de,k){const j=[];let X=0;for(const ie of de.matchAll(k)){const ce=ie[0];X0&&j.push(ce),X=ie.index+ce.length}return X=19968&&de<=40959||de>=13312&&de<=19903||de>=131072&&de<=173791||de>=173824&&de<=177983||de>=177984&&de<=178207||de>=178208&&de<=183983||de>=63744&&de<=64255||de>=194560&&de<=195103}function E(de,k,j){const X=[];let ie=0;for(;iethis.tokens_to_ids.get(j)??this.unk_token_id)}convert_ids_to_tokens(k){return k.map(j=>this.vocab[j]??this.unk_token)}}class q extends K{constructor(k){super(k),this.tokens_to_ids=f(k.vocab),this.unk_token_id=this.tokens_to_ids.get(k.unk_token),this.unk_token=k.unk_token,this.max_input_chars_per_word=k.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[j,X]of this.tokens_to_ids)this.vocab[X]=j}encode(k){const j=[];for(const X of k){const ie=[...X];if(ie.length>this.max_input_chars_per_word){j.push(this.unk_token);continue}let ce=!1,xe=0;const Re=[];for(;xe0&&(Ye=this.config.continuing_subword_prefix+Ye),this.tokens_to_ids.has(Ye)){We=Ye;break}--Qe}if(We===null){ce=!0;break}Re.push(We),xe=Qe}ce?j.push(this.unk_token):j.push(...Re)}return j}}class R extends K{constructor(k,j){super(k);const X=k.vocab.length;this.vocab=new Array(X),this.scores=new Array(X);for(let ie=0;ie[ie,ce])),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,i.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(k){const j=k.chars,X=1;let ie=0;for(;ie{const de=[...Array.from({length:94},(ie,ce)=>ce+33),...Array.from({length:12},(ie,ce)=>ce+161),...Array.from({length:82},(ie,ce)=>ce+174)],k=de.slice();let j=0;for(let ie=0;ie<256;++ie)de.includes(ie)||(de.push(ie),k.push(256+j),j+=1);const X=k.map(ie=>String.fromCharCode(ie));return Object.fromEntries(de.map((ie,ce)=>[ie,X[ce]]))})(),H=(0,o.reverseDictionary)(Z);class J extends K{constructor(k){super(k),this.tokens_to_ids=f(k.vocab),this.unk_token_id=this.tokens_to_ids.get(k.unk_token),this.unk_token=k.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[X,ie]of this.tokens_to_ids)this.vocab[ie]=X;const j=Array.isArray(k.merges[0]);this.merges=j?k.merges:k.merges.map(X=>X.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((X,ie)=>[JSON.stringify(X),ie])),this.end_of_word_suffix=k.end_of_word_suffix,this.continuing_subword_suffix=k.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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(k){if(k.length===0)return[];const j=this.cache.get(k);if(j!==void 0)return j;const X=Array.from(k);this.end_of_word_suffix&&(X[X.length-1]+=this.end_of_word_suffix);let ie=[];if(X.length>1){const ce=new l.PriorityQueue((Qe,We)=>Qe.score`<0x${Re.toString(16).toUpperCase().padStart(2,"0")}>`);xe.every(Re=>this.tokens_to_ids.has(Re))?j.push(...xe):j.push(this.unk_token)}else j.push(this.unk_token)}return j}}class Q extends K{constructor(k,j){super(k),this.tokens_to_ids=f(j.target_lang?k.vocab[j.target_lang]:k.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[X,ie]of this.tokens_to_ids)this.vocab[ie]=X}encode(k){return k}}class se extends s.Callable{constructor(k){super(),this.config=k}static fromConfig(k){if(k===null)return null;switch(k.type){case"BertNormalizer":return new pe(k);case"Precompiled":return new bt(k);case"Sequence":return new Ue(k);case"Replace":return new fe(k);case"NFC":return new V(k);case"NFD":return new A(k);case"NFKC":return new U(k);case"NFKD":return new ee(k);case"Strip":return new _e(k);case"StripAccents":return new le(k);case"Lowercase":return new ye(k);case"Prepend":return new ze(k);default:throw new Error(`Unknown Normalizer type: ${k.type}`)}}normalize(k){throw Error("normalize should be implemented in subclass.")}_call(k){return this.normalize(k)}}class fe extends se{normalize(k){const j=_(this.config.pattern);return j===null?k:k.replaceAll(j,this.config.content)}}class ae extends se{constructor(){super(...arguments);Y(this,"form")}normalize(j){return j=j.normalize(this.form),j}}class V extends ae{constructor(){super(...arguments);Y(this,"form","NFC")}}class A extends ae{constructor(){super(...arguments);Y(this,"form","NFD")}}class U extends ae{constructor(){super(...arguments);Y(this,"form","NFKC")}}class ee extends ae{constructor(){super(...arguments);Y(this,"form","NFKD")}}class _e extends se{normalize(k){return this.config.strip_left&&this.config.strip_right?k=k.trim():(this.config.strip_left&&(k=k.trimStart()),this.config.strip_right&&(k=k.trimEnd())),k}}class le extends se{normalize(k){return k=g(k),k}}class ye extends se{normalize(k){return k=k.toLowerCase(),k}}class ze extends se{normalize(k){return k=this.config.prepend+k,k}}class Ue extends se{constructor(k){super(k),this.normalizers=k.normalizers.map(j=>se.fromConfig(j))}normalize(k){return this.normalizers.reduce((j,X)=>X.normalize(j),k)}}class pe extends se{_tokenize_chinese_chars(k){const j=[];for(let X=0;Xthis.pre_tokenize_text(X,j)):this.pre_tokenize_text(k,j)).flat()}_call(k,j){return this.pre_tokenize(k,j)}}class re extends W{constructor(k){super(),this.pattern=new RegExp(`[^\\s${b}]+|[${b}]`,"gu")}pre_tokenize_text(k,j){return k.trim().match(this.pattern)||[]}}class G extends W{constructor(k){super(),this.config=k,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=Z,this.text_encoder=new TextEncoder}pre_tokenize_text(k,j){return this.add_prefix_space&&!k.startsWith(" ")&&(k=" "+k),(this.use_regex?k.match(this.pattern)||[]:[k]).map(ie=>Array.from(this.text_encoder.encode(ie),ce=>this.byte_encoder[ce]).join(""))}}class be extends W{constructor(k){super(),this.config=k,this.pattern=_(this.config.pattern,this.config.invert)}pre_tokenize_text(k,j){var X;return this.pattern===null?[]:this.config.invert?k.match(this.pattern)||[]:((X=this.config.behavior)==null?void 0:X.toLowerCase())==="removed"?k.split(this.pattern).filter(ie=>ie):d(k,this.pattern)}}class we extends W{constructor(k){super(),this.config=k,this.pattern=new RegExp(`[^${b}]+|[${b}]+`,"gu")}pre_tokenize_text(k,j){return k.match(this.pattern)||[]}}class Se extends W{constructor(k){super(),this.config=k;const j=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(j,"gu")}pre_tokenize_text(k,j){return k.match(this.pattern)||[]}}class Pe extends s.Callable{constructor(k){super(),this.config=k}static fromConfig(k){if(k===null)return null;switch(k.type){case"TemplateProcessing":return new Be(k);case"ByteLevel":return new He(k);case"RobertaProcessing":return new Fe(k);case"BertProcessing":return new $e(k);case"Sequence":return new qe(k);default:throw new Error(`Unknown PostProcessor type: ${k.type}`)}}post_process(k,...j){throw Error("post_process should be implemented in subclass.")}_call(k,...j){return this.post_process(k,...j)}}class $e extends Pe{constructor(k){super(k),this.cls=k.cls[0],this.sep=k.sep[0]}post_process(k,j=null,{add_special_tokens:X=!0}={}){X&&(k=(0,o.mergeArrays)([this.cls],k,[this.sep]));let ie=new Array(k.length).fill(0);if(j!==null){const ce=X&&this instanceof Fe?[this.sep]:[],xe=X?[this.sep]:[];k=(0,o.mergeArrays)(k,ce,j,xe),ie=(0,o.mergeArrays)(ie,new Array(j.length+ce.length+xe.length).fill(1))}return{tokens:k,token_type_ids:ie}}}class Fe extends $e{}class Be extends Pe{constructor(k){super(k),this.single=k.single,this.pair=k.pair}post_process(k,j=null,{add_special_tokens:X=!0}={}){const ie=j===null?this.single:this.pair;let ce=[],xe=[];for(const Re of ie)"SpecialToken"in Re?X&&(ce.push(Re.SpecialToken.id),xe.push(Re.SpecialToken.type_id)):"Sequence"in Re&&(Re.Sequence.id==="A"?(ce=(0,o.mergeArrays)(ce,k),xe=(0,o.mergeArrays)(xe,new Array(k.length).fill(Re.Sequence.type_id))):Re.Sequence.id==="B"&&(ce=(0,o.mergeArrays)(ce,j),xe=(0,o.mergeArrays)(xe,new Array(j.length).fill(Re.Sequence.type_id))));return{tokens:ce,token_type_ids:xe}}}class He extends Pe{post_process(k,j=null){return j&&(k=(0,o.mergeArrays)(k,j)),{tokens:k}}}class qe extends Pe{constructor(k){super(k),this.processors=k.processors.map(j=>Pe.fromConfig(j))}post_process(k,j=null,X={}){let ie;for(const ce of this.processors)if(ce instanceof He)k=ce.post_process(k).tokens,j&&(j=ce.post_process(j).tokens);else{const xe=ce.post_process(k,j,X);k=xe.tokens,ie=xe.token_type_ids}return{tokens:k,token_type_ids:ie}}}class ke extends s.Callable{constructor(k){super(),this.config=k,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=k.trim_offsets}static fromConfig(k){if(k===null)return null;switch(k.type){case"WordPiece":return new Ge(k);case"Metaspace":return new or(k);case"ByteLevel":return new Ie(k);case"Replace":return new Ve(k);case"ByteFallback":return new Ze(k);case"Fuse":return new st(k);case"Strip":return new at(k);case"Sequence":return new St(k);case"CTC":return new pt(k);case"BPEDecoder":return new Vt(k);default:throw new Error(`Unknown Decoder type: ${k.type}`)}}_call(k){return this.decode(k)}decode(k){return this.decode_chain(k).join("")}decode_chain(k){throw Error("`decode_chain` should be implemented in subclass.")}}class Ve extends ke{decode_chain(k){const j=_(this.config.pattern);return j===null?k:k.map(X=>X.replaceAll(j,this.config.content))}}class Ze extends ke{constructor(k){super(k),this.text_decoder=new TextDecoder}decode_chain(k){const j=[];let X=[];for(const ie of k){let ce=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const xe=parseInt(ie.slice(3,5),16);isNaN(xe)||(ce=xe)}if(ce!==null)X.push(ce);else{if(X.length>0){const xe=this.text_decoder.decode(Uint8Array.from(X));j.push(xe),X=[]}j.push(ie)}}if(X.length>0){const ie=this.text_decoder.decode(Uint8Array.from(X));j.push(ie),X=[]}return j}}class st extends ke{decode_chain(k){return[k.join("")]}}class at extends ke{constructor(k){super(k),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(k){return k.map(j=>{let X=0;for(let ce=0;ce(X!==0&&(j.startsWith(this.config.prefix)?j=j.replace(this.config.prefix,""):j=" "+j),this.cleanup&&(j=$(j)),j))}}class Ie extends ke{constructor(k){super(k),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(k){const j=k.join(""),X=new Uint8Array([...j].map(ce=>this.byte_decoder[ce]));return this.text_decoder.decode(X)}decode_chain(k){const j=[];let X=[];for(const ie of k)this.added_tokens.find(ce=>ce.content===ie)!==void 0?(X.length>0&&(j.push(this.convert_tokens_to_string(X)),X=[]),j.push(ie)):X.push(ie);return X.length>0&&j.push(this.convert_tokens_to_string(X)),j}}class pt extends ke{constructor(k){super(k),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(k){if(k.length===0)return"";const j=[k[0]];for(let ce=1;cece!==this.pad_token).join("");return this.cleanup&&(ie=$(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain(k){return[this.convert_tokens_to_string(k)]}}class St extends ke{constructor(k){super(k),this.decoders=k.decoders.map(j=>ke.fromConfig(j))}decode_chain(k){return this.decoders.reduce((j,X)=>X.decode_chain(j),k)}}class Vt extends ke{constructor(k){super(k),this.suffix=this.config.suffix}decode_chain(k){return k.map((j,X)=>j.replaceAll(this.suffix,X===k.length-1?"":" "))}}class zt extends ke{decode_chain(k){let j="";for(let X=1;XX.normalize("NFKC")).join("~"):k=k.normalize("NFKC"),k}}class Zr extends W{constructor(k){super(),this.tokenizers=k.pretokenizers.map(j=>W.fromConfig(j))}pre_tokenize_text(k,j){return this.tokenizers.reduce((X,ie)=>ie.pre_tokenize(X,j),[k])}}class D extends W{constructor(k){super()}pre_tokenize_text(k,j){return k.match(/\w+|[^\w\s]+/g)||[]}}class oe extends W{constructor(k){super()}pre_tokenize_text(k,j){return x(k)}}class B extends W{constructor(k){super(),this.config=k,this.pattern=_(this.config.pattern),this.content=this.config.content}pre_tokenize_text(k,j){return this.pattern===null?[k]:[k.replaceAll(this.pattern,this.config.content)]}}const te=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function me(de,k,j,X){for(const ie of Object.keys(de)){const ce=k-de[ie].length,xe=j(ie),Re=new Array(ce).fill(xe);de[ie]=X==="right"?(0,o.mergeArrays)(de[ie],Re):(0,o.mergeArrays)(Re,de[ie])}}function Oe(de,k){for(const j of Object.keys(de))de[j].length=k}class ve extends s.Callable{constructor(j,X){super();Y(this,"return_token_type_ids",!1);Y(this,"padding_side","right");this._tokenizer_config=X,this.normalizer=se.fromConfig(j.normalizer),this.pre_tokenizer=W.fromConfig(j.pre_tokenizer),this.model=K.fromConfig(j.model,X),this.post_processor=Pe.fromConfig(j.post_processor),this.decoder=ke.fromConfig(j.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of j.added_tokens){const ce=new z(ie);this.added_tokens.push(ce),this.model.tokens_to_ids.set(ce.content,ce.id),this.model.vocab[ce.id]=ce.content,ce.special&&(this.special_tokens.push(ce.content),this.all_special_ids.push(ce.id))}if(this.additional_special_tokens=X.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_splitter=new l.DictionarySplitter(this.added_tokens.map(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),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=X.model_max_length,this.remove_space=X.remove_space,this.clean_up_tokenization_spaces=X.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=X.do_lowercase_and_remove_accent??!1,X.padding_side&&(this.padding_side=X.padding_side),this.legacy=!1,this.chat_template=X.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:ce,template:xe}of this.chat_template){if(typeof ce!="string"||typeof xe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[ce]=xe}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...j){for(const X of j){const ie=this._tokenizer_config[X];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(j,{progress_callback:X=null,config:ie=null,cache_dir:ce=null,local_files_only:xe=!1,revision:Re="main",legacy:Qe=null}={}){const We=await c(j,{progress_callback:X,config:ie,cache_dir:ce,local_files_only:xe,revision:Re,legacy:Qe});return new this(...We)}_call(j,{text_pair:X=null,add_special_tokens:ie=!0,padding:ce=!1,truncation:xe=null,max_length:Re=null,return_tensor:Qe=!0,return_token_type_ids:We=null}={}){const Ye=Array.isArray(j);let _t;if(Ye){if(j.length===0)throw Error("text array must be non-empty");if(X!==null){if(Array.isArray(X)){if(j.length!==X.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");_t=j.map((At,Jt)=>this._encode_plus(At,{text_pair:X[Jt],add_special_tokens:ie,return_token_type_ids:We}))}else _t=j.map(At=>this._encode_plus(At,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(j==null)throw Error("text may not be null or undefined");if(Array.isArray(X))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");_t=[this._encode_plus(j,{text_pair:X,add_special_tokens:ie,return_token_type_ids:We})]}if(Re===null?Re=this.model_max_length:xe===null&&(ce===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),Re=this.model_max_length):ce===!1&&(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."),xe=!0)),ce===!0&&(Re=Math.min((0,i.max)(_t.map(At=>At.input_ids.length))[0],Re??1/0)),Re=Math.min(Re,this.model_max_length??1/0),ce||xe)for(let At=0;At<_t.length;++At)_t[At].input_ids.length!==Re&&(_t[At].input_ids.length>Re?xe&&Oe(_t[At],Re):ce&&me(_t[At],Re,Jt=>Jt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ot={};if(Qe){if(!(ce&&xe)&&_t.some(Jt=>{var Ut;for(const mr of Object.keys(Jt))if(Jt[mr].length!==((Ut=_t[0][mr])==null?void 0:Ut.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 At=[_t.length,_t[0].input_ids.length];for(const Jt of Object.keys(_t[0]))Ot[Jt]=new a.Tensor("int64",BigInt64Array.from(_t.flatMap(Ut=>Ut[Jt]).map(BigInt)),At)}else{for(const At of Object.keys(_t[0]))Ot[At]=_t.map(Jt=>Jt[At]);if(!Ye)for(const At of Object.keys(Ot))Ot[At]=Ot[At][0]}return Ot}_encode_text(j){if(j===null)return null;const X=this.added_tokens_splitter.split(j);for(let ce=0;ce0&&(X[ce-1]=X[ce-1].trimEnd()),xe.rstrip&&ce{if(ce.length===0)return[];if(this.added_tokens_map.has(ce))return[ce];if(this.remove_space===!0&&(ce=ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ce=w(ce)),this.normalizer!==null&&(ce=this.normalizer(ce)),ce.length===0)return[];const Re=this.pre_tokenizer!==null?this.pre_tokenizer(ce,{section_index:xe}):[ce];return this.model(Re)})}_encode_plus(j,{text_pair:X=null,add_special_tokens:ie=!0,return_token_type_ids:ce=null}={}){const{tokens:xe,token_type_ids:Re}=this._tokenize_helper(j,{pair:X,add_special_tokens:ie}),Qe=this.model.convert_tokens_to_ids(xe),We={input_ids:Qe,attention_mask:new Array(Qe.length).fill(1)};return(ce??this.return_token_type_ids)&&Re&&(We.token_type_ids=Re),We}_tokenize_helper(j,{pair:X=null,add_special_tokens:ie=!1}={}){const ce=this._encode_text(j),xe=this._encode_text(X);return this.post_processor?this.post_processor(ce,xe,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(ce??[],xe??[])}}tokenize(j,{pair:X=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(j,{pair:X,add_special_tokens:ie}).tokens}encode(j,{text_pair:X=null,add_special_tokens:ie=!0,return_token_type_ids:ce=null}={}){return this._encode_plus(j,{text_pair:X,add_special_tokens:ie,return_token_type_ids:ce}).input_ids}batch_decode(j,X={}){return j instanceof a.Tensor&&(j=j.tolist()),j.map(ie=>this.decode(ie,X))}decode(j,X={}){if(j instanceof a.Tensor&&(j=v(j)),!Array.isArray(j)||j.length===0||!(0,o.isIntegralNumber)(j[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(j,X)}decode_single(j,{skip_special_tokens:X=!1,clean_up_tokenization_spaces:ie=null}){let ce=this.model.convert_ids_to_tokens(j);X&&(ce=ce.filter(Re=>!this.special_tokens.includes(Re)));let xe=this.decoder?this.decoder(ce):ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(xe=xe.replaceAll(this.decoder.end_of_word_suffix," "),X&&(xe=xe.trim())),(ie??this.clean_up_tokenization_spaces)&&(xe=$(xe)),xe}get_chat_template({chat_template:j=null,tools:X=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(j!==null&&Object.hasOwn(ie,j))j=ie[j];else if(j===null)if(X!==null&&"tool_use"in ie)j=ie.tool_use;else if("default"in ie)j=ie.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(ie).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:X=null,documents:ie=null,chat_template:ce=null,add_generation_prompt:xe=!1,tokenize:Re=!0,padding:Qe=!1,truncation:We=!1,max_length:Ye=null,return_tensor:_t=!0,return_dict:Ot=!1,tokenizer_kwargs:At={},...Jt}={}){if(ce=this.get_chat_template({chat_template:ce,tools:X}),typeof ce!="string")throw Error(`chat_template must be a string, but got ${typeof ce}`);let Ut=this._compiled_template_cache.get(ce);Ut===void 0&&(Ut=new u.Template(ce),this._compiled_template_cache.set(ce,Ut));const mr=Object.create(null);for(const Er of te){const Pr=this.getToken(Er);Pr&&(mr[Er]=Pr)}const br=Ut.render({messages:j,add_generation_prompt:xe,tools:X,documents:ie,...mr,...Jt});if(Re){const Er=this._call(br,{add_special_tokens:!1,padding:Qe,truncation:We,max_length:Ye,return_tensor:_t,...At});return Ot?Er:Er.input_ids}return br}}class yt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Ft extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class ht extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class lt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class rt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Bt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Ht extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class wr extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Xt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Or extends ve{}class es extends ve{}class ds extends ve{constructor(j,X){super(j,X);Y(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 ts extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Cs extends ve{}class jr extends ve{}class Ss extends ve{}class Kr extends ve{constructor(k,j){super(k,j),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)),this.lang_to_token=X=>X}_build_translation_inputs(k,j,X){return ur(this,k,j,X)}}class ps extends Kr{}class $s extends ve{}class ks extends ve{}const ir="▁";class Is extends ve{constructor(j,X){super(j,X);Y(this,"padding_side","left");this.legacy=X.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gr({replacement:ir,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 X=super._encode_text(ir+j.replaceAll(ir," "));return X.length>1&&X[0]===ir&&this.special_tokens.includes(X[1])&&(X=X.slice(1)),X}}class Tr extends ve{}class hs extends ve{}class zr extends ve{}class Ae extends ve{}class Je extends ve{}class it extends ve{}class Rt extends ve{}class rs extends ve{}class ss extends ve{}function ur(de,k,j,X){if(!("language_codes"in de)||!Array.isArray(de.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in de)||!(de.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in de)||typeof de.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=X.src_lang,ce=X.tgt_lang;if(!de.language_codes.includes(ce))throw new Error(`Target language code "${ce}" is not valid. Must be one of: {${de.language_codes.join(", ")}}`);if(ie!==void 0){if(!de.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${de.language_codes.join(", ")}}`);for(const xe of de.post_processor.config.single)if("SpecialToken"in xe&&de.languageRegex.test(xe.SpecialToken.id)){xe.SpecialToken.id=de.lang_to_token(ie);break}}return X.forced_bos_token_id=de.model.convert_tokens_to_ids([de.lang_to_token(ce)])[0],de._call(k,j)}class ns extends ve{constructor(k,j){super(k,j),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)),this.lang_to_token=X=>X}_build_translation_inputs(k,j,X){return ur(this,k,j,X)}}class cr extends ve{constructor(k,j){super(k,j),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)).map(X=>X.slice(2,-2)),this.lang_to_token=X=>`__${X}__`}_build_translation_inputs(k,j,X){return ur(this,k,j,X)}}class hr extends ve{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(k,{return_timestamps:j=!1,return_language:X=!1,time_precision:ie=null,force_full_sequences:ce=!0}={}){if(ie===null)throw Error("Must specify time_precision");let xe=null;const Re=j==="word";function Qe(){return{language:xe,timestamp:[null,null],text:""}}const We=[];let Ye=Qe(),_t=0;const Ot=this.timestamp_begin,Jt=Ot+1500;let Ut=[],mr=[],br=!1,Er=null;const Pr=new Set(this.all_special_ids);for(const Kt of k){const fr=Kt.tokens,Dr=Re?Kt.token_timestamps:null;let Hr=null,qr=Ot;if("stride"in Kt){const[Mr,er,dr]=Kt.stride;if(_t-=er,Er=Mr-dr,er&&(qr=er/ie+Ot),dr)for(let pr=fr.length-1;pr>=0;--pr){const Ir=Number(fr[pr]);if(Ir>=Ot){if(Hr!==null&&(Ir-Ot)*ie=Ot&&er<=Jt){const dr=(er-Ot)*ie+_t,pr=(0,i.round)(dr,2);if(Hr!==null&&er>=Hr)br=!0;else if(br||Ut.length>0&&er0?(Ut.push(kr),Re&&mr.push(Lr)):Ut.every(Mr=>Mr.length===0)&&(Ye=Qe(),Ut=[],kr=[],mr=[],Lr=[])}if(Ut.length>0){if(ce&&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[Kt,fr]=this.findLongestCommonSequence(Ut,mr),Dr=this.decode(Kt);Ye.text=Dr,Re&&(Ye.words=this.collateWordTimestamps(Kt,fr,xe)),We.push(Ye)}let Zt=Object.create(null);const fs=We.map(Kt=>Kt.text).join("");if(j||X){for(let Kt=0;Kt0;let Re=xe?[]:null,Qe=xe?j[0]:null;for(let We=1;Weer===qr[dr]&&Qe[fs+dr]<=j[We][Dr+dr]).length:kr=fr.filter((er,dr)=>er===qr[dr]).length;const Lr=Zt/1e4,Mr=kr/Zt+Lr;kr>1&&Mr>_t&&(_t=Mr,Ot=[fs,Kt,Dr,Hr])}const[Jt,Ut,mr,br]=Ot,Er=Math.floor((Ut+Jt)/2),Pr=Math.floor((br+mr)/2);ce.push(...X.slice(0,Er)),X=Ye.slice(Pr),ie=X.length,xe&&(Re.push(...Qe.slice(0,Er)),Qe=j[We].slice(Pr))}return ce.push(...X),xe?(Re.push(...Qe),[ce,Re]):[ce,[]]}collateWordTimestamps(k,j,X){const[ie,ce,xe]=this.combineTokensIntoWords(k,X),Re=[];for(let Qe=0;Qe=ie){const Re=((xe-ie)*X).toFixed(2);ce.push(`<|${Re}|>`),ce.push([])}else ce[ce.length-1].push(xe);return ce=ce.map(xe=>typeof xe=="string"?xe:super.decode(xe,j)),ce.join("")}splitTokensOnUnicode(k){const j=this.decode(k,{decode_with_timestamps:!0}),X="�",ie=[],ce=[],xe=[];let Re=[],Qe=[],We=0;for(let Ye=0;Ye=this.model.tokens_to_ids.get("<|endoftext|>"),Jt=Ye.startsWith(" "),Ut=Ye.trim(),mr=Qe.test(Ut);if(At||Jt||mr||ce.length===0)ce.push(Ye),xe.push(_t),Re.push(Ot);else{const br=ce.length-1;ce[br]+=Ye,xe[br].push(..._t),Re[br].push(...Ot)}}return[ce,xe,Re]}mergePunctuations(k,j,X,ie,ce){const xe=structuredClone(k),Re=structuredClone(j),Qe=structuredClone(X);let We=xe.length-2,Ye=xe.length-1;for(;We>=0;)xe[We].startsWith(" ")&&ie.includes(xe[We].trim())?(xe[Ye]=xe[We]+xe[Ye],Re[Ye]=(0,o.mergeArrays)(Re[We],Re[Ye]),Qe[Ye]=(0,o.mergeArrays)(Qe[We],Qe[Ye]),xe[We]="",Re[We]=[],Qe[We]=[]):Ye=We,--We;for(We=0,Ye=1;Ye_t),Re.filter(_t=>_t.length>0),Qe.filter(_t=>_t.length>0)]}}class os extends ve{}class ms extends ve{}class rn extends ve{}class sn extends ve{constructor(k,j){super(k,j),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(X=>this.languageRegex.test(X)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(k){if(k===null)return null;const[j,...X]=k.trim().split(this.languageRegex);if(X.length===0)return super._encode_text(j);if(X.length===2){const[ie,ce]=X;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(ce))}}}class nn extends ve{}class on extends ve{}class an extends ve{}class As extends ve{}class Vs extends ve{}class ln extends ve{constructor(k,j){super(k,j),this.decoder=new zt({})}}class un extends ve{}class cn extends ve{}class Fs{static async from_pretrained(k,{progress_callback:j=null,config:X=null,cache_dir:ie=null,local_files_only:ce=!1,revision:xe="main",legacy:Re=null}={}){var Ot;const[Qe,We]=await c(k,{progress_callback:j,config:X,cache_dir:ie,local_files_only:ce,revision:xe,legacy:Re}),Ye=((Ot=We.tokenizer_class)==null?void 0:Ot.replace(/Fast$/,""))??"PreTrainedTokenizer";let _t=this.TOKENIZER_CLASS_MAPPING[Ye];return _t||(console.warn(`Unknown tokenizer class "${Ye}", attempting to construct from base class.`),_t=ve),new _t(Qe,We)}}Y(Fs,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Cs,DistilBertTokenizer:Or,CamembertTokenizer:es,DebertaTokenizer:rt,DebertaV2Tokenizer:Bt,BertTokenizer:yt,HerbertTokenizer:Ht,ConvBertTokenizer:wr,RoFormerTokenizer:Xt,XLMTokenizer:ds,ElectraTokenizer:ts,MobileBertTokenizer:ht,SqueezeBertTokenizer:lt,AlbertTokenizer:Ft,GPT2Tokenizer:jr,BartTokenizer:Ss,MBartTokenizer:Kr,MBart50Tokenizer:ps,RobertaTokenizer:$s,WhisperTokenizer:hr,CodeGenTokenizer:os,CLIPTokenizer:ms,SiglipTokenizer:rn,MarianTokenizer:sn,BloomTokenizer:ks,NllbTokenizer:ns,M2M100Tokenizer:cr,LlamaTokenizer:Is,CodeLlamaTokenizer:Tr,XLMRobertaTokenizer:hs,MPNetTokenizer:zr,FalconTokenizer:Ae,GPTNeoXTokenizer:Je,EsmTokenizer:it,Wav2Vec2CTCTokenizer:nn,BlenderbotTokenizer:on,BlenderbotSmallTokenizer:an,SpeechT5Tokenizer:As,NougatTokenizer:Vs,VitsTokenizer:ln,Qwen2Tokenizer:Rt,GemmaTokenizer:rs,Grok1Tokenizer:ss,CohereTokenizer:un,MgpstrTokenizer:cn,PreTrainedTokenizer:ve})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>d,hanning:()=>c,mel_filter_bank:()=>C,read_audio:()=>u,spectrogram:()=>S,window_function:()=>F});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(R,Z){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)(R)).arrayBuffer(),J=new AudioContext({sampleRate:Z});typeof Z>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const Q=await J.decodeAudioData(H);let se;if(Q.numberOfChannels===2){const fe=Math.sqrt(2),ae=Q.getChannelData(0),V=Q.getChannelData(1);se=new Float32Array(ae.length);for(let A=0;A2595*Math.log10(1+R/700),kaldi:R=>1127*Math.log(1+R/700),slaney:(R,Z=1e3,H=15,J=27/Math.log(6.4))=>R>=Z?H+Math.log(R/Z)*J:3*R/200};function f(R,Z="htk"){const H=_[Z];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(J=>H(J))}const v={htk:R=>700*(10**(R/2595)-1),kaldi:R=>700*(Math.exp(R/1127)-1),slaney:(R,Z=1e3,H=15,J=Math.log(6.4)/27)=>R>=H?Z*Math.exp(J*(R-H)):200*R/3};function $(R,Z="htk"){const H=v[Z];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(J=>H(J))}function g(R,Z){const H=Float64Array.from({length:Z.length-1},(fe,ae)=>Z[ae+1]-Z[ae]),J=Array.from({length:R.length},()=>new Array(Z.length));for(let fe=0;fenew Array(R.length));for(let fe=0;feR+J*se)}function C(R,Z,H,J,Q,se=null,fe="htk",ae=!1){if(se!==null&&se!=="slaney")throw new Error('norm must be one of null or "slaney"');if(R<2)throw new Error(`Require num_frequency_bins: ${R} >= 2`);if(H>J)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${J}`);const V=f(H,fe),A=f(J,fe),U=w(V,A,Z+2);let ee=$(U,fe),_e;if(ae){const ye=Q/((R-1)*2);_e=f(Float64Array.from({length:R},(ze,Ue)=>Ue*ye),fe),ee=U}else _e=w(0,Math.floor(Q/2),R);const le=g(_e,ee);if(se!==null&&se==="slaney")for(let ye=0;yeQ)throw Error(`frame_length (${H}) may not be larger than fft_length (${Q})`);if(be!==H)throw new Error(`Length of the window (${be}) must equal frame_length (${H})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(se===null&&U!==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(fe){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const st=Math.floor((Q-1)/2)+1;R=E(R,st,st)}let we=Math.floor(1+Math.floor((R.length-H)/J));pe!==null&&wewe?re&&($e=W):$e=Pe=W);const Fe=new o.FFT(Q),Be=new Float64Array(Q),He=new Float64Array(Fe.outputBufferSize),qe=new Float32Array(Se*$e);for(let st=0;st=1;--Ie)Be[Ie]-=A*Be[Ie-1];Be[0]*=1-A}for(let Ie=0;IeMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${Z}.`)}if(H&&(fe=fe.subarray(0,R)),J===null)return fe;if(R>J)throw new Error(`Length of the window (${R}) may not be larger than frame_length (${J})`);return fe}function z(R,Z){let H=44;const J=new ArrayBuffer(H+R.length*4),Q=new DataView(J);K(Q,0,"RIFF"),Q.setUint32(4,36+R.length*4,!0),K(Q,8,"WAVE"),K(Q,12,"fmt "),Q.setUint32(16,16,!0),Q.setUint16(20,3,!0),Q.setUint16(22,1,!0),Q.setUint32(24,Z,!0),Q.setUint32(28,Z*4,!0),Q.setUint16(32,4,!0),Q.setUint16(34,32,!0),K(Q,36,"data"),Q.setUint32(40,R.length*4,!0);for(let se=0;se{let se=await Q.arrayBuffer();a.writeFileSync(J,Buffer.from(se))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Z,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>_,count:()=>g,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>$,mergeArrays:()=>c,pick:()=>v,pop:()=>p,product:()=>d,reverseDictionary:()=>o,saveBlob:()=>f});function s(w,C){w&&w(C)}function o(w){return Object.fromEntries(Object.entries(w).map(([C,E])=>[E,C]))}function n(w){return w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(w){var C,E,x;return((x=(E=(C=w==null?void 0:w.prototype)==null?void 0:C.__proto__)==null?void 0:E.constructor)==null?void 0:x.name)==="TypedArray"}function a(w){return Number.isInteger(w)||typeof w=="bigint"}function l(w){return w==null||w===-1}function u(w){const C=[];let E=w;for(;Array.isArray(E);)C.push(E.length),E=E[0];return C}function p(w,C,E=void 0){const x=w[C];if(x!==void 0)return delete w[C],x;if(E===void 0)throw Error(`Key ${C} does not exist in object.`);return E}function c(...w){return Array.prototype.concat.apply([],w)}function d(...w){return w.reduce((C,E)=>C.flatMap(x=>E.map(b=>[x,b])))}function _(w,C){return Math.abs((w+C)%(2*C)-C)}function f(w,C){const E=URL.createObjectURL(C),x=document.createElement("a");x.href=E,x.download=w,x.click(),x.remove(),URL.revokeObjectURL(E)}function v(w,C){return Object.assign({},...C.map(E=>{if(w[E]!==void 0)return{[E]:w[E]}}))}function $(w){let C=0;for(const E of w)++C;return C}function g(w,C){let E=0;for(const x of w)x===C&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(c=(_,f)=>_>f,d=1/0){this._heap=[],this._comparator=c,this._maxSize=d}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...c){return this.extend(c)}extend(c){for(const d of c)if(this.size0&&this._swap(0,d),this._heap.pop(),this._siftDown(),c}replace(c){const d=this.peek();return this._heap[0]=c,this._siftDown(),d}_parent(c){return(c+1>>>1)-1}_left(c){return(c<<1)+1}_right(c){return c+1<<1}_greater(c,d){return this._comparator(this._heap[c],this._heap[d])}_swap(c,d){const _=this._heap[c];this._heap[c]=this._heap[d],this._heap[d]=_}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(c){for(;c>0&&this._greater(c,this._parent(c));)this._swap(c,this._parent(c)),c=this._parent(c)}_siftDown(){let c=0;for(;this._left(c)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const f=new a(this.bosTokenId,0,0,0,0),v=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(f.clone()),this.nodes.push(v.clone()),this.beginNodes[this.len].push(v),this.endNodes[0].push(f)}insert(c,d,_,f){const v=this.nodes.length,$=new a(f,v,c,d,_);this.beginNodes[c].push($),this.endNodes[c+d].push($),this.nodes.push($)}viterbi(){const c=this.len;let d=0;for(;d<=c;){if(this.beginNodes[d].length==0)return[];for(let g of this.beginNodes[d]){g.prev=null;let w=0,C=null;for(let E of this.endNodes[d]){const x=E.backtraceScore+g.score;(C===null||x>w)&&(C=E.clone(),w=x)}if(C!==null)g.prev=C,g.backtraceScore=w;else return[]}++d}const _=[],v=this.beginNodes[c][0].prev;if(v===null)return[];let $=v.clone();for(;$.prev!==null;)_.push($.clone()),$=$.clone().prev.clone();return _.reverse(),_}piece(c){return this.chars.slice(c.pos,c.pos+c.length).join("")}tokens(){return this.viterbi().map(d=>this.piece(d))}tokenIds(){return this.viterbi().map(d=>d.tokenId)}}class a{constructor(c,d,_,f,v){this.tokenId=c,this.nodeId=d,this.pos=_,this.length=f,this.score=v,this.prev=null,this.backtraceScore=0}clone(){const c=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return c.prev=this.prev,c.backtraceScore=this.backtraceScore,c}}class l{constructor(c){this.trie=this._buildTrie(c)}_buildTrie(c){var _;const d=Object.create(null);for(const f of c){let v=d;for(let $=0;$f&&d.push(c.slice(f,v)),d.push(g),v+=g.length,f=v):++v}return f<_&&d.push(c.slice(f)),d}}class u{constructor(c){this.capacity=c,this.cache=new Map}get(c){if(!this.cache.has(c))return;const d=this.cache.get(c);return this.cache.delete(c),this.cache.set(c,d),d}put(c,d){this.cache.has(c)&&this.cache.delete(c),this.cache.set(c,d),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./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:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){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:()=>_,getModelFile:()=>w,getModelJSON:()=>C});var s=t("?7a2c"),o=t("?a42a"),n=t("./src/env.js"),i=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 u{constructor(y){if(this.filePath=y,this.headers=new Headers,this.exists=s.existsSync(y),this.exists){this.status=200,this.statusText="OK";let S=s.statSync(y);this.headers.set("content-length",S.size.toString()),this.updateContentType();const F=s.createReadStream(y);this.body=new ReadableStream({start(z){F.on("data",K=>z.enqueue(K)),F.on("end",()=>z.close()),F.on("error",K=>z.error(K))},cancel(){F.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const y=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[y]??"application/octet-stream")}clone(){let y=new u(this.filePath);return y.exists=this.exists,y.status=this.status,y.statusText=this.statusText,y.headers=new Headers(this.headers),y}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const y=await s.promises.readFile(this.filePath);return new Blob([y],{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(b,y=null,S=null){let F;try{F=new URL(b)}catch{return!1}return!(y&&!y.includes(F.protocol)||S&&!S.includes(F.hostname))}const c=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function d(b){return!(!c.test(b)||b.includes("..")||b.includes("--")||b.endsWith(".git")||b.endsWith(".ipynb"))}async function _(b){var y;if(n.env.useFS&&!p(b,["http:","https:","blob:"]))return new u(b instanceof URL?b.protocol==="file:"?b.pathname:b.toString():b);if(typeof process<"u"&&((y=process==null?void 0:process.release)==null?void 0:y.name)==="node"){const S=!!(Rs!=null&&Rs.TESTING_REMOTELY),F=n.env.version,z=new Headers;if(z.set("User-Agent",`transformers.js/${F}; is_ci/${S};`),p(b,["http:","https:"],["huggingface.co","hf.co"])){const q=(Rs==null?void 0:Rs.HF_TOKEN)??(Rs==null?void 0:Rs.HF_ACCESS_TOKEN);q&&z.set("Authorization",`Bearer ${q}`)}return fetch(b,{headers:z})}else return fetch(b)}const f={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 v(b,y,S){if(!S)return null;const F=f[b]??`Error (${b}) occurred while trying to load file`;throw Error(`${F}: "${y}".`)}class ${constructor(y){this.path=y}async match(y){let S=o.join(this.path,y),F=new u(S);if(F.exists)return F}async put(y,S,F=void 0){let z=o.join(this.path,y);try{const K=S.headers.get("Content-Length"),q=parseInt(K??"0");let R=0;await s.promises.mkdir(o.dirname(z),{recursive:!0});const Z=s.createWriteStream(z),H=S.body.getReader();for(;;){const{done:J,value:Q}=await H.read();if(J)break;await new Promise((fe,ae)=>{Z.write(Q,V=>{if(V){ae(V);return}fe()})}),R+=Q.length;const se=q?R/q*100:0;F==null||F({progress:se,loaded:R,total:q})}Z.close()}catch(K){try{await s.promises.unlink(z)}catch{}throw K}}}async function g(b,...y){for(let S of y)try{let F=await b.match(S);if(F)return F}catch{continue}}async function w(b,y,S=!0,F={},z=!1){if(!n.env.allowLocalModels){if(F.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,i.dispatchCallback)(F.progress_callback,{status:"initiate",name:b,file:y});let K;if(!K&&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");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(ee){console.warn("An error occurred while opening the browser cache:",ee)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new $(F.cache_dir??n.env.cacheDir)}const q=F.revision??"main",R=x(b,y),Z=d(b),H=Z?x(n.env.localModelPath,R):R,J=x(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",b).replaceAll("{revision}",encodeURIComponent(q)),y);let Q;const se=K instanceof $?q==="main"?R:x(b,q,y):J;let fe=!1,ae;K&&(ae=await g(K,H,se));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(R,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${R}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${R}.`)}else try{ae=await _(H),Q=H}catch(_e){console.warn(`Unable to load from local path "${H}": "${_e}"`)}if(ae===void 0||ae.status===404){if(F.local_files_only||!n.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!Z)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${b}".`);if(ae=await _(J),ae.status!==200)return v(ae.status,J,S);Q=se}fe=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(F.progress_callback,{status:"download",name:b,file:y});let A;if(!(n.apis.IS_NODE_ENV&&z)){let ee;F.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ee=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:b,file:y,progress:100,loaded:ee.length,total:ee.length})):ee=await E(ae,_e=>{(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:b,file:y,..._e})}):ee=new Uint8Array(await ae.arrayBuffer()),A=ee}if(fe&&Q&&await K.match(Q)===void 0&&(A?await K.put(Q,new Response(A,{headers:ae.headers})).catch(ee=>{console.warn(`Unable to add response to browser cache: ${ee}.`)}):await K.put(Q,ae,F.progress_callback)),(0,i.dispatchCallback)(F.progress_callback,{status:"done",name:b,file:y}),A){if(!n.apis.IS_NODE_ENV&&z)throw new Error("Cannot return path in a browser environment.");return A}if(ae instanceof u)return ae.filePath;const U=await(K==null?void 0:K.match(Q));if(U instanceof u)return U.filePath;if(U instanceof Response)return new Uint8Array(await U.arrayBuffer());if(typeof U=="string")return U;throw new Error("Unable to get model file path or buffer.")}async function C(b,y,S=!0,F={}){const z=await w(b,y,S,F,!1);if(z===null)return{};const q=new TextDecoder("utf-8").decode(z);return JSON.parse(q)}async function E(b,y){const S=b.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(S??"0"),z=new Uint8Array(F),K=0;const q=b.body.getReader();async function R(){const{done:Z,value:H}=await q.read();if(Z)return;const J=K+H.length;if(J>F){F=J;const se=new Uint8Array(F);se.set(z),z=se}z.set(H,K),K=J;const Q=K/F*100;return y({progress:Q,loaded:K,total:F}),R()}return await R(),z}function x(...b){return b=b.map((y,S)=>(S&&(y=y.replace(new RegExp("^/"),"")),S!==b.length-1&&(y=y.replace(new RegExp("/$"),"")),y)),b.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>f,load_image:()=>v});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const c=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(c)l=($,g)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas($,g)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async $=>{const w=(await $.metadata()).channels,{data:C,info:E}=await $.rotate().raw().toBuffer({resolveWithObject:!0}),x=new f(new Uint8ClampedArray(C),E.width,E.height,E.channels);return w!==void 0&&w!==E.channels&&x.convert(w),x};else throw new Error("Unable to load image processing library.");const d={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(g,w,C,E){this.data=g,this.width=w,this.height=C,this.channels=E}get size(){return[this.width,this.height]}static async read(g){if(g instanceof f)return g;if(typeof g=="string"||g instanceof URL)return await this.fromURL(g);if(g instanceof Blob)return await this.fromBlob(g);if(typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&g instanceof OffscreenCanvas)return this.fromCanvas(g);throw new Error(`Unsupported input type: ${typeof g}`)}static fromCanvas(g){if(!c)throw new Error("fromCanvas() is only supported in browser environments.");const C=g.getContext("2d").getImageData(0,0,g.width,g.height).data;return new f(C,g.width,g.height,4)}static async fromURL(g){const w=await(0,o.getFile)(g);if(w.status!==200)throw new Error(`Unable to read image from "${g}" (${w.status} ${w.statusText})`);const C=await w.blob();return this.fromBlob(C)}static async fromBlob(g){if(c){const w=await p(g),C=l(w.width,w.height).getContext("2d");return C.drawImage(w,0,0),new this(C.getImageData(0,0,w.width,w.height).data,w.width,w.height,4)}else{const w=a(await g.arrayBuffer());return await p(w)}}static fromTensor(g,w="CHW"){if(g.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${g.dims.length} dimensions.`);if(w==="CHW")g=g.transpose(1,2,0);else if(w!=="HWC")throw new Error(`Unsupported channel format: ${w}`);if(!(g.data instanceof Uint8ClampedArray||g.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${g.type}`);switch(g.dims[2]){case 1:case 2:case 3:case 4:return new f(g.data,g.dims[1],g.dims[0],g.dims[2]);default:throw new Error(`Unsupported number of channels: ${g.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const g=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let w=0,C=0;w=0?S=C:z=-C,E>=0?F=E:K=-E,y.drawImage(b,S,F,g,w,z,K,g,w),new f(y.getImageData(0,0,g,w).data,g,w,4).convert(x)}else{let x=this.toSharp();if(C>=0&&E>=0)x=x.extract({left:Math.floor(C),top:Math.floor(E),width:g,height:w});else if(C<=0&&E<=0){const b=Math.floor(-E),y=Math.floor(-C);x=x.extend({top:b,left:y,right:g-this.width-y,bottom:w-this.height-b})}else{let b=[0,0],y=0;E<0?(b[0]=Math.floor(-E),b[1]=w-this.height-b[0]):y=Math.floor(E);let S=[0,0],F=0;C<0?(S[0]=Math.floor(-C),S[1]=g-this.width-S[0]):F=Math.floor(C),x=x.extend({top:b[0],bottom:b[1],left:S[0],right:S[1]}).extract({left:F,top:y,width:g,height:w})}return await p(x)}}async toBlob(g="image/png",w=1){if(!c)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:g,quality:w})}toTensor(g="CHW"){let w=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(g!=="HWC")if(g==="CHW")w=w.permute(2,0,1);else throw new Error(`Unsupported channel format: ${g}`);return w}toCanvas(){if(!c)throw new Error("toCanvas() is only supported in browser environments.");const g=this.clone().rgba(),w=l(g.width,g.height),C=new u(g.data,g.width,g.height);return w.getContext("2d").putImageData(C,0,0),w}split(){const{data:g,width:w,height:C,channels:E}=this,x=g.constructor,b=g.length/E,y=Array.from({length:E},()=>new x(b));for(let S=0;Snew f(S,w,C,1))}_update(g,w,C,E=null){return this.data=g,this.width=w,this.height=C,E!==null&&(this.channels=E),this}clone(){return new f(this.data.slice(),this.width,this.height,this.channels)}convert(g){if(this.channels===g)return this;switch(g){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(g){if(c){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const w=g.split(".").pop().toLowerCase(),C=_.get(w)??"image/png",E=await this.toBlob(C);(0,s.saveBlob)(g,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(g);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(c)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 v=f.read.bind(f)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>v,bankers_round:()=>w,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>C,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>c,medianFilter:()=>$,min:()=>p,permute_data:()=>o,round:()=>g,softmax:()=>n});function s(E,[x,b,y],[S,F],z="bilinear",K=!1){const q=F/y,R=S/b,Z=new E.constructor(S*F*x),H=b*y,J=S*F;for(let Q=0;Q=0;--K)S[K]=q,y[K]=x[b[K]],q*=y[K];const F=b.map((K,q)=>S[b.indexOf(q)]),z=new E.constructor(E.length);for(let K=0;K=0;--R)q+=Z%x[R]*F[R],Z=Math.floor(Z/x[R]);z[q]=E[K]}return[z,y]}function n(E){const x=c(E)[0],b=E.map(F=>Math.exp(F-x)),y=b.reduce((F,z)=>F+z,0);return b.map(F=>F/y)}function i(E){const x=c(E)[0];let b=0;for(let F=0;FF-x-y)}function a(E,x){let b=0;for(let y=0;yx+b*b,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let x=E[0],b=0;for(let y=1;yx&&(x=E[y],b=y);return[x,b]}function d(E){return E>0&&(E&E-1)===0}class _{constructor(x){if(this.size=x|0,this.size<=1||!d(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=x<<1,this.table=new Float64Array(this.size*2);for(let y=0;yy;y<<=1)++b;this._width=b%2===0?b-1:b,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=x[S];return y}toComplexArray(x,b){const y=b||this.createComplexArray();for(let S=0;S>>1],y[S+1]=0;return y}transform(x,b){if(x===b)throw new Error("Input and output buffers must be different");this._transform4(x,b,1)}realTransform(x,b){if(x===b)throw new Error("Input and output buffers must be different");this._realTransform4(x,b,1)}inverseTransform(x,b){if(x===b)throw new Error("Input and output buffers must be different");this._transform4(x,b,-1);for(let y=0;y>=2;z>=2;z>>=2){K=S/z<<1;const J=K>>>2;for(q=0;q>>1,z>>>1)}else for(q=0,R=0;q>>1,z>>>1,y)}const H=this.table;for(z>>=2;z>=2;z>>=2){K=S/z<<1;const Q=K>>>1,se=Q>>>1,fe=se>>>1;for(q=0;q>>1;for(let Q=2;Q>1;++Z){const H=(Z+1-x)**2/2,J=Math.sqrt(q**2+R**2)**H,Q=H*Math.atan2(R,q),se=2*Z;F[se]=J*Math.cos(Q),F[se+1]=J*Math.sin(Q),z[se]=F[se],z[se+1]=-F[se+1]}this._slicedChirpBuffer=F.subarray(b,y),this._f=new _(S>>1),this._f.transform(this._chirpBuffer,z)}_transform(x,b,y){const S=this._buffer1,F=this._buffer2,z=this._outBuffer1,K=this._outBuffer2,q=this._chirpBuffer,R=this._slicedChirpBuffer,Z=this._a;if(y)for(let H=0;H>1,se=b[Q];S[H]=se*R[H],S[J]=se*R[J]}else for(let H=0;H=E.length&&(q=2*(E.length-1)-q),y[z++]=E[q]}y.sort(),b[F]=y[S]}return b}function g(E,x){const b=Math.pow(10,x);return Math.round(E*b)/b}function w(E){const x=Math.round(E);return Math.abs(E)%1===.5?x%2===0?x:x-1:x}function C(E){const x=E.length,b=E[0].length,y=[x+1,b+1],S=Array.from({length:y[0]},()=>Array(y[1]).fill(1/0));S[0][0]=0;const F=Array.from({length:y[0]},()=>Array(y[1]).fill(-1));for(let Z=1;Z0||K>0;)switch(q.push(z-1),R.push(K-1),F[z][K]){case 0:--z,--K;break;case 1:--z;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${z}, ${K}]. Please file a bug report.`)}return q.reverse(),R.reverse(),[q,R]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>b,full:()=>R,full_like:()=>Z,interpolate:()=>p,interpolate_4d:()=>c,layer_norm:()=>w,matmul:()=>d,mean:()=>z,mean_pooling:()=>g,ones:()=>H,ones_like:()=>J,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>fe,rfft:()=>_,slice:()=>$,stack:()=>y,std_mean:()=>F,topk:()=>f,zeros:()=>Q,zeros_like:()=>se});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=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(...A){Y(this,"ort_tensor");return(0,o.isONNXTensor)(A[0])?this.ort_tensor=A[0]:this.ort_tensor=new o.Tensor(A[0],A[1],A[2]),new Proxy(this,{get:(U,ee)=>{if(typeof ee=="string"){let _e=Number(ee);if(Number.isInteger(_e))return U._getitem(_e)}return U[ee]},set:(U,ee,_e)=>U[ee]=_e})}get dims(){return this.ort_tensor.dims}set dims(A){this.ort_tensor.dims=A}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[A,...U]=this.dims;if(U.length>0){const ee=U.reduce((_e,le)=>_e*le);for(let _e=0;_e0){const _e=ee.reduce((le,ye)=>le*ye);return this._subarray(A,_e,ee)}else return new a(this.type,[this.data[A]],ee)}indexOf(A){const U=this.data;for(let ee=0;eeG)throw new Error(`Invalid slice: ${W}`);const be=[Math.max(re,0),Math.min(G,this.dims[pe])];ee.push(be),U.push(be[1]-be[0])}else throw new Error(`Invalid slice: ${W}`)}const _e=ee.map(([pe,W])=>W-pe),le=_e.reduce((pe,W)=>pe*W),ye=this.data,ze=new ye.constructor(le),Ue=this.stride();for(let pe=0;pe=0;--re){const be=_e[re];W+=(G%be+ee[re][0])*Ue[re],G=Math.floor(G/be)}ze[pe]=ye[W]}return new a(this.type,ze,U)}permute(...A){return u(this,A)}transpose(...A){return this.permute(...A)}sum(A=null,U=!1){return this.norm(1,A,U)}norm(A="fro",U=null,ee=!1){if(A==="fro")A=2;else if(typeof A=="string")throw Error(`Unsupported norm: ${A}`);const _e=this.data,le=(pe,W)=>pe+W**A;if(U===null){const pe=_e.reduce(le,0)**(1/A);return new a(this.type,[pe],[])}const[ye,ze,Ue]=S(le,this,U,ee);if(A!==1)for(let pe=0;pe=0;--Ue){const re=this.dims[Ue];if(Ue!==U){const G=pe%re;ze+=G*W,W*=this.dims[Ue]}pe=Math.floor(pe/re)}_e[ye]/=le[ze]}return this}normalize(A=2,U=1){return this.clone().normalize_(A,U)}stride(){return K(this.dims)}squeeze(A=null){return new a(this.type,this.data,C(this.dims,A))}squeeze_(A=null){return this.dims=C(this.dims,A),this}unsqueeze(A=null){return new a(this.type,this.data,E(this.dims,A))}unsqueeze_(A=null){return this.dims=E(this.dims,A),this}flatten_(A=0,U=-1){U=(U+this.dims.length)%this.dims.length;let ee=this.dims.slice(0,A),_e=this.dims.slice(A,U+1),le=this.dims.slice(U+1);return this.dims=[...ee,_e.reduce((ye,ze)=>ye*ze,1),...le],this}flatten(A=0,U=-1){return this.clone().flatten_(A,U)}view(...A){let U=-1;for(let _e=0;_eze!==U?le*ye:le,1);A[U]=ee.length/_e}return new a(this.type,ee,A)}neg_(){const A=this.data;for(let U=0;UA?1:0;return new a("bool",U,this.dims)}lt(A){const U=new Uint8Array(this.data.length),ee=this.data;for(let _e=0;_eMath.min(ye,ze),this,A,U,1/0);return new a(ee,_e,le)}max(A=null,U=!1){if(A===null){const ye=(0,s.max)(this.data)[0];return new a(this.type,[ye],[])}const[ee,_e,le]=S((ye,ze)=>Math.max(ye,ze),this,A,U,-1/0);return new a(ee,_e,le)}argmin(A=null,U=!1){if(A!==null)throw new Error("`dim !== null` not yet implemented.");const ee=(0,s.min)(this.data)[1];return new a("int64",[BigInt(ee)],[])}argmax(A=null,U=!1){if(A!==null)throw new Error("`dim !== null` not yet implemented.");const ee=(0,s.max)(this.data)[1];return new a("int64",[BigInt(ee)],[])}to(A){if(this.type===A)return this;if(!i.hasOwnProperty(A))throw new Error(`Unsupported type: ${A}`);let U;const ee=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(A);return ee&&!_e?U=Number:!ee&&_e&&(U=BigInt),new a(A,i[A].from(this.data,U),this.dims)}}function l(V,A){const U=V.length,ee=A.reduce((le,ye)=>le*ye);if(U!==ee)throw Error(`cannot reshape array of size ${U} into shape (${A})`);let _e=V;for(let le=A.length-1;le>=0;le--)_e=_e.reduce((ye,ze)=>{let Ue=ye[ye.length-1];return Ue.lengthnew a("int64",V,[V.length]);async function $(V,A,U,ee,_e){return await(await n.TensorOpRegistry.slice)({x:V,s:v(A),e:v(U),a:v(ee),t:v(_e??new Array(ee.length).fill(1))})}function g(V,A){const U=V.data,ee=A.data,_e=[V.dims[0],V.dims[2]],le=new U.constructor(_e[0]*_e[1]),[ye,ze,Ue]=V.dims;let pe=0;for(let W=0;WU!==1):typeof A=="number"?V[A]===1&&V.splice(A,1):Array.isArray(A)&&(V=V.filter((U,ee)=>U!==1||!A.includes(ee))),V}function E(V,A){return A=x(A,V.length+1),V=V.slice(),V.splice(A,0,1),V}function x(V,A,U=null,ee=!0){if(V<-A||V>=A){if(ee)throw new Error(`IndexError: index ${V} is out of bounds for dimension${U===null?"":" "+U} with size ${A}`);return V<-A?0:A}return V<0&&(V=(V%A+A)%A),V}function b(V,A=0){A=x(A,V[0].dims.length);const U=V[0].dims.slice();U[A]=V.reduce((ye,ze)=>ye+ze.dims[A],0);const ee=U.reduce((ye,ze)=>ye*ze,1),_e=new V[0].data.constructor(ee),le=V[0].type;if(A===0){let ye=0;for(const ze of V){const Ue=ze.data;_e.set(Ue,ye),ye+=Ue.length}}else{let ye=0;for(let ze=0;ze=0;--G){const Se=pe[G];let Pe=be%Se;G===A&&(Pe+=ye),re+=Pe*we,we*=U[G],be=Math.floor(be/Se)}_e[re]=Ue[W]}ye+=pe[A]}}return new a(le,_e,U)}function y(V,A=0){return b(V.map(U=>U.unsqueeze(A)),A)}function S(V,A,U=null,ee=!1,_e=null){const le=A.data,ye=A.dims;U=x(U,ye.length);const ze=ye.slice();ze[U]=1;const Ue=new le.constructor(le.length/ye[U]);_e!==null&&Ue.fill(_e);for(let pe=0;pe=0;--re){const we=ye[re];if(re!==U){const Se=G%we;W+=Se*be,be*=ze[re]}G=Math.floor(G/we)}Ue[W]=V(Ue[W],le[pe],pe,W)}return ee||ze.splice(U,1),[A.type,Ue,ze]}function F(V,A=null,U=1,ee=!1){const _e=V.data,le=V.dims;if(A===null){const be=_e.reduce(($e,Fe)=>$e+Fe,0)/_e.length,we=Math.sqrt(_e.reduce(($e,Fe)=>$e+(Fe-be)**2,0)/(_e.length-U)),Se=new a(V.type,[be],[]);return[new a(V.type,[we],[]),Se]}A=x(A,le.length);const ye=z(V,A,ee),ze=ye.data,[Ue,pe,W]=S((G,be,we,Se)=>G+(be-ze[Se])**2,V,A,ee);for(let G=0;Gpe+W,0);return new a(V.type,[Ue/_e.length],[])}A=x(A,ee.length);const[le,ye,ze]=S((Ue,pe)=>Ue+pe,V,A,U);if(ee[A]!==1)for(let Ue=0;Ue=0;--U)A[U]=ee,ee*=V[U];return A}function q(V,A,U,ee){const _e=V.reduce((le,ye)=>le*ye,1);return new a(U,new ee(_e).fill(A),V)}function R(V,A){let U,ee;if(typeof A=="number")U="float32",ee=Float32Array;else if(typeof A=="bigint")U="int64",ee=BigInt64Array;else if(typeof A=="boolean")U="bool",ee=Uint8Array;else throw new Error(`Unsupported data type: ${typeof A}`);return q(V,A,U,ee)}function Z(V,A){return R(V.dims,A)}function H(V){return q(V,1n,"int64",BigInt64Array)}function J(V){return H(V.dims)}function Q(V){return q(V,0n,"int64",BigInt64Array)}function se(V){return Q(V.dims)}function fe(V){const A=V.reduce((U,ee)=>U*ee,1);return new a("float32",Float32Array.from({length:A},()=>Math.random()),V)}function ae(V,A){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(A))throw new Error("The precision must be either 'binary' or 'ubinary'");const U=A==="binary",ee=U?"int8":"uint8",_e=U?Int8Array:Uint8Array,le=V.data,ye=new _e(le.length/8);for(let ze=0;ze0?1:0,pe=Math.floor(ze/8),W=ze%8;ye[pe]|=Ue<<7-W,U&&W===0&&(ye[pe]-=128)}return new a(ee,ye,[V.dims[0],V.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((c,d)=>new n(c,(d+1)/(u.length+1)*p))),this.frames=u,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:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const c=[],d=document.createElement("video");if(d.crossOrigin="anonymous",d.muted=!0,typeof l=="string")d.src=l;else if(l instanceof Blob)d.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)d.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(C=>d.onloadedmetadata=C),d.seekable.start(0)===d.seekable.end(0)){const E=await(await fetch(d.src)).blob();d.src=URL.createObjectURL(E),await new Promise(x=>d.onloadedmetadata=x)}const _=d.duration;let f,v;u!=null?(f=u,v=u===1?0:_/(u-1)):(v=1/p,f=Math.floor(_/v));let $=[];for(let C=0;C{d.onseeked=y}),w.drawImage(d,0,0,g.width,g.height);const E=w.getImageData(0,0,g.width,g.height),x=new s.RawImage(E.data,g.width,g.height,4),b=new n(x,C);c.push(b)}return d.remove(),new i(c,_)}}},ub={};function jt(e){var r=ub[e];if(r!==void 0)return r.exports;var t=ub[e]={exports:{}};return cT[e](t,t.exports,jt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;jt.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 o=Object.create(null);jt.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,jt.d(o,n),o}})();jt.d=(e,r)=>{for(var t in r)jt.o(r,t)&&!jt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};jt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);jt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/jt.r(m),jt.d(m,{ASTFeatureExtractor:()=>c.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:()=>o.AutoConfig,AutoFeatureExtractor:()=>d.AutoFeatureExtractor,AutoImageProcessor:()=>v.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:()=>w.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:()=>C.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:()=>c.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>x.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,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,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:()=>c.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:()=>c.EncodecFeatureExtractor,EosTokenCriteria:()=>E.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:()=>u.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:()=>g.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>x.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>x.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:()=>g.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:()=>g.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>c.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>_.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>g.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:()=>x.LogitsProcessor,LogitsProcessorList:()=>x.LogitsProcessorList,LogitsWarper:()=>x.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:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>g.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>x.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>x.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:()=>c.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>g.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:()=>x.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>x.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:()=>g.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>f.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>g.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:()=>g.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>$.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>f.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>c.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>g.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:()=>g.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>f.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>x.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:()=>g.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>c.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:()=>g.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>c.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>g.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:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>x.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:()=>x.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>C.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>x.TopKLogitsWarper,TopPLogitsWarper:()=>x.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>g.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:()=>g.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:()=>c.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>g.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>g.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>c.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>c.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>g.WhisperProcessor,WhisperTextStreamer:()=>C.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>x.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:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.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=jt("./src/env.js"),r=jt("./src/pipelines.js"),t=jt("./src/models.js"),s=jt("./src/tokenizers.js"),o=jt("./src/configs.js"),n=jt("./src/utils/audio.js"),i=jt("./src/utils/image.js"),a=jt("./src/utils/video.js"),l=jt("./src/utils/tensor.js"),u=jt("./src/utils/maths.js"),p=jt("./src/base/feature_extraction_utils.js"),c=jt("./src/models/feature_extractors.js"),d=jt("./src/models/auto/feature_extraction_auto.js"),_=jt("./src/base/image_processors_utils.js"),f=jt("./src/models/image_processors.js"),v=jt("./src/models/auto/image_processing_auto.js"),$=jt("./src/base/processing_utils.js"),g=jt("./src/models/processors.js"),w=jt("./src/models/auto/processing_auto.js"),C=jt("./src/generation/streamers.js"),E=jt("./src/generation/stopping_criteria.js"),x=jt("./src/generation/logits_process.js")})();m.ASTFeatureExtractor;m.ASTForAudioClassification;m.ASTModel;m.ASTPreTrainedModel;m.AlbertForMaskedLM;m.AlbertForQuestionAnswering;m.AlbertForSequenceClassification;m.AlbertModel;m.AlbertPreTrainedModel;m.AlbertTokenizer;m.AudioClassificationPipeline;m.AutoConfig;m.AutoFeatureExtractor;m.AutoImageProcessor;var dT=m.AutoModel;m.AutoModelForAudioClassification;m.AutoModelForAudioFrameClassification;m.AutoModelForAudioTextToText;m.AutoModelForCTC;m.AutoModelForCausalLM;m.AutoModelForDepthEstimation;m.AutoModelForDocumentQuestionAnswering;m.AutoModelForImageClassification;m.AutoModelForImageFeatureExtraction;m.AutoModelForImageMatting;m.AutoModelForImageSegmentation;m.AutoModelForImageTextToText;m.AutoModelForImageToImage;m.AutoModelForMaskGeneration;m.AutoModelForMaskedLM;m.AutoModelForNormalEstimation;m.AutoModelForObjectDetection;m.AutoModelForPoseEstimation;m.AutoModelForQuestionAnswering;m.AutoModelForSemanticSegmentation;m.AutoModelForSeq2SeqLM;m.AutoModelForSequenceClassification;m.AutoModelForSpeechSeq2Seq;m.AutoModelForTextToSpectrogram;m.AutoModelForTextToWaveform;m.AutoModelForTokenClassification;m.AutoModelForUniversalSegmentation;m.AutoModelForVision2Seq;m.AutoModelForXVector;m.AutoModelForZeroShotObjectDetection;var pT=m.AutoProcessor;m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline;m.BackgroundRemovalPipeline;m.BartForConditionalGeneration;m.BartForSequenceClassification;m.BartModel;m.BartPretrainedModel;m.BartTokenizer;m.BaseModelOutput;m.BaseStreamer;m.BeitFeatureExtractor;m.BeitForImageClassification;m.BeitModel;m.BeitPreTrainedModel;m.BertForMaskedLM;m.BertForQuestionAnswering;m.BertForSequenceClassification;m.BertForTokenClassification;m.BertModel;m.BertPreTrainedModel;m.BertTokenizer;m.BitImageProcessor;m.BlenderbotForConditionalGeneration;m.BlenderbotModel;m.BlenderbotPreTrainedModel;m.BlenderbotSmallForConditionalGeneration;m.BlenderbotSmallModel;m.BlenderbotSmallPreTrainedModel;m.BlenderbotSmallTokenizer;m.BlenderbotTokenizer;m.BloomForCausalLM;m.BloomModel;m.BloomPreTrainedModel;m.BloomTokenizer;m.CLIPFeatureExtractor;m.CLIPImageProcessor;m.CLIPModel;m.CLIPPreTrainedModel;m.CLIPSegForImageSegmentation;m.CLIPSegModel;m.CLIPSegPreTrainedModel;m.CLIPTextModel;m.CLIPTextModelWithProjection;m.CLIPTokenizer;m.CLIPVisionModel;m.CLIPVisionModelWithProjection;m.CamembertForMaskedLM;m.CamembertForQuestionAnswering;m.CamembertForSequenceClassification;m.CamembertForTokenClassification;m.CamembertModel;m.CamembertPreTrainedModel;m.CamembertTokenizer;m.CausalLMOutput;m.CausalLMOutputWithPast;m.ChineseCLIPFeatureExtractor;m.ChineseCLIPModel;m.ChineseCLIPPreTrainedModel;m.ClapAudioModelWithProjection;m.ClapFeatureExtractor;m.ClapModel;m.ClapPreTrainedModel;m.ClapTextModelWithProjection;m.ClassifierFreeGuidanceLogitsProcessor;m.CodeGenForCausalLM;m.CodeGenModel;m.CodeGenPreTrainedModel;m.CodeGenTokenizer;m.CodeLlamaTokenizer;m.CohereForCausalLM;m.CohereModel;m.CoherePreTrainedModel;m.CohereTokenizer;m.ConvBertForMaskedLM;m.ConvBertForQuestionAnswering;m.ConvBertForSequenceClassification;m.ConvBertForTokenClassification;m.ConvBertModel;m.ConvBertPreTrainedModel;m.ConvBertTokenizer;m.ConvNextFeatureExtractor;m.ConvNextForImageClassification;m.ConvNextImageProcessor;m.ConvNextModel;m.ConvNextPreTrainedModel;m.ConvNextV2ForImageClassification;m.ConvNextV2Model;m.ConvNextV2PreTrainedModel;m.DFineForObjectDetection;m.DFineModel;m.DFinePreTrainedModel;m.DPTFeatureExtractor;m.DPTForDepthEstimation;m.DPTImageProcessor;m.DPTModel;m.DPTPreTrainedModel;m.DacDecoderModel;m.DacDecoderOutput;m.DacEncoderModel;m.DacEncoderOutput;m.DacFeatureExtractor;m.DacModel;m.DacPreTrainedModel;m.DataTypeMap;m.DebertaForMaskedLM;m.DebertaForQuestionAnswering;m.DebertaForSequenceClassification;m.DebertaForTokenClassification;m.DebertaModel;m.DebertaPreTrainedModel;m.DebertaTokenizer;m.DebertaV2ForMaskedLM;m.DebertaV2ForQuestionAnswering;m.DebertaV2ForSequenceClassification;m.DebertaV2ForTokenClassification;m.DebertaV2Model;m.DebertaV2PreTrainedModel;m.DebertaV2Tokenizer;m.DecisionTransformerModel;m.DecisionTransformerPreTrainedModel;m.DeiTFeatureExtractor;m.DeiTForImageClassification;m.DeiTImageProcessor;m.DeiTModel;m.DeiTPreTrainedModel;m.DepthAnythingForDepthEstimation;m.DepthAnythingPreTrainedModel;m.DepthEstimationPipeline;m.DepthProForDepthEstimation;m.DepthProPreTrainedModel;m.DetrFeatureExtractor;m.DetrForObjectDetection;m.DetrForSegmentation;m.DetrImageProcessor;m.DetrModel;m.DetrObjectDetectionOutput;m.DetrPreTrainedModel;m.DetrSegmentationOutput;m.Dinov2ForImageClassification;m.Dinov2Model;m.Dinov2PreTrainedModel;m.Dinov2WithRegistersForImageClassification;m.Dinov2WithRegistersModel;m.Dinov2WithRegistersPreTrainedModel;m.DistilBertForMaskedLM;m.DistilBertForQuestionAnswering;m.DistilBertForSequenceClassification;m.DistilBertForTokenClassification;m.DistilBertModel;m.DistilBertPreTrainedModel;m.DistilBertTokenizer;m.DocumentQuestionAnsweringPipeline;m.DonutFeatureExtractor;m.DonutImageProcessor;m.DonutSwinModel;m.DonutSwinPreTrainedModel;m.EfficientNetForImageClassification;m.EfficientNetImageProcessor;m.EfficientNetModel;m.EfficientNetPreTrainedModel;m.ElectraForMaskedLM;m.ElectraForQuestionAnswering;m.ElectraForSequenceClassification;m.ElectraForTokenClassification;m.ElectraModel;m.ElectraPreTrainedModel;m.ElectraTokenizer;m.EncodecFeatureExtractor;m.EosTokenCriteria;m.EsmForMaskedLM;m.EsmForSequenceClassification;m.EsmForTokenClassification;m.EsmModel;m.EsmPreTrainedModel;m.EsmTokenizer;m.ExaoneForCausalLM;m.ExaoneModel;m.ExaonePreTrainedModel;m.FFT;m.FalconForCausalLM;m.FalconModel;m.FalconPreTrainedModel;m.FalconTokenizer;m.FastViTForImageClassification;m.FastViTModel;m.FastViTPreTrainedModel;m.FeatureExtractionPipeline;m.FeatureExtractor;m.FillMaskPipeline;m.Florence2ForConditionalGeneration;m.Florence2PreTrainedModel;m.Florence2Processor;m.ForcedBOSTokenLogitsProcessor;m.ForcedEOSTokenLogitsProcessor;m.GLPNFeatureExtractor;m.GLPNForDepthEstimation;m.GLPNModel;m.GLPNPreTrainedModel;m.GPT2LMHeadModel;m.GPT2Model;m.GPT2PreTrainedModel;m.GPT2Tokenizer;m.GPTBigCodeForCausalLM;m.GPTBigCodeModel;m.GPTBigCodePreTrainedModel;m.GPTJForCausalLM;m.GPTJModel;m.GPTJPreTrainedModel;m.GPTNeoForCausalLM;m.GPTNeoModel;m.GPTNeoPreTrainedModel;m.GPTNeoXForCausalLM;m.GPTNeoXModel;m.GPTNeoXPreTrainedModel;m.GPTNeoXTokenizer;m.Gemma2ForCausalLM;m.Gemma2Model;m.Gemma2PreTrainedModel;m.Gemma3ForCausalLM;m.Gemma3Model;m.Gemma3PreTrainedModel;m.GemmaForCausalLM;m.GemmaModel;m.GemmaPreTrainedModel;m.GemmaTokenizer;m.GlmForCausalLM;m.GlmModel;m.GlmPreTrainedModel;m.GraniteForCausalLM;m.GraniteModel;m.GranitePreTrainedModel;m.Grok1Tokenizer;m.GroundingDinoForObjectDetection;m.GroundingDinoImageProcessor;m.GroundingDinoPreTrainedModel;m.GroundingDinoProcessor;m.GroupViTModel;m.GroupViTPreTrainedModel;m.HeliumForCausalLM;m.HeliumModel;m.HeliumPreTrainedModel;m.HerbertTokenizer;m.HieraForImageClassification;m.HieraModel;m.HieraPreTrainedModel;m.HubertForCTC;m.HubertForSequenceClassification;m.HubertModel;m.HubertPreTrainedModel;m.IJepaForImageClassification;m.IJepaModel;m.IJepaPreTrainedModel;m.Idefics3ForConditionalGeneration;m.Idefics3ImageProcessor;m.Idefics3PreTrainedModel;m.Idefics3Processor;m.ImageClassificationPipeline;m.ImageFeatureExtractionPipeline;m.ImageFeatureExtractor;m.ImageMattingOutput;m.ImageProcessor;m.ImageSegmentationPipeline;m.ImageToImagePipeline;m.ImageToTextPipeline;m.InterruptableStoppingCriteria;m.JAISLMHeadModel;m.JAISModel;m.JAISPreTrainedModel;m.JinaCLIPImageProcessor;m.JinaCLIPModel;m.JinaCLIPPreTrainedModel;m.JinaCLIPProcessor;m.JinaCLIPTextModel;m.JinaCLIPVisionModel;m.LiteWhisperForConditionalGeneration;m.LlamaForCausalLM;m.LlamaModel;m.LlamaPreTrainedModel;m.LlamaTokenizer;m.LlavaForConditionalGeneration;m.LlavaOnevisionForConditionalGeneration;m.LlavaOnevisionImageProcessor;m.LlavaPreTrainedModel;m.LogitsProcessor;m.LogitsProcessorList;m.LogitsWarper;m.LongT5ForConditionalGeneration;m.LongT5Model;m.LongT5PreTrainedModel;m.M2M100ForConditionalGeneration;m.M2M100Model;m.M2M100PreTrainedModel;m.M2M100Tokenizer;m.MBart50Tokenizer;m.MBartForCausalLM;m.MBartForConditionalGeneration;m.MBartForSequenceClassification;m.MBartModel;m.MBartPreTrainedModel;m.MBartTokenizer;m.MPNetForMaskedLM;m.MPNetForQuestionAnswering;m.MPNetForSequenceClassification;m.MPNetForTokenClassification;m.MPNetModel;m.MPNetPreTrainedModel;m.MPNetTokenizer;m.MT5ForConditionalGeneration;m.MT5Model;m.MT5PreTrainedModel;m.MarianMTModel;m.MarianModel;m.MarianPreTrainedModel;m.MarianTokenizer;m.Mask2FormerImageProcessor;m.MaskFormerFeatureExtractor;m.MaskFormerForInstanceSegmentation;m.MaskFormerImageProcessor;m.MaskFormerModel;m.MaskFormerPreTrainedModel;m.MaskedLMOutput;m.MaxLengthCriteria;m.Metric3DForDepthEstimation;m.Metric3DPreTrainedModel;m.Metric3Dv2ForDepthEstimation;m.Metric3Dv2PreTrainedModel;m.MgpstrForSceneTextRecognition;m.MgpstrModelOutput;m.MgpstrPreTrainedModel;m.MgpstrProcessor;m.MgpstrTokenizer;m.MimiDecoderModel;m.MimiDecoderOutput;m.MimiEncoderModel;m.MimiEncoderOutput;m.MimiModel;m.MimiPreTrainedModel;m.MinLengthLogitsProcessor;m.MinNewTokensLengthLogitsProcessor;m.MistralForCausalLM;m.MistralModel;m.MistralPreTrainedModel;m.MobileBertForMaskedLM;m.MobileBertForQuestionAnswering;m.MobileBertForSequenceClassification;m.MobileBertModel;m.MobileBertPreTrainedModel;m.MobileBertTokenizer;m.MobileLLMForCausalLM;m.MobileLLMModel;m.MobileLLMPreTrainedModel;m.MobileNetV1FeatureExtractor;m.MobileNetV1ForImageClassification;m.MobileNetV1ForSemanticSegmentation;m.MobileNetV1ImageProcessor;m.MobileNetV1Model;m.MobileNetV1PreTrainedModel;m.MobileNetV2FeatureExtractor;m.MobileNetV2ForImageClassification;m.MobileNetV2ForSemanticSegmentation;m.MobileNetV2ImageProcessor;m.MobileNetV2Model;m.MobileNetV2PreTrainedModel;m.MobileNetV3FeatureExtractor;m.MobileNetV3ForImageClassification;m.MobileNetV3ForSemanticSegmentation;m.MobileNetV3ImageProcessor;m.MobileNetV3Model;m.MobileNetV3PreTrainedModel;m.MobileNetV4FeatureExtractor;m.MobileNetV4ForImageClassification;m.MobileNetV4ForSemanticSegmentation;m.MobileNetV4ImageProcessor;m.MobileNetV4Model;m.MobileNetV4PreTrainedModel;m.MobileViTFeatureExtractor;m.MobileViTForImageClassification;m.MobileViTImageProcessor;m.MobileViTModel;m.MobileViTPreTrainedModel;m.MobileViTV2ForImageClassification;m.MobileViTV2Model;m.MobileViTV2PreTrainedModel;m.ModelOutput;m.ModernBertForMaskedLM;m.ModernBertForSequenceClassification;m.ModernBertForTokenClassification;m.ModernBertModel;m.ModernBertPreTrainedModel;m.Moondream1ForConditionalGeneration;m.MoonshineFeatureExtractor;m.MoonshineForConditionalGeneration;m.MoonshineModel;m.MoonshinePreTrainedModel;m.MoonshineProcessor;m.MptForCausalLM;m.MptModel;m.MptPreTrainedModel;m.MultiModalityCausalLM;m.MultiModalityPreTrainedModel;m.MusicgenForCausalLM;m.MusicgenForConditionalGeneration;m.MusicgenModel;m.MusicgenPreTrainedModel;m.NllbTokenizer;m.NoBadWordsLogitsProcessor;m.NoRepeatNGramLogitsProcessor;m.NomicBertModel;m.NomicBertPreTrainedModel;m.NougatImageProcessor;m.NougatTokenizer;m.OPTForCausalLM;m.OPTModel;m.OPTPreTrainedModel;m.ObjectDetectionPipeline;m.Olmo2ForCausalLM;m.Olmo2Model;m.Olmo2PreTrainedModel;m.OlmoForCausalLM;m.OlmoModel;m.OlmoPreTrainedModel;m.OpenELMForCausalLM;m.OpenELMModel;m.OpenELMPreTrainedModel;m.OwlViTFeatureExtractor;m.OwlViTForObjectDetection;m.OwlViTImageProcessor;m.OwlViTModel;m.OwlViTPreTrainedModel;m.OwlViTProcessor;m.Owlv2ForObjectDetection;m.Owlv2ImageProcessor;m.Owlv2Model;m.Owlv2PreTrainedModel;m.PaliGemmaForConditionalGeneration;m.PaliGemmaPreTrainedModel;m.PaliGemmaProcessor;m.PatchTSMixerForPrediction;m.PatchTSMixerModel;m.PatchTSMixerPreTrainedModel;m.PatchTSTForPrediction;m.PatchTSTModel;m.PatchTSTPreTrainedModel;m.Phi3ForCausalLM;m.Phi3Model;m.Phi3PreTrainedModel;m.Phi3VForCausalLM;m.Phi3VImageProcessor;m.Phi3VPreTrainedModel;m.Phi3VProcessor;m.PhiForCausalLM;m.PhiModel;m.PhiPreTrainedModel;m.Pipeline;m.PreTrainedModel;m.PreTrainedTokenizer;m.PretrainedConfig;m.PretrainedMixin;m.Processor;m.PvtForImageClassification;m.PvtImageProcessor;m.PvtModel;m.PvtPreTrainedModel;m.PyAnnoteFeatureExtractor;m.PyAnnoteForAudioFrameClassification;m.PyAnnoteModel;m.PyAnnotePreTrainedModel;m.PyAnnoteProcessor;m.QuestionAnsweringModelOutput;m.QuestionAnsweringPipeline;m.Qwen2ForCausalLM;m.Qwen2Model;m.Qwen2PreTrainedModel;m.Qwen2Tokenizer;m.Qwen2VLForConditionalGeneration;m.Qwen2VLImageProcessor;m.Qwen2VLPreTrainedModel;m.Qwen2VLProcessor;m.Qwen3ForCausalLM;m.Qwen3Model;m.Qwen3PreTrainedModel;m.RFDetrForObjectDetection;m.RFDetrModel;m.RFDetrObjectDetectionOutput;m.RFDetrPreTrainedModel;m.RTDetrForObjectDetection;m.RTDetrImageProcessor;m.RTDetrModel;m.RTDetrObjectDetectionOutput;m.RTDetrPreTrainedModel;m.RTDetrV2ForObjectDetection;m.RTDetrV2Model;m.RTDetrV2ObjectDetectionOutput;m.RTDetrV2PreTrainedModel;m.RawAudio;var cb=m.RawImage;m.RawVideo;m.RawVideoFrame;m.RepetitionPenaltyLogitsProcessor;m.ResNetForImageClassification;m.ResNetModel;m.ResNetPreTrainedModel;m.RoFormerForMaskedLM;m.RoFormerForQuestionAnswering;m.RoFormerForSequenceClassification;m.RoFormerForTokenClassification;m.RoFormerModel;m.RoFormerPreTrainedModel;m.RoFormerTokenizer;m.RobertaForMaskedLM;m.RobertaForQuestionAnswering;m.RobertaForSequenceClassification;m.RobertaForTokenClassification;m.RobertaModel;m.RobertaPreTrainedModel;m.RobertaTokenizer;m.SamImageProcessor;m.SamImageSegmentationOutput;m.SamModel;m.SamPreTrainedModel;m.SamProcessor;m.SapiensForDepthEstimation;m.SapiensForNormalEstimation;m.SapiensForSemanticSegmentation;m.SapiensPreTrainedModel;m.SeamlessM4TFeatureExtractor;m.SegformerFeatureExtractor;m.SegformerForImageClassification;m.SegformerForSemanticSegmentation;m.SegformerImageProcessor;m.SegformerModel;m.SegformerPreTrainedModel;m.Seq2SeqLMOutput;m.SequenceClassifierOutput;m.SiglipImageProcessor;m.SiglipModel;m.SiglipPreTrainedModel;m.SiglipTextModel;m.SiglipTokenizer;m.SiglipVisionModel;m.SmolVLMForConditionalGeneration;m.SmolVLMImageProcessor;m.SmolVLMProcessor;m.SnacDecoderModel;m.SnacEncoderModel;m.SnacFeatureExtractor;m.SnacModel;m.SnacPreTrainedModel;m.SpeechT5FeatureExtractor;m.SpeechT5ForSpeechToText;m.SpeechT5ForTextToSpeech;m.SpeechT5HifiGan;m.SpeechT5Model;m.SpeechT5PreTrainedModel;m.SpeechT5Processor;m.SpeechT5Tokenizer;m.SqueezeBertForMaskedLM;m.SqueezeBertForQuestionAnswering;m.SqueezeBertForSequenceClassification;m.SqueezeBertModel;m.SqueezeBertPreTrainedModel;m.SqueezeBertTokenizer;m.StableLmForCausalLM;m.StableLmModel;m.StableLmPreTrainedModel;m.Starcoder2ForCausalLM;m.Starcoder2Model;m.Starcoder2PreTrainedModel;m.StoppingCriteria;m.StoppingCriteriaList;m.StyleTextToSpeech2Model;m.StyleTextToSpeech2PreTrainedModel;m.SummarizationPipeline;m.SuppressTokensAtBeginLogitsProcessor;m.Swin2SRForImageSuperResolution;m.Swin2SRImageProcessor;m.Swin2SRModel;m.Swin2SRPreTrainedModel;m.SwinForImageClassification;m.SwinForSemanticSegmentation;m.SwinModel;m.SwinPreTrainedModel;m.T5ForConditionalGeneration;m.T5Model;m.T5PreTrainedModel;m.T5Tokenizer;m.TableTransformerForObjectDetection;m.TableTransformerModel;m.TableTransformerObjectDetectionOutput;m.TableTransformerPreTrainedModel;m.TemperatureLogitsWarper;m.Tensor;m.Text2TextGenerationPipeline;m.TextClassificationPipeline;m.TextGenerationPipeline;m.TextStreamer;m.TextToAudioPipeline;m.TokenClassificationPipeline;m.TokenClassifierOutput;m.TokenizerModel;m.TopKLogitsWarper;m.TopPLogitsWarper;m.TrOCRForCausalLM;m.TrOCRPreTrainedModel;m.TranslationPipeline;m.UltravoxModel;m.UltravoxPreTrainedModel;m.UltravoxProcessor;m.UniSpeechForCTC;m.UniSpeechForSequenceClassification;m.UniSpeechModel;m.UniSpeechPreTrainedModel;m.UniSpeechSatForAudioFrameClassification;m.UniSpeechSatForCTC;m.UniSpeechSatForSequenceClassification;m.UniSpeechSatModel;m.UniSpeechSatPreTrainedModel;m.VLChatProcessor;m.VLMImageProcessor;m.ViTFeatureExtractor;m.ViTForImageClassification;m.ViTImageProcessor;m.ViTMAEModel;m.ViTMAEPreTrainedModel;m.ViTMSNForImageClassification;m.ViTMSNModel;m.ViTMSNPreTrainedModel;m.ViTModel;m.ViTPreTrainedModel;m.VisionEncoderDecoderModel;m.VitMatteForImageMatting;m.VitMatteImageProcessor;m.VitMattePreTrainedModel;m.VitPoseForPoseEstimation;m.VitPoseImageProcessor;m.VitPosePreTrainedModel;m.VitsModel;m.VitsModelOutput;m.VitsPreTrainedModel;m.VitsTokenizer;m.Wav2Vec2BertForCTC;m.Wav2Vec2BertForSequenceClassification;m.Wav2Vec2BertModel;m.Wav2Vec2BertPreTrainedModel;m.Wav2Vec2CTCTokenizer;m.Wav2Vec2FeatureExtractor;m.Wav2Vec2ForAudioFrameClassification;m.Wav2Vec2ForCTC;m.Wav2Vec2ForSequenceClassification;m.Wav2Vec2Model;m.Wav2Vec2PreTrainedModel;m.Wav2Vec2Processor;m.Wav2Vec2ProcessorWithLM;m.WavLMForAudioFrameClassification;m.WavLMForCTC;m.WavLMForSequenceClassification;m.WavLMForXVector;m.WavLMModel;m.WavLMPreTrainedModel;m.WeSpeakerFeatureExtractor;m.WeSpeakerResNetModel;m.WeSpeakerResNetPreTrainedModel;m.WhisperFeatureExtractor;m.WhisperForConditionalGeneration;m.WhisperModel;m.WhisperPreTrainedModel;m.WhisperProcessor;m.WhisperTextStreamer;m.WhisperTimeStampLogitsProcessor;m.WhisperTokenizer;m.XLMForQuestionAnswering;m.XLMForSequenceClassification;m.XLMForTokenClassification;m.XLMModel;m.XLMPreTrainedModel;m.XLMRobertaForMaskedLM;m.XLMRobertaForQuestionAnswering;m.XLMRobertaForSequenceClassification;m.XLMRobertaForTokenClassification;m.XLMRobertaModel;m.XLMRobertaPreTrainedModel;m.XLMRobertaTokenizer;m.XLMTokenizer;m.XLMWithLMHeadModel;m.XVectorOutput;m.YolosFeatureExtractor;m.YolosForObjectDetection;m.YolosImageProcessor;m.YolosModel;m.YolosObjectDetectionOutput;m.YolosPreTrainedModel;m.ZeroShotAudioClassificationPipeline;m.ZeroShotClassificationPipeline;m.ZeroShotImageClassificationPipeline;m.ZeroShotObjectDetectionPipeline;m.bankers_round;m.cat;m.cos_sim;m.dot;m.dynamic_time_warping;var hT=m.env;m.full;m.full_like;m.getKeyValueShapes;m.hamming;m.hanning;m.interpolate;m.interpolate_4d;m.interpolate_data;m.is_chinese_char;m.layer_norm;m.load_image;m.load_video;m.log_softmax;m.magnitude;m.matmul;m.max;m.mean;m.mean_pooling;m.medianFilter;m.mel_filter_bank;m.min;m.ones;m.ones_like;m.permute;m.permute_data;m.pipeline;m.quantize_embeddings;m.rand;m.read_audio;m.rfft;m.round;m.slice;m.softmax;m.spectrogram;m.stack;m.std_mean;m.topk;m.window_function;m.zeros;m.zeros_like;async function mT(){try{if(fT())return{supported:!1,isNode:!0,reason:"",fp16Supported:!1};if(typeof navigator>"u"||!navigator.gpu)return{supported:!1,isNode:!1,reason:"WebGPU is not available (navigator.gpu is undefined)",fp16Supported:!1};const e=await navigator.gpu.requestAdapter();return e?{supported:!0,isNode:!1,reason:"",adapter:e,fp16Supported:e.features.has("shader-f16")}:{supported:!1,isNode:!1,reason:"WebGPU is not supported (no adapter found)",fp16Supported:!1}}catch(e){return{supported:!1,isNode:!1,reason:e instanceof Error?e.toString():String(e),fp16Supported:!1}}}function fT(){return typeof process<"u"&&"versions"in process&&process.versions!=null&&typeof process.versions=="object"&&"node"in process.versions&&process.versions.node!=null}const _T={flex:"","flex-col":"","items-center":"","gap-4":""},gT=["disabled"],wT={"h-full":"","w-full":"",flex:"","gap-2":""},bT={w:"[50%]",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","min-h":"120",h:"auto","overflow-hidden":"","rounded-lg":""},MT=["src"],yT={w:"[50%]",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","min-h":"120",h:"auto",relative:"","overflow-hidden":"","rounded-lg":""},vT={key:0,bg:"black/50",absolute:"","inset-0":"","z-10":"",flex:"","flex-col":"","items-center":"","justify-center":""},xT={"mb-4":"","text-white":"","font-medium":""},TT={bg:"gray-200/30",w:"70%","h-2":"","overflow-hidden":"","rounded-full":""},ET=["src"],PT={bg:"black/0 group-hover:black/20",absolute:"","inset-0":"",flex:"","items-center":"","justify-center":"","transition-all":"","duration-200":""},CT=["onClick"],ST={key:1,absolute:"","bottom-2":"","right-2":""},DT=bv({__name:"background-remove",setup(e){const r=zs(),t=zs(),s=zs(),o=zs(),n=zs(!1),i=zs(0),a=zs(),l=zs(),u=zs([]),p=Mv(()=>u.value.map(f=>URL.createObjectURL(f)));yv(async()=>{try{if(!(await mT()).supported)throw new Error("WebGPU is not supported in this browser.");const f="Xenova/modnet";hT.backends.onnx.wasm.proxy=!1,r.value??(r.value=await dT.from_pretrained(f,{device:"webgpu"})),t.value??(t.value=await pT.from_pretrained(f,{}))}catch(f){s.value=f}o.value=!1});async function c(){if(!r.value||!t.value)return;n.value=!0,i.value=0,a.value=[];const f=p.value.length;for(let v=0;v=a.value.length||!u.value[f])return;const v=u.value[f].name,$=v.substring(0,v.lastIndexOf("."))||v,g=v.substring(v.lastIndexOf("."))||".png",w=`${$}-background-removed${g}`,C=document.createElement("a");C.href=a.value[f],C.download=w,document.body.appendChild(C),C.click(),document.body.removeChild(C)}function _(){!a.value||a.value.length===0||a.value.forEach((f,v)=>{setTimeout(()=>d(v),v*100)})}return(f,v)=>(En(),Tn("div",_T,[Vr("button",{bg:"neutral-100 dark:neutral-800","w-full":"","cursor-pointer":"","rounded-lg":"","px-3":"","py-2":"",disabled:n.value,onClick:c},Ef(n.value?"Processing...":"Process"),9,gT),Vr("div",wT,[Vr("div",bT,[(En(!0),Tn(Pf,null,Cf(p.value,($,g)=>(En(),Tn("img",{key:g,src:$,"h-full":"","w-full":"","object-cover":""},null,8,MT))),128))]),Vr("div",yT,[n.value?(En(),Tn("div",vT,[Vr("div",xT,Ef(i.value)+"% ",1),Vr("div",TT,[Vr("div",{bg:"emerald-500","h-full":"",style:xv({width:`${i.value}%`}),"transition-all":"","duration-200":""},null,4)])])):Sf("",!0),(En(!0),Tn(Pf,null,Cf(a.value,($,g)=>(En(),Tn("div",{key:g,relative:"",class:"group","h-full":"","w-full":""},[Vr("img",{src:$,"h-full":"","w-full":"","object-cover":""},null,8,ET),Vr("div",PT,[Vr("button",{bg:"emerald-500 hover:emerald-600","rounded-full":"","p-2":"","text-white":"","opacity-0":"","transition-all":"","duration-200":"","group-hover:opacity-100":"",onClick:w=>d(g)},v[1]||(v[1]=[Vr("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[Vr("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1)]),8,CT)])]))),128)),a.value&&a.value.length>1?(En(),Tn("div",ST,[Vr("button",{bg:"emerald-500 hover:emerald-600","rounded-full":"","p-2":"","text-white":"",onClick:_},v[2]||(v[2]=[Vr("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[Vr("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"})],-1)]))])):Sf("",!0)])]),vv(Tv(wv),{modelValue:u.value,"onUpdate:modelValue":v[0]||(v[0]=$=>u.value=$),"w-full":""},null,8,["modelValue"])]))}});export{DT as default}; diff --git a/assets/background-remove-C4yhDB9Z.js b/assets/background-remove-C4yhDB9Z.js deleted file mode 100644 index 888eedb0f27d995af17c675f1c38a02534abe868..0000000000000000000000000000000000000000 --- a/assets/background-remove-C4yhDB9Z.js +++ /dev/null @@ -1,2887 +0,0 @@ -var uv=Object.defineProperty;var dv=(e,r,t)=>r in e?uv(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var te=(e,r,t)=>dv(e,typeof r!="symbol"?r+"":r,t);import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as cv}from"./InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js";import{d as pv,r as ks,h as hv,H as mv,c as Tn,o as En,e as Sr,i as fv,t as wf,F as bf,l as Mf,j as yf,z as _v,b as gv}from"./index-BQKiy4UR.js";import"./floating-ui.core-CgBsuaUc.js";const la=new Map,kn=[],wv=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=la.get(e);if(s===void 0)la.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 o=kn.indexOf(e);o!==-1&&kn.splice(o,1);for(let n=0;n{const r=la.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}}},Mv=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?kn:t;let o;const n=[],i=new Set;for(const l of s){const u=await bv(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},yv="1.21.1";let vf="warning";const ms={wasm:{},webgl:{},webgpu:{},versions:{common:yv},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}`);vf=e}},get logLevel(){return vf}};Object.defineProperty(ms,"logLevel",{enumerable:!0});const vv=ms,xv=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let d=0,c=p,_=p*2,f=-1;i==="RGBA"?(d=0,c=p,_=p*2,f=p*3):i==="RGB"?(d=0,c=p,_=p*2):i==="RBG"&&(d=0,_=p,c=p*2);for(let v=0;v{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const c=4;let _=0,f=1,v=2,$=3,w=0,g=d,C=d*2,E=-1;a==="RGBA"?(w=0,g=d,C=d*2,E=d*3):a==="RGB"?(w=0,g=d,C=d*2):a==="RBG"&&(w=0,C=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{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,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let d=4,c=0,_=1,f=2,v=3,$=0,w=u,g=u*2,C=-1;a==="RGB"&&(d=3,c=0,_=1,f=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?($=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,$=u*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,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")},u=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 d=u(p);if(d!=null){let c=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,_=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=c,a.width=_}else a.tensorFormat="RGBA",a.height=c,a.width=_;d.drawImage(e,0,0),i=d.getImageData(0,0,_,c).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const c=l();c.width=d,c.height=p;const _=u(c);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 d=u(p);if(d!=null){const c=e.height,_=e.width;return d.drawImage(e,0,0,_,c),i=d.getImageData(0,0,_,c).data,a.height=c,a.width=_,kl(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{const c=l(),_=u(c);if(!e||!_)return d();const f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{c.width=f.width,c.height=f.height,_.drawImage(f,0,0,c.width,c.height);const v=_.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(kl(v.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return kl(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Pv=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Qr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Cv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Qr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Sv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Qr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},$v=(e,r,t)=>new Qr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),so=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ua=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let xf=!1;const kv=()=>{if(!xf){xf=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(so.set("int64",BigInt64Array),ua.set(BigInt64Array,"int64")),r&&(so.set("uint64",BigUint64Array),ua.set(BigUint64Array,"uint64")),s?(so.set("float16",t),ua.set(t,"float16")):so.set("float16",Uint16Array)}},Iv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Qr(e.type,e.data,r);case"cpu-pinned":return new Qr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Qr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Qr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Qr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Qr=class{constructor(r,t,s){kv();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=so.get(o);if(!a)throw new TypeError(`unsupported type "${o}" 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(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" 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(o=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 u=so.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)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&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=ua.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,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 i=Iv(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return Ev(r,t)}static fromTexture(r,t){return Pv(r,t)}static fromGpuBuffer(r,t){return Cv(r,t)}static fromMLTensor(r,t){return Sv(r,t)}static fromPinnedBuffer(r,t,s){return $v(r,t,s)}toDataURL(r){return xv(this,r)}toImageData(r){return Tv(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 Av(this,r)}};const to=Qr,nb=(e,r)=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||console.timeStamp(`${e}::ORT::${r}`)},ob=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||ob("BEGIN",e)},Iu=e=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||ob("END",e)};let Fv=class ib{constructor(r){this.handler=r}async run(r,t,s){ku();const o={};let n={};if(typeof r!="object"||r===null||r instanceof to||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof to)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.");i=!1;for(const u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const c=t[d];(c===null||c instanceof to)&&(u=!0,i=!1,o[d]=c)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof to?l[u]=p:l[u]=new to(p.type,p.data,p.dims)}return Iu(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){ku();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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 d=0,c=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,d,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Mv(i),u=await a.createInferenceSessionHandler(n,l);return Iu(),new ib(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const Ov=Fv,Dv=Object.freeze(Object.defineProperty({__proto__:null,InferenceSession:Ov,TRACE:nb,TRACE_FUNC_BEGIN:ku,TRACE_FUNC_END:Iu,Tensor:to,env:vv,registerBackend:wv},Symbol.toStringTag,{value:"Module"}));/*! - * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */var qu=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,zv=Object.getOwnPropertyNames,Bv=Object.prototype.hasOwnProperty,Rv=(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')}),Re=(e,r)=>()=>(e&&(r=e(e=0)),r),ao=(e,r)=>{for(var t in r)qu(e,t,{get:r[t],enumerable:!0})},jv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of zv(r))!Bv.call(e,o)&&o!==t&&qu(e,o,{get:()=>r[o],enumerable:!(s=Lv(r,o))||s.enumerable});return e},Jo=e=>jv(qu({},"__esModule",{value:!0}),e),Lo,Hs,Fn,Tf,ab,lb=Re(()=>{Lo=new Map,Hs=[],Fn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Lo.get(e);if(s===void 0)Lo.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 o=Hs.indexOf(e);o!==-1&&Hs.splice(o,1);for(let n=0;n{let r=Lo.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}}},ab=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Hs:t,o,n=[],i=new Set;for(let l of s){let u=await Tf(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),Nv=Re(()=>{lb()}),ub,Vv=Re(()=>{ub="1.22.0-dev.20250409-89f8206ba4"}),Il,Xr,db=Re(()=>{Vv(),Il="warning",Xr={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}`);Il=e}},get logLevel(){return Il}},Object.defineProperty(Xr,"logLevel",{enumerable:!0})}),jt,Uv=Re(()=>{db(),jt=Xr}),cb,pb,Wv=Re(()=>{cb=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,d=0,c=p,_=p*2,f=-1;i==="RGBA"?(d=0,c=p,_=p*2,f=p*3):i==="RGB"?(d=0,c=p,_=p*2):i==="RBG"&&(d=0,_=p,c=p*2);for(let v=0;v{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let c=4,_=0,f=1,v=2,$=3,w=0,g=d,C=d*2,E=-1;a==="RGBA"?(w=0,g=d,C=d*2,E=d*3):a==="RGB"?(w=0,g=d,C=d*2):a==="RBG"&&(w=0,C=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{Xu(),qi=(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,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),d=4,c=0,_=1,f=2,v=3,$=0,w=u,g=u*2,C=-1;a==="RGB"&&(d=3,c=0,_=1,f=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?($=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,$=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,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")},u=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 d=u(p);if(d!=null){let c=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,_=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=c,a.width=_}else a.tensorFormat="RGBA",a.height=c,a.width=_;d.drawImage(e,0,0),i=d.getImageData(0,0,_,c).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let c=l();c.width=d,c.height=p;let _=u(c);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 d=u(p);if(d!=null){let c=e.height,_=e.width;return d.drawImage(e,0,0,_,c),i=d.getImageData(0,0,_,c).data,a.height=c,a.width=_,qi(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{let c=l(),_=u(c);if(!e||!_)return d();let f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{c.width=f.width,c.height=f.height,_.drawImage(f,0,0,c.width,c.height);let v=_.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(qi(v.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return qi(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},mb=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Nr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},fb=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Nr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},_b=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Nr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},gb=(e,r,t)=>new Nr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),In,Ko,Al,wb,Kv=Re(()=>{In=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Al=!1,wb=()=>{if(!Al){Al=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(In.set("int64",BigInt64Array),Ko.set(BigInt64Array,"int64")),r&&(In.set("uint64",BigUint64Array),Ko.set(BigUint64Array,"uint64")),s?(In.set("float16",t),Ko.set(t,"float16")):In.set("float16",Uint16Array)}}}),bb,Mb,Hv=Re(()=>{Xu(),bb=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Nr(e.type,e.data,r);case"cpu-pinned":return new Nr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Nr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Nr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Nr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Nr,Xu=Re(()=>{Wv(),Gv(),Kv(),Hv(),Nr=class{constructor(e,r,t){wb();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=In.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,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.");i=r}else{let l=In.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"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=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)i=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",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=Ko.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=bb(o);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=o,this.size=n}static async fromImage(e,r){return hb(e,r)}static fromTexture(e,r){return mb(e,r)}static fromGpuBuffer(e,r){return fb(e,r)}static fromMLTensor(e,r){return _b(e,r)}static fromPinnedBuffer(e,r,t){return gb(e,r,t)}toDataURL(e){return cb(this,e)}toImageData(e){return pb(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 Mb(this,e)}}}),hs,yb=Re(()=>{Xu(),hs=Nr}),Yo,Fl,fs,Jr,vb=Re(()=>{db(),Yo=(e,r)=>{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Fl=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||Fl("BEGIN",e)},Jr=e=>{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||Fl("END",e)}}),xb,qv=Re(()=>{lb(),yb(),vb(),xb=class Tb{constructor(r){this.handler=r}async run(r,t,s){fs();let o={},n={};if(typeof r!="object"||r===null||r instanceof hs||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof hs)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.");i=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let c=t[d];(c===null||c instanceof hs)&&(u=!0,i=!1,o[d]=c)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof hs?l[u]=p:l[u]=new hs(p.type,p.data,p.dims)}return Jr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){fs();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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,d=0,c=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,d,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await ab(i),u=await a.createInferenceSessionHandler(n,l);return Jr(),new Tb(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qu,Xv=Re(()=>{qv(),Qu=xb}),Qv=Re(()=>{}),Jv=Re(()=>{}),Yv=Re(()=>{}),Zv=Re(()=>{}),Eb={};ao(Eb,{InferenceSession:()=>Qu,TRACE:()=>Yo,TRACE_FUNC_BEGIN:()=>fs,TRACE_FUNC_END:()=>Jr,Tensor:()=>hs,env:()=>jt,registerBackend:()=>Fn});var _s=Re(()=>{Nv(),Uv(),Xv(),yb(),Qv(),Jv(),vb(),Yv(),Zv()}),Ju=Re(()=>{}),Pb={};ao(Pb,{default:()=>Cb});var Ol,Dl,Cb,ex=Re(()=>{var e;A0(),zn(),Yu(),Ol="ort-wasm-proxy-worker",Dl=((e=globalThis.self)==null?void 0:e.name)===Ol,Dl&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Zu(s.wasm).then(()=>{gd(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;wd(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=wa(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;bd(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":Md(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;yd(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},xd([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":vd(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Cb=Dl?null:r=>new Worker(r??jr,{type:"module",name:Ol})}),Sb={};ao(Sb,{default:()=>$b});var Ll,zl,$b,Ef,tx=Re(()=>{var e,r;zl=(Ll=import.meta.url,async function(t={}){var Oo;var s,o,n=t,i=new Promise((h,T)=>{s=h,o=T}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((Oo=self.name)==null?void 0:Oo.startsWith("em-pthread"));n.mountExternalData=(h,T)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,T)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=h=>async(...T)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:T[0],errors:[]},U=await h(...T);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let ue=L.errors;if(0Oe),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=T;let I=n.Jb;n.jsepRegisterBuffer=(L,U,ue,Te)=>I.registerBuffer(L,U,ue,Te),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,U,ue)=>I.createDownloader(L,U,ue),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,U)=>{I.upload(L,U)}}else if(h==="webnn"){let I=T[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=T.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,U)=>{I.registerMLContext(L,U)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,U)=>I.createMLTensorDownloader(L,U),n.webnnRegisterMLTensor=(L,U,ue,Te)=>I.registerMLTensor(L,U,ue,Te),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,U,ue,Te,Oe,Ke)=>I.registerMLConstant(L,U,ue,Te,Oe,n.Eb,Ke),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let c=()=>{let h=(T,I,L)=>(...U)=>{let ue=Nt,Te=I==null?void 0:I();U=T(...U);let Oe=I==null?void 0:I();return Te!==Oe&&(T=Oe,L(Te),I=L=null),Nt!=ue?new Promise((Ke,Ye)=>{Lr={resolve:Ke,reject:Ye}}):U};(()=>{for(let T of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[T]=h(n[T],()=>n[T],I=>n[T]=I)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),c=void 0};n.asyncInit=()=>{c==null||c()};var _,f,v=Object.assign({},n),$=(h,T)=>{throw T},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),Ll&&(w=Ll),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(f=h=>{var T=new XMLHttpRequest;return T.open("GET",h,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}),_=async h=>{if(V(h))return new Promise((I,L)=>{var U=new XMLHttpRequest;U.open("GET",h,!0),U.responseType="arraybuffer",U.onload=()=>{U.status==200||U.status==0&&U.response?I(U.response):L(U.status)},U.onerror=L,U.send(null)});var T=await fetch(h,{credentials:"same-origin"});if(T.ok)return T.arrayBuffer();throw Error(T.status+" : "+T.url)});var g=console.log.bind(console),C=console.error.bind(console),E=g,y=C;Object.assign(n,v),v=null;var b,x,S,A,B,K,G,j,ee,H,Z,X,oe,me=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function F(){return b.buffer!=A.buffer&&R(),A}function W(){return b.buffer!=A.buffer&&R(),B}function re(){return b.buffer!=A.buffer&&R(),K}function fe(){return b.buffer!=A.buffer&&R(),G}function se(){return b.buffer!=A.buffer&&R(),j}function ce(){return b.buffer!=A.buffer&&R(),ee}function $e(){return b.buffer!=A.buffer&&R(),H}function Ue(){return b.buffer!=A.buffer&&R(),oe}if(u){let h=function(T){try{var I=T.data,L=I.Bb;if(L==="load"){let U=[];self.onmessage=ue=>U.push(ue),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ue of U)h(ue);self.onmessage=h};for(let ue of I.Rb)n[ue]&&!n[ue].proxy||(n[ue]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ue,args:Te})},ue=="print"&&(E=n[ue]),ue=="printErr"&&(y=n[ue]));b=I.kc,R(),we(I.lc)}else if(L==="run"){kr(I.Ab),_n(I.Ab,0,0,1,0,0),lr(),ve(I.Ab),q||(Po(),q=!0);try{Ds(I.fc,I.Hb)}catch(U){if(U!="unwind")throw U}}else I.target!=="setimmediate"&&(L==="checkMailbox"?q&&je():L&&(y(`worker: received unknown command ${L}`),y(I)))}catch(U){throw Co(),U}};var we,q=!1;y=function(...T){T=T.join(" "),console.error(T)},self.alert=function(...T){postMessage({Bb:"alert",text:T.join(" "),ic:Ws()})},self.onunhandledrejection=T=>{throw T.reason||T},self.onmessage=h}function R(){var h=b.buffer;n.HEAP8=A=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=B=new Uint8Array(h),n.HEAPU16=G=new Uint16Array(h),n.HEAP32=j=new Int32Array(h),n.HEAPU32=ee=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=oe=new Float64Array(h),n.HEAP64=Z=new BigInt64Array(h),n.HEAPU64=X=new BigUint64Array(h)}function pe(){u?startWorker(n):nt.Ca()}u||(b=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R());var xe,Me=0,Se=null;function Ae(){if(--Me==0&&Se){var h=Se;Se=null,h()}}function Fe(h){throw y(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function ze(){return{a:{L:Y,Aa:O,b:Ls,$:Zr,A:es,pa:ts,X:De,Z:Qe,qa:et,na:Bt,ga:Or,ma:Pr,J:rs,Y:ss,V:Ur,oa:ns,W:os,va:Ys,E:Zs,Q:en,O:rn,D:nn,u:on,r:Ms,P:an,z:N,R:Q,ja:ie,T:He,aa:Je,M:dt,F:vt,ia:ve,sa:Et,t:Kt,Ba:Mr,w:or,o:Zt,l:Rs,c:Ps,n:ei,j:si,v:ni,p:oi,f:ii,s:ai,m:lo,e:li,k:ui,i:uo,g:di,d:co,da:ci,ea:ho,fa:hi,ba:pn,ca:mo,N:fo,xa:fi,ua:gi,h:wi,C:_o,G:Ss,ta:_i,x:bi,ra:ba,U:Mi,q:mi,y:Ma,K:yi,S:go,za:vi,ya:xi,ka:Mo,la:Vn,_:Xe,B:yo,I:vo,ha:Un,H:xo,a:b,wa:Ie}}}var Ve={829644:(h,T,I,L,U)=>{if(n===void 0||!n.Eb)return 1;if((h=Ft(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(T=Number(T>>>0),I=Number(I>>>0),L=Number(L>>>0),T+I>h.byteLength)return 3;try{let ue=h.subarray(T,T+I);switch(U){case 0:W().set(ue,L>>>0);break;case 1:n.mc?n.mc(L,ue):n.bc(L,ue);break;default:return 4}return 0}catch{return 4}},830468:(h,T,I)=>{n.Ob(h,W().subarray(T>>>0,T+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,T,I)=>{n.Kb(Number(h),Number(T),Number(I),!0)},830824:(h,T,I)=>{n.Kb(Number(h),Number(T),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,T,I)=>{n.jb("HardSigmoid",h,{alpha:T,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,T,I)=>{n.jb("Clip",h,{min:T,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,T)=>{n.jb("Elu",h,{alpha:T})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,T)=>{n.jb("LeakyRelu",h,{alpha:T})},832564:(h,T)=>{n.jb("ThresholdedRelu",h,{alpha:T})},832634:(h,T)=>{n.jb("Cast",h,{to:T})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,T,I,L,U)=>{n.jb("ReduceMean",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833403:(h,T,I,L,U)=>{n.jb("ReduceMax",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833577:(h,T,I,L,U)=>{n.jb("ReduceMin",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833751:(h,T,I,L,U)=>{n.jb("ReduceProd",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833926:(h,T,I,L,U)=>{n.jb("ReduceSum",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834100:(h,T,I,L,U)=>{n.jb("ReduceL1",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834273:(h,T,I,L,U)=>{n.jb("ReduceL2",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834446:(h,T,I,L,U)=>{n.jb("ReduceLogSum",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834623:(h,T,I,L,U)=>{n.jb("ReduceSumSquare",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834803:(h,T,I,L,U)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,T,I)=>{n.jb("Transpose",h,{perm:T?Array.from(se().subarray(Number(T)>>>0,Number(I)>>>0)):[]})},835160:(h,T,I,L)=>{n.jb("DepthToSpace",h,{blocksize:T,mode:Ft(I),format:L?"NHWC":"NCHW"})},835293:(h,T,I,L)=>{n.jb("DepthToSpace",h,{blocksize:T,mode:Ft(I),format:L?"NHWC":"NCHW"})},835426:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr,$s)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:T,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ye>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(xt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft($s)})},835859:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:T,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],outputShape:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},836520:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr,$s)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:T,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ye>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(xt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft($s)})},836953:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:T,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],outputShape:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},837614:(h,T)=>{n.jb("GlobalAveragePool",h,{format:T?"NHWC":"NCHW"})},837705:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},838184:(h,T)=>{n.jb("GlobalAveragePool",h,{format:T?"NHWC":"NCHW"})},838275:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},838754:(h,T)=>{n.jb("GlobalMaxPool",h,{format:T?"NHWC":"NCHW"})},838841:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},839316:(h,T)=>{n.jb("GlobalMaxPool",h,{format:T?"NHWC":"NCHW"})},839403:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},839878:(h,T,I,L,U)=>{n.jb("Gemm",h,{alpha:T,beta:I,transA:L,transB:U})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,T,I,L)=>{n.jb("ArgMax",h,{keepDims:!!T,selectLastIndex:!!I,axis:L})},840144:(h,T,I,L)=>{n.jb("ArgMin",h,{keepDims:!!T,selectLastIndex:!!I,axis:L})},840252:(h,T)=>{n.jb("Softmax",h,{axis:T})},840315:(h,T)=>{n.jb("Concat",h,{axis:T})},840375:(h,T,I,L,U)=>{n.jb("Split",h,{axis:T,numOutputs:I,splitSizes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,T)=>{n.jb("Gather",h,{axis:Number(T)})},840656:(h,T)=>{n.jb("GatherElements",h,{axis:Number(T)})},840735:(h,T)=>{n.jb("GatherND",h,{batch_dims:Number(T)})},840814:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht)=>{n.jb("Resize",h,{antialias:T,axes:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:Ft(U),cubicCoeffA:ue,excludeOutside:Te,extrapolationValue:Oe,keepAspectRatioPolicy:Ft(Ke),mode:Ft(Ye),nearestMode:Ft(ht)})},841176:(h,T,I,L,U,ue,Te)=>{n.jb("Slice",h,{starts:T?Array.from(se().subarray(Number(T)>>>0,Number(I)>>>0)):[],ends:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[],axes:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,T,I)=>{n.jb("InstanceNormalization",h,{epsilon:T,format:I?"NHWC":"NCHW"})},841606:(h,T,I)=>{n.jb("InstanceNormalization",h,{epsilon:T,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,T)=>{n.jb("Einsum",h,{equation:Ft(T)})},841854:(h,T,I,L,U)=>{n.jb("Pad",h,{mode:T,value:I,pads:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},841997:(h,T,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:T,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842166:(h,T,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:T,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842335:(h,T,I)=>{n.jb("CumSum",h,{exclusive:Number(T),reverse:Number(I)})},842432:(h,T,I)=>{n.jb("DequantizeLinear",h,{axis:T,blockSize:I})},842522:(h,T,I,L,U)=>{n.jb("GridSample",h,{align_corners:T,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842692:(h,T,I,L,U)=>{n.jb("GridSample",h,{align_corners:T,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842862:(h,T)=>{n.jb("ScatterND",h,{reduction:Ft(T)})},842947:(h,T,I,L,U,ue,Te,Oe,Ke)=>{n.jb("Attention",h,{numHeads:T,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue,qkvHiddenSizes:Te?Array.from(se().subarray(Number(Oe)>>>0,Number(Oe)+Te>>>0)):[],pastPresentShareBuffer:!!Ke})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr,$s,Ei)=>{n.jb("Conv",h,{format:xt?"NHWC":"NCHW",auto_pad:T,dilations:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:U,kernel_shape:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],pads:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],strides:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],w_is_const:()=>!!F()[Number(It)>>>0],activation:Ft(sr),activation_params:$s?Array.from($e().subarray(Number($s)>>>0,Number(Ei)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,T,I,L,U,ue,Te,Oe,Ke)=>{n.jb("GroupQueryAttention",h,{numHeads:T,kvNumHeads:I,scale:L,softcap:U,doRotary:ue,rotaryInterleaved:Te,smoothSoftmax:Oe,localWindowSize:Ke})},844244:(h,T,I,L)=>{n.jb("LayerNormalization",h,{axis:T,epsilon:I,simplified:!!L})},844355:(h,T,I,L)=>{n.jb("LayerNormalization",h,{axis:T,epsilon:I,simplified:!!L})},844466:(h,T,I,L,U,ue)=>{n.jb("MatMulNBits",h,{k:T,n:I,accuracyLevel:L,bits:U,blockSize:ue})},844593:(h,T,I,L,U,ue)=>{n.jb("MultiHeadAttention",h,{numHeads:T,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue})},844752:(h,T)=>{n.jb("QuickGelu",h,{alpha:T})},844816:(h,T,I,L,U)=>{n.jb("RotaryEmbedding",h,{interleaved:!!T,numHeads:I,rotaryEmbeddingDim:L,scale:U})},844955:(h,T,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:T,simplified:!!I})},845057:(h,T,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:T,simplified:!!I})},845159:(h,T,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:T,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,T)=>n.ac(Number(h),Number(T),n.Fb.dc,n.Fb.errors)};function O(h,T,I){return zr(async()=>{await n.Xb(Number(h),Number(T),Number(I))})}function Y(){return typeof wasmOffsetConverter<"u"}class z{constructor(T){te(this,"name","ExitStatus");this.message=`Program terminated with exit(${T})`,this.status=T}}var J=h=>{h.terminate(),h.onmessage=()=>{}},le=[],ye=h=>{Ge.length==0&&(gs(),Yr(Ge[0]));var T=Ge.pop();if(!T)return 6;lt.push(T),Gt[h.Ab]=T,T.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return T.postMessage(I,h.Mb),0},Ee=0,ke=(h,T,...I)=>{for(var L=2*I.length,U=qn(),ue=wn(8*L),Te=ue>>>3,Oe=0;Oe>>0]=Ke)}return h=So(h,0,L,ue,T),gn(U),h};function Ie(h){if(u)return ke(0,1,h);if(S=h,!(0{if(S=h,u)throw Be(h),"unwind";Ie(h)},Ge=[],lt=[],wt=[],Gt={},Ot=h=>{var T=h.Ab;delete Gt[T],Ge.push(h),lt.splice(lt.indexOf(h),1),h.Ab=0,Gn(T)};function lr(){wt.forEach(h=>h())}var Yr=h=>new Promise(T=>{h.onmessage=U=>{var ue=(U=U.data).Bb;if(U.Gb&&U.Gb!=Ws()){var Te=Gt[U.Gb];Te?Te.postMessage(U,U.Mb):y(`Internal error! Worker sent a message "${ue}" to target pthread ${U.Gb}, but that thread no longer exists!`)}else ue==="checkMailbox"?je():ue==="spawnThread"?ye(U):ue==="cleanupThread"?Ot(Gt[U.hc]):ue==="loaded"?(h.loaded=!0,T(h)):ue==="alert"?alert(`Thread ${U.ic}: ${U.text}`):U.target==="setimmediate"?h.postMessage(U):ue==="callHandler"?n[U.Qb](...U.args):ue&&y(`worker sent an unknown command ${ue}`)},h.onerror=U=>{throw y(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:b,lc:x})});function gs(){var h=new Worker((()=>{let T=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new T("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ge.push(h)}var kr=h=>{R();var T=ce()[h+52>>>2>>>0];h=ce()[h+56>>>2>>>0],ko(T,T-h),gn(T)},Ds=(h,T)=>{Ee=0,h=Io(h,T),0>>=0);throw T>>>=0,I>>>=0,ce()[L.Ib+16>>>2>>>0]=0,ce()[L.Ib+4>>>2>>>0]=T,ce()[L.Ib+8>>>2>>>0]=I,h}function at(h,T,I,L){return u?ke(2,1,h,T,I,L):Zr(h,T,I,L)}function Zr(h,T,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var U=[];return u&&U.length===0?at(h,T>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:U},u?(h.Bb="spawnThread",postMessage(h,U),0):ye(h))}var Ir=typeof TextDecoder<"u"?new TextDecoder:void 0,ws=(h,T=0,I=NaN)=>{var L=(T>>>=0)+I;for(I=T;h[I]&&!(I>=L);)++I;if(16(U=(240&U)==224?(15&U)<<12|ue<<6|Te:(7&U)<<18|ue<<12|Te<<6|63&h[T++])?L+=String.fromCharCode(U):(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else L+=String.fromCharCode(U)}return L},Ft=(h,T)=>(h>>>=0)?ws(W(),h,T):"";function es(h,T,I){return u?ke(3,1,h,T,I):0}function ts(h,T){if(u)return ke(4,1,h,T)}var bs=h=>{for(var T=0,I=0;I=L?T++:2047>=L?T+=2:55296<=L&&57343>=L?(T+=4,++I):T+=3}return T},Xt=(h,T,I)=>{var L=W();if(T>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&h.charCodeAt(++ue)),127>=Te){if(T>=I)break;L[T++>>>0]=Te}else{if(2047>=Te){if(T+1>=I)break;L[T++>>>0]=192|Te>>6}else{if(65535>=Te){if(T+2>=I)break;L[T++>>>0]=224|Te>>12}else{if(T+3>=I)break;L[T++>>>0]=240|Te>>18,L[T++>>>0]=128|Te>>12&63}L[T++>>>0]=128|Te>>6&63}L[T++>>>0]=128|63&Te}}L[T>>>0]=0,h=T-U}else h=0;return h};function De(h,T){if(u)return ke(5,1,h,T)}function Qe(h,T,I){if(u)return ke(6,1,h,T,I)}function et(h,T,I){return u?ke(7,1,h,T,I):0}function Bt(h,T){if(u)return ke(8,1,h,T)}function Or(h,T,I){if(u)return ke(9,1,h,T,I)}function Pr(h,T,I,L){if(u)return ke(10,1,h,T,I,L)}function rs(h,T,I,L){if(u)return ke(11,1,h,T,I,L)}function ss(h,T,I,L){if(u)return ke(12,1,h,T,I,L)}function Ur(h){if(u)return ke(13,1,h)}function ns(h,T){if(u)return ke(14,1,h,T)}function os(h,T,I){if(u)return ke(15,1,h,T,I)}var Wr,yr,Ys=()=>Fe(""),vr=h=>{for(var T="";W()[h>>>0];)T+=Wr[W()[h++>>>0]];return T},Ts={},Es={};function fr(h,T,I={}){return function(L,U,ue={}){var Te=U.name;if(!L)throw new yr(`type "${Te}" must have a positive integer typeid pointer`);if(Es.hasOwnProperty(L)){if(ue.Sb)return;throw new yr(`Cannot register type '${Te}' twice`)}Es[L]=U,Ts.hasOwnProperty(L)&&(U=Ts[L],delete Ts[L],U.forEach(Oe=>Oe()))}(h,T,I)}var zs=(h,T,I)=>{switch(T){case 1:return I?L=>F()[L>>>0]:L=>W()[L>>>0];case 2:return I?L=>re()[L>>>1>>>0]:L=>fe()[L>>>1>>>0];case 4:return I?L=>se()[L>>>2>>>0]:L=>ce()[L>>>2>>>0];case 8:return I?L=>Z[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${T}): ${h}`)}};function Zs(h,T,I){I>>>=0,fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:L=>L,toWireType:function(L,U){if(typeof U!="bigint"&&typeof U!="number")throw U=U===null?"null":(L=typeof U)=="object"||L==="array"||L==="function"?U.toString():""+U,new TypeError(`Cannot convert "${U}" to ${this.name}`);return typeof U=="number"&&(U=BigInt(U)),U},Cb:Ar,readValueFromPointer:zs(T,I,T.indexOf("u")==-1),Db:null})}var Ar=8;function en(h,T,I,L){fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:function(U){return!!U},toWireType:function(U,ue){return ue?I:L},Cb:Ar,readValueFromPointer:function(U){return this.fromWireType(W()[U>>>0])},Db:null})}var Gr=[],xr=[];function Ps(h){9<(h>>>=0)&&--xr[h+1]==0&&(xr[h]=void 0,Gr.push(h))}var ur=h=>{if(!h)throw new yr("Cannot use deleted val. handle = "+h);return xr[h]},_r=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let T=Gr.pop()||xr.length;return xr[T]=h,xr[T+1]=1,T}};function Dr(h){return this.fromWireType(ce()[h>>>2>>>0])}var tn={name:"emscripten::val",fromWireType:h=>{var T=ur(h);return Ps(h),T},toWireType:(h,T)=>_r(T),Cb:Ar,readValueFromPointer:Dr,Db:null};function rn(h){return fr(h>>>0,tn)}var sn=(h,T)=>{switch(T){case 4:return function(I){return this.fromWireType($e()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ue()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${T}): ${h}`)}};function nn(h,T,I){I>>>=0,fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:L=>L,toWireType:(L,U)=>U,Cb:Ar,readValueFromPointer:sn(T,I),Db:null})}function on(h,T,I,L,U){if(h>>>=0,I>>>=0,T=vr(T>>>0),U===-1&&(U=4294967295),U=Oe=>Oe,L===0){var ue=32-8*I;U=Oe=>Oe<>>ue}var Te=T.includes("unsigned")?function(Oe,Ke){return Ke>>>0}:function(Oe,Ke){return Ke};fr(h,{name:T,fromWireType:U,toWireType:Te,Cb:Ar,readValueFromPointer:zs(T,I,L!==0),Db:null})}function Ms(h,T,I){function L(ue){var Te=ce()[ue>>>2>>>0];return ue=ce()[ue+4>>>2>>>0],new U(F().buffer,ue,Te)}var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][T];fr(h>>>=0,{name:I=vr(I>>>0),fromWireType:L,Cb:Ar,readValueFromPointer:L},{Sb:!0})}function an(h,T){fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:function(I){for(var L,U=ce()[I>>>2>>>0],ue=I+4,Te=ue,Oe=0;Oe<=U;++Oe){var Ke=ue+Oe;Oe!=U&&W()[Ke>>>0]!=0||(Te=Ft(Te,Ke-Te),L===void 0?L=Te:(L+="\0",L+=Te),Te=Ke+1)}return Br(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var U=typeof L=="string";if(!(U||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new yr("Cannot pass non-string to std::string");var ue=U?bs(L):L.length,Te=fn(4+ue+1),Oe=Te+4;if(ce()[Te>>>2>>>0]=ue,U)Xt(L,Oe,ue+1);else if(U)for(U=0;U>>0]=Ke}else for(U=0;U>>0]=L[U];return I!==null&&I.push(Br,Te),Te},Cb:Ar,readValueFromPointer:Dr,Db(I){Br(I)}})}var Bs=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ln=(h,T)=>{for(var I=h>>1,L=I+T/2;!(I>=L)&&fe()[I>>>0];)++I;if(32<(I<<=1)-h&&Bs)return Bs.decode(W().slice(h,I));for(I="",L=0;!(L>=T/2);++L){var U=re()[h+2*L>>>1>>>0];if(U==0)break;I+=String.fromCharCode(U)}return I},un=(h,T,I)=>{if(I??(I=2147483647),2>I)return 0;var L=T;I=(I-=2)<2*h.length?I/2:h.length;for(var U=0;U>>1>>>0]=ue,T+=2}return re()[T>>>1>>>0]=0,T-L},ys=h=>2*h.length,dn=(h,T)=>{for(var I=0,L="";!(I>=T/4);){var U=se()[h+4*I>>>2>>>0];if(U==0)break;++I,65536<=U?(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U)):L+=String.fromCharCode(U)}return L},he=(h,T,I)=>{if(T>>>=0,I??(I=2147483647),4>I)return 0;var L=T;I=L+I-4;for(var U=0;U=ue&&(ue=65536+((1023&ue)<<10)|1023&h.charCodeAt(++U)),se()[T>>>2>>>0]=ue,(T+=4)+4>I)break}return se()[T>>>2>>>0]=0,T-L},k=h=>{for(var T=0,I=0;I=L&&++I,T+=4}return T};function N(h,T,I){if(h>>>=0,T>>>=0,I=vr(I>>>=0),T===2)var L=ln,U=un,ue=ys,Te=Oe=>fe()[Oe>>>1>>>0];else T===4&&(L=dn,U=he,ue=k,Te=Oe=>ce()[Oe>>>2>>>0]);fr(h,{name:I,fromWireType:Oe=>{for(var Ke,Ye=ce()[Oe>>>2>>>0],ht=Oe+4,xt=0;xt<=Ye;++xt){var It=Oe+4+xt*T;xt!=Ye&&Te(It)!=0||(ht=L(ht,It-ht),Ke===void 0?Ke=ht:(Ke+="\0",Ke+=ht),ht=It+T)}return Br(Oe),Ke},toWireType:(Oe,Ke)=>{if(typeof Ke!="string")throw new yr(`Cannot pass non-string to C++ string type ${I}`);var Ye=ue(Ke),ht=fn(4+Ye+T);return ce()[ht>>>2>>>0]=Ye/T,U(Ke,ht+4,Ye+T),Oe!==null&&Oe.push(Br,ht),ht},Cb:Ar,readValueFromPointer:Dr,Db(Oe){Br(Oe)}})}function Q(h,T){fr(h>>>=0,{Tb:!0,name:T=vr(T>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){_n(h>>>0,!l,1,!a,131072,!1),lr()}var de=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(se(),h>>>2,h).value.then(je),h+=128,Atomics.store(se(),h>>>2,1))}var je=()=>{var h=Ws();h&&(ve(h),de(Hn))};function He(h,T){(h>>>=0)==T>>>0?setTimeout(je):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=Gt[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function Je(h,T,I,L,U){for(T>>>=0,L/=2,We.length=L,I=U>>>0>>>3,U=0;U>>0];return(T?Ve[T]:To[h])(...We)}var dt=()=>{Ee=0};function vt(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):Ot(Gt[h])}function Et(h){}var Rt=(h,T)=>{var I=Es[h];if(I===void 0)throw h=Eo(h),I=vr(h),Br(h),new yr(`${T} has unknown type ${I}`);return I},kt=(h,T,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ce()[T>>>2>>>0]=_r(L)),h};function Kt(h,T,I){return T>>>=0,I>>>=0,h=ur(h>>>0),T=Rt(T,"emval::as"),kt(T,I,h)}function Mr(h,T){return T>>>=0,h=ur(h>>>0),(T=Rt(T,"emval::as")).toWireType(null,h)}var dr=h=>{try{h()}catch(T){Fe(T)}},cr=0,Nt=null,Kr=0,Dt=[],rr={},gr={},Hr=0,Lr=null,Yt=[];function zr(h){return function(T){if(!ae){if(cr===0){var I=!1,L=!1;T((U=0)=>{if(!ae&&(Kr=U,I=!0,L)){cr=2,dr(()=>Fo(Nt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),U=!1;try{var ue=function(){var Ke=se()[Nt+8>>>2>>>0];return Ke=nt[gr[Ke]],--Ee,Ke()}()}catch(Ke){ue=Ke,U=!0}var Te=!1;if(!Nt){var Oe=Lr;Oe&&(Lr=null,(U?Oe.reject:Oe.resolve)(ue),Te=!0)}if(U&&!Te)throw ue}}),L=!0,I||(cr=1,Nt=function(){var U=fn(65548),ue=U+12;ce()[U>>>2>>>0]=ue,ce()[U+4>>>2>>>0]=ue+65536,ue=Dt[0];var Te=rr[ue];return Te===void 0&&(Te=Hr++,rr[ue]=Te,gr[Te]=ue),ue=Te,se()[U+8>>>2>>>0]=ue,U}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),dr(()=>Xn(Nt)))}else cr===2?(cr=0,dr(Qn),Br(Nt),Nt=null,Yt.forEach(de)):Fe(`invalid state: ${cr}`);return Kr}}(T=>{h().then(T)})}function or(h){return h>>>=0,zr(async()=>{var T=await ur(h);return _r(T)})}var Vt=[];function Zt(h,T,I,L){return I>>>=0,L>>>=0,(h=Vt[h>>>0])(null,T=ur(T>>>0),I,L)}var er={},tr=h=>{var T=er[h];return T===void 0?vr(h):T};function Rs(h,T,I,L,U){return I>>>=0,L>>>=0,U>>>=0,(h=Vt[h>>>0])(T=ur(T>>>0),T[I=tr(I)],L,U)}var cn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function ei(h){return(h>>>=0)==0?_r(cn()):(h=tr(h),_r(cn()[h]))}var ti=h=>{var T=Vt.length;return Vt.push(h),T},ri=(h,T)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},Cs=(h,T)=>Object.defineProperty(T,"name",{value:h});function si(h,T,I){var L=(T=ri(h,T>>>0)).shift();h--;var U=`return function (obj, func, destructorsRef, args) { -`,ue=0,Te=[];I===0&&Te.push("obj");for(var Oe=["retType"],Ke=[L],Ye=0;Yeht.name).join(", ")}) => ${L.name}>`,ti(Cs(I,h))}function ni(h){return h=tr(h>>>0),_r(n[h])}function oi(h,T){return T>>>=0,h=ur(h>>>0),T=ur(T),_r(h[T])}function ii(h){9<(h>>>=0)&&(xr[h+1]+=1)}function ai(){return _r([])}function lo(h){h=ur(h>>>0);for(var T=Array(h.length),I=0;I>>0))}function ui(){return _r({})}function uo(h){for(var T=ur(h>>>=0);T.length;){var I=T.pop();T.pop()(I)}Ps(h)}function di(h,T,I){T>>>=0,I>>>=0,h=ur(h>>>0),T=ur(T),I=ur(I),h[T]=I}function co(h,T){return T>>>=0,h=(h=Rt(h>>>0,"_emval_take_value")).readValueFromPointer(T),_r(h)}function ci(h,T){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[T>>>2>>>0]=h.getUTCSeconds(),se()[T+4>>>2>>>0]=h.getUTCMinutes(),se()[T+8>>>2>>>0]=h.getUTCHours(),se()[T+12>>>2>>>0]=h.getUTCDate(),se()[T+16>>>2>>>0]=h.getUTCMonth(),se()[T+20>>>2>>>0]=h.getUTCFullYear()-1900,se()[T+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,se()[T+28>>>2>>>0]=h}var Rn=h=>h%4==0&&(h%100!=0||h%400==0),pi=[0,31,60,91,121,152,182,213,244,274,305,335],po=[0,31,59,90,120,151,181,212,243,273,304,334];function ho(h,T){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[T>>>2>>>0]=h.getSeconds(),se()[T+4>>>2>>>0]=h.getMinutes(),se()[T+8>>>2>>>0]=h.getHours(),se()[T+12>>>2>>>0]=h.getDate(),se()[T+16>>>2>>>0]=h.getMonth(),se()[T+20>>>2>>>0]=h.getFullYear()-1900,se()[T+24>>>2>>>0]=h.getDay();var I=(Rn(h.getFullYear())?pi:po)[h.getMonth()]+h.getDate()-1|0;se()[T+28>>>2>>>0]=I,se()[T+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),se()[T+32>>>2>>>0]=h}function hi(h){h>>>=0;var T=new Date(se()[h+20>>>2>>>0]+1900,se()[h+16>>>2>>>0],se()[h+12>>>2>>>0],se()[h+8>>>2>>>0],se()[h+4>>>2>>>0],se()[h>>>2>>>0],0),I=se()[h+32>>>2>>>0],L=T.getTimezoneOffset(),U=new Date(T.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(T.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ue,U);return 0>I?se()[h+32>>>2>>>0]=+(U!=ue&&Te==L):0>>2>>>0]=T.getDay(),I=(Rn(T.getFullYear())?pi:po)[T.getMonth()]+T.getDate()-1|0,se()[h+28>>>2>>>0]=I,se()[h>>>2>>>0]=T.getSeconds(),se()[h+4>>>2>>>0]=T.getMinutes(),se()[h+8>>>2>>>0]=T.getHours(),se()[h+12>>>2>>>0]=T.getDate(),se()[h+16>>>2>>>0]=T.getMonth(),se()[h+20>>>2>>>0]=T.getYear(),h=T.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function pn(h,T,I,L,U,ue,Te){return u?ke(16,1,h,T,I,L,U,ue,Te):-52}function mo(h,T,I,L,U,ue){if(u)return ke(17,1,h,T,I,L,U,ue)}var js={},mi=()=>performance.timeOrigin+performance.now();function fo(h,T){if(u)return ke(18,1,h,T);if(js[h]&&(clearTimeout(js[h].id),delete js[h]),!T)return 0;var I=setTimeout(()=>{delete js[h],de(()=>$o(h,performance.timeOrigin+performance.now()))},T);return js[h]={id:I,qc:T},0}function fi(h,T,I,L){h>>>=0,T>>>=0,I>>>=0,L>>>=0;var U=new Date().getFullYear(),ue=new Date(U,0,1).getTimezoneOffset();U=new Date(U,6,1).getTimezoneOffset();var Te=Math.max(ue,U);ce()[h>>>2>>>0]=60*Te,se()[T>>>2>>>0]=+(ue!=U),h=(T=Oe=>{var Ke=Math.abs(Oe);return`UTC${0<=Oe?"-":"+"}${String(Math.floor(Ke/60)).padStart(2,"0")}${String(Ke%60).padStart(2,"0")}`})(ue),T=T(U),UDate.now();function gi(h,T,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Z[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Ns=[],jn=(h,T)=>{Ns.length=0;for(var I;I=W()[h++>>>0];){var L=I!=105;T+=(L&=I!=112)&&T%8?4:0,Ns.push(I==112?ce()[T>>>2>>>0]:I==106?Z[T>>>3]:I==105?se()[T>>>2>>>0]:Ue()[T>>>3>>>0]),T+=L?8:4}return Ns};function wi(h,T,I){return h>>>=0,T=jn(T>>>0,I>>>0),Ve[h](...T)}function _o(h,T,I){return h>>>=0,T=jn(T>>>0,I>>>0),Ve[h](...T)}var Ss=()=>{};function bi(h,T){return y(Ft(h>>>0,T>>>0))}var ba=()=>{throw Ee+=1,"unwind"};function Mi(){return 4294901760}var Ma=()=>navigator.hardwareConcurrency;function yi(){return Fe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function go(h){h>>>=0;var T=W().length;if(h<=T||4294901760=I;I*=2){var L=T*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-b.buffer.byteLength+65535)/65536|0;try{b.grow(L),R();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1}var hn=()=>(Fe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Vs={},wo=h=>{h.forEach(T=>{hn()})};function vi(){var h=Error().stack.toString().split(` -`);return h[0]=="Error"&&h.shift(),wo(h),Vs.Lb=hn(),Vs.cc=h,Vs.Lb}function xi(h,T,I){if(h>>>=0,T>>>=0,Vs.Lb==h)var L=Vs.cc;else(L=Error().stack.toString().split(` -`))[0]=="Error"&&L.shift(),wo(L);for(var U=3;L[U]&&hn()!=h;)++U;for(h=0;h>>2>>>0]=hn();return h}var Us,Nn={},bo=()=>{if(!Us){var h,T={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(h in Nn)Nn[h]===void 0?delete T[h]:T[h]=Nn[h];var I=[];for(h in T)I.push(`${h}=${T[h]}`);Us=I}return Us};function Mo(h,T){if(u)return ke(19,1,h,T);h>>>=0,T>>>=0;var I=0;return bo().forEach((L,U)=>{var ue=T+I;for(U=ce()[h+4*U>>>2>>>0]=ue,ue=0;ue>>0]=L.charCodeAt(ue);F()[U>>>0]=0,I+=L.length+1}),0}function Vn(h,T){if(u)return ke(20,1,h,T);h>>>=0,T>>>=0;var I=bo();ce()[h>>>2>>>0]=I.length;var L=0;return I.forEach(U=>L+=U.length+1),ce()[T>>>2>>>0]=L,0}function yo(h){return u?ke(21,1,h):52}function vo(h,T,I,L){return u?ke(22,1,h,T,I,L):52}function Un(h,T,I,L){return u?ke(23,1,h,T,I,L):70}var Ti=[null,[],[]];function xo(h,T,I,L){if(u)return ke(24,1,h,T,I,L);T>>>=0,I>>>=0,L>>>=0;for(var U=0,ue=0;ue>>2>>>0],Oe=ce()[T+4>>>2>>>0];T+=8;for(var Ke=0;Ke>>0],ht=Ti[h];Ye===0||Ye===10?((h===1?E:y)(ws(ht)),ht.length=0):ht.push(Ye)}U+=Oe}return ce()[L>>>2>>>0]=U,0}u||function(){for(var h=n.numThreads-1;h--;)gs();le.unshift(()=>{Me++,function(T){u?T():Promise.all(Ge.map(Yr)).then(T)}(()=>Ae())})}();for(var Wn=Array(256),mn=0;256>mn;++mn)Wn[mn]=String.fromCharCode(mn);Wr=Wn,yr=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},xr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>xr.length/2-5-Gr.length;var nt,To=[Ie,Be,at,es,ts,De,Qe,et,Bt,Or,Pr,rs,ss,Ur,ns,os,pn,mo,fo,Mo,Vn,yo,vo,Un,xo];(async function(){function h(L,U){return nt=L.exports,nt=function(){var ue=nt,Te={};for(let[Oe,Ke]of Object.entries(ue))Te[Oe]=typeof Ke=="function"?(...Ye)=>{Dt.push(Oe);try{return Ke(...Ye)}finally{ae||(Dt.pop(),Nt&&cr===1&&Dt.length===0&&(cr=0,Ee+=1,dr(Ao),typeof Fibers<"u"&&Fibers.rc()))}}:Ke;return Te}(),nt=function(){var ue=nt,Te=Ke=>Ye=>Ke(Ye)>>>0,Oe=Ke=>()=>Ke()>>>0;return(ue=Object.assign({},ue)).Da=Te(ue.Da),ue.fb=Oe(ue.fb),ue.hb=Te(ue.hb),ue.tb=Te(ue.tb),ue.ub=Oe(ue.ub),ue.__cxa_get_exception_ptr=Te(ue.__cxa_get_exception_ptr),ue}(),wt.push(nt.ib),x=U,Ae(),nt}Me++;var T=ze();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(T,(U,ue)=>{h(U,ue),L(U.exports)})});if(u)return new Promise(L=>{we=U=>{var ue=new WebAssembly.Instance(U,ze());L(h(ue,U))}});xe??(xe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",w):w+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href);try{var I=await async function(L){var U=xe;if(!me&&typeof WebAssembly.instantiateStreaming=="function"&&!V(U))try{var ue=fetch(U,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ue,L)}catch(Te){y(`wasm streaming compile failed: ${Te}`),y("falling back to ArrayBuffer instantiation")}return async function(Te,Oe){try{var Ke=await async function(Ye){if(!me)try{var ht=await _(Ye);return new Uint8Array(ht)}catch{}if(Ye==xe&&me)Ye=new Uint8Array(me);else{if(!f)throw"both async and sync fetching of the wasm failed";Ye=f(Ye)}return Ye}(Te);return await WebAssembly.instantiate(Ke,Oe)}catch(Ye){y(`failed to asynchronously prepare wasm: ${Ye}`),Fe(Ye)}}(U,L)}(T);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var Eo=h=>(Eo=nt.Da)(h),Po=()=>(Po=nt.Ea)();n._OrtInit=(h,T)=>(n._OrtInit=nt.Fa)(h,T),n._OrtGetLastError=(h,T)=>(n._OrtGetLastError=nt.Ga)(h,T),n._OrtCreateSessionOptions=(h,T,I,L,U,ue,Te,Oe,Ke,Ye)=>(n._OrtCreateSessionOptions=nt.Ha)(h,T,I,L,U,ue,Te,Oe,Ke,Ye),n._OrtAppendExecutionProvider=(h,T,I,L,U)=>(n._OrtAppendExecutionProvider=nt.Ia)(h,T,I,L,U),n._OrtAddFreeDimensionOverride=(h,T,I)=>(n._OrtAddFreeDimensionOverride=nt.Ja)(h,T,I),n._OrtAddSessionConfigEntry=(h,T,I)=>(n._OrtAddSessionConfigEntry=nt.Ka)(h,T,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=nt.La)(h),n._OrtCreateSession=(h,T,I)=>(n._OrtCreateSession=nt.Ma)(h,T,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=nt.Na)(h),n._OrtGetInputOutputCount=(h,T,I)=>(n._OrtGetInputOutputCount=nt.Oa)(h,T,I),n._OrtGetInputOutputMetadata=(h,T,I,L)=>(n._OrtGetInputOutputMetadata=nt.Pa)(h,T,I,L),n._OrtFree=h=>(n._OrtFree=nt.Qa)(h),n._OrtCreateTensor=(h,T,I,L,U,ue)=>(n._OrtCreateTensor=nt.Ra)(h,T,I,L,U,ue),n._OrtGetTensorData=(h,T,I,L,U)=>(n._OrtGetTensorData=nt.Sa)(h,T,I,L,U),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=nt.Ta)(h),n._OrtCreateRunOptions=(h,T,I,L)=>(n._OrtCreateRunOptions=nt.Ua)(h,T,I,L),n._OrtAddRunConfigEntry=(h,T,I)=>(n._OrtAddRunConfigEntry=nt.Va)(h,T,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=nt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=nt.Xa)(h),n._OrtBindInput=(h,T,I)=>(n._OrtBindInput=nt.Ya)(h,T,I),n._OrtBindOutput=(h,T,I,L)=>(n._OrtBindOutput=nt.Za)(h,T,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=nt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=nt.$a)(h),n._OrtRunWithBinding=(h,T,I,L,U)=>(n._OrtRunWithBinding=nt.ab)(h,T,I,L,U),n._OrtRun=(h,T,I,L,U,ue,Te,Oe)=>(n._OrtRun=nt.bb)(h,T,I,L,U,ue,Te,Oe),n._OrtEndProfiling=h=>(n._OrtEndProfiling=nt.cb)(h),n._JsepOutput=(h,T,I)=>(n._JsepOutput=nt.db)(h,T,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=nt.eb)(h);var Ws=()=>(Ws=nt.fb)(),Br=n._free=h=>(Br=n._free=nt.gb)(h),fn=n._malloc=h=>(fn=n._malloc=nt.hb)(h),_n=(h,T,I,L,U,ue)=>(_n=nt.kb)(h,T,I,L,U,ue),Co=()=>(Co=nt.lb)(),So=(h,T,I,L,U)=>(So=nt.mb)(h,T,I,L,U),Gn=h=>(Gn=nt.nb)(h),Kn=h=>(Kn=nt.ob)(h),$o=(h,T)=>($o=nt.pb)(h,T),Hn=()=>(Hn=nt.qb)(),ko=(h,T)=>(ko=nt.rb)(h,T),gn=h=>(gn=nt.sb)(h),wn=h=>(wn=nt.tb)(h),qn=()=>(qn=nt.ub)(),Io=n.dynCall_ii=(h,T)=>(Io=n.dynCall_ii=nt.vb)(h,T),Xn=h=>(Xn=nt.wb)(h),Ao=()=>(Ao=nt.xb)(),Fo=h=>(Fo=nt.yb)(h),Qn=()=>(Qn=nt.zb)();return n.stackSave=()=>qn(),n.stackRestore=h=>gn(h),n.stackAlloc=h=>wn(h),n.setValue=function(h,T,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":F()[h>>>0]=T;break;case"i16":re()[h>>>1>>>0]=T;break;case"i32":se()[h>>>2>>>0]=T;break;case"i64":Z[h>>>3]=BigInt(T);break;case"float":$e()[h>>>2>>>0]=T;break;case"double":Ue()[h>>>3>>>0]=T;break;case"*":ce()[h>>>2>>>0]=T;break;default:Fe(`invalid type for setValue: ${I}`)}},n.getValue=function(h,T="i8"){switch(T.endsWith("*")&&(T="*"),T){case"i1":case"i8":return F()[h>>>0];case"i16":return re()[h>>>1>>>0];case"i32":return se()[h>>>2>>>0];case"i64":return Z[h>>>3];case"float":return $e()[h>>>2>>>0];case"double":return Ue()[h>>>3>>>0];case"*":return ce()[h>>>2>>>0];default:Fe(`invalid type for getValue: ${T}`)}},n.UTF8ToString=Ft,n.stringToUTF8=Xt,n.lengthBytesUTF8=bs,function h(){if(0{Ju(),Bl=typeof location>"u"?void 0:location.origin,Au=import.meta.url>"file:"&&import.meta.url<"file;",Pf=()=>{{if(Au){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,Bl).href}return import.meta.url}},jr=Pf(),kb=()=>{if(jr&&!jr.startsWith("blob:"))return jr.substring(0,jr.lastIndexOf("/")+1)},Xi=(e,r)=>{try{let t=r??jr;return(t?new URL(e,t):new URL(e)).origin===Bl}catch{return!1}},Cf=(e,r)=>{let t=r??jr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},Sf=(e,r)=>`${r??"./"}${e}`,Rl=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},$f=async e=>(await import(e)).default,jl=(ex(),Jo(Pb)).default,Ib=async()=>{if(!jr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Xi(jr))return[void 0,jl()];let e=await Rl(jr);return[e,jl(e)]},Nl=(tx(),Jo(Sb)).default,Ab=async(e,r,t)=>{if(!e&&!r&&Nl&&jr&&Xi(jr))return[void 0,Nl];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??Cf(s,r),n=t&&o&&!Xi(o,r),i=n?await Rl(o):o??Sf(s,r);return[n?i:void 0,await $f(i)]}}}),Vl,Qi,zo,Ul,kf,If,Af,Zu,zt,zn=Re(()=>{Yu(),Qi=!1,zo=!1,Ul=!1,kf=()=>{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}},If=()=>{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}},Af=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Zu=async e=>{if(Qi)return Promise.resolve();if(zo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ul)throw new Error("previous call to 'initializeWebAssembly()' failed.");zo=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Af())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!If())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=kf();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 o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[d,c]=await Ab(a,n,t>1),_=!1,f=[];if(r>0&&f.push(new Promise(v=>{setTimeout(()=>{_=!0,v()},r)})),f.push(new Promise((v,$)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(u||n)w.locateFile=g=>u??n+g;else if(a&&a.indexOf("blob:")!==0)w.locateFile=g=>new URL(g,a).href;else if(d){let g=kb();g&&(w.locateFile=C=>g+C)}c(w).then(g=>{zo=!1,Qi=!0,Vl=g,v(),d&&URL.revokeObjectURL(d)},g=>{zo=!1,Ul=!0,$(g)})})),await Promise.race(f),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},zt=()=>{if(Qi&&Vl)return Vl;throw new Error("WebAssembly is not initialized yet.")}}),ps,pa,At,ed=Re(()=>{zn(),ps=(e,r)=>{let t=zt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},pa=(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(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")pa(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},At=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),Fb,rx=Re(()=>{zn(),ed(),Fb=e=>{let r=zt(),t=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.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)o.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&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=ps(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&pa(e.extra,"",new WeakSet,(i,a)=>{let l=ps(i,s),u=ps(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&At(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),Ff,Of,Df,Bo,Lf,Ob,sx=Re(()=>{zn(),ed(),Ff=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}`)}},Of=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Df=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)},Bo=(e,r,t,s)=>{let o=ps(r,s),n=ps(t,s);zt()._OrtAddSessionConfigEntry(e,o,n)!==0&&At(`Can't set a session config entry: ${r} - ${t}.`)},Lf=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&Bo(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);Bo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ps(o,t),a=n.length,l=0,u=0;if(a>0){l=zt()._malloc(a*zt().PTR_SIZE),t.push(l),u=zt()._malloc(a*zt().PTR_SIZE),t.push(u);for(let p=0;p{let r=zt(),t=0,s=[],o=e||{};Df(o);try{let n=Ff(o.graphOptimizationLevel??"all"),i=Of(o.executionMode??"sequential"),a=typeof o.logId=="string"?ps(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?ps(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&At("Can't create session options."),o.executionProviders&&await Lf(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Bo(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[d,c]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof c!="number"||!Number.isInteger(c)||c<0)throw new Error(`free dimension override value must be a non-negative integer: ${c}`);let _=ps(d,s);r._OrtAddFreeDimensionOverride(t,_,c)!==0&&At(`Can't set a free dimension override: ${d} - ${c}.`)}return o.extra!==void 0&&pa(o.extra,"",new WeakSet,(d,c)=>{Bo(t,d,c,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),ro,Fs,An,td,ha,rd,sd,Fu,ut=Re(()=>{ro=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}`)}},Fs=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}`)}},An=(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((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},td=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}`)}},ha=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}`)}},rd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",sd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Fu=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}`)}}}),nd,Db=Re(()=>{Ju(),nd=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 o=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 i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zf,Bf,Rf,jf,od,Nf,Tt,Os=Re(()=>{ut(),zf=["V","I","W","E","F"],Bf=(e,r)=>{console.log(`[${zf[e]},${new Date().toISOString()}]${r}`)},od=(e,r)=>{Rf=e,jf=r},Nf=(e,r)=>{let t=ha(e),s=ha(Rf);t>=s&&Bf(t,typeof r=="function"?r():r)},Tt=(...e)=>{jf&&Nf(...e)}}),Vf,oo,be,ma,Lb,zb,Bb,ft=Re(()=>{Vf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},oo=class{static calcShape(e,r,t=!1){let s=e.length,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=Vf.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},be=class da{static size(r){return da.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}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 da.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 da.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+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((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ma=class Ho{static adjustPoolAttributes(r,t,s,o,n,i){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]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,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(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ut(),id=(e,r)=>new(td(r))(e)}),Ou,Wl,Uf,Gl,Wf,Kl,Hl,ql,Gf,jb,nx=Re(()=>{Os(),Ou=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Wl=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Uf=1,Gl=()=>Uf++,Wf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Kl=(e,r)=>{let t=Wf.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Hl=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Kl(this.dataType,this.tensorShape)}destroy(){Tt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Wl(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):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,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},ql=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 o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",Tt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Kl(o,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 a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=Ou(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Tt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Wl(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Gf=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=Gl();return this.tensorTrackersById.set(e,new ql(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,o){Tt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Tt("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 o=this.getMLContext(e),n=Gl(),i=new Hl({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new ql(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Tt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(u,1)[0];return d.sessionId=e,d}Tt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Hl({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},jb=(...e)=>new Gf(...e)}),Ji,Kf,Nb,ox=Re(()=>{ut(),zn(),Rb(),nx(),Os(),Ji=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Kf=(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((o,n)=>o===s[n]&&e[o]===r[o])},Nb=class{constructor(e){this.tensorManager=jb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,od(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Tt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Tt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Tt("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=>Kf(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(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Tt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=Ji.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){Tt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Ji.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!zt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Tt("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 id(t,r)}}registerMLTensor(e,r,t,s){let o=Ji.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return Tt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=Ou(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Tt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),ad=Re(()=>{}),Xl,Yi,Zi,Hf,qf,Ql,Du,Xf,Vb,ix=Re(()=>{Os(),ad(),Xl=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]]),Yi=[],Zi=e=>Math.ceil(Number(e)/16)*16,Hf=e=>{for(let r=0;rqf++,Du=async(e,r,t,s)=>{let o=Zi(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),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()}},Xf=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 Xl)Yi.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=Zi(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);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,o)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),Tt("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 o=Zi(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Tt("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=Ql();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Tt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Tt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Hf(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?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 i={id:Ql(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Tt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}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 Tt("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 Du(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=Xl.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&&(Tt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Vb=(...e)=>new Xf(...e)}),Qf,$t,Jt=Re(()=>{Qf=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}},$t=e=>new Qf(e)}),io,ea,mr,Er,st,qt,Lu,no,Qs,rt,Ro,Pe,Ze,Ub,ld,Jf,Wb,_t=Re(()=>{ut(),ft(),io=64,ea=(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}`)}},mr=(e,r=1)=>{let t=ea(e,r);return typeof t=="string"?t:t[0]},Er=(e,r=1)=>{let t=ea(e,r);return typeof t=="string"?t:t[1]},st=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:be.computeStrides(t)})}),r},qt=e=>e%4===0?4:e%2===0?2:1,Lu=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,no=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Qs=(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,Ro=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=ea(r,o),p=typeof u=="string"?u:u[1],d=typeof u=="string"?u:u[0],c={indices:l,value:p,storage:d,tensor:r},_=V=>typeof V=="string"?V:`${V}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},v=n?"uniforms.":"",$=`${v}${e}_shape`,w=`${v}${e}_strides`,g="";for(let V=0;V ${c.indices} { - var indices: ${c.indices}; - var current = offset; - ${g} - return indices; - }`,E=V=>(f.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),y=[];if(i>=2)for(let V=i-1;V>=0;V--)y.push(`${rt(w,V,i)} * (indices[${V}])`);let b=i<2?"":` - fn i2o_${e}(indices: ${c.indices}) -> u32 { - return ${y.join("+")}; - }`,x=V=>(f.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),S=(...V)=>i===0?"0u":`${c.indices}(${V.map(_).join(",")})`,A=(V,F)=>i<2?`${V}`:`${rt(V,F,i)}`,B=(V,F,W)=>i<2?`${V}=${W};`:`${rt(V,F,i)}=${W};`,K={},G=(V,F)=>{f.broadcastedIndicesToOffset=!0;let W=`${F.name}broadcastedIndicesTo${e}Offset`;if(W in K)return`${W}(${V})`;let re=[];for(let fe=i-1;fe>=0;fe--){let se=F.indicesGet("outputIndices",fe+F.rank-i);re.push(`${A(w,fe)} * (${se} % ${A($,fe)})`)}return K[W]=`fn ${W}(outputIndices: ${F.type.indices}) -> u32 { - return ${re.length>0?re.join("+"):"0u"}; - }`,`${W}(${V})`},j=(V,F)=>(()=>{if(c.storage===c.value)return`${e}[${V}]=${F};`;if(c.storage==="vec2"&&c.value==="i32")return`${e}[${V}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(c.storage==="vec2"&&c.value==="u32")return`${e}[${V}]=vec2(u32(${F}), 0u);`;if(c.storage==="u32"&&c.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),ee=V=>(()=>{if(c.storage===c.value)return`${e}[${V}]`;if(c.storage==="vec2"&&c.value==="i32")return`i32(${e}[${V}].x)`;if(c.storage==="vec2"&&c.value==="u32")return`u32(${e}[${V}].x)`;if(c.storage==="u32"&&c.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),H=i<2?"":` - fn get_${e}ByIndices(indices: ${c.indices}) -> ${p} { - return ${ee(`i2o_${e}(indices)`)}; - }`,Z=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` - fn get_${e}(${V}) -> ${p} { - return get_${e}ByIndices(${S(F)}); - }`})(),X=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let F=V.map(_).join(",");return i===0?ee("0u"):i===1?ee(F[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${F})`)},oe=V=>i<2?ee(V):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${V})`),me=i<2?"":` - fn set_${e}ByIndices(indices: ${c.indices}, value: ${p}) { - ${j(`i2o_${e}(indices)`,"value")} - }`,ae=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` - fn set_${e}(${V}, value: ${p}) { - set_${e}ByIndices(${S(F)}, value); - }`})();return{impl:()=>{let V=[],F=!1;return f.offsetToIndices&&(V.push(C),F=!0),f.indicesToOffset&&(V.push(b),F=!0),f.broadcastedIndicesToOffset&&(Object.values(K).forEach(W=>V.push(W)),F=!0),f.set&&(V.push(ae),F=!0),f.setByIndices&&(V.push(me),F=!0),f.get&&(V.push(Z),F=!0),f.getByIndices&&(V.push(H),F=!0),!n&&F&&V.unshift(`const ${$} = ${c.indices}(${t.join(",")});`,`const ${w} = ${c.indices}(${be.computeStrides(t).join(",")});`),V.join(` -`)},type:c,offsetToIndices:E,indicesToOffset:x,broadcastedIndicesToOffset:G,indices:S,indicesGet:A,indicesSet:B,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let F=V[i];if(typeof F!="string")throw new Error("value must be string");let W=V.slice(0,i).map(_).join(",");return i===0?j("0u",F):i===1?j(W[0],F):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${W}, ${F})`)},setByOffset:j,setByIndices:(V,F)=>i<2?j(V,F):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${F});`),get:X,getByOffset:ee,getByIndices:oe,usage:s,name:e,strides:w,shape:$,rank:i}},Pe=(e,r,t,s=1)=>Ro(e,r,t,"input",s),Ze=(e,r,t,s=1)=>Ro(e,r,t,"output",s),Ub=(e,r,t)=>Ro(e,r,t,"atomicOutput",1),ld=(e,r,t,s=1)=>Ro(e,r,t,"internal",s),Jf=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=io){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 o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@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, - @builtin(local_invocation_id) local_id : vec3, - @builtin(local_invocation_index) local_idx : u32, - @builtin(workgroup_id) workgroup_id : vec3, - @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; - let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + - workgroup_id.y * num_workgroups[0] + workgroup_id.x; - let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) - fn main(${n}) { - ${i} - `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` -`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` - 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])}},Wb=(e,r)=>new Jf(e,r)}),Yf,Jl,Zf,e_,t_,r_,Vr,Gb,Kb,Js=Re(()=>{ut(),ft(),Jt(),_t(),Yf=(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}`)},Jl=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Zf=(e,r)=>be.sortBasedOnPerm(e,Jl(e.length,r)),e_=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { - var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=Jl(s,r),n=Zf(e.dims,o),i=e.dims,a=n,l=s<2||r_(o,e.dims),u;if(l)return u=f=>{let v=Pe("input",t,i,4),$=Ze("output",t,a,4);return` - ${f.registerUniform("output_size","u32").declareVariables(v,$)} - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let f=be.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:u};let{newShape:p,newPerm:d}=t_(e.dims,o),c=be.areEqual(d,[2,3,1]),_=be.areEqual(d,[3,1,2]);if(p.length===2||c||_){i=c?[p[0],p[1]*p[2]]:_?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let f=16;return u=v=>{let $=Pe("a",t,i.length),w=Ze("output",t,a.length);return` - ${v.registerUniform("output_size","u32").declareVariables($,w)} - var tile : array, ${f}>; - ${v.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 * ${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] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)}; - } - workgroupBarrier(); - - 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]) { - ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} - } - }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let v=be.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:v},...st(i,a)]}},getShaderSource:u}}return u=f=>{let v=Pe("a",t,i.length),$=Ze("output",t,a.length);return` - ${f.registerUniform("output_size","u32").declareVariables(v,$)} - - ${e_(o,s,v,$)} - - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${$.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${$.setByOffset("global_idx",v.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let f=be.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...st(i,a)]}},getShaderSource:u}},Gb=(e,r)=>{Yf(e.inputs,r.perm),e.compute(Vr(e.inputs[0],r.perm))},Kb=e=>$t({perm:e.perm})}),s_,n_,o_,i_,a_,l_,u_,d_,c_,p_,as,Hb,qb,Xb,Qb,Jb,Yb,Zb,eM,tM,rM,ax=Re(()=>{ut(),ft(),_t(),ud(),Js(),s_={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"},n_={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"},o_={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},i_={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},a_=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},u_=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!d_(e,r)){for(let s=0;st.push(s))}return t},p_=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=be.size(n),u=be.size(i),p=Pe("_A",t[0].dataType,a),d=Ze("output",o,n),c=64;l===1&&(c=256);let _=` - var aBestValues : array; - `,f=v=>` - ${v.registerUniform("reduceSize","u32").declareVariables(p,d)} - ${_} - fn DIV_CEIL(a : u32, b : u32) -> u32 { - return ((a - 1u) / b + 1u); - } - ${v.mainStart(c)} - - let outputIndex = global_idx / ${c}; - let offset = outputIndex * uniforms.reduceSize; - - var bestValue = f32(${o_[s]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${c}) { - let candidate = f32(${p.getByOffset("offset + k")}); - bestValue = ${s_[s]}; - } - aBestValues[local_idx] = bestValue; - workgroupBarrier(); - - var reduceSize = min(Length, ${c}u); - for (var currentSize = reduceSize / 2u; reduceSize > 1u; - currentSize = reduceSize / 2u) { - let interval = DIV_CEIL(reduceSize, 2u); - if (local_idx < currentSize) { - let candidate = aBestValues[local_idx + interval]; - bestValue = ${n_[s]}; - aBestValues[local_idx] = bestValue; - } - reduceSize = interval; - workgroupBarrier(); - } - - if (local_idx == 0u) { - ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${i_[s]})`}`)}; - } - }`;return{name:e,shaderCache:{hint:`${r};${c}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},as=(e,r,t,s)=>{let o=e.inputs.length===1?t:zu(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((_,f)=>f));let i=be.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=c_(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Vr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=a_(a.length,l.dims.length));let[p,d]=l_(l.dims,a),c=p;o.keepDims&&(c=u_(p,i)),e.compute(p_(r,o.cacheKey,[l],s,e.inputs[0].dataType,c,d),{inputs:[l]})},Hb=(e,r)=>{as(e,"ReduceMeanShared",r,"mean")},qb=(e,r)=>{as(e,"ReduceL1Shared",r,"l1")},Xb=(e,r)=>{as(e,"ReduceL2Shared",r,"l2")},Qb=(e,r)=>{as(e,"ReduceLogSumExpShared",r,"logSumExp")},Jb=(e,r)=>{as(e,"ReduceMaxShared",r,"max")},Yb=(e,r)=>{as(e,"ReduceMinShared",r,"min")},Zb=(e,r)=>{as(e,"ReduceProdShared",r,"prod")},eM=(e,r)=>{as(e,"ReduceSumShared",r,"sum")},tM=(e,r)=>{as(e,"ReduceSumSquareShared",r,"sumSquare")},rM=(e,r)=>{as(e,"ReduceLogSumShared",r,"logSum")}}),ls,h_,fa,zu,us,m_,f_,__,g_,w_,b_,M_,y_,v_,x_,ds,sM,nM,oM,iM,aM,lM,uM,dM,cM,pM,ud=Re(()=>{ut(),ft(),Jt(),_t(),ax(),ls=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.")},h_=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fa=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,d=be.normalizeAxes(o,p),c=!a&&d.length===0;u.forEach((v,$)=>{c||d.indexOf($)>=0?i&&l.push(1):l.push(v)});let _=l.length,f=be.size(l);return{name:e,shaderCache:r,getShaderSource:v=>{let $=[],w=Pe("_A",t[0].dataType,p),g=Ze("output",n,_),C=s(w,g,d),E=C[2];for(let y=0,b=0;y=0?(i&&b++,E=`for(var j${y}: u32 = 0; j${y} < ${u[y]}; j${y}++) { - ${C[2].includes("last_index")?`let last_index = j${y};`:""} - ${w.indicesSet("input_indices",y,`j${y}`)} - ${E} - }`):($.push(`${w.indicesSet("input_indices",y,g.indicesGet("output_indices",b))};`),b++);return` - - ${v.registerUniform("output_size","u32").declareVariables(w,g)} - - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${w.type.indices}; - let output_indices = ${g.offsetToIndices("global_idx")}; - - ${$.join(` -`)} - ${C[0]} // init ops for reduce max/min - ${C[1]} - ${E} - ${C[3]} - ${C.length===4?g.setByOffset("global_idx","value"):C.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...st(u,l)]})}},zu=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),$t({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},us=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:zu(o,t);e.compute(fa(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?h_:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},m_=(e,r)=>{ls(e.inputs),us(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},f_=(e,r)=>{ls(e.inputs),us(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},__=(e,r)=>{ls(e.inputs),us(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);"])},g_=(e,r)=>{ls(e.inputs),us(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},w_=(e,r)=>{ls(e.inputs),us(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},b_=(e,r)=>{ls(e.inputs),us(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},M_=(e,r)=>{ls(e.inputs),us(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},y_=(e,r)=>{ls(e.inputs),us(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},v_=(e,r)=>{ls(e.inputs),us(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},x_=(e,r)=>{ls(e.inputs),us(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;`,""])},ds=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},sM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?b_(e,r):Hb(e,r)},nM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?f_(e,r):qb(e,r)},oM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?__(e,r):Xb(e,r)},iM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?g_(e,r):Qb(e,r)},aM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?w_(e,r):Jb(e,r)},lM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?M_(e,r):Yb(e,r)},uM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?y_(e,r):Zb(e,r)},dM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?v_(e,r):eM(e,r)},cM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?x_(e,r):tM(e,r)},pM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?m_(e,r):rM(e,r)}}),Yl,hM,mM,Bu,lx=Re(()=>{ut(),Jt(),ud(),Yl=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.")},hM=(e,r)=>{Yl(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(fa("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},mM=(e,r)=>{Yl(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(fa("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Bu=e=>$t(e)}),T_,ta,E_,P_,C_,Zo,S_,fM,dd=Re(()=>{ut(),ft(),ad(),_t(),T_=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&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],u=t.dims[1],p=t.dims[2];if(o.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(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=o.dims[0]/3,c=d,_=c;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let C of r.qkvHiddenSizes)if(C%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],c=r.qkvHiddenSizes[1],_=r.qkvHiddenSizes[2]}let f=u;if(d!==c)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+c+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let v=0;if(i){if(c!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==c/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(v=i.dims[3])}let $=f+v,w=-1,g=0;if(n)throw new Error("Mask not supported");if(i)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]!==u||a.dims[3]!==$)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:v,kvSequenceLength:f,totalSequenceLength:$,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:_,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(_/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ta=(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; - let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; - total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; - var past_sequence_length: u32 = 0; - if (is_first_prompt == false) { - past_sequence_length = total_sequence_length - sequence_length; - } - `:` - ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; - let present_sequence_length = total_sequence_length; - `,E_=(e,r,t,s,o,n,i,a)=>{let l=qt(i?1:n),u=64,p=n/l;p{let g=Ze("x",e.dataType,e.dims,l),C=[g],E=i?Pe("seq_lens",i.dataType,i.dims):void 0;E&&C.push(E);let y=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;y&&C.push(y);let b=Er(e.dataType),x=[{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; - ${w.registerUniforms(x).declareVariables(...C)} - ${w.mainStart([u,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; - ${ta(E,y,!1)} - let local_offset = local_idx * uniforms.elements_per_thread; - let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset; - let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; - 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(${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(); - - var max_value = f32(-3.402823e+38f); - for (var i = 0u; i < ${u}; i++) { - max_value = max(thread_max[i], max_value); - } - - 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(${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(); - - var sum: f32 = 0; - for (var i = 0u; i < ${u}; i++) { - sum += thread_sum[i]; - } - - if (sum == 0) { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - x[offset + i] = ${g.type.value}(${b}(1.0) / ${b}(seq_causal_length)); - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - var f32input = ${f}(x[offset + i]); - x[offset + i] = ${g.type.value}(exp(f32input - max_value) / sum); - } - } - ${i?` - 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] = ${g.type.value}(${b}(0)); - }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${_};${l}`,inputDependencies:v},getShaderSource:$,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:c})}},P_=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],d=e>1&&s,c=n.kvNumHeads?n.kvNumHeads:n.numHeads,_=d?[n.batchSize,c,u,n.headSize]:void 0,f=n.nReps?n.nReps:1,v=n.scale===0?1/Math.sqrt(n.headSize):n.scale,$=qt(n.headSize),w=n.headSize/$,g=12,C={x:Math.ceil(u/g),y:Math.ceil(n.sequenceLength/g),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:v},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:f}],y=d&&s&&be.size(s.dims)>0,b=["type","type"];y&&b.push("type"),o&&b.push("type"),a&&b.push("type"),l&&b.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:_,dataType:r.dataType,gpuDataType:0});let S=A=>{let B=Pe("q",r.dataType,r.dims,$),K=Pe("key",t.dataType,t.dims,$),G=[B,K];if(y){let me=Pe("past_key",s.dataType,s.dims,$);G.push(me)}o&&G.push(Pe("attention_bias",o.dataType,o.dims));let j=a?Pe("seq_lens",a.dataType,a.dims):void 0;j&&G.push(j);let ee=l?Pe("total_sequence_length_input",l.dataType,l.dims):void 0;ee&&G.push(ee);let H=Ze("output",r.dataType,p),Z=[H];d&&Z.push(Ze("present_key",r.dataType,_,$));let X=Er(1,$),oe=[{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 = ${g}u; - - var tileQ: array<${B.type.storage}, ${g*g}>; - var tileK: array<${B.type.storage}, ${g*g}>; - ${A.registerUniforms(oe).declareVariables(...G,...Z)} - ${A.mainStart([g,g,1])} - // x holds the N and y holds the M - let headIdx = workgroup_id.z % uniforms.num_heads; - 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; - let sequence_length = uniforms.M; - var total_sequence_length = uniforms.N; - ${ta(j,ee,!0)} - let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; - let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; - ${y&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; - let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; - ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} - var value = ${X}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { - tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; - } - if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${y&&d?` - if (n + local_id.y < past_sequence_length) { - tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { - tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; - }`:` - if (n + local_id.y < uniforms.kv_sequence_length) { - tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - }`} - ${d?`if (n + local_id.y < present_sequence_length) { - present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; - }`:""} - } - workgroupBarrier(); - - for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { - value += ${X}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); - } - - workgroupBarrier(); - } - - if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { - let headOffset = workgroup_id.z * uniforms.M * uniforms.N; - let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; - var sum: f32 = ${(()=>{switch($){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: ${$}`)}})()}; - output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; - } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${$};${o!==void 0};${s!==void 0};${e}`,inputDependencies:b},getRunData:()=>({outputs:x,dispatchGroup:C,programUniforms:E}),getShaderSource:S}},C_=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,d=e>1&&s,c=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=d?[o.batchSize,c,l,o.headSize]:void 0,f=[o.batchSize,o.sequenceLength,p],v=12,$={x:Math.ceil(o.vHeadSize/v),y:Math.ceil(o.sequenceLength/v),z:o.batchSize*o.numHeads},w=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:u}],g=d&&s&&be.size(s.dims)>0,C=["type","type"];g&&C.push("type"),i&&C.push("type"),a&&C.push("type");let E=[{dims:f,dataType:r.dataType,gpuDataType:0}];d&&E.push({dims:_,dataType:r.dataType,gpuDataType:0});let y=b=>{let x=Pe("probs",r.dataType,r.dims),S=Pe("v",t.dataType,t.dims),A=[x,S];g&&A.push(Pe("past_value",s.dataType,s.dims));let B=i?Pe("seq_lens",i.dataType,i.dims):void 0;i&&A.push(B);let K=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;a&&A.push(K);let G=[Ze("output",r.dataType,f)];d&&G.push(Ze("present_value",r.dataType,_));let j=[{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 = ${v}u; - var tileQ: array<${x.type.value}, ${v*v}>; - var tileV: array<${x.type.value}, ${v*v}>; - ${b.registerUniforms(j).declareVariables(...A,...G)} - ${b.mainStart([v,v,1])} - let headIdx = workgroup_id.z % uniforms.num_heads; - let batchIdx = workgroup_id.z / uniforms.num_heads; - let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${u===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; - let m = global_id.y; - let n = global_id.x; - let sequence_length = uniforms.M; - var total_sequence_length = uniforms.K; - ${ta(B,K,!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 - ${g&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; - let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; - ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} - var value = ${x.type.storage}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (m < uniforms.M && w + local_id.x < uniforms.K) { - tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; - } - if (n < uniforms.N && w + local_id.y < uniforms.K) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${g&&d?` - if (w + local_id.y < past_sequence_length) { - tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; - } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { - tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; - } - `:` - if (w + local_id.y < uniforms.kv_sequence_length) { - tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; - }`} - ${d?` - if (w + local_id.y < present_sequence_length) { - present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; - }`:""} - } - workgroupBarrier(); - for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { - value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; - } - workgroupBarrier(); - } - - // we need to transpose output from BNSH_v to BSND_v - if (m < uniforms.M && n < uniforms.N) { - let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size - + headIdx * uniforms.N + n; - output[outputIdx] = value; - } - }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:C},getRunData:()=>({outputs:E,dispatchGroup:$,programUniforms:w}),getShaderSource:y}},Zo=(e,r,t,s,o,n,i,a,l,u,p=void 0,d=void 0)=>{let c=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),_=c>1?u.pastSequenceLength:0,f=_+u.kvSequenceLength,v=l&&be.size(l.dims)>0?l:void 0,$=[r,t];c>1&&i&&be.size(i.dims)>0&&$.push(i),v&&$.push(v),p&&$.push(p),d&&$.push(d);let w=e.compute(P_(c,r,t,i,v,u,_,p,d),{inputs:$,outputs:c>1?[-1,1]:[-1]})[0];e.compute(E_(w,u.batchSize,u.numHeads,_,u.sequenceLength,f,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let g=[w,s];c>1&&a&&be.size(a.dims)>0&&g.push(a),p&&g.push(p),d&&g.push(d),e.compute(C_(c,w,s,a,u,_,p,d),{inputs:g,outputs:c>1?[0,2]:[0]})},S_=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:o},{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=d=>{let c=Ze("output_q",l[0].dataType,t),_=Ze("output_k",l[0].dataType,t),f=Ze("output_v",l[0].dataType,t),v=Pe("input",l[0].dataType,l[0].dims),$=Pe("weight",l[1].dataType,l[1].dims),w=Pe("bias",l[2].dataType,l[2].dims),g=v.type.storage,C=[{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 = ${i}u; - var tileInput: array<${g}, ${i*i}>; - var tileWeightQ: array<${g}, ${i*i}>; - var tileWeightK: array<${g}, ${i*i}>; - var tileWeightV: array<${g}, ${i*i}>; - ${d.registerUniforms(C).declareVariables(v,$,w,c,_,f)} - ${d.mainStart([i,i,1])} - let batchIndex = workgroup_id.z / uniforms.num_heads; - let headNumber = workgroup_id.z % uniforms.num_heads; - let m = global_id.y; - let n = global_id.x; - - let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; - let biasOffsetQ = headNumber * uniforms.head_size; - let biasOffsetK = uniforms.hidden_size + biasOffsetQ; - let biasOffsetV = uniforms.hidden_size + biasOffsetK; - - var valueQ = ${g}(0); - var valueK = ${g}(0); - var valueV = ${g}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (m < uniforms.M && w + local_id.x < uniforms.K) { - tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; - } - if (n < uniforms.N && w + local_id.y < uniforms.K) { - let offset = n + (w + local_id.y) * uniforms.ldb; - tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; - tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; - tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; - } - workgroupBarrier(); - for (var k: u32 = 0u; k({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:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},fM=(e,r)=>{let t=T_(e.inputs,r),[s,o,n]=S_(e,t);return Zo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),$_,k_,I_,_M,ux=Re(()=>{_s(),ut(),ft(),Jt(),_t(),$_=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.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")},k_=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?qt(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=be.size(n)/i,u=s,p=u?n.length:n,d=Pe("x",e[0].dataType,e[0].dims,i),c=Pe("scale",e[1].dataType,e[1].dims,a),_=Pe("bias",e[2].dataType,e[2].dims,a),f=Pe("inputMean",e[3].dataType,e[3].dims,a),v=Pe("inputVar",e[4].dataType,e[4].dims,a),$=Ze("y",e[0].dataType,p,i),w=()=>{let C="";if(s)C=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")C=` - ${$.indicesSet("outputIndices","0","0")} - let cOffset = ${$.indicesToOffset("outputIndices")};`;else{C=`var cIndices = ${c.type.indices}(0); - cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` - const epsilon = ${t}; - ${C.registerUniform("outputSize","u32").declareVariables(d,c,_,f,v,$)} - ${C.mainStart()} - ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${$.offsetToIndices(`global_idx * ${i}`)}; - ${w()} - let scale = ${c.getByOffset("cOffset")}; - let bias = ${_.getByOffset("cOffset")}; - let inputMean = ${f.getByOffset("cOffset")}; - let inputVar = ${v.getByOffset("cOffset")}; - let x = ${d.getByOffset("global_idx")}; - let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; - ${$.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...st(n)]:[{type:12,data:l}]})}},I_=e=>$t(e),_M=(e,r)=>{let{inputs:t,outputCount:s}=e,o=I_({...r,outputCount:s});if(jt.webgpu.validateInputContent&&$_(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(k_(t,o))}}),A_,F_,gM,dx=Re(()=>{ft(),_t(),A_=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")},F_=e=>{let r=e[0].dims,t=e[0].dims[2],s=be.size(r)/4,o=e[0].dataType,n=Pe("input",o,r,4),i=Pe("bias",o,[t],4),a=Pe("residual",o,r,4),l=Ze("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` - const channels = ${t}u / 4; - ${u.declareVariables(n,i,a,l)} - - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} - let value = ${n.getByOffset("global_idx")} - + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; - ${l.setByOffset("global_idx","value")} - }`}},gM=e=>{A_(e.inputs),e.compute(F_(e.inputs))}}),O_,Ct,wM,bM,MM,yM,vM,xM,TM,EM,PM,D_,CM,SM,$M,kM,qo,IM,ca,AM,FM,OM,DM,LM,zM,BM,RM,jM,NM,VM,UM,WM,GM,KM,HM,Zl,qM,Ru,ju,XM,QM,JM,L_,z_,YM,cd=Re(()=>{ut(),ft(),Jt(),_t(),O_=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Pe("inputData",t,[a],4),p=Ze("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` - ${e.registerUniforms(d).declareVariables(u,p)} - - ${n??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - - let a = ${u.getByOffset("global_idx")}; - ${p.setByOffset("global_idx",l)} - }`},Ct=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(be.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:u=>O_(u,be.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(be.size(u[0].dims)/64/4)},programUniforms:l})}},wM=e=>{e.compute(Ct(e.inputs[0],"Abs","abs"))},bM=e=>{e.compute(Ct(e.inputs[0],"Acos","acos"))},MM=e=>{e.compute(Ct(e.inputs[0],"Acosh","acosh"))},yM=e=>{e.compute(Ct(e.inputs[0],"Asin","asin"))},vM=e=>{e.compute(Ct(e.inputs[0],"Asinh","asinh"))},xM=e=>{e.compute(Ct(e.inputs[0],"Atan","atan"))},TM=e=>{e.compute(Ct(e.inputs[0],"Atanh","atanh"))},EM=e=>$t(e),PM=(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(Ct(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},D_=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return $t({min:r,max:t})},CM=(e,r)=>{let t=r||D_(e.inputs),s=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Clip",o=>`clamp(${o}, 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]})},SM=e=>{e.compute(Ct(e.inputs[0],"Ceil","ceil"))},$M=e=>{e.compute(Ct(e.inputs[0],"Cos","cos"))},kM=e=>{e.compute(Ct(e.inputs[0],"Cosh","cosh"))},qo=e=>$t(e),IM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` - const elu_alpha_ = ${t}(${r.alpha}); - - fn elu_f32(a: ${t}) -> ${t} { - return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); - } - - fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { - return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,r.cacheKey))},ca=(e="f32")=>` -const r0: ${e} = 0.3275911; -const r1: ${e} = 0.254829592; -const r2: ${e} = -0.284496736; -const r3: ${e} = 1.421413741; -const r4: ${e} = -1.453152027; -const r5: ${e} = 1.061405429; - -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)); -}`,AM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ca(r)))},FM=e=>{e.compute(Ct(e.inputs[0],"Exp","exp"))},OM=e=>{e.compute(Ct(e.inputs[0],"Floor","floor"))},DM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ca(r)))},LM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(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))},zM=e=>{e.compute(Ct(e.inputs[0],"Not",r=>`!${r}`))},BM=e=>{e.compute(Ct(e.inputs[0],"Neg",r=>`-${r}`))},RM=e=>{e.compute(Ct(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},jM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},NM=e=>{e.compute(Ct(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},VM=e=>$t(e),UM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(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))},WM=e=>{e.compute(Ct(e.inputs[0],"Sin","sin"))},GM=e=>{e.compute(Ct(e.inputs[0],"Sinh","sinh"))},KM=e=>{e.compute(Ct(e.inputs[0],"Sqrt","sqrt"))},HM=e=>{e.compute(Ct(e.inputs[0],"Tan","tan"))},Zl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,qM=e=>{e.compute(Ct(e.inputs[0],"Tanh",Zl))},Ru=(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 ${Zl("v")}; -} -`,ju=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,XM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"FastGelu",ju,Ru(r),void 0,e.inputs[0].dataType))},QM=(e,r)=>{let t=Er(e.inputs[0].dataType);return e.compute(Ct(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},JM=e=>{e.compute(Ct(e.inputs[0],"Log","log"))},L_=(e,r)=>` -const alpha = vec4<${e}>(${r}); -const one = ${e}(1.0); -const zero = ${e}(0.0); - -fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { - let v = x *alpha; - var x1 : vec4<${e}>; - for (var i = 0; i < 4; i = i + 1) { - if (v[i] >= zero) { - x1[i] = one / (one + exp(-v[i])); - } else { - x1[i] = one - one / (one + exp(v[i])); - } - } - return x * x1; -} -`,z_=e=>`quick_gelu_impl(${e})`,YM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"QuickGelu",z_,L_(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),B_,R_,ZM,cx=Re(()=>{ft(),_t(),cd(),B_=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")},R_=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Pe("input",e[0].dataType,e[0].dims,4),s=Pe("bias",e[0].dataType,[e[0].dims[2]],4),o=Ze("output",e[0].dataType,r,4),n=be.size(r)/4,i=mr(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; - - ${a.declareVariables(t,s,o)} - - ${ca(i)} - - ${a.mainStart()} - ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} - let biasIdx = global_idx % halfChannels; - let batchIndex = global_idx / halfChannels; - let inputOffset = biasIdx + batchIndex * halfChannels * 2; - let valueLeft = input[inputOffset] + bias[biasIdx]; - let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; - let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); - - ${o.setByOffset("global_idx","valueLeft * geluRight")} - }`}},ZM=e=>{B_(e.inputs),e.compute(R_(e.inputs))}}),j_,N_,cs,ey,ty,ry,sy,ny,oy,iy,ay,ly,uy,px=Re(()=>{ut(),ft(),_t(),j_=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c,_;typeof a=="string"?c=_=(g,C)=>`${a}((${g}),(${C}))`:typeof a=="function"?c=_=a:(c=a.scalar,_=a.vector);let f=Ze("outputData",p,s.length,4),v=Pe("aData",l,r.length,4),$=Pe("bData",u,t.length,4),w;if(o)if(n){let g=be.size(r)===1,C=be.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;g||C?w=f.setByOffset("global_idx",_(g?`${v.type.value}(${v.getByOffset("0")}.x)`:v.getByOffset("global_idx"),C?`${$.type.value}(${$.getByOffset("0")}.x)`:$.getByOffset("global_idx"))):w=` - let outputIndices = ${f.offsetToIndices("global_idx * 4u")}; - let offsetA = ${v.broadcastedIndicesToOffset("outputIndices",f)}; - let offsetB = ${$.broadcastedIndicesToOffset("outputIndices",f)}; - ${f.setByOffset("global_idx",_(i||E?v.getByOffset("offsetA / 4u"):`${v.type.value}(${v.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?$.getByOffset("offsetB / 4u"):`${$.type.value}(${$.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else w=f.setByOffset("global_idx",_(v.getByOffset("global_idx"),$.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let g=(C,E,y="")=>{let b=`aData[indexA${E}][componentA${E}]`,x=`bData[indexB${E}][componentB${E}]`;return` - let outputIndices${E} = ${f.offsetToIndices(`global_idx * 4u + ${E}u`)}; - let offsetA${E} = ${v.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; - let offsetB${E} = ${$.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; - let indexA${E} = offsetA${E} / 4u; - let indexB${E} = offsetB${E} / 4u; - let componentA${E} = offsetA${E} % 4u; - let componentB${E} = offsetB${E} % 4u; - ${C}[${E}] = ${y}(${c(b,x)}); - `};p===9?w=` - var data = vec4(0); - ${g("data",0,"u32")} - ${g("data",1,"u32")} - ${g("data",2,"u32")} - ${g("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` - ${g("outputData[global_idx]",0)} - ${g("outputData[global_idx]",1)} - ${g("outputData[global_idx]",2)} - ${g("outputData[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(v,$,f)} - - ${d??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${w} - }`},N_=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(v=>Number(v)??1),l=s.dims.map(v=>Number(v)??1),u=!be.areEqual(a,l),p=a,d=be.size(a),c=!1,_=!1,f=[u];if(u){let v=oo.calcShape(a,l,!1);if(!v)throw new Error("Can't perform binary op on the given tensors");p=v.slice(),d=be.size(p);let $=be.size(a)===1,w=be.size(l)===1,g=a.length>0&&a[a.length-1]%4===0,C=l.length>0&&l[l.length-1]%4===0;f.push($),f.push(w),f.push(g),f.push(C);let E=1;for(let y=1;yv.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:v=>j_(v,a,l,p,c,u,_,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(be.size(p)/4)},...st(a,l,p)]})}},cs=(e,r,t,s,o,n)=>{e.compute(N_(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},ey=e=>{cs(e,"Add",(r,t)=>`${r}+${t}`)},ty=e=>{cs(e,"Div",(r,t)=>`${r}/${t}`)},ry=e=>{cs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},sy=e=>{cs(e,"Mul",(r,t)=>`${r}*${t}`)},ny=e=>{let r=Pe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;cs(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); - } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { - return ${r}(pow(f32(a), f32(b))); // NaN - } - return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); - } - fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { - // 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)); - } - `)},oy=e=>{cs(e,"Sub",(r,t)=>`${r}-${t}`)},iy=e=>{cs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},ay=e=>{cs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},ly=e=>{cs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},uy=e=>{cs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),V_,U_,W_,G_,dy,cy,hx=Re(()=>{ut(),ft(),Jt(),_t(),V_=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},U_=(e,r)=>` - fn calculateInputIndex(index: u32) -> u32 { - let sizeInConcatAxis = array(${r}); - for (var i: u32 = 0u; i < ${e}; i += 1u ) { - if (index < sizeInConcatAxis[i]) { - return i; - } - } - return ${e}u; - }`,W_=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=be.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:o}];for(let v=0;v`uniforms.sizeInConcatAxis${v}`).join(","),f=v=>` - - ${(()=>{v.registerUniform("outputSize","u32");for(let $=0;$(${_}); - ${c} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${W_(i,d)} - }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:f}},dy=(e,r)=>{let t=e.inputs,s=t[0].dims,o=be.normalizeAxis(r.axis,s.length);V_(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>be.size(a.dims)>0);e.compute(G_(i,o,n,t[0].dataType),{inputs:i})},cy=e=>$t({axis:e.axis})}),On,Dn,Ln,pd,Bn=Re(()=>{ut(),ft(),On=(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}`)}},Dn=(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})},Ln=(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"})},pd=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)||[zb,Bb];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}}}),br,py,hd=Re(()=>{br=(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.`)}},py=e=>` - ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),hy,mx=Re(()=>{hy=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)); -} -fn getOutputIndexFromCoords(coords : vec4) -> i32 { - return dot(coords, vec4( - i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); -} -`}),Qo,md,fd=Re(()=>{ut(),ft(),_t(),Bn(),Qo=(e,r,t,s,o)=>{let n=s-t;return` - ${Array.from({length:t}).map((i,a)=>` - if (${rt(r.shape,a,r.rank)} != 1) { - ${r.indicesSet(e,a,rt(o,a+n,s))} - } else { - ${r.indicesSet(e,a,0)} - }`).join("")} -`},md=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],d=qt(u),c=qt(p),_=qt(l),f=be.size(t)/d/_,v=e.length>2,$=s?s.slice(0,-2):t.slice(0,-2),w=[be.size($),l,u],g=[{type:12,data:f},{type:12,data:l},{type:12,data:u},{type:12,data:p}];Dn(r,g),g.push(...st($,i,a)),v&&g.push(...st(e[2].dims)),g.push(...st(w));let C=E=>{let y=ld("batch_dims",e[0].dataType,$.length),b=Pe("a",e[0].dataType,i.length,c),x=Pe("b",e[1].dataType,a.length,d),S=Ze("output",e[0].dataType,w.length,d),A=mr(S.type.tensor),B=On(r,S.type.value,A),K=[b,x],G="";if(v){let H=o?d:1;K.push(Pe("bias",e[2].dataType,e[2].dims.length,H)),G=`${o?`value += bias[col / ${H}];`:`value += ${S.type.value}(bias[row + i]);`}`}let j=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ln(r,j);let ee=()=>{let H=`var a_data: ${b.type.value};`;for(let Z=0;Z; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${c}) { - ${ee()} - } - for (var i = 0u; i < ${_}u; i++) { - var value = values[i]; - ${G} - ${B} - let cur_indices = ${S.type.indices}(batch, row + i, col); - let offset = ${S.indicesToOffset("cur_indices")}; - ${S.setByOffset(`offset / ${d}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${c};${_};${o}`,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:g}),getShaderSource:C}}}),K_,H_,Nu,eu,q_,Vu,X_,_a,_d=Re(()=>{ut(),ft(),_t(),Bn(),fd(),hd(),K_=(e,r)=>e?` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - kStart + inputRow, - globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); - `:` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - globalRow + innerRow, - kStart / innerElementSize + inputCol${r?", batchIndices":""}); - `,H_=(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]; - ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} - for (var i = 0; i < rowPerThread; i = i + 1) { - acc[i] = BCached0 * ACached0[i] + acc[i]; - acc[i] = BCached1 * ACached1[i] + acc[i]; - acc[i] = BCached2 * ACached2[i] + acc[i]; - ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} - }`:` - for (var i = 0; i < rowPerThread; i = i + 1) { - let ACached = mm_Asub[tileRow + i][k]; - acc[i] = BCached0 * ACached.x + acc[i]; - acc[i] = BCached1 * ACached.y + acc[i]; - acc[i] = BCached2 * ACached.z + acc[i]; - ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,Nu=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,d=o?n:l,c=p/r[0],_=n/r[1];if(!((o&&c===4&&e[1]===4||!o&&(c===3||c===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${c} and workPerThread[1] ${e[1]} must be 4. - Otherwise, innerElementSize ${c} 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/c}>, ${d}>; -var mm_Bsub: array, ${u/e[0]}>, ${n}>; - -const rowPerThread = ${e[1]}; -const colPerThread = ${e[0]}; -const innerElementSize = ${c}; -const tileInner = ${n}; - -@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let localRow = i32(localId.y); - let tileRow = localRow * rowPerThread; - let tileCol = i32(localId.x); - - let globalRow =i32(globalId.y) * rowPerThread; - let globalCol = i32(globalId.x); - let batch = ${i?"0":"i32(globalId.z)"}; - ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} - let globalRowStart = i32(workgroupId.y) * ${l}; - - let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; - - var acc: array, rowPerThread>; - - // Loop over shared dimension. - let tileRowB = localRow * ${_}; - for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let inputRow = tileRow + innerRow; - let inputCol = tileCol; - ${K_(o,s)} - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { - let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; - let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; - let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; - ${c===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - - ${H_(o,c)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},eu=(e,r)=>e?` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - kStart + inputRow, - globalRowStart + inputCol${r?", batchIndices":""}); - `:` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - globalRowStart + inputRow, - kStart + inputCol${r?", batchIndices":""}); - `,q_=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Vu=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],d=o?u:n,c=o?n:u;if(!(c%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${c} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let _=c/r[1],f=d/r[0],v=n/r[1],$=l?` - let localRow = i32(localId.y); - let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${u}; - let globalColStart = i32(workgroupId.x) * ${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 inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${r[1]}) { - for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { - ${eu(o,s)} - } - } - // Load one tile of B into local memory. - for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { - for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalColStart + inputCol${s?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${t}, colPerThread>; - for (var k = 0; k < tileInner; k = k + 1) { - for (var inner = 0; inner < colPerThread; inner = inner + 1) { - BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; - } - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - acc[innerRow][innerCol] = acc[innerRow][innerCol] + - ACached * BCached[innerCol]; - } - } - } - workgroupBarrier(); - } - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let gRow = globalRowStart + localRow + innerRow * ${r[1]}; - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let gCol = globalColStart + localCol + innerCol * ${r[0]}; - mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); - } - } - `:` -let tileRow = i32(localId.y) * rowPerThread; -let tileCol = i32(localId.x) * colPerThread; - -let globalRow = i32(globalId.y) * rowPerThread; -let globalCol = i32(globalId.x) * colPerThread; -let globalRowStart = i32(workgroupId.y) * ${u}; - -let tileRowA = i32(localId.y) * ${_}; -let tileColA = i32(localId.x) * ${f}; -let tileRowB = i32(localId.y) * ${v}; -// 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 < ${_}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${eu(o,s)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${v}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol + innerCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalCol + innerCol${s?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${t}, colPerThread>; - for (var k = 0; k < tileInner; k = k + 1) { - for (var inner = 0; inner < colPerThread; inner = inner + 1) { - BCached[inner] = mm_Bsub[k][tileCol + inner]; - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${q_(o)} - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; - } - } - } - - workgroupBarrier(); -} - -for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - mm_write(batch, globalRow + innerRow, globalCol + innerCol, - acc[innerRow][innerCol]); - } -} -`;return` - var mm_Asub : array, ${c}>; - var mm_Bsub : array, ${n}>; - const rowPerThread = ${e[1]}; - const colPerThread = ${e[0]}; - const tileInner = ${n}; - -@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let batch = ${i?"0":"i32(globalId.z)"}; - ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} - let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; - - var acc : array, rowPerThread>; - ${$} - } -`},X_=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=mr(s[0].type.tensor);return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${br(e,u)} { - var value = ${br(e,u)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) - { - var aIndices: ${i.type.indices}; - ${Qo("aIndices",i,i.rank-2,n.rank,"batchIndices")} - ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} - ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} - value = ${i.getByIndices("aIndices")}; - } - return value; - } - - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${br(e,u)} { - var value = ${br(e,u)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) - { - var bIndices: ${a.type.indices}; - ${Qo("bIndices",a,a.rank-2,n.rank,"batchIndices")} - ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} - ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} - value = ${a.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${br(e,u)}) { - let col = colIn * ${e}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { - var value = valueIn; - let coords = vec3(batch, row, colIn); - ${r?`value = value + ${o?"bias[colIn]":`${br(e,u)}(bias[row])`};`:""} - ${t} - ${l.setByIndices("vec3(coords)","value")} - } - } - `},_a=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=be.size(p),c=i[i.length-2],_=i[i.length-1],f=a[a.length-1],v=_%4===0&&f%4===0,$=c<=8?[4,1,1]:[4,4,1],w=[8,8,1],g=[Math.ceil(f/w[0]/$[0]),Math.ceil(c/w[1]/$[1]),Math.ceil(d/w[2]/$[2])],C=v?4:1,E=[...l,c,_/C],y=E.length,b=[...u,_,f/C],x=b.length,S=[d,c,f/C],A=[{type:6,data:c},{type:6,data:f},{type:6,data:_}];Dn(r,A),A.push(...st(p,E,b));let B=["rank","rank"],K=e.length>2;K&&(A.push(...st(e[2].dims)),B.push("rank")),A.push(...st(S));let G=j=>{let ee=p.length,H=ld("batchDims",e[0].dataType,ee,1),Z=mr(e[0].dataType),X=Pe("a",e[0].dataType,y,C),oe=Pe("b",e[1].dataType,x,C),me=Ze("result",e[0].dataType,S.length,C),ae=[X,oe];if(K){let fe=o?C:1;ae.push(Pe("bias",e[2].dataType,e[2].dims.length,fe))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ln(r,V);let F=mr(me.type.tensor),W=On(r,me.type.value,F),re=X_(C,K,W,[H,X,oe,me],o);return` - ${j.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,me)} - ${re} - ${v?Nu($,w,Z,H):Vu($,w,Z,H)} - `};return{name:"MatMul",shaderCache:{hint:`${$};${r.activation};${v};${o}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:A}),getShaderSource:G}}}),Q_,my,fx=Re(()=>{ut(),Os(),_t(),Bn(),hd(),mx(),_d(),Q_=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=A=>{switch(A){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${A} is not supported.`)}},d=A=>{switch(A){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 ${A} is not supported.`)}},c=e?` - let coord = vec4(batch, xRow, xCol, xCh); - `:` - let coord = vec4(batch, xCh, xRow, xCol); - `,_=e?` - let coords = vec4( - batch, - row / outWidth, - row % outWidth, - col); - `:` - let coords = vec4( - batch, - row, - col / outWidth, - col % outWidth); - `,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",v=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",$=e?"row":"col",w=e?"col":"row",g=` - let inChannels = i32(uniforms.w_shape[2]); - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${$} / outWidth; - let outCol = ${$} % outWidth; - - let WRow = ${w} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${w} / 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 = ${w} % inChannels; - var resData = ${br(i,u)}(0.0); - // The bounds checking is always needed since we use it to pad zero for - // the 'same' padding type. - if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${v}) { - ${c} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${p(i)} - } - return resData;`,C=e?r&&s?` - let col = colIn * ${i}; - ${g}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${g} - } - return ${br(i,u)}(0.0);`:s&&t?` - let col = colIn * ${i}; - ${g}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${g} - } - return ${br(i,u)}(0.0);`,E=e?s&&t?d(a):` - let col = colIn * ${a}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${d(a)} - } - return ${br(a,u)}(0.0);`:` - let col = colIn * ${a}; - if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { - ${d(a)} - } - return ${br(a,u)}(0.0);`,y=br(l,u),b=br(e?i:a,u),x=br(e?a:i,u),S=On(n,y,u);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${b} { - ${e?C:E} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { - ${e?E:C} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) { - let col = colIn * ${l}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) - { - var value = valueIn; - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${_} - ${py(o)} - ${S} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},my=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],d=t[0],c=u?t[2]:t[3],_=u?t[1]:t[2],f=u?t[3]:t[1],v=u&&(p%4===0||p%3===0)&&f%4===0,$=u?f:c*_,w=u?c*_:f,g=[8,8,1],C=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil($/g[0]/C[0]),Math.ceil(w/g[1]/C[1]),Math.ceil(d/g[2]/C[2])];Tt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let y=v?u&&p%4!==0?3:4:1,b=g[1]*C[1],x=g[0]*C[0],S=Math.max(g[0]*y,g[1]),A=s%b===0,B=o%x===0,K=n%S===0,G=v?[y,4,4]:[1,1,1],j=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];Dn(r,j),j.push(...st(e[0].dims,e[1].dims));let ee=["rank","rank"];i&&(j.push(...st(e[2].dims)),ee.push("rank")),j.push(...st(t));let H=Z=>{let X=[{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}];Ln(r,X);let oe=v?4:1,me=mr(e[0].dataType),ae=` - fn setOutputAtIndex(flatIndex : i32, value : ${v?`vec4<${me}>`:me}) { - result[flatIndex] = ${v?`vec4<${me}>`:me}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${v?`vec4<${me}>`:me}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${v?"/ 4":""}, value); - }`,V=Pe("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=Pe("w",e[1].dataType,e[1].dims.length,oe),W=[V,F],re=Ze("result",e[0].dataType,t.length,oe);if(i){let fe=Pe("bias",e[2].dataType,e[2].dims.length,oe);W.push(fe),ae+=` - fn getBiasByOutputCoords(coords : vec4) -> ${v?`vec4<${me}>`:me} { - return bias[coords.${u?"w":"y"}${v?"/ 4":""}]; - }`}return` - ${hy("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 }; - ${Z.registerUniforms(X).declareVariables(...W,re)} - ${ae} - ${Q_(u,A,B,K,i,r,G[0],G[1],G[2],me)} - ${v?Nu(C,g,me,void 0,!u,S):Vu(C,g,me,void 0,!u,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${v};${A};${B};${K};${b};${x};${S}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:j}),getShaderSource:H}}}),J_,tu,jo,Y_,ru,Z_,fy,_y,_x=Re(()=>{ut(),Os(),ft(),_t(),Bn(),hd(),J_=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,jo=(e,r)=>r<=1?e:e+(e-1)*(r-1),Y_=(e,r,t,s=1)=>{let o=jo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},ru=(e,r,t,s,o)=>{o==null&&(o=Y_(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},Z_=(e,r,t,s,o,n,i,a,l,u)=>{let p,d,c,_;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=ru([r,t,s,1],[a,l,u],1,[o,n,i],e);d=f[0],c=f[1],_=f[2]}else if(Array.isArray(e)){if(!e.every((v,$,w)=>v===w[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=ru([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);d=f[0],c=f[1],_=f[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),c=Math.ceil(t/n),_=Math.ceil(s/i);let f=(d-1)*o+a-r,v=(c-1)*n+l-t,$=(_-1)*i+u-s,w=Math.floor(f/2),g=f-w,C=Math.floor(v/2),E=v-C,y=Math.floor($/2),b=$-y;p={top:C,bottom:E,left:y,right:b,front:w,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:c,outWidth:_}},fy=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,d;if(i==="channelsLast")[a,l,u,p,d]=e;else if(i==="channelsFirst")[a,d,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,,_,f,v]=r,[$,w,g]=tu(t),[C,E,y]=tu(s),b=jo(_,C),x=jo(f,E),S=jo(v,y),{padInfo:A,outDepth:B,outHeight:K,outWidth:G}=Z_(o,l,u,p,$,w,g,b,x,S),j=n?c*d:c,ee=[0,0,0,0,0];return i==="channelsFirst"?ee=[a,j,B,K,G]:i==="channelsLast"&&(ee=[a,B,K,G,j]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:d,outDepth:B,outHeight:K,outWidth:G,outChannels:j,padInfo:A,strideDepth:$,strideHeight:w,strideWidth:g,filterDepth:_,filterHeight:f,filterWidth:v,effectiveFilterDepth:b,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:C,dilationHeight:E,dilationWidth:y,inShape:e,outShape:ee,filterShape:r}},_y=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map(($,w)=>w)},u=[Math.ceil(J_(l.x.map($=>t[$]))/a[0]),1,1];Tt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,d=be.size(t),c=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];Dn(r,c),c.push(...st(e[0].dims,e[1].dims));let _=["rank","rank"],f=e.length===3;f&&(c.push(...st(e[2].dims)),_.push("rank")),c.push(...st(t));let v=$=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];Ln(r,w);let g=1,C=mr(e[0].dataType),E=Pe("x",e[0].dataType,e[0].dims.length,p),y=Pe("W",e[1].dataType,e[1].dims.length,g),b=[E,y],x=Ze("result",e[0].dataType,t.length,g),S="";if(f){let K=Pe("bias",e[2].dataType,e[2].dims.length,g);b.push(K),S+=` - fn getBiasByOutputCoords(coords : array) -> ${C} { - return bias[${i?rt("coords",4,5):rt("coords",1,5)}]; - }`}let A=br(p,C),B=On(r,A,C);return` - ${S} - fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${E.getByIndices("aIndices")}; - } - fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${y.getByIndices("aIndices")}; - } - ${$.registerUniforms(w).declareVariables(...b,x)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let coords = ${x.offsetToIndices("global_idx")}; - let batch = ${rt("coords",0,E.rank)}; - let d2 = ${i?rt("coords",E.rank-1,E.rank):rt("coords",1,E.rank)}; - let xFRCCorner = vec3(${i?rt("coords",1,E.rank):rt("coords",2,E.rank)}, - ${i?rt("coords",2,E.rank):rt("coords",3,E.rank)}, - ${i?rt("coords",3,E.rank):rt("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; - let xFCorner = xFRCCorner.x; - let xRCorner = xFRCCorner.y; - let xCCorner = xFRCCorner.z; - let xShapeY = ${i?rt("uniforms.x_shape",1,E.rank):rt("uniforms.x_shape",2,E.rank)}; - let xShapeZ = ${i?rt("uniforms.x_shape",2,E.rank):rt("uniforms.x_shape",3,E.rank)}; - let xShapeW = ${i?rt("uniforms.x_shape",3,E.rank):rt("uniforms.x_shape",4,E.rank)}; - let xShapeU = ${i?rt("uniforms.x_shape",4,E.rank):rt("uniforms.x_shape",1,E.rank)}; - let inputDepthNearestVec4 = (xShapeU / 4) * 4; - let inputDepthVec4Remainder = xShapeU % 4; - - var value = 0.0; - for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { - let xF = xFCorner + wF * uniforms.dilations[0]; - if (xF < 0 || xF >= xShapeY) { - continue; - } - - for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { - let xR = xRCorner + wR * uniforms.dilations[1]; - if (xR < 0 || xR >= xShapeZ) { - continue; - } - - for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { - let xC = xCCorner + wC * uniforms.dilations[2]; - if (xC < 0 || xC >= xShapeW) { - continue; - } - - for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { - ${i?`let xValues = vec4( - getX(batch, xF, xR, xC, d1), - getX(batch, xF, xR, xC, d1 + 1), - getX(batch, xF, xR, xC, d1 + 2), - getX(batch, xF, xR, xC, d1 + 3)); - `:`let xValues = vec4( - getX(batch, d1, xF, xR, xC), - getX(batch, d1 + 1, xF, xR, xC), - getX(batch, d1 + 2, xF, xR, xC), - getX(batch, d1 + 3, xF, xR, xC)); - `} - let wValues = vec4( - getW(d2, d1, wF, wR, wC), - getW(d2, d1 + 1, wF, wR, wC), - getW(d2, d1 + 2, wF, wR, wC), - getW(d2, d1 + 3, wF, wR, wC)); - value += dot(xValues, wValues); - } - if (inputDepthVec4Remainder == 1) { - ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} - } else if (inputDepthVec4Remainder == 2) { - ${i?`let xValues = vec2( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); - `:`let xValues = vec2( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); - `} - let wValues = vec2( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); - value += dot(xValues, wValues); - } else if (inputDepthVec4Remainder == 3) { - ${i?`let xValues = vec3( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); - `:`let xValues = vec3( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); - `} - let wValues = vec3( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); - value += dot(xValues, wValues); - } - } - } - } - ${f?"value = value + getBiasByOutputCoords(coords)":""}; - ${B} - result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:c}),getShaderSource:v}}}),gy,wy,gx=Re(()=>{ut(),ft(),_t(),Bn(),gy=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,d=l&&p>=4?qt(u):1,c=be.size(t)/d,_=[{type:12,data:c},{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}];Dn(r,_),_.push(...st(i,[a[0],a[1],a[2],a[3]/d]));let f=o?["rank","rank","rank"]:["rank","rank"];_.push(...st([t[0],t[1],t[2],t[3]/d]));let v=$=>{let w=Ze("output",e[0].dataType,t.length,d),g=mr(w.type.tensor),C=On(r,w.type.value,g),E=Pe("x",e[0].dataType,i.length),y=Pe("w",e[1].dataType,a.length,d),b=[E,y];o&&b.push(Pe("b",e[2].dataType,e[2].dims,d));let x=[{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"}];Ln(r,x);let S=l?` - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { - continue; - } - - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; - let wVal = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; - value += xVal * wVal; - } - } - } - `:` - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { - continue; - } - - let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal * wVal; - } - } - } - `;return` - ${$.registerUniforms(x).declareVariables(...b,w)} - - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let outputIndices = ${w.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 * ${d} / uniforms.output_channels_per_group; - var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; - - var value: ${w.type.value} = ${w.type.value}(0); - ${S} - ${n} - ${C} - ${w.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:_}),getShaderSource:v}},wy=(e,r,t,s)=>{let o=e.length>2,n=qt(t[3]),i=qt(t[2]),a=be.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],u=[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],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];Dn(r,d),d.push(...st(l,u,p));let c=(i-1)*r.strides[1]+u[1],_=f=>{let v=Ze("output",e[0].dataType,p.length,n),$=mr(v.type.tensor),w=On(r,v.type.value,$),g=Pe("x",e[0].dataType,l.length,n),C=Pe("w",e[1].dataType,u.length,n),E=[g,C];o&&E.push(Pe("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",b=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ln(r,b),` - ${f.registerUniforms(b).declareVariables(...E,v)} - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let width0 = uniforms.output_shape[3]; - let output_channel = global_idx % width0; - var index1 = global_idx / width0; - let width1 = uniforms.output_shape[2] / ${i}u; - let col = (index1 % width1) * ${i}u; - index1 = index1 / width1; - let row = index1 % uniforms.output_shape[1]; - let batch = index1 / uniforms.output_shape[1]; - - let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; - - var x_vals: array<${g.type.value}, ${c}>; - var values: array<${v.type.value}, ${i}>; - let input_channel = output_channel; - // Use constant instead of uniform can give better performance for w's height/width. - for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) { - let x_height = x_corner.x + i32(w_height); - if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { - for (var i = 0; i < ${c}; i++) { - let x_width = x_corner.y + i; - if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { - x_vals[i] = ${g.get("batch","u32(x_height)","u32(x_width)","input_channel")}; - } else { - x_vals[i] = ${g.type.value}(0); - } - } - for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { - let w_val = ${C.get("w_height","w_width","0","output_channel")}; - for (var i = 0u; i < ${i}u; i++) { - values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); - } - } - } - } - - for (var i = 0u; i < ${i}u; i++) { - var value = values[i]; - ${y} - ${w} - ${v.set("batch","row","col + i","output_channel","value")}; - } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${c};${u[0]};${u[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:_}}}),eg,ra,tg,sa,Uu,su,rg,sg,Wu,wx=Re(()=>{ft(),fx(),_x(),_d(),gx(),Bn(),fd(),Js(),eg=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((c,_)=>c+(c-1)*(t[_]-1)),d=a.map((c,_)=>c+s[_]+s[_+l]).map((c,_)=>Math.floor((c-p[_]+o[_])/o[_]));return d.splice(0,0,i),d.splice(n?3:1,0,u),d},ra=[2,3,1,0],tg=(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 o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},sa=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=pd(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},su=(e,r,t,s)=>{let o=t.format==="NHWC",n=eg(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let b=[r[0]];if(o){let x=e.kernelCustomData.wT??e.compute(Vr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),b.push(x)}else b.push(r[1]);r.length===3&&b.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(wy(b,t,n,s),{inputs:b}):e.compute(gy(b,t,n,s),{inputs:b});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],c=n[o?1:2],_=n[o?2:3],f=n[o?3:1],v=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(v||p===1&&d===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 b=n[0],x,S,A,B=[];if(o){let j=e.kernelCustomData.wT??e.compute(Vr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j),v){let ee=a*l*u;x=r[0].reshape([1,b,ee]),S=j.reshape([1,ee,f]),A=[1,b,f]}else x=r[0].reshape([b,a*l,u]),S=j.reshape([1,u,f]),A=[b,c*_,f];B.push(x),B.push(S)}else x=r[0].reshape([b,u,a*l]),S=r[1].reshape([1,f,u]),A=[b,f,c*_],B.push(S),B.push(x);i&&B.push(r[2]);let K=A[2],G=B[0].dims[B[0].dims.length-1];K<8&&G<8?e.compute(md(B,t,n,A,o,s),{inputs:B}):e.compute(_a(B,t,n,A,o,s),{inputs:B});return}let $=!0,w=e.kernelCustomData.wT??e.compute(Vr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let g=[r[0],w];i&&g.push(r[2]);let C=o?c*_:f,E=o?f:c*_,y=p*d*u;e.compute(my(g,t,n,C,E,y,i,$,s),{inputs:g})},rg=(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 o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=sa({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);su(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},sg=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=sa(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=fy(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(_y(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Wu=(e,r)=>{if(tg(e.inputs,r),e.inputs[0].dims.length===3)rg(e,r);else if(e.inputs[0].dims.length===5)sg(e,e.inputs,r);else{let t=sa(r,e.inputs);su(e,e.inputs,t)}}}),by,bx=Re(()=>{ut(),Os(),ft(),_t(),by=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,u=a[3],p=n?qt(l):1,d=n&&u===1&&l>=4,c=d?Math.floor(l/4)*4:Math.floor(l/p)*p,_=l-c,f=n?qt(u):1,v=n?u===1?p:f:1,$=be.size(o)/f,w=[Math.ceil($/64),1,1];Tt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let g=["rank","rank"],C=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],b=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],x=[b[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),b[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:$},{type:12,data:C},{type:12,data:E},{type:12,data:y},{type:12,data:b},{type:6,data:x},{type:12,data:c},{type:12,data:l},{type:12,data:u},...st(e[0].dims,e[1].dims)];s&&(S.push(...st(e[2].dims)),g.push("rank")),S.push(...st(o));let A=B=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:C.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:b.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],G=mr(e[0].dataType),j=n?1:2,ee=n?2:3,H=n?3:1,Z=Pe("W",e[1].dataType,e[1].dims.length,v),X=Pe("Dy",e[0].dataType,e[0].dims.length,p),oe=[X,Z];s&&oe.push(Pe("bias",e[2].dataType,[o[H]].length,f));let me=Ze("result",e[0].dataType,o.length,f),ae=()=>{let W="";if(d)p===4?W+=` - let xValue = ${X.getByOffset("x_offset")}; - let wValue = ${Z.getByOffset("w_offset")}; - dotProd = dotProd + dot(xValue, wValue); - x_offset += 1u; - w_offset += 1u;`:p===2?W+=` - dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")})); - x_offset += 2u; - w_offset += 2u;`:p===1&&(W+=` - dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}, ${X.getByOffset("x_offset + 2u")}, ${X.getByOffset("x_offset + 3u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")}, ${Z.getByOffset("w_offset + 2u")}, ${Z.getByOffset("w_offset + 3u")})); - x_offset += 4u; - w_offset += 4u;`);else if(W+=` - let xValue = ${n?X.getByOffset(`${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):X.get("batch","inputChannel","idyR","idyC")}; - `,p===1)W+=` - let w_offset = ${Z.indicesToOffset(`${Z.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; - let wValue = ${Z.getByOffset(`w_offset / ${v}`)}; - dotProd = dotProd + xValue * wValue;`;else for(let re=0;re{if(_===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let W="";if(p===1){W+="dotProd = dotProd";for(let re=0;re<_;re++)W+=` - + ${X.getByOffset(`x_offset + ${re}`)} * ${Z.getByOffset(`w_offset + ${re}`)}`;W+=";"}else if(p===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);W+=` - let xValue = ${X.getByOffset("x_offset")}; - let wValue = ${Z.getByOffset("w_offset")}; - dotProd = dotProd + dot(xValue, wValue);`}return W},F=` - let outputIndices = ${me.offsetToIndices(`global_idx * ${f}`)}; - let batch = ${me.indicesGet("outputIndices",0)}; - let d1 = ${me.indicesGet("outputIndices",H)}; - let r = ${me.indicesGet("outputIndices",j)}; - let c = ${me.indicesGet("outputIndices",ee)}; - let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; - let dyRCorner = dyCorner.x; - let dyCCorner = dyCorner.y; - let groupId = d1 / uniforms.output_channels_per_group; - let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; - // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). - // ? = to be determined. : = across all values in that axis. - var dotProd = ${me.type.value}(0.0); - var wR: u32 = 0; - if (uniforms.dilations.x == 1) { - // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 - wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); - } - for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { - if (wR % uniforms.dilations.x != 0) { - continue; - } - let dyR = (${G}(dyRCorner) + ${G}(wR)) / ${G}(uniforms.strides[0]); - let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; - if (dyR < 0.0 || dyR >= ${G}(uniforms.Dy_shape[${j}]) || fract(dyR) > 0.0 || - wRPerm < 0) { - continue; - } - let idyR: u32 = u32(dyR); - var wC: u32 = 0; - if (uniforms.dilations.y == 1) { - // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 - wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); - } - for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { - if (wC % uniforms.dilations.y != 0) { - continue; - } - let dyC = (${G}(dyCCorner) + ${G}(wC)) / ${G}(uniforms.strides.y); - let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; - if (dyC < 0.0 || dyC >= ${G}(uniforms.Dy_shape[${ee}]) || - fract(dyC) > 0.0 || wCPerm < 0) { - continue; - } - let idyC: u32 = u32(dyC); - var inputChannel = groupId * uniforms.input_channels_per_group; - ${d?` - var x_offset = ${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; - var w_offset = ${Z.indicesToOffset(`${Z.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${v}; - `:""} - for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { - ${ae()} - inputChannel = inputChannel + ${d?4:p}; - } - ${V()} - wC = wC + uniforms.strides.y - 1; - } - wR = wR + uniforms.strides[0] - 1; - } - let value = dotProd${s?` + bias[d1 / ${f}]`:""}; - ${me.setByOffset("global_idx","value")}; - `;return` - ${B.registerUniforms(K).declareVariables(...oe,me)} - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${v}${f}${d}${_}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:A}}}),ng,og,ig,nu,My,ag,ou,lg,yy,Mx=Re(()=>{bx(),Bn(),Js(),ng=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,og=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},ig=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,d=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,c)=>d*c,1)===0){t.length=0;for(let d=2;dd+c,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let u=e.strides.slice();if(u.reduce((d,c)=>d+c,0)===0){let d=r[0].dims.length-2;u=new Array(d).fill(1)}ig(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},My=e=>{let r=pd(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},ag=(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 o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+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((i,a)=>i+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")},ou=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(Vr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(by(n,t,s),{inputs:n})},lg=(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 o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let u=nu({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);ou(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},yy=(e,r)=>{if(ag(e.inputs,r),e.inputs[0].dims.length===3)lg(e,r);else{let t=nu(r,e.inputs);ou(e,e.inputs,t)}}}),ug,vy,xy,yx=Re(()=>{ut(),ft(),Jt(),_t(),ug=(e,r,t,s)=>{let o=be.size(r),n=r.length,i=Pe("input",e,n),a=Ze("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=be.normalizeAxis(l,n),p=d=>{let c=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,_=rt("uniforms.input_shape","uniforms.axis",n),f=s.reverse?c+(s.exclusive?" + 1":""):"0",v=s.reverse?_:c+(s.exclusive?"":" + 1");return` - ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var inputIndices = ${a.offsetToIndices("global_idx")}; - var sum = ${a.type.value}(0); - let first : i32 = ${f}; - let last : i32 = ${v}; - for (var i : i32 = first; i < last; i++) { - ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; - sum = sum + ${i.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(o/64)},programUniforms:[{type:12,data:o},{type:12,data:u},...st(r,r)]}),getShaderSource:p}},vy=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(ug(s,t,o,r),{inputs:[0]})},xy=e=>{let r=e.exclusive===1,t=e.reverse===1;return $t({exclusive:r,reverse:t})}}),dg,cg,pg,Ty,Ey,vx=Re(()=>{ut(),ft(),Jt(),_t(),dg=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.")},cg=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { - var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),c=d.dims.length,_=e.dataType,f=Pe("a",_,c),v=Ze("output",_,c),$=w=>` - ${w.registerUniform("output_size","u32").declareVariables(f,v)} - - ${cg(a,c,f,v)} - - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${v.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${v.setByOffset("global_idx",f.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let g=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],C=be.size(g),E=d.dims,y=be.sortBasedOnPerm(E,a);return{outputs:[{dims:g,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...st(E,y)]}},getShaderSource:$}},Ty=(e,r)=>{dg(e.inputs),e.compute(pg(e.inputs[0],r))},Ey=e=>$t({blocksize:e.blocksize,mode:e.mode,format:e.format})}),na,No,iu,hg,mg,fg,_g,au,gg,Py,Cy,xx=Re(()=>{ut(),ft(),Jt(),_t(),na="[a-zA-Z]|\\.\\.\\.",No="("+na+")+",iu="^"+No+"$",hg="("+No+",)*"+No,mg="^"+hg+"$",fg=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)}},_g=class{constructor(e,r){var o;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(mg)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(iu)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(No)))throw new Error("Invalid RHS");(o=s.match(RegExp(na,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.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 o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(iu))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(na,"g")),u=new fg(s);return l==null||l.forEach((p,d)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let c=o-l.length+1;if(c<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+c),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let _=0;_e+"_max",gg=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Pe(`input${p}`,r,u)),n=be.size(s),i=Ze("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],d="var prod = 1.0;",c="var sum = 0.0;",_="sum += prod;",f=[],v=[],$=[],w=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,y)=>{var b;if(t.rhs.symbolToIndices.has(y)){let x=(b=t.rhs.symbolToIndices.get(y))==null?void 0:b[0];x!==void 0&&t.lhs.forEach((S,A)=>{if(E.inputIndices.includes(A)){let B=S.symbolToIndices.get(y);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(K=>{p.push(`${o[A].indicesSet(`input${A}Indices`,K,i.indicesGet("outputIndices",x))}`)})}})}else t.lhs.forEach((x,S)=>{if(E.inputIndices.includes(S)){let A=x.symbolToIndices.get(y);if(A===void 0)throw new Error("Invalid symbol error");A.forEach(B=>{f.push(`${o[S].indicesSet(`input${S}Indices`,B,`${y}`)}`)}),w.push(`prod *= ${o[S].getByIndices(`input${S}Indices`)};`)}}),v.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${au(y)}; ${y}++) {`),$.push("}")});let C=g?[...p,`let sum = ${o.map((E,y)=>E.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,c,...v,...f,d,...w,_,...$];return` - ${u.registerUniforms(a.map(E=>({name:`${au(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} - - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${i.offsetToIndices("global_idx")}; - ${o.map((E,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` -`)} - ${C.join(` -`)}; - ${i.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(d=>t.symbolToInfo.has(d)).map(d=>{var c;return{type:12,data:((c=t.symbolToInfo.get(d))==null?void 0:c.dimValue)||0}});u.push({type:12,data:n});let p=e.map((d,c)=>[...st(d)]).reduce((d,c)=>d.concat(c),u);return p.push(...st(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Py=(e,r)=>{let t=new _g(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(gg(o,e.inputs[0].dataType,t,s))},Cy=e=>{let r=e.equation.replace(/\s+/g,"");return $t({equation:r})}}),wg,lu,bg,Mg,Sy,Tx=Re(()=>{ut(),ft(),_t(),wg=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 o=0;oe.length>r.length?lu(e,r):lu(r,e),Mg=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=bg(r,t),o=e[0].dataType,n=o===9||be.size(r)===1,i=o===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(be.size(s)/a),u=d=>{let c=Pe("input",o,r.length,i),_=Ze("output",o,s.length,a),f;if(o===9){let v=($,w,g="")=>` - let outputIndices${w} = ${_.offsetToIndices(`outputOffset + ${w}u`)}; - let offset${w} = ${c.broadcastedIndicesToOffset(`outputIndices${w}`,_)}; - let index${w} = offset${w} / 4u; - let component${w} = offset${w} % 4u; - ${$}[${w}] = ${g}(${c.getByOffset(`index${w}`)}[component${w}]); - `;f=` - let outputOffset = global_idx * ${a}; - var data = vec4(0); - ${v("data",0,"u32")} - ${v("data",1,"u32")} - ${v("data",2,"u32")} - ${v("data",3,"u32")} - ${_.setByOffset("global_idx","data")} - }`}else f=` - let outputIndices = ${_.offsetToIndices(`global_idx * ${a}`)}; - let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",_)}; - let data = ${_.type.value}(${c.getByOffset(`inputOffset / ${i}`)}); - ${_.setByOffset("global_idx","data")} - }`;return` - ${d.registerUniform("vec_size","u32").declareVariables(c,_)} - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${f}`},p=[{type:12,data:l},...st(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Sy=e=>{wg(e.inputs),e.compute(Mg(e.inputs),{inputs:[0]})}}),yg,$y,Ex=Re(()=>{ut(),ft(),_t(),cd(),yg=e=>{let r=e[0].dataType,t=be.size(e[0].dims),s=be.size(e[1].dims),o=s%4===0,n=i=>{let a=Pe("x",r,[1],4),l=Pe("bias",r,[1],4),u=Ze("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=_=>` - let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size; - let bias${_} = ${l.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,c=o?` - let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} - let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,u)} - - ${Ru(Er(r))} - - ${i.mainStart(io)} - ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} - - let x = ${a.getByOffset("global_idx")}; - ${c} - let x_in = x + bias; - ${u.setByOffset("global_idx",ju("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/io/4)}})}},$y=e=>{e.inputs.length<2||be.size(e.inputs[1].dims)===0?XM(e):e.compute(yg(e.inputs))}}),vg,xg,ky,Iy,Px=Re(()=>{ut(),ft(),Jt(),_t(),vg=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},xg=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=be.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(be.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...st(e[0].dims,e[1].dims,i)],d=c=>{let _=Pe("data",e[0].dataType,e[0].dims.length,l),f=Pe("inputIndices",e[1].dataType,e[1].dims.length),v=Ze("output",e[0].dataType,i.length,l),$=g=>{let C=s.length,E=`var indicesIndices${g} = ${f.type.indices}(0);`;for(let y=0;y1?`indicesIndices${g}[${y}]`:`indicesIndices${g}`} = ${i.length>1?`outputIndices${g}[uniforms.axis + ${y}]`:`outputIndices${g}`};`;E+=` - var idx${g} = ${f.getByIndices(`indicesIndices${g}`)}; - if (idx${g} < 0) { - idx${g} = idx${g} + uniforms.axisDimLimit; - } - var dataIndices${g} : ${_.type.indices}; - `;for(let y=0,b=0;y1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = u32(idx${g});`,b+=C):(E+=`${o>1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = ${i.length>1?`outputIndices${g}[${b}]`:`outputIndices${g}`};`,b++);return E},w;if(e[0].dataType===9){let g=(C,E,y="")=>` - let outputIndices${E} = ${v.offsetToIndices(`outputOffset + ${E}u`)}; - ${$(E)}; - let offset${E} = ${_.indicesToOffset(`dataIndices${E}`)}; - let index${E} = offset${E} / 4u; - let component${E} = offset${E} % 4u; - ${C}[${E}] = ${y}(${_.getByOffset(`index${E}`)}[component${E}]); - `;w=` - let outputOffset = global_idx * ${l}; - var value = vec4(0); - ${g("value",0,"u32")} - ${g("value",1,"u32")} - ${g("value",2,"u32")} - ${g("value",3,"u32")} - ${v.setByOffset("global_idx","value")} - `}else w=` - let outputIndices = ${v.offsetToIndices("global_idx")}; - ${$("")}; - let value = ${_.getByIndices("dataIndices")}; - ${v.setByOffset("global_idx","value")}; - `;return` - ${c.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,f,v)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${w} - }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:d}},ky=e=>$t({axis:e.axis}),Iy=(e,r)=>{let t=e.inputs;vg(t),e.compute(xg(e.inputs,r))}}),Tg,Ay,Fy,Cx=Re(()=>{ut(),ft(),_t(),Tg=(e,r,t,s,o,n,i,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...st(r.dims,p));let d=c=>{let _=Pe("indices_data",r.dataType,r.dims.length),f=Ze("input_slice_offsets_data",12,1,1),v=[_,f],$=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.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` - ${c.registerUniforms($).declareVariables(...v)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let batch_idx = global_idx / uniforms.num_slices_per_batch; - let base_offset = batch_idx * uniforms.input_batch_stride; - - let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; - var relative_slice_offset = 0; - for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { - var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); - let input_dim_idx = uniforms.batch_dims + dim_idx; - if (index < 0) { - ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} - } - ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} - } - - input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); - }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},Ay=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=be.sizeToDimension(n,n.length-1),l=be.sizeFromDimension(s,r.batchDims+i),u=be.sizeToDimension(s,r.batchDims),p=be.sizeFromDimension(s,r.batchDims),d=a/u,c=new Array(i),_=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let $=n.slice(0,-1).concat(s.slice(v)),w=be.size($),g=[{type:12,data:w},{type:12,data:l},...st(t[0].dims,f.dims,$)],C=E=>{let y=Pe("data",t[0].dataType,t[0].dims.length),b=Pe("slice_offsets",12,f.dims.length),x=Ze("output",t[0].dataType,$.length);return` - ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,b,x)} - ${E.mainStart()} - ${E.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:$,dataType:o}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:g}),getShaderSource:C},{inputs:[t[0],f]})},Fy=e=>({batchDims:e.batch_dims,cacheKey:""})}),Eg,Pg,Oy,Dy,Sx=Re(()=>{ut(),ft(),Jt(),_t(),Eg=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=be.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.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(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.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.")}},Pg=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=be.normalizeAxis(r.gatherAxis,o),i=be.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=be.size(a),u=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...st(...e.map((_,f)=>_.dims),a)],c=_=>{let f=Pe("data",e[0].dataType,e[0].dims.length),v=Pe("inputIndices",e[1].dataType,e[1].dims.length),$=Pe("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Pe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=Ze("output",u,a.length),C=[f,v,$];w&&C.push(w);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${_.registerUniforms(E).declareVariables(...C,g)} - ${_.mainStart()} - let output_indices = ${g.offsetToIndices("global_idx")}; - var indices_indices = ${v.type.indices}(0); - ${s.length>1?` - for (var i: u32 = 0; i < ${s.length}; i++) { - let index = ${g.indicesGet("output_indices","uniforms.gather_axis + i")}; - ${v.indicesSet("indices_indices","i","index")}; - }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; - var data_indices = ${f.type.indices}(0); - for (var i: u32 = 0; i < uniforms.gather_axis; i++) { - let index = ${g.indicesGet("output_indices","i")}; - ${f.indicesSet("data_indices","i","index")}; - } - var index_from_indices = ${v.getByIndices("indices_indices")}; - if (index_from_indices < 0) { - index_from_indices += ${t[n]}; - } - ${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; - for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { - let index = ${g.indicesGet("output_indices",`i + ${s.length} - 1`)}; - ${f.indicesSet("data_indices","i","index")}; - } - 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 = ${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]; - var scale_indices = data_indices; - let quantize_axis_index = ${$.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; - ${$.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; - var scale = ${$.getByIndices("scale_indices")}; - ${w?` - let zero_point_indices = scale_indices; - let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; - let zero_point_index = zero_point_offset % 8; - let packed_4bit_zero_points = ${w.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 = ${Er(u)}(quantized_data - zero_point) * scale; - ${g.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((_,f)=>f!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,f)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:c}},Oy=(e,r)=>{let t=e.inputs;Eg(t,r),e.compute(Pg(e.inputs,r))},Dy=e=>$t({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Cg,Sg,Ly,zy,$x=Re(()=>{ut(),ft(),Jt(),_t(),Cg=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.`)},Sg=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=be.normalizeAxis(r.axis,o),l=t[a],u=n.slice(0),p=be.size(u),d=Pe("input",s,o),c=Pe("indicesInput",i,n.length),_=Ze("output",s,u.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return f.push(...st(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:v=>` - ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,c,_)} - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let outputIndices = ${_.offsetToIndices("global_idx")}; - - var idx = ${c.getByOffset("global_idx")}; - if (idx < 0) { - idx = idx + uniforms.axisDimLimit; - } - var inputIndices = ${d.type.indices}(outputIndices); - ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; - let value = ${d.getByIndices("inputIndices")}; - - ${_.setByOffset("global_idx","value")}; - }`}},Ly=e=>$t({axis:e.axis}),zy=(e,r)=>{let t=e.inputs;Cg(t),e.compute(Sg(e.inputs,r))}}),$g,kg,By,Ry,kx=Re(()=>{ut(),ft(),_t(),$g=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")},kg=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=Lb.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,c=be.size(a),_=[{type:12,data:d?u:c},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(_.push(...st(e[2].dims)),f.push("rank")),_.push(...st(a));let v=w=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=r.alpha===1?"":"value *= uniforms.alpha;",E=Pe("a",e[0].dataType,e[0].dims),y=Pe("b",e[1].dataType,e[1].dims),b=E.type.value,x=null,S=[E,y];e.length===3&&(x=Pe("c",e[2].dataType,e[2].dims.length),S.push(x));let A=Ze("output",e[0].dataType,a.length);S.push(A);let B=[{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` - ${w.registerUniforms(B).declareVariables(...S)} - - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${b}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${g} - } - - ${C} - ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${b}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} - output[global_idx] = value; - }`},$=w=>{let g=Pe("a",e[0].dataType,e[0].dims),C=Pe("b",e[1].dataType,e[1].dims),E=null,y=[g,C];e.length===3&&(E=Pe("c",e[2].dataType,e[2].dims.length),y.push(E));let b=Ze("output",e[0].dataType,a.length);y.push(b);let x=[{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"}],S="",A="";r.transA&&r.transB?(A=` - var col = tile_row_start + local_id.x; - var row = k_start + local_id.y; - if (col < uniforms.M && row < uniforms.K) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = k_start + local_id.x; - row = tile_col_start + local_id.y; - 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] = ${C.type.value}(0); - } - `,S="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(A=` - var col = tile_row_start + local_id.x; - var row = k_start + local_id.y; - if (col < uniforms.M && row < uniforms.K) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = tile_col_start + local_id.x; - row = k_start + local_id.y; - 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] = ${C.type.value}(0); - } - `,S="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(A=` - var col = k_start + local_id.x; - var row = tile_row_start + local_id.y; - if (col < uniforms.K && row < uniforms.M) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = k_start + local_id.x; - row = tile_col_start + local_id.y; - 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] = ${C.type.value}(0); - } - `,S="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(A=` - var col = k_start + local_id.x; - var row = tile_row_start + local_id.y; - if (col < uniforms.K && row < uniforms.M) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = tile_col_start + local_id.x; - row = k_start + local_id.y; - 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] = ${C.type.value}(0); - } - `,S="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let B=r.alpha===1?"":"value *= uniforms.alpha;";return` - ${w.registerUniforms(x).declareVariables(...y)} - var tile_a: array, ${l}>; - var tile_b: array, ${l}>; - ${w.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; - var k_start = 0u; - var value = ${b.type.value}(0); - for (var t: u32 = 0u; t < num_tiles; t++) { - ${A} - k_start = k_start + ${l}; - workgroupBarrier(); - - for (var k: u32 = 0u; k < ${l}; k++) { - ${S} - } - workgroupBarrier(); - } - - ${B} - let m = tile_row_start + local_id.y; - let n = tile_col_start + local_id.x; - ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",b)}; value += ${b.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} - if (m < uniforms.M && n < uniforms.N) { - output[m * uniforms.N + n] = value; - } - }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:_}),getShaderSource:$}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:_}),getShaderSource:v}},By=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Ry=(e,r)=>{$g(e.inputs),e.compute(kg(e.inputs,r))}}),vs,Is,Pn,Cn,Ig,Ag,Fg,Og,Dg,Lg,zg,Bg,jy,Ny,Ix=Re(()=>{ut(),ft(),Jt(),_t(),[vs,Is,Pn,Cn]=[0,1,2,3],Ig=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")},Ag=` - fn gs_get_cubic_coeffs(x: f32) -> vec4 { - let cubic_alpha = -0.75f; - let x_abs = abs(x); - var coeffs: vec4; - coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); - coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); - coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); - coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); - return coeffs; - } -`,Fg=e=>` - fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { - var v: vec4; - var coeffs = gs_get_cubic_coeffs(x); - for (var i = 0; i < 4; i++) { - v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; - } - coeffs = gs_get_cubic_coeffs(y); - let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); - return pixel; - } -`,Og=e=>` - fn gs_denormalize(n: f32, length: i32) -> f32 { - ${e.alignCorners===0?` - // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] - return ((n + 1.0) * f32(length) - 1.0) / 2.0; - `:` - // alignCorners: true => [-1, 1] to [0, length - 1] - return (n + 1.0) / 2.0 * (f32(length - 1)); - `} - } -`,Dg=e=>` - ${e.paddingMode==="reflection"?` - fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { - var dx = 0.0; - var fx = f32(x); - let range = x_max - x_min; - if (fx < x_min) { - dx = x_min - fx; - let n = u32(dx / range); - let r = dx - f32(n) * range; - if (n % 2 == 0) { - fx = x_min + r; - } else { - fx = x_max - r; - } - } else if (fx > x_max) { - dx = fx - x_max; - let n = u32(dx / range); - let r = dx - f32(n) * range; - if (n % 2 == 0) { - fx = x_max - r; - } else { - fx = x_min + r; - } - } - return u32(fx); - }`:""} -`,Lg=(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); - indices[${vs}] = batch; - indices[${Is}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` - if (r >= 0 && r < H && c >=0 && c < W) { - indices[${Pn}] = u32(r); - indices[${Cn}] = u32(c); - } else { - return ${r}(0); - } - `;case"border":return` - indices[${Pn}] = u32(clamp(r, 0, H - 1)); - indices[${Cn}] = u32(clamp(c, 0, W - 1)); - `;case"reflection":return` - indices[${Pn}] = gs_reflect(r, border[1], border[3]); - indices[${Cn}] = gs_reflect(c, border[0], border[2]); - `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` - return ${e.getByIndices("indices")}; - } -`,zg=(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)); - let y1 = i32(floor(y)); - let x2 = x1 + 1; - let y2 = y1 + 1; - - let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${vs}], indices[${Is}], border); - let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${vs}], indices[${Is}], border); - let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${vs}], indices[${Is}], border); - let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${vs}], indices[${Is}], border); - - let dx2 = ${r}(f32(x2) - x); - let dx1 = ${r}(x - f32(x1)); - let dy2 = ${r}(f32(y2) - y); - let dy1 = ${r}(y - f32(y1)); - let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); - `;case"bicubic":return` - let x0 = i32(floor(x)) - 1; - let y0 = i32(floor(y)) - 1; - var p: mat4x4<${r}>; - for (var h = 0; h < 4; h++) { - for (var w = 0; w < 4; w++) { - p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${vs}], indices[${Is}], border); - } - } - - 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")}`,Bg=(e,r)=>{let t=Pe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Pe("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,Pn,Cn]=[0,3,1,2]);let i=Ze("output",e[0].dataType,n.length),a=t.type.value,l=be.size(n),u=[{type:12,data:l},...st(e[0].dims,s,n)],p=d=>` - ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} - ${Ag} - ${Fg(a)} - ${Og(r)} - ${Dg(r)} - ${Lg(t,a,r)} - - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let H_in = i32(uniforms.x_shape[${Pn}]); - let W_in = i32(uniforms.x_shape[${Cn}]); - - ${r.alignCorners===0?` - let x_min = -0.5; - let x_max = f32(W_in) - 0.5; - let y_min = -0.5; - let y_max = f32(H_in) - 0.5; - `:` - let x_min = 0.0; - let x_max = f32(W_in) - 1.0; - let y_min = 0.0; - let y_max = f32(H_in) - 1.0; - `}; - let border = vec4(x_min, y_min, x_max, y_max); - - let indices = ${i.offsetToIndices("global_idx")}; - var grid_indices = vec3(indices[${vs}], indices[${Pn}], indices[${Cn}]); - let nxy = ${o.getByIndices("grid_indices")}; - var x = gs_denormalize(f32(nxy[0]), W_in); - var y = gs_denormalize(f32(nxy[1]), H_in); - - ${zg(i,a,r)} - }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let c=be.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u}},getShaderSource:p}},jy=(e,r)=>{Ig(e.inputs),e.compute(Bg(e.inputs,r))},Ny=e=>$t({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),$r,Rg,Vy,uu,jg,Xo,Uy,Wy=Re(()=>{ut(),ft(),Jt(),ad(),dd(),_t(),Js(),$r=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Rg=(e,r)=>{let t=e[0],s=$r(e,1),o=$r(e,2),n=$r(e,3),i=$r(e,4),a=$r(e,5),l=$r(e,6),u=$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],d=t.dims[1],c=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],_=d,f=0,v=0,$=Math.floor(c/r.numHeads);if(l&&u&&be.size(l.dims)&&be.size(u.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]!==$)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==$)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],v=l.dims[2]}else if(l&&be.size(l.dims)||u&&be.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&be.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)');w=2,_=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,_=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');w=0,_=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');w=3}if(n&&be.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 g=f+_,C=0;if(i&&be.size(i.dims)>0){C=8;let x=i.dims;throw x.length===1?x[0]===p?C=1:x[0]===3*p+2&&(C=3):x.length===2&&x[0]===p&&x[1]===g&&(C=5),C===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let E=!1,y=c;if(o&&be.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],E=!0}}let b=!1;if(i&&be.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&be.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]!==d||a.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:f,kvSequenceLength:_,totalSequenceLength:g,maxSequenceLength:v,inputHiddenSize:0,hiddenSize:c,vHiddenSize:y,headSize:$,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:C,scale:r.scale,broadcastResPosBias:b,passPastInKv:E,qkvFormat:w}},Vy=e=>$t({...e}),uu=$t({perm:[0,2,1,3]}),jg=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=be.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let c=Ze("qkv_with_bias",r.dataType,a),_=Pe("qkv",r.dataType,a),f=Pe("bias",t.dataType,a),v=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${d.registerUniforms(v).declareVariables(_,f,c)} - ${d.mainStart()} - ${d.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:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Xo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&be.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=jg(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(Vr(l,uu.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(Vr(l,uu.perm),{inputs:[l],outputs:[-1]})[0]},Uy=(e,r)=>{let t=Rg(e.inputs,r),s=e.inputs[0],o=$r(e.inputs,1),n=$r(e.inputs,2),i=$r(e.inputs,3),a=$r(e.inputs,4),l=$r(e.inputs,5),u=$r(e.inputs,6),p=$r(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let d=o&&n&&o.dims.length===4&&n.dims.length===4,c=Xo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return Zo(e,c,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let _=Xo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),f=Xo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);Zo(e,c,_,f,a,void 0,u,p,l,t)}}),Ng,Vg,Ug,Wg,Gu,Gy,Ky,Hy=Re(()=>{ut(),ft(),Jt(),_t(),Ng=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Vg=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),$t({numOutputs:s,axis:r.axis,splitSizes:t})},Ug=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)}) { - return i; - } - } - return ${e}u; -}`,Wg=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=be.size(t),o=e[0].dataType,n=be.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Pe("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],d=0,c=[{type:12,data:s}];for(let f=0;f` - ${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} - ${Ug(l.length)} - ${Wg(i)} - - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} - - var indices = ${a.offsetToIndices("global_idx")}; - var index = ${a.indicesGet("indices",n)}; - let output_number = calculateOutputIndex(index); - if (output_number != 0) { - index -= ${rt("uniforms.size_in_split_axis","output_number - 1u",l.length)}; - ${a.indicesSet("indices",n,"index")}; - } - writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c})}},Gy=(e,r)=>{Ng(e.inputs);let t=e.inputs.length===1?r:Vg(e.inputs,r);e.compute(Gu(e.inputs,t),{inputs:[0]})},Ky=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 $t({axis:r,numOutputs:s,splitSizes:t})}}),Gg,ga,qy,Xy=Re(()=>{ut(),ft(),Jt(),_t(),Gg=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,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(!be.areEqual(s.dims,[])&&!be.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(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!be.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],p=o.dims[0],d=be.sizeFromDimension(t.dims,1)/u,c=a===0?o.dims[1]*2:d/i;if(a>c)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(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(c/2!==o.dims[1]&&a/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ga=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=be.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],d=o===0?p*2:u/s,c=new Array(i,l,u/d,d-p),_=be.computeStrides(c),f=[{type:1,data:n},{type:12,data:c},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[a,u,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...st(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],v=$=>{let w=Pe("input",e[0].dataType,e[0].dims.length),g=Pe("position_ids",e[1].dataType,e[1].dims.length),C=Pe("cos_cache",e[2].dataType,e[2].dims.length),E=Pe("sin_cache",e[3].dataType,e[3].dims.length),y=Ze("output",e[0].dataType,e[0].dims.length);return $.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:c.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),` - ${$.declareVariables(w,g,C,E,y)} - - ${$.mainStart(io)} - let half_rotary_emb_dim = uniforms.${C.name}_shape[1]; - let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; - let size = uniforms.global_shape[0] * uniforms.global_strides[0]; - ${$.guardAgainstOutOfBoundsWorkgroupSizes("size")} - - if (bsnh[3] < half_rotary_emb_dim) { - let position_ids_idx = - ${g.broadcastedIndicesToOffset("bsnh.xy",Ze("",g.type.tensor,2))}; - let position_id = - u32(${g.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 = ${w.getByOffset("i")} * ${C.get("position_id","bsnh[3]")} - - ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; - ${y.setByOffset("i","re")} - let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + - ${w.getByOffset("j")} * ${C.get("position_id","bsnh[3]")}; - ${y.setByOffset("j","im")} - } else { - let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; - ${y.setByOffset("k",w.getByOffset("k"))} - } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:$t({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(be.size(c)/io)},programUniforms:f})}},qy=(e,r)=>{Gg(e.inputs,r),e.compute(ga(e.inputs,r))}}),Kg,Hg,du,qg,Qy,Ax=Re(()=>{Jt(),ut(),dd(),Wy(),Hy(),Js(),Xy(),_t(),Kg=(e,r)=>{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],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");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],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=u,c=0,_=!s||s.dims.length===0,f=Math.floor(_?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);_&&(p=f*r.numHeads);let v=n&&n.dims.length!==0,$=i&&i.dims.length!==0;if(v&&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(v&&$){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');c=n.dims[2]}else if(v||$)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=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"');d=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');d=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');d=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');w=3}let g=0,C=!1,E=r.kvNumHeads?f*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],C=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.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:u,pastSequenceLength:c,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:f,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:C,qkvFormat:w}},Hg=$t({perm:[0,2,1,3]}),du=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(Vr(s,Hg.perm),{inputs:[s],outputs:[-1]})[0]),s},qg=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],u=p=>{let d=Pe("seq_lens",t.dataType,t.dims),c=Pe("total_seq_lens",s.dataType,s.dims),_=Ze("pos_ids",o,i),f=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` - ${p.registerUniforms(f).declareVariables(d,c,_)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let total_sequence_length = u32(${c.getByOffset("0")}); - let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; - let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; - let batch_idx = global_idx / uniforms.sequence_length; - let sequence_idx = i32(global_idx % uniforms.sequence_length); - var pos_id: i32 = 0; - let seqlen = ${d.getByOffset("batch_idx")}; - let total_seqlen = seqlen + 1; - if (is_first_prompt) { - if (sequence_idx < total_seqlen) { - pos_id = sequence_idx; - } else { - pos_id = 1; - } - ${_.setByOffset("global_idx","pos_id")} - } else if (is_subsequent_prompt) { - let past_seqlen = total_seqlen - i32(uniforms.sequence_length); - if (past_seqlen + sequence_idx < total_seqlen) { - pos_id = past_seqlen + sequence_idx; - } else { - pos_id = 1; - } - ${_.setByOffset("global_idx","pos_id")} - } else if (global_idx < uniforms.batch_size) { - ${_.setByOffset("global_idx","seqlen")} - }; - } - `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:u}},Qy=(e,r)=>{var E;let t=Kg(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=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,i=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,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=$t({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[c,_,f]=!o&&!n?e.compute(Gu([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],v,$;if(r.doRotary){let y=e.compute(qg(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],b=e.inputs[7],x=e.inputs[8],S=$t({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),A=[c,y,b,x],B=[-1];v=e.compute(ga(A,S),{inputs:A,outputs:B})[0],A.splice(0,1,_);let K=$t({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});$=e.compute(ga(A,K),{inputs:A,outputs:B})[0]}let w=Xo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?v:c,void 0,0),g=du(e,r.doRotary?$:_,t),C=du(e,f,t);Zo(e,w,g,C,void 0,void 0,i,a,void 0,t,l,u)}}),cu,Xg,Qg,Jy,Fx=Re(()=>{ut(),ft(),Js(),_t(),cu=(e,r,t,s,o,n,i,a)=>{let l=qt(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*i,c=64;d===1&&(c=256);let _=[o,i,n/l],f=[o,i,2],v=["rank","type","type"],$=[];$.push(...st(_,f));let w=g=>{let C=Pe("x",r.dataType,3,l),E=Pe("scale",t.dataType,t.dims),y=Pe("bias",s.dataType,s.dims),b=Ze("output",1,3,2),x=[C,E,y,b];return` - var workgroup_shared : array<${p}, ${c}>; - const workgroup_size = ${c}u; - ${g.declareVariables(...x)} - ${g.mainStart(c)} - let batch = workgroup_index / uniforms.x_shape[1]; - let channel = workgroup_index % uniforms.x_shape[1]; - let hight = uniforms.x_shape[2]; - // initialize workgroup memory - var sum = ${u}(0); - var squared_sum = ${u}(0); - for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${u}(${C.get("batch","channel","h")}); - sum += value; - squared_sum += value * value; - } - workgroup_shared[local_idx] = ${p}(sum, squared_sum); - workgroupBarrier(); - - for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { - if (local_idx < currSize) { - workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; - } - workgroupBarrier(); - } - if (local_idx == 0) { - let sum_final = ${Qs("workgroup_shared[0][0]",l)} / f32(hight * ${l}); - let squared_sum_final = ${Qs("workgroup_shared[0][1]",l)} / f32(hight * ${l}); - - let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); - let channel_scale = inv_std_dev * f32(scale[channel]); - 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};${c}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:d},programUniforms:$}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},Xg=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=be.sizeFromDimension(s,n),u=qt(l),p=be.size(o)/u,d=cu(e,r[0],r[1],r[2],i,l,a,t.epsilon),c=[i,a,l/u],_=[i,a],f=["type","none"],v=$=>{let w=Pe("x",r[0].dataType,c.length,u),g=Pe("scale_shift",1,_.length,2),C=Ze("output",r[0].dataType,c.length,u),E=[w,g,C];return` - ${$.registerUniform("output_size","u32").declareVariables(...E)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${C.offsetToIndices("global_idx")}; - let batch = outputIndices[0]; - let channel = outputIndices[1]; - let scale_shift = ${g.getByIndices("vec2(batch, channel)")}; - let value = ${w.getByOffset("global_idx")} * ${C.type.value}(scale_shift.x) + ${C.type.value}(scale_shift.y); - ${C.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...st(c,_,c)]}),getShaderSource:v},{inputs:[r[0],d]})},Qg=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=be.sizeFromDimension(s,1)/i,l=qt(i),u=be.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],c=!1,_=[0,s.length-1];for(let w=0;ws[_[g]])),v=cu(e,f,r[1],r[2],n,a,i,t.epsilon),$=w=>{let g=mr(r[0].dataType),C=l===1?"vec2f":`mat${l}x2f`,E=x=>{let S=x===0?"x":"y",A=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${A}(scale.${S}))`;case 2:return`vec2<${g}>(${A}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${g}>(${A}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=Pe("input",r[0].dataType,r[0].dims,l),b=Ze("output",r[0].dataType,o,l);return` - @group(0) @binding(0) var input : array<${y.type.storage}>; - @group(0) @binding(1) var scale_input : array<${C}>; - @group(0) @binding(2) var output : array<${b.type.storage}>; - struct Uniforms {H: u32, C : u32}; - @group(0) @binding(3) var uniforms: Uniforms; - - ${w.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], ${E(0)}, ${E(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:$},{inputs:[r[0],v]})},Jy=(e,r)=>{r.format==="NHWC"?Qg(e,e.inputs,r):Xg(e,e.inputs,r)}}),Jg,Yg,Yy,Ox=Re(()=>{ut(),ft(),_t(),Jg=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Yg=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=be.normalizeAxis(r.axis,o.length),u=be.sizeToDimension(o,l),p=be.sizeFromDimension(o,l),d=be.size(n.dims),c=i?be.size(i.dims):0;if(d!==p||i&&c!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. - Size of scale and bias (if provided) must match this. - Got scale size of ${d} and bias size of ${c}`);let _=[];for(let y=0;y1,g=t>2,C=y=>{let b=mr(e[0].dataType),x=[Pe("x",e[0].dataType,e[0].dims,f),Pe("scale",n.dataType,n.dims,f)];i&&x.push(Pe("bias",i.dataType,i.dims,f)),x.push(Ze("output",e[0].dataType,a,f)),w&&x.push(Ze("mean_data_output",1,_)),g&&x.push(Ze("inv_std_output",1,_));let S=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${y.registerUniforms(S).declareVariables(...x)} - ${y.mainStart()} - ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${Lu("f32",f)}; - var mean_square_vector = ${Lu("f32",f)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${no(b,f,"x[h + offset]")}; - mean_vector += value; - mean_square_vector += value * value; - } - let mean = ${Qs("mean_vector",f)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Qs("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 = ${no(b,f,"x[j + offset]")}; - let f32scale = ${no(b,f,"scale[j]")}; - output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale - ${i?`+ ${no(b,f,"bias[j]")}`:""} - ); - } - - ${w?"mean_data_output[global_idx] = mean":""}; - ${g?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:_,dataType:1}),g&&E.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:v},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:$}),getShaderSource:C}},Yy=(e,r)=>{Jg(e.inputs),e.compute(Yg(e.inputs,r,e.outputCount))}}),Zg,Zy,Dx=Re(()=>{ft(),fd(),_d(),Zg=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.")},Zy=e=>{Zg(e.inputs);let r=oo.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(md(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=be.size(e.inputs[0].dims.slice(0,-2)),i=be.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),u=[1,n,t],p=[a,l];e.compute(_a(p,{activation:""},r,u),{inputs:p})}else e.compute(_a(e.inputs,{activation:""},r))}}}),ew,tw,rw,e0,t0,Lx=Re(()=>{ut(),ft(),Jt(),_t(),ew=(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 o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!be.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(be.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(be.size(l)!==u)throw new Error("zeroPoints input size error.")}},tw=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=be.size(a),u=e[1].dims[2]/4,p=e[0].dataType,d=qt(r.k),c=qt(u),_=qt(i),f=a.concat([o,i]),v=o>1&&i/_%2===0?2:1,$=be.size(f)/_/v,w=64,g=[],C=[l,o,n/d],E=be.convertShape(e[1].dims).slice();E.splice(-1,1,u/c),g.push(...st(C)),g.push(...st(E)),g.push(...st(e[2].dims)),e.length===4&&g.push(...st(be.convertShape(e[3].dims)));let y=[l,o,i/_];g.push(...st(y));let b=x=>{let S=C.length,A=Pe("a",e[0].dataType,S,d),B=Pe("b",12,E.length,c),K=Pe("scales",e[2].dataType,e[2].dims.length),G=[A,B,K],j=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;j&&G.push(j);let ee=y.length,H=Ze("output",e[0].dataType,ee,_),Z=mr(e[0].dataType),X=(()=>{switch(d){case 1:return`array<${Z}, 8>`;case 2:return`mat4x2<${Z}>`;case 4:return`mat2x4<${Z}>`;default:throw new Error(`${d}-component is not supported.`)}})(),oe=()=>{let V=` - // reuse a data - var input_offset = ${A.indicesToOffset(`${A.type.indices}(batch, row, word_offset)`)}; - var a_data: ${X}; - for (var j: u32 = 0; j < ${8/d}; j++) { - a_data[j] = ${A.getByOffset("input_offset")}; - input_offset++; - } - `;for(let F=0;F<_*v;F++)V+=` - b_value = ${c===1?`b${F}_data`:`b${F}_data[i]`}; - b_value_lower = unpack4xU8(b_value & b_mask); - b_value_upper = unpack4xU8((b_value >> 4) & b_mask); - b_quantized_values = ${X}(${Array.from({length:4},(W,re)=>`${Z}(b_value_lower[${re}]), ${Z}(b_value_upper[${re}])`).join(", ")}); - b_dequantized_values = ${d===1?`${X}(${Array.from({length:8},(W,re)=>`(b_quantized_values[${re}] - ${j?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${X}(${Array(8).fill(`${j?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; - workgroup_shared[local_id.x * ${v} + ${Math.floor(F/_)}]${_>1?`[${F%_}]`:""} += ${Array.from({length:8/d},(W,re)=>`${d===1?`a_data[${re}] * b_dequantized_values[${re}]`:`dot(a_data[${re}], b_dequantized_values[${re}])`}`).join(" + ")}; - `;return V},me=()=>{let V=` - var col_index = col * ${_}; - ${j?` - let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; - var zero_point_byte_count: u32; - var zero_point_word_index: u32; - var zero_point_byte_offset: u32; - let zero_point_nibble_offset: u32 = block & 0x1u; - var zero_point_bits_offset: u32; - var zero_point_word: u32;`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${Z}(8);`} - `;for(let F=0;F<_*v;F++)V+=` - let scale${F} = ${K.getByOffset("col_index * nBlocksPerCol + block")}; - ${j?` - zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u); - zero_point_word_index = zero_point_byte_count >> 0x2u; - zero_point_byte_offset = zero_point_byte_count & 0x3u; - zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point${F} = ${Z}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${_};`;for(let F=0;F<_*v;F++)V+=` - let b${F}_data = ${B.getByIndices(`${B.type.indices}(col_index, block, word)`)}; - col_index += 1;`;return V+=` - var b_value: u32; - let b_mask: u32 = 0x0F0F0F0Fu; - var b_value_lower: vec4; - var b_value_upper: vec4; - var b_quantized_values: ${X}; - var b_dequantized_values: ${X};`,V};return` - var workgroup_shared: array<${H.type.value}, ${v*w}>; - ${x.declareVariables(...G,H)} - ${x.mainStart([w,1,1])} - let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${v}`)}; - 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 += ${w}) { - //process one block - var word_offset: u32 = block * ${r.blockSize/d}; - ${me()} - for (var word: u32 = 0; word < ${u}; word += ${c}) { - ${ae()} - for (var i: u32 = 0; i < ${c}; i++) { - ${oe()} - word_offset += ${8/d}; - } - } - } - workgroupBarrier(); - - if (local_id.x < ${v}) { - var output_value: ${H.type.value} = ${H.type.value}(0); - var workgroup_shared_offset: u32 = local_id.x; - for (var b: u32 = 0u; b < ${w}u; b++) { - output_value += workgroup_shared[workgroup_shared_offset]; - workgroup_shared_offset += ${v}; - } - ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; - } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${c};${_};${v};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:$},programUniforms:g}),getShaderSource:b}},rw=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=be.size(a),u=e[1].dims[2]/4,p=e[0].dataType,d=qt(r.k),c=qt(u),_=a.concat([o,i]),f=128,v=i%8===0?8:i%4===0?4:1,$=f/v,w=$*c*8,g=w/d,C=w/r.blockSize,E=be.size(_)/v,y=[],b=[l,o,n/d],x=be.convertShape(e[1].dims).slice();x.splice(-1,1,u/c),y.push(...st(b)),y.push(...st(x)),y.push(...st(e[2].dims)),e.length===4&&y.push(...st(be.convertShape(e[3].dims)));let S=[l,o,i];y.push(...st(S));let A=B=>{let K=b.length,G=Pe("a",e[0].dataType,K,d),j=Pe("b",12,x.length,c),ee=Pe("scales",e[2].dataType,e[2].dims.length),H=[G,j,ee],Z=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;Z&&H.push(Z);let X=S.length,oe=Ze("output",e[0].dataType,X),me=mr(e[0].dataType),ae=()=>{switch(d){case 1:return` - let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); - let a_data1 = vec4<${me}>(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<${me}>(sub_a[word_offset], sub_a[word_offset + 1]); - let a_data1 = vec4<${me}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` - let a_data0 = sub_a[word_offset]; - let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` - var sub_a: array<${G.type.value}, ${g}>; - var inter_results: array, ${v}>; - ${B.declareVariables(...H,oe)} - ${B.mainStart([$,v,1])} - let output_indices = ${oe.offsetToIndices(`workgroup_index * ${v}`)}; - 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) / ${C} + 1; - - // Loop over shared dimension. - for (var tile: u32 = 0; tile < num_tiles; tile += 1) { - let a_col_start = tile * ${g}; - // load one tile A data into shared memory. - for (var a_offset = local_idx; a_offset < ${g}; a_offset += ${f}) - { - let a_col = a_col_start + a_offset; - if (a_col < uniforms.a_shape[2]) - { - sub_a[a_offset] = ${G.getByIndices(`${G.type.indices}(batch, row, a_col)`)}; - } else { - sub_a[a_offset] = ${G.type.value}(0); - } - } - workgroupBarrier(); - - // each thread process one block - let b_row = col + local_id.y; - let block = tile * ${C} + local_id.x; - ${Z?` - 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); - let zero_point_word_index = zero_point_byte_count >> 0x2u; - let zero_point_byte_offset = zero_point_byte_count & 0x3u; - let zero_point_nibble_offset: u32 = block & 0x1u; - let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - let zero_point_word = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point = ${me}((zero_point_word) & 0xFu);`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${me}(8);`} - let scale = ${ee.getByOffset("b_row * n_blocks_per_col + block")}; - let b_data = ${j.getByIndices(`${j.type.indices}(b_row, block, 0)`)}; - var word_offset = local_id.x * ${r.blockSize/d}; - for (var i: u32 = 0; i < ${c}; i++) { - ${ae()} - let b_value = ${c===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<${me}>(${Array.from({length:4},(V,F)=>`${me}(b_value_lower[${F}]), ${me}(b_value_upper[${F}])`).join(", ")}); - let b_dequantized_values = (b_quantized_values - mat2x4<${me}>(${Array(8).fill("zero_point").join(",")})) * scale; - inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; - word_offset += ${8/d}; - } - workgroupBarrier(); - } - - if (local_idx < ${v}) { - var output_value: ${oe.type.value} = ${oe.type.value}(0); - for (var b = 0u; b < ${$}; b++) { - output_value += inter_results[local_idx][b]; - } - if (col + local_idx < uniforms.output_shape[2]) - { - ${oe.setByIndices(`${oe.type.indices}(batch, row, col + local_idx)`,"output_value")} - } - } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${c};${$};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:E},programUniforms:y}),getShaderSource:A}},e0=(e,r)=>{ew(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(rw(e.inputs,r)):e.compute(tw(e.inputs,r))},t0=e=>$t(e)}),sw,nw,ow,iw,aw,lw,uw,dw,r0,zx=Re(()=>{ut(),ft(),_t(),sw=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].")}},nw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; - if (k < 0) { - break; - } - if (k >= i32(${rt("uniforms.x_shape",o,r)})) { - break; - } - offset += k * i32(${rt("uniforms.x_strides",o,r)}); - `;return` - value = ${e.type.value}(uniforms.constant_value); - for (var i = 0; i < 1; i++) { - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - } - `},ow=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${rt("uniforms.x_shape",o,r)}) - 1); - k = k % _2n_1; - if(k >= i32(${rt("uniforms.x_shape",o,r)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${rt("uniforms.x_strides",o,r)}); - `;return` - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - `},iw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${rt("uniforms.x_shape",o,r)})) { - k = i32(${rt("uniforms.x_shape",o,r)}) - 1; - } - offset += k * i32(${rt("uniforms.x_strides",o,r)}); - `;return` - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - `},aw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; - if (k < 0) { - k += i32(${rt("uniforms.x_shape",o,r)}]); - } - if (k >= i32(${rt("uniforms.x_shape",o,r)})) { - k -= i32(${rt("uniforms.x_shape",o,r)}); - } - offset += k * i32(${rt("uniforms.x_strides",o,r)}); - `;return` - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - `},lw=(e,r,t)=>{switch(t.mode){case 0:return nw(e,r,t.pads.length);case 1:return ow(e,r,t.pads.length);case 2:return iw(e,r,t.pads.length);case 3:return aw(e,r,t.pads.length);default:throw new Error("Invalid mode")}},uw=(e,r)=>{let t=be.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=be.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...st(e[0].dims,t));let a=["rank"],l=u=>{let p=Ze("output",e[0].dataType,t.length),d=Pe("x",e[0].dataType,s.length),c=d.type.value,_=lw(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:i?c:"f32"}),` - ${u.registerUniforms(f).declareVariables(d,p)} - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${p.offsetToIndices("global_idx")}; - - var value = ${c}(0); - ${_} - output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(be.size(t)/64)},programUniforms:n}),getShaderSource:l}},dw=(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,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},r0=(e,r)=>{sw(e.inputs);let t=dw(e.inputs,r);e.compute(uw(e.inputs,t),{inputs:[0]})}}),Vo,pu,hu,mu,fu,cw,pw,_u,gu,s0,n0,wu,o0,i0,bu,a0,l0,u0,d0,Bx=Re(()=>{_s(),ut(),ft(),_t(),Vo=e=>{if(jt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},pu=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();ma.adjustPoolAttributes(t,o,i,a,l,u);let p=ma.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let c=p.slice();return c.push(c.splice(1,1)[0]),[d,s?c:p]},hu=(e,r)=>{let t=r.format==="NHWC",s=be.size(e),o=be.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{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],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let c=!1;if(r.kernelShape.length===2){let _=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],v=r.pads[r.pads.length/2-2],$=r.pads[r.pads.length-2];c=!!(v+$),n.push({type:12,data:_},{type:12,data:f},{type:12,data:v},{type:12,data:$}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,d,c]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=be.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.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((u,p)=>u+p);return[n,i,!!l,!1,!1]}},mu=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c=o.format==="NHWC",_=r.type.value,f=Ze("output",r.type.tensor,s);if(o.kernelShape.length<=2){let v="",$="",w="",g=t-(c?2:1);if(p?v=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${g}] < 0 || xIndices[${g}] - >= uniforms.x_shape[${g}]) { - pad++; - continue; - } - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - }`:v=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - }`,o.kernelShape.length===2){let C=t-(c?3:2);d?$=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j; - if (xIndices[${C}] < 0 || xIndices[${C}] >= uniforms.x_shape[${C}]) { - pad += i32(uniforms.kw); - continue; - } - `:$=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j; - `,w=` - } - `}return` - ${e.registerUniforms(l).declareVariables(r,f)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let indices = ${f.offsetToIndices("global_idx")}; - var xIndices = ${f.offsetToIndices("global_idx")}; - - var value = ${_}(${a}); - var pad = 0; - ${$} - ${v} - ${w} - ${i} - - output[global_idx] = value; - }`}else{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let v=o.kernelShape.length,$=o.pads.length,w="";return u?w=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - }`:w=` - } - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - `,` - ${e.registerUniforms(l).declareVariables(r,f)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${f.offsetToIndices("global_idx")}; - var xIndices = ${f.offsetToIndices("global_idx")}; - - var offsets: array; - - var value = ${_}(${a}); - var pad = 0; - var isPad = false; - - for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { - var offset = i; - for (var j = 0u; j < ${v-1}u; j++) { - offsets[j] = offset / ${rt("uniforms.kernelStrides","j",v)}; - offset -= offsets[j] * ${rt("uniforms.kernelStrides","j",v)}; - } - offsets[${v-1}] = offset; - - isPad = false; - for (var j = ${t-v}u; j < ${t}u; j++) { - xIndices[j] = indices[j] * ${rt("uniforms.strides",`j - ${t-v}u`,v)} - + offsets[j - ${t-v}u] - ${rt("uniforms.pads","j - 2u",$)}; - ${w} - } - ${i} - - output[global_idx] = value; - }`}},fu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,cw=e=>`${fu(e)};${e.countIncludePad}`,pw=e=>`${fu(e)};${e.storageOrder};${e.dilations}`,_u=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}),gu=(e,r,t,s)=>{let[o,n]=pu(r,s,t),i=Pe("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,c,_,f]=hu(n,o);p.push(...st(r.dims,n));let v=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${c};${_};${f}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(be.size(n)/64)},programUniforms:p}),getShaderSource:$=>mu($,i,r.dims.length,n.length,o,l,u,0,d,c,_,f)}},s0=e=>{let r=e.count_include_pad!==0,t=_u(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:cw(s)}},n0=(e,r)=>{Vo(e.inputs),e.compute(gu("AveragePool",e.inputs[0],!1,r))},wu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},o0=e=>{let r=e.format;return{format:r,...wu,cacheKey:r}},i0=(e,r)=>{Vo(e.inputs),e.compute(gu("GlobalAveragePool",e.inputs[0],!0,r))},bu=(e,r,t,s)=>{let[o,n]=pu(r,s,t),i=` - value = max(x_val, value); - `,a="",l=Pe("x",r.dataType,r.dims.length),u=["rank"],[p,d,c,_,f]=hu(n,o);return p.push(...st(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${c};${_};${f}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(be.size(n)/64)},programUniforms:p}),getShaderSource:v=>mu(v,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,c,_,f)}},a0=(e,r)=>{Vo(e.inputs),e.compute(bu("MaxPool",e.inputs[0],!1,r))},l0=e=>{let r=e.storage_order,t=e.dilations,s=_u(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 o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:pw(o)}},u0=e=>{let r=e.format;return{format:r,...wu,cacheKey:r}},d0=(e,r)=>{Vo(e.inputs),e.compute(bu("GlobalMaxPool",e.inputs[0],!0,r))}}),hw,mw,c0,p0,Rx=Re(()=>{ut(),ft(),Jt(),_t(),hw=(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((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&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)].")}},mw=(e,r)=>{let t=be.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=be.size(n),l=s===3||s===2,u=l?[Math.ceil(be.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,c=d?l?[Math.ceil(be.size(d.dims)/4)]:d.dims:void 0,_=p.length===0||p.length===1&&p[0]===1,f=_===!1&&p.length===1,v=qt(a),$=_&&(!l||v===4),w=$?v:1,g=$&&!l?v:1,C=Pe("input",l?12:s,u.length,g),E=Pe("scale",i,p.length),y=d?Pe("zero_point",l?12:s,c.length):void 0,b=Ze("output",i,n.length,w),x=[C,E];y&&x.push(y);let S=[u,p];d&&S.push(c);let A=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...st(...S,n)],B=K=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${K.registerUniforms(G).declareVariables(...x,b)} - ${K.mainStart()} - ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${b.offsetToIndices("global_idx")}; - - // Set input x - ${l?` - let input = ${C.getByOffset("global_idx / 4")}; - let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; - let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${C.getByOffset("global_idx")};`}; - - // Set scale input - ${_?`let scale_value= ${E.getByOffset("0")}`:f?` - let scale_index = ${b.indicesGet("output_indices","uniforms.axis")}; - let scale_value= ${E.getByOffset("scale_index")};`:` - var scale_indices: ${E.type.indices} = output_indices; - let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; - ${E.indicesSet("scale_indices","uniforms.axis","index")}; - let scale_value= ${E.getByIndices("scale_indices")};`}; - - // Set zero-point input - ${y?_?l?` - let zero_point_input = ${y.getByOffset("0")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:f?l?` - let zero_point_index = ${b.indicesGet("output_indices","uniforms.axis")}; - let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_index % 4]`:` - let zero_point_index = ${b.indicesGet("output_indices","uniforms.axis")}; - let zero_point_value = ${y.getByOffset("zero_point_index")};`:l?` - let zero_point_offset = ${E.indicesToOffset("scale_indices")}; - let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":C.type.value}(0);`}; - // Compute and write output - ${b.setByOffset("global_idx",`${b.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:A})}},c0=(e,r)=>{hw(e.inputs,r),e.compute(mw(e.inputs,r))},p0=e=>$t({axis:e.axis,blockSize:e.blockSize})}),fw,_w,h0,jx=Re(()=>{_s(),ut(),_t(),fw=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},_w=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...st(n)],l=u=>{let p=Ze("output",s,n.length),d=p.type.value,c=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` - ${u.registerUniforms(c).declareVariables(p)} - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},h0=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]),jt.webgpu.validateInputContent&&fw(r,t,s),e.compute(_w(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),gw,Mu,yu,ww,m0,f0,Nx=Re(()=>{ut(),ft(),Jt(),_t(),gw=(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 o=`{ - var oldValue = 0; - loop { - let newValueF32 =`,n=`; - let newValue = bitcast(newValueF32); - let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); - if res.exchanged { - break; - } - oldValue = res.old_value; - } - }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` - ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` - ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Mu=(e,r)=>`${e===1?` - let element_count_dim = uniforms.output_strides; - let dim_value = uniforms.output_shape;`:` - let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; - let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} - - if (index >= 0) { - if (index >= i32(dim_value)) { - index = i32(dim_value - 1); - } - } else { - if (index < -i32(dim_value)) { - index = 0; - } else { - index += i32(dim_value); - } - } - data_offset += u32((u32(index) * element_count_dim));`,yu=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { - let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; - ${gw(e.reduction,"output[data_offset + i]","value",r)} - }`,ww=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(be.size(s)/n),a=s[s.length-1],l=be.sizeFromDimension(t,a),u=be.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...st(e[1].dims,e[2].dims,o)],d=c=>{let _=Pe("indices",e[1].dataType,e[1].dims.length),f=Pe("updates",e[2].dataType,e[2].dims.length,n),v=r.reduction!=="none"&&r.reduction!==""?Ub("output",e[0].dataType,o.length):Ze("output",e[0].dataType,o.length,n);return` - ${c.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(_,f,v)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var hasDuplicates = false; - if (${r.reduction==="none"}) { - for (var i = 0; i < ${u}; i = i + 1) { - for (var j = i + 1; j < ${u}; j = j + 1) { - var index_i = i32(indices[i].x); - var index_j = i32(indices[j].x); - if (index_i == index_j) { - hasDuplicates = true; - break; - } - } - if (hasDuplicates) { - break; - } - } - } - - if (${r.reduction==="none"} && hasDuplicates) { - if (global_idx != 0u) { - return; - } - // Process each index-update pair individually when duplicates exist - for (var idx = 0u; idx < ${u}u; idx++) { - var data_offset = 0u; - for (var i = 0u; i < uniforms.last_index_dimension; i++) { - var index = i32(indices[idx * uniforms.last_index_dimension + i].x); - ${Mu(t.length,!1)} - } - ${yu(r,v.type.value,!1)} - } - return; - } - - var data_offset = 0u; - var indices_start = uniforms.last_index_dimension * global_idx; - var indices_end = indices_start + uniforms.last_index_dimension; - for (var i = indices_start; i < indices_end; i++) { - var index = i32(indices[i].x); - ${Mu(t.length,!0)} - } - ${yu(r,v.type.value,!0)} - }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},m0=e=>$t({reduction:e.reduction}),f0=(e,r)=>{e.compute(ww(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),bw,Mw,yw,vu,vw,xw,Tw,Ew,Pw,Cw,Sw,$w,xu,kw,Iw,Aw,Fw,Ow,_0,g0,Vx=Re(()=>{ut(),ft(),Jt(),_t(),bw=(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")}},Mw=(e,r,t)=>{r.every(o=>o>=0&&o{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((o,n)=>s[o]=e[n]),s},yw=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].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!==u&&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");bw(s,r),r.axes.length>0&&Mw(s,r.axes,u).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==u&&t>=18&&o.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(o.length!==0&&o.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 o<"u"&&s.length>0&&o.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},vu=(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(). - let big = (${e}) * (${r}); - let whole = ${s}(big / (${t})); - let fract = ${s}(big % (${t})) / ${s}(${t}); - return whole + fract; -`,vw=(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 { - ${vu("xResized","lengthOriginal","lengthResized",r)} - } - `;case"pytorch_half_pixel":return`if (lengthResized > 1) { - return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; - } else { - return 0.0; - }`;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 { - ${vu("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)) / - ${r}(lengthResized - 1); - } else { - return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); - }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); - 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`)}})()+"}",xw=(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`)}})()+"}",Tw=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},Ew=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},Pw=(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 o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},Cw=(e,r,t,s,o)=>` - 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++) { - var output_index = ${e.indicesGet("output_indices","i")}; - var scale = ${rt("uniforms.scales","i",s)}; - var roi_low = ${rt("uniforms.roi","i",o)}; - var roi_hi = ${rt("uniforms.roi",`i + ${r.length}`,o)}; - if (scale == 1.0) { - original_indices[i] = ${e.type.value}(output_index); - } else { - var input_shape_i = ${rt("uniforms.input_shape","i",r.length)}; - var output_shape_i = ${rt("uniforms.output_shape","i",t.length)}; - original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - } - } - return original_indices; - }`,Sw=(e,r,t,s,o,n,i)=>` - 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++) { - var output_index = ${r.indicesGet("output_indices","i")}; - var input_index: u32; - var scale = ${rt("uniforms.scales","i",o)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${rt("uniforms.roi","i",n)}; - var roi_hi = ${rt("uniforms.roi",`i + ${t.length}`,n)}; - var input_shape_i = ${rt("uniforms.input_shape","i",t.length)}; - var output_shape_i = ${rt("uniforms.output_shape","i",s.length)}; - var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { - if (original_idx < 0) { - input_index = 0; - } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { - input_index = input_shape_i - 1; - } else { - input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); - } - } else { - input_index = u32(original_idx); - } - } - ${e.indicesSet("input_indices","i","input_index")} - } - return input_indices; - }`,$w=(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")}; - if (input_index < 0 || input_index >= ${rt("uniforms.input_shape","i",r.length)}) { - return false; - } - } - return true; - }`,xu=(e,r,t,s)=>e.rank>s?` - ${e.indicesSet("input_indices",r,"channel")}; - ${e.indicesSet("input_indices",t,"batch")}; -`:"",kw=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; - ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; - ${xu(e,l,n,2)} - return ${e.getByIndices("input_indices")}; - } - - fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var row:${u} = originalIndices[${i}]; - var col:${u} = originalIndices[${a}]; - ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { - return ${o}; - }`:""}; - row = max(0, min(row, ${t[i]} - 1)); - col = max(0, min(col, ${t[a]} - 1)); - var row1: u32 = u32(row); - var col1: u32 = u32(col); - var row2: u32 = u32(row + 1); - var col2: u32 = u32(col + 1); - var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; - var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; - var x11: ${u} = getInputValue(batch, channel, row1, col1); - var x12: ${u} = getInputValue(batch, channel, row1, col2); - var x21: ${u} = getInputValue(batch, channel, row2, col1); - var x22: ${u} = getInputValue(batch, channel, row2, col2); - var dx1: ${u} = abs(row - ${u}(row1)); - var dx2: ${u} = abs(${u}(row2) - row); - var dy1: ${u} = abs(col - ${u}(col1)); - var dy2: ${u} = abs(${u}(col2) - col); - if (row1 == row2) { - dx1 = 0.5; - dx2 = 0.5; - } - if (col1 == col2) { - dy1 = 0.5; - dy2 = 0.5; - } - return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); - }`},Iw=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[d,c]=p?[0,1]:[2,3],_=e.type.value,f=v=>{let $=v===d?"row":"col";return` - fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${_} { - var output_index = ${r.indicesGet("output_indices",v)}; - var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[v]}, - ${s[v]}, ${t[v]}, ${n[v]}, ${n[v]} + ${t.length}); - var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${a} && (originalIdx < 0 || originalIdx > (${t[v]} - 1))) { - return ${l}; - } - var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); - for (var i: i32 = -1; i < 3; i++) { - var ${$}: ${_} = originalIdx + ${_}(i); - if (${$} < 0 || ${$} >= ${t[v]}) { - ${u?`coefs[i + 1] = 0.0; - continue;`:a?`return ${l};`:`${$} = max(0, min(${$}, ${t[v]} - 1));`}; - } - var input_indices_copy: ${e.type.indices} = input_indices; - ${e.indicesSet("input_indices_copy",v,`u32(${$})`)}; - data[i + 1] = ${v===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${f(d)}; - ${f(c)}; - fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> { - var absS = abs(s); - var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); - var oneMinusAbsS: ${_} = 1.0 - absS; - var twoMinusAbsS: ${_} = 2.0 - absS; - var onePlusAbsS: ${_} = 1.0 + absS; - coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; - coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; - coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; - coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; - return coeffs; - } - - fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} { - var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; - return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; - } - - fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${_} { - var input_indices: ${e.type.indices} = output_indices; - return colCubicInterpolation(input_indices, output_indices); - } - `},Aw=(e,r,t,s,o)=>{let[n,i,a,l,u]=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",i,`max(0, min(depth, ${t[i]} - 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))`)}; - ${xu(e,u,n,3)} - return ${e.getByIndices("input_indices")}; - } - - fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var depth:${p} = originalIndices[${i}]; - var height:${p} = originalIndices[${a}]; - var width:${p} = originalIndices[${l}]; - ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { - return ${o}; - }`:""}; - - depth = max(0, min(depth, ${t[i]} - 1)); - height = max(0, min(height, ${t[a]} - 1)); - width = max(0, min(width, ${t[l]} - 1)); - var depth1: u32 = u32(depth); - var height1: u32 = u32(height); - var width1: u32 = u32(width); - var depth2: u32 = u32(depth + 1); - var height2: u32 = u32(height + 1); - var width2: u32 = u32(width + 1); - var channel: u32 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; - var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; - - var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); - var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); - var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); - var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); - var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); - var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); - var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); - var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); - var dx1: ${p} = abs(depth - ${p}(depth1)); - var dx2: ${p} = abs(${p}(depth2) - depth); - var dy1: ${p} = abs(height - ${p}(height1)); - var dy2: ${p} = abs(${p}(height2) - height); - var dz1: ${p} = abs(width - ${p}(width1)); - var dz2: ${p} = abs(${p}(width2) - width); - if (depth1 == depth2) { - dx1 = 0.5; - dx2 = 0.5; - } - if (height1 == height2) { - dy1 = 0.5; - dy2 = 0.5; - } - if (width1 == width2) { - dz1 = 0.5; - dz2 = 0.5; - } - 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); - }`},Fw=(e,r,t,s,o,n)=>{let i=e.dims,a=Tw(n,r.axes,i.length),l=Ew(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((g,C)=>g===0?1:l[C]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=Pw(i,u,r)));let p=Ze("output",e.dataType,l.length),d=Pe("input",e.dataType,i.length),c=be.size(l),_=i.length===l.length&&i.every((g,C)=>g===l[C]),f=r.coordinateTransformMode==="tf_crop_and_resize",v=r.extrapolationValue,$=d.type.value,w=g=>` - ${_?"":` - ${vw(r.coordinateTransformMode,$)}; - ${(()=>{switch(r.mode){case"nearest":return` - ${$w(d,i)}; - ${xw(r.nearestMode,t,$)}; - ${Sw(d,p,i,l,u.length,a.length,f)}; - `;case"linear":return` - ${Cw(p,i,l,u.length,a.length)}; - ${(()=>{if(i.length===2||i.length===4)return`${kw(d,p,i,f,v)}`;if(i.length===3||i.length===5)return`${Aw(d,p,i,f,v)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; - `;case"cubic":return` - ${(()=>{if(i.length===2||i.length===4)return`${Iw(d,p,i,l,u,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")}})()}; - `} - ${g.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} - ${g.mainStart()} - ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${_?"output[global_idx] = input[global_idx];":` - let output_indices = ${p.offsetToIndices("global_idx")}; - var input_indices: ${d.type.indices}; - ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); - if (checkInputIndices(input_indices)) { - output[global_idx] = ${d.getByIndices("input_indices")}; - } else { - output[global_idx] = ${r.extrapolationValue}; - }`;case"linear":return`output[global_idx] = ${i.length===2||i.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}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${_}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:1,data:u},{type:1,data:a},...st(i,l)]})}},Ow=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},_0=(e,r)=>{let t=[],s=[],o=[],n=Ow(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");yw(e.inputs,r,n,t,s,o),e.compute(Fw(e.inputs[0],r,n,t,s,o),{inputs:[0]})},g0=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return $t({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),Dw,Lw,w0,Ux=Re(()=>{ut(),ft(),_t(),Dw=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 o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)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]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Lw=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=be.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,c=e.length>4,_=s&&t>1,f=s&&t>2,v=t>3,$=64,w=qt(u),g=[{type:12,data:l},{type:12,data:w},{type:12,data:u},{type:1,data:r.epsilon}],C=y=>{let b=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[Pe("x",e[0].dataType,e[0].dims,w),Pe("skip",e[1].dataType,e[1].dims,w),Pe("gamma",e[2].dataType,e[2].dims,w)];d&&x.push(Pe("beta",e[3].dataType,e[3].dims,w)),c&&x.push(Pe("bias",e[4].dataType,e[4].dims,w)),x.push(Ze("output",e[0].dataType,a,w)),_&&x.push(Ze("mean_output",1,p)),f&&x.push(Ze("inv_std_output",1,p)),v&&x.push(Ze("input_skip_bias_sum",e[0].dataType,a,w));let S=mr(e[0].dataType),A=mr(1,w);return` - - ${y.registerUniforms(b).declareVariables(...x)} - var sum_shared : array<${A}, ${$}>; - var sum_squared_shared : array<${A}, ${$}>; - - ${y.mainStart([$,1,1])} - let ix = local_id.x; - let iy = global_id.x / ${$}; - - let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; - var stride = hidden_size_vectorized / ${$}; - let offset = ix * stride + iy * hidden_size_vectorized; - let offset1d = stride * ix; - if (ix == ${$-1}) { - stride = hidden_size_vectorized - stride * ix; - } - for (var i: u32 = 0; i < stride; i++) { - let skip_value = skip[offset + i]; - let bias_value = ${c?"bias[offset1d + i]":S+"(0.0)"}; - let input_value = x[offset + i]; - let value = input_value + skip_value + bias_value; - ${v?"input_skip_bias_sum[offset + i] = value;":""} - output[offset + i] = value; - let f32_value = ${no(S,w,"value")}; - sum_shared[ix] += f32_value; - sum_squared_shared[ix] += f32_value * f32_value; - } - workgroupBarrier(); - - var reduce_size : u32 = ${$}; - for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { - reduce_size = curr_size + (reduce_size & 1); - if (ix < curr_size) { - sum_shared[ix] += sum_shared[ix + reduce_size]; - sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; - } - workgroupBarrier(); - } - - let sum = sum_shared[0]; - let square_sum = sum_squared_shared[0]; - let mean = ${Qs("sum",w)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Qs("square_sum",w)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); - ${_?"mean_output[global_idx] = mean;":""} - ${f?"inv_std_output[global_idx] = inv_std_dev;":""} - - for (var i: u32 = 0; i < stride; i++) { - output[offset + i] = (output[offset + i] ${o?"":`- ${S}(mean)`}) * - ${S}(inv_std_dev) * gamma[offset1d + i] - ${d?"+ beta[offset1d + i]":""}; - } - }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${_};${f};${v}`,inputDependencies:e.map((y,b)=>"type")},getShaderSource:C,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:g})}},w0=(e,r)=>{Dw(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(Lw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),zw,Uo,Bw,Tu,Rw,jw,b0,M0,Wx=Re(()=>{ut(),ft(),Jt(),_t(),zw=(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`)})},Uo=(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},Bw=(e,r)=>{if(e.length>1){let t=Uo(e,1),s=Uo(e,2),o=Uo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),$t({starts:t,ends:s,axes:o})}else return r},Tu=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},Rw=(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--) { - let input_shape_i = ${rt("uniforms.input_shape","i",t.length)}; - let steps_i = ${rt("uniforms.steps","i",t.length)}; - let signs_i = ${rt("uniforms.signs","i",t.length)}; - let starts_i = ${rt("uniforms.starts","i",t.length)}; - var output_index = ${r.indicesGet("output_indices","i")}; - var input_index = output_index * steps_i + starts_i + carry; - carry = input_index / input_shape_i; - input_index = input_index % input_shape_i; - if (signs_i < 0) { - input_index = input_shape_i - input_index - 1u + starts_i; - } - ${e.indicesSet("input_indices","i","input_index")}; - } - return input_indices; - }`,jw=(e,r)=>{let t=e[0].dims,s=be.size(t),o=r.axes.length>0?be.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=Uo(e,4);n.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((w,g)=>Tu(w,g,t,o,n)),a=r.ends.map((w,g)=>Tu(w,g,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let w=0;wMath.sign(w));n.forEach((w,g,C)=>{if(w<0){let E=(a[g]-i[g])/w,y=i[g],b=y+E*n[g];i[g]=b,a[g]=y,C[g]=-w}});let u=t.slice(0);o.forEach((w,g)=>{u[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:u,dataType:e[0].dataType},d=Ze("output",e[0].dataType,u.length),c=Pe("input",e[0].dataType,e[0].dims.length),_=be.size(u),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],v=[{type:12,data:_},{type:12,data:i},{type:6,data:l},{type:12,data:n},...st(e[0].dims,u)],$=w=>` - ${w.registerUniforms(f).declareVariables(c,d)} - ${Rw(c,d,t)} - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let output_indices = ${d.offsetToIndices("global_idx")}; - let input_indices = calculateInputIndices(output_indices); - ${d.setByOffset("global_idx",c.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:v})}},b0=(e,r)=>{zw(e.inputs,r);let t=Bw(e.inputs,r);e.compute(jw(e.inputs,t),{inputs:[0]})},M0=e=>{let r=e.starts,t=e.ends,s=e.axes;return $t({starts:r,ends:t,axes:s})}}),Nw,Vw,y0,v0,Gx=Re(()=>{ut(),ft(),Jt(),Js(),_t(),Nw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Vw=(e,r)=>{let t=e.inputs[0],s=t.dims,o=be.size(s),n=s.length,i=be.normalizeAxis(r.axis,n),a=iS),u[i]=n-1,u[n-1]=i,l=e.compute(Vr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],c=o/d,_=qt(d),f=d/_,v=64;c===1&&(v=256);let $=(x,S)=>S===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:S===2?`max(${x}.x, ${x}.y)`:S===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,w=Pe("x",l.dataType,l.dims,_),g=Ze("result",l.dataType,l.dims,_),C=w.type.value,E=mr(l.dataType)==="f32"?`var threadMax = ${C}(-3.402823e+38f);`:`var threadMax = ${C}(-65504.0h);`,y=x=>` - var rowMaxShared : ${C}; - var rowSumShared : ${C}; - var threadShared : array<${C}, ${v}>; - - fn getValue(row: i32, col: i32, row_stride: i32) -> ${C} { - let index = row * row_stride + col; - return x[index]; - } - - fn setValue(row: i32, col: i32, row_stride: i32, value: ${C}) { - let index = row * row_stride + col; - result[index] = value; - } - ${x.registerUniform("packedCols","i32").declareVariables(w,g)} - ${x.mainStart(v)} - let gindex = i32(global_idx); - let lindex = i32(local_idx); - const wg = ${v}; - let row = gindex / wg; - let cols = uniforms.packedCols; - let row_stride : i32 = uniforms.packedCols; - - // find the rows max - ${E} - for (var col = lindex; col < cols; col += wg) { - let value = getValue(row, col, row_stride); - threadMax = max(threadMax, value); - } - if (lindex < cols) { - threadShared[lindex] = threadMax; - } - workgroupBarrier(); - - var reduceSize = min(cols, wg); - for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { - reduceSize = currSize + (reduceSize & 1); - if (lindex < currSize) { - threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); - } - workgroupBarrier(); - } - if (lindex == 0) { - rowMaxShared = ${C}(${$("threadShared[0]",_)}); - } - workgroupBarrier(); - - // find the rows sum - var threadSum = ${C}(0.0); - for (var col = lindex; col < cols; col += wg) { - let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); - threadSum += subExp; - } - threadShared[lindex] = threadSum; - workgroupBarrier(); - - for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { - if (lindex < currSize) { - threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; - } - workgroupBarrier(); - } - if (lindex == 0) { - rowSumShared = ${C}(${Qs("threadShared[0]",_)}); - } - workgroupBarrier(); - - // calculate final value for each element in the row - for (var col = lindex; col < cols; col += wg) { - let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; - setValue(row, col, row_stride, value); - } - }`,b=e.compute({name:"Softmax",shaderCache:{hint:`${_};${v}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:f}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Vr(b,u),{inputs:[b]})},y0=(e,r)=>{Nw(e.inputs),Vw(e,r)},v0=e=>$t({axis:e.axis})}),Eu,Uw,Ww,Gw,x0,Kx=Re(()=>{ut(),ft(),_t(),Eu=e=>Array.from(e.getBigInt64Array(),Number),Uw=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(Eu(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")},Ww=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Eu(e[1]),o=Ww(t,s),n=be.size(o),i=e[0].dataType,a=Pe("input",i,t.length),l=Ze("output",i,o.length),u=p=>` - const inputShape = ${a.indices(...t)}; - ${p.registerUniform("output_size","u32").declareVariables(a,l)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${l.offsetToIndices("global_idx")}; - var input_indices: ${a.type.indices}; - for (var i = 0; i < ${t.length}; i++) { - let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; - let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; - - ${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:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...st(e[0].dims,o)]}),getShaderSource:u}},x0=e=>{Uw(e.inputs),e.compute(Gw(e.inputs),{inputs:[0]})}}),Kw,Hw,T0,Hx=Re(()=>{ut(),ft(),_t(),Kw=(e,r,t,s,o)=>{let n=Ze("output_data",o,t.length,4),i=Pe("a_data",r[1].dataType,r[1].dims.length,4),a=Pe("b_data",r[2].dataType,r[2].dims.length,4),l=Pe("c_data",r[0].dataType,r[0].dims.length,4),u,p=(d,c,_)=>`select(${c}, ${d}, ${_})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(c,_,f="")=>{let v=`a_data[index_a${_}][component_a${_}]`,$=`b_data[index_b${_}][component_b${_}]`,w=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return` - let output_indices${_} = ${n.offsetToIndices(`global_idx * 4u + ${_}u`)}; - let offset_a${_} = ${i.broadcastedIndicesToOffset(`output_indices${_}`,n)}; - let offset_b${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,n)}; - let offset_c${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,n)}; - let index_a${_} = offset_a${_} / 4u; - let index_b${_} = offset_b${_} / 4u; - let index_c${_} = offset_c${_} / 4u; - let component_a${_} = offset_a${_} % 4u; - let component_b${_} = offset_b${_} % 4u; - let component_c${_} = offset_c${_} % 4u; - ${c}[${_}] = ${f}(${p(v,$,w)}); - `};o===9?u=` - var data = vec4(0); - ${d("data",0,"u32")} - ${d("data",1,"u32")} - ${d("data",2,"u32")} - ${d("data",3,"u32")} - output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` - ${d("output_data[global_idx]",0)} - ${d("output_data[global_idx]",1)} - ${d("output_data[global_idx]",2)} - ${d("output_data[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${u} - }`},Hw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(be.areEqual(r,t)&&be.areEqual(t,s)),i=r,a=be.size(r);if(n){let u=oo.calcShape(oo.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=be.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>Kw(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...st(s,r,t,i)]})}},T0=e=>{e.compute(Hw(e.inputs))}}),E0,qx=Re(()=>{lx(),dd(),ux(),dx(),cx(),px(),hx(),wx(),Mx(),yx(),vx(),xx(),Tx(),Ex(),Px(),Cx(),Sx(),$x(),kx(),Ix(),Ax(),Fx(),Ox(),Dx(),Lx(),Wy(),zx(),Bx(),Rx(),jx(),Nx(),ud(),Vx(),Xy(),Ux(),Wx(),Gx(),Hy(),Kx(),Js(),cd(),Hx(),E0=new Map([["Abs",[wM]],["Acos",[bM]],["Acosh",[MM]],["Add",[ey]],["ArgMax",[mM,Bu]],["ArgMin",[hM,Bu]],["Asin",[yM]],["Asinh",[vM]],["Atan",[xM]],["Atanh",[TM]],["Attention",[fM]],["AveragePool",[n0,s0]],["BatchNormalization",[_M]],["BiasAdd",[gM]],["BiasSplitGelu",[ZM]],["Cast",[PM,EM]],["Ceil",[SM]],["Clip",[CM]],["Concat",[dy,cy]],["Conv",[Wu,Uu]],["ConvTranspose",[yy,My]],["Cos",[$M]],["Cosh",[kM]],["CumSum",[vy,xy]],["DepthToSpace",[Ty,Ey]],["DequantizeLinear",[c0,p0]],["Div",[ty]],["Einsum",[Py,Cy]],["Elu",[IM,qo]],["Equal",[ry]],["Erf",[AM]],["Exp",[FM]],["Expand",[Sy]],["FastGelu",[$y]],["Floor",[OM]],["FusedConv",[Wu,Uu]],["Gather",[Iy,ky]],["GatherElements",[zy,Ly]],["GatherBlockQuantized",[Oy,Dy]],["GatherND",[Ay,Fy]],["Gelu",[DM]],["Gemm",[Ry,By]],["GlobalAveragePool",[i0,o0]],["GlobalMaxPool",[d0,u0]],["Greater",[iy]],["GreaterOrEqual",[ly]],["GridSample",[jy,Ny]],["GroupQueryAttention",[Qy]],["HardSigmoid",[UM,VM]],["InstanceNormalization",[Jy]],["LayerNormalization",[Yy]],["LeakyRelu",[LM,qo]],["Less",[ay]],["LessOrEqual",[uy]],["Log",[JM]],["MatMul",[Zy]],["MatMulNBits",[e0,t0]],["MaxPool",[a0,l0]],["Mul",[sy]],["MultiHeadAttention",[Uy,Vy]],["Neg",[BM]],["Not",[zM]],["Pad",[r0]],["Pow",[ny]],["QuickGelu",[YM,qo]],["Range",[h0]],["Reciprocal",[RM]],["ReduceMin",[lM]],["ReduceMean",[sM]],["ReduceMax",[aM]],["ReduceSum",[dM]],["ReduceProd",[uM]],["ReduceL1",[nM]],["ReduceL2",[oM]],["ReduceLogSum",[pM]],["ReduceLogSumExp",[iM]],["ReduceSumSquare",[cM]],["Relu",[jM]],["Resize",[_0,g0]],["RotaryEmbedding",[qy]],["ScatterND",[f0,m0]],["Sigmoid",[NM]],["Sin",[WM]],["Sinh",[GM]],["Slice",[b0,M0]],["SkipLayerNormalization",[w0]],["Split",[Gy,Ky]],["Sqrt",[KM]],["Softmax",[y0,v0]],["Sub",[oy]],["Tan",[HM]],["Tanh",[qM]],["ThresholdedRelu",[QM,qo]],["Tile",[x0]],["Transpose",[Gb,Kb]],["Where",[T0]]])}),P0,Xx=Re(()=>{_s(),Os(),_t(),P0=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,o){fs(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.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(),Jr(e.programInfo.name)}dispose(){}build(e,r){fs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=Wb(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` -`)} -${o.additionalImplementations} -${n}`,a=t.createShaderModule({code:i,label:e.name});Tt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Jr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.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,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),C0={};ao(C0,{WebGpuBackend:()=>S0});var qw,Xw,Qw,S0,Qx=Re(()=>{_s(),ut(),Os(),Rb(),ix(),qx(),Xx(),qw=(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 o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${qw(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Qw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},S0=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},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Qw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Vb(this),this.programManager=new P0(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,od(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;fs(),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 o=0;o"u"&&(this.queryTimeBase=_);let v=Number(_-this.queryTimeBase),$=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(v)||!Number.isSafeInteger($))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(w=>({dims:w.dims,dataType:Fs(w.dataType)})),outputsMetadata:c.map(w=>({dims:w.dims,dataType:Fs(w.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:v,endTime:$});else{let w="";d.forEach((C,E)=>{w+=`input[${E}]: [${C.dims}] | ${Fs(C.dataType)}, `});let g="";c.forEach((C,E)=>{g+=`output[${E}]: [${C.dims}] | ${Fs(C.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${w}${g}execution time: ${$-v} ns`)}Yo("GPU",`${p}::${_}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),Jr()}run(e,r,t,s,o,n){fs(e.name);let i=[];for(let g=0;gC):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],c=[];for(let g=0;g=n)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let C=p[g]===-1,E=p[g]===-2,y=C||E?o(a[g].dataType,a[g].dims):s(p[g],a[g].dataType,a[g].dims);if(d.push(y),y.data===0)continue;let b=this.gpuDataManager.get(y.data);if(!b)throw new Error(`no GPU data for output: ${y.data}`);if(C&&this.temporaryData.push(b),E){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(b)}c.push(b)}if(i.length!==r.length||c.length!==d.length){if(c.length===0)return Jr(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(u){let g=0,C=[];u.forEach(x=>{let S=typeof x.data=="number"?[x.data]:x.data;if(S.length===0)return;let A=x.type===10?2:4,B,K;x.type===10?(K=S.length>4?16:S.length>2?8:S.length*A,B=S.length>4?16:A*S.length):(K=S.length<=2?S.length*A:16,B=16),g=Math.ceil(g/K)*K,C.push(g);let G=x.type===10?8:4;g+=S.length>4?Math.ceil(S.length/G)*B:S.length*A});let E=16;g=Math.ceil(g/E)*E;let y=new ArrayBuffer(g);u.forEach((x,S)=>{let A=C[S],B=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(y,A,B.length).set(B);else if(x.type===12)new Uint32Array(y,A,B.length).set(B);else if(x.type===10)new Uint16Array(y,A,B.length).set(B);else if(x.type===1)new Float32Array(y,A,B.length).set(B);else throw new Error(`Unsupported uniform type: ${Fs(x.type)}`)});let b=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(b.buffer,0,y,0,g),this.gpuDataManager.release(b.id),_={offset:0,size:g,buffer:b.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),v=f[1]===1&&f[2]===1,$=Xw(e,r,v),w=this.programManager.getArtifact($);if(w||(w=this.programManager.build(e,f),this.programManager.setArtifact($,w),Tt("info",()=>`[artifact] key: ${$}, programName: ${e.name}`)),u&&w.uniformVariablesInfo){if(u.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${u.length} in program "${w.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${$}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(w,i,c,f,_),Jr(e.name),d}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 o=E0.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[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 o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Tt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}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 Du(this,e,r);return id(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(){Tt("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(){Tt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Tt("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()}}}),$0={};ao($0,{init:()=>k0});var oa,Jw,k0,Jx=Re(()=>{ut(),Os(),ft(),ox(),oa=class I0{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=be.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=be.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=be.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=be.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(be.size(r)!==be.size(this.dims))throw new Error("Invalid new shape");return new I0(this.module,this.dataType,this.data,r)}},Jw=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,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,u)=>new oa(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=An(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new oa(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(Qx(),Jo(C0)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)Tt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{Tt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),d)}},async(a,l,u)=>{Tt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{Tt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let d=new Jw(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Nb(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Yw,gd,wd,qs,Zw,Pu,wa,bd,Md,Cu,yd,vd,xd,A0=Re(()=>{rx(),sx(),ut(),zn(),ed(),Db(),Yw=(e,r)=>{zt()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},gd=async e=>{Yw(e.wasm.numThreads,ha(e.logLevel))},wd=async(e,r)=>{var t,s;(s=(t=zt()).asyncInit)==null||s.call(t);{let o=(Jx(),Jo($0)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",zt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",zt(),e)}}},qs=new Map,Zw=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&At("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},Pu=(e,r)=>{let t=zt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&At("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let u=t.HEAPU32[o/4+1],p=[];for(let d=0;d{let r=zt(),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]},bd=async(e,r)=>{var d,c,_,f;let t,s,o=zt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=wa(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await Ob(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let S=[];for(let A of r.externalData){let B=typeof A=="string"?A:A.path;S.push(nd(typeof A=="string"?A:A.data).then(K=>{o.mountExternalData(B,K)}))}await Promise.all(S)}for(let S of(r==null?void 0:r.executionProviders)??[])if((typeof S=="string"?S:S.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof S!="string"){let A=S,B=A==null?void 0:A.context,K=A==null?void 0:A.gpuDevice,G=A==null?void 0:A.deviceType,j=A==null?void 0:A.powerPreference;B?o.currentContext=B:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:G,powerPreference:j})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&At("Can't create a session."),(c=o.jsepOnCreateSession)==null||c.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[v,$]=Zw(n),w=!!(r!=null&&r.enableGraphCapture),g=[],C=[],E=[],y=[],b=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),x={handle:a,outputPreferredLocations:b,outputPreferredLocationsEncoded:b.map(S=>Fu(S))}),qs.set(n,[n,u,p,x,w,!1]),[n,g,C,E,y]}catch(v){throw u.forEach($=>o._OrtFree($)),p.forEach($=>o._OrtFree($)),a!==0&&o._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&At("Can't release session."),v}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&At("Can't release session options."),l.forEach(v=>o._free(v)),(f=o.unmountExternalData)==null||f.call(o)}},Md=e=>{var l,u,p;let r=zt(),t=qs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&At("Can't release session."),qs.delete(e)},Cu=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=zt(),l=a.PTR_SIZE,u=e[0],p=e[1],d=e[3],c=d,_,f;if(u==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;f=An(ro(u),p);{let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=g(s,n,w,f)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;f=An(ro(u),p);let g=a.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=g(s,w,ro(u),p)}else{let w=e[2];if(Array.isArray(w)){f=l*w.length,_=a._malloc(f),t.push(_);for(let g=0;ga.setValue($+C*l,g,l===4?"i32":"i64"));let w=a._OrtCreateTensor(ro(u),_,f,$,p.length,Fu(c));w===0&&At(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(v)}},yd=async(e,r,t,s,o,n)=>{var K,G,j,ee;let i=zt(),a=i.PTR_SIZE,l=qs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],d=l[2],c=l[3],_=l[4],f=l[5],v=r.length,$=s.length,w=0,g=[],C=[],E=[],y=[],b=i.stackSave(),x=i.stackAlloc(v*a),S=i.stackAlloc(v*a),A=i.stackAlloc($*a),B=i.stackAlloc($*a);try{[w,g]=Fb(n);for(let X=0;Xq*R,1);F=Fs(fe);let we=c==null?void 0:c.outputPreferredLocations[s[X]];if(F==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let q=[];for(let R=0;R0){let q=i.jsepGetBuffer;if(!q)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let R=q(W),pe=An(fe,Ue);if(pe===void 0||!rd(F))throw new Error(`Unsupported data type: ${F}`);V=!0,Z.push([F,$e,{gpuBuffer:R,download:i.jsepCreateDownloader(R,pe,F),dispose:()=>{i._OrtReleaseTensor(oe)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&Ue>0){let q=i.webnnEnsureTensor,R=i.webnnIsInt64Supported;if(!q||!R)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(An(fe,Ue)===void 0||!sd(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!R(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let pe=await q(e,W,fe,$e,!1);V=!0,Z.push([F,$e,{mlTensor:pe,download:i.webnnCreateMLTensorDownloader(W,F),dispose:()=>{i.webnnReleaseTensorId(W),i._OrtReleaseTensor(oe)}},"ml-tensor"])}else{let q=td(F),R=new q(Ue);new Uint8Array(R.buffer,R.byteOffset,R.byteLength).set(i.HEAPU8.subarray(W,W+R.byteLength)),Z.push([F,$e,R,"cpu"])}}finally{i.stackRestore(me),F==="string"&&W&&i._free(W),V||i._OrtReleaseTensor(oe),(ee=i.webnnOnRunEnd)==null||ee.call(i,u)}}return c&&!_&&(i._OrtClearBoundOutputs(c.handle)!==0&&At("Can't clear bound outputs."),qs.set(e,[u,p,d,c,_,!1])),Z}finally{i.stackRestore(b),C.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),g.forEach(H=>i._free(H))}},vd=e=>{let r=zt(),t=qs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&At("Can't get an profile file name."),r._OrtFree(o)},xd=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Xs,Fr,eo,Wo,Go,ia,Su,aa,Sn,$n,eb,F0,O0,D0,L0,z0,B0,R0,j0=Re(()=>{_s(),A0(),zn(),Yu(),Xs=()=>!!jt.wasm.proxy&&typeof document<"u",eo=!1,Wo=!1,Go=!1,aa=new Map,Sn=(e,r)=>{let t=aa.get(e);t?t.push(r):aa.set(e,[r])},$n=()=>{if(eo||!Wo||Go||!Fr)throw new Error("worker not ready")},eb=e=>{switch(e.data.type){case"init-wasm":eo=!1,e.data.err?(Go=!0,Su[1](e.data.err)):(Wo=!0,Su[0]()),ia&&(URL.revokeObjectURL(ia),ia=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=aa.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},F0=async()=>{if(!Wo){if(eo)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(eo=!0,Xs())return new Promise((e,r)=>{Fr==null||Fr.terminate(),Ib().then(([t,s])=>{try{Fr=s,Fr.onerror=n=>r(n),Fr.onmessage=eb,Su=[e,r];let o={type:"init-wasm",in:jt};!o.in.wasm.wasmPaths&&(t||Au)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href}),Fr.postMessage(o),ia=t}catch(o){r(o)}},r)});try{await Zu(jt.wasm),await gd(jt),Wo=!0}catch(e){throw Go=!0,e}finally{eo=!1}}},O0=async e=>{if(Xs())return $n(),new Promise((r,t)=>{Sn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:jt}};Fr.postMessage(s)});await wd(jt,e)},D0=async e=>Xs()?($n(),new Promise((r,t)=>{Sn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Fr.postMessage(s,[e.buffer])})):wa(e),L0=async(e,r)=>{if(Xs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $n(),new Promise((t,s)=>{Sn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Fr.postMessage(o,n)})}else return bd(e,r)},z0=async e=>{if(Xs())return $n(),new Promise((r,t)=>{Sn("release",[r,t]);let s={type:"release",in:e};Fr.postMessage(s)});Md(e)},B0=async(e,r,t,s,o,n)=>{if(Xs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return $n(),new Promise((i,a)=>{Sn("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Fr.postMessage(u,xd(l))})}else return yd(e,r,t,s,o,n)},R0=async e=>{if(Xs())return $n(),new Promise((r,t)=>{Sn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Fr.postMessage(s)});vd(e)}}),$u,tb,N0,Yx=Re(()=>{_s(),j0(),ut(),Ju(),Db(),$u=(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()}`)}},tb=e=>{switch(e[3]){case"cpu":return new hs(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!rd(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return hs.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!sd(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return hs.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},N0=class{async fetchModelAndCopyToWasmMemory(e){return D0(await nd(e))}async loadModel(e,r){fs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await L0(t,r),Jr()}async dispose(){return z0(this.sessionId)}async run(e,r,t){fs();let s=[],o=[];Object.entries(e).forEach(d=>{let c=d[0],_=d[1],f=this.inputNames.indexOf(c);if(f===-1)throw new Error(`invalid input '${c}'`);s.push(_),o.push(f)});let n=[],i=[];Object.entries(r).forEach(d=>{let c=d[0],_=d[1],f=this.outputNames.indexOf(c);if(f===-1)throw new Error(`invalid output '${c}'`);n.push(_),i.push(f)});let a=s.map((d,c)=>$u(d,()=>`input "${this.inputNames[o[c]]}"`)),l=n.map((d,c)=>d?$u(d,()=>`output "${this.outputNames[i[c]]}"`):null),u=await B0(this.sessionId,o,a,i,l,t),p={};for(let d=0;dHu,initializeFlags:()=>Ku,wasmBackend:()=>U0});var Ku,Hu,U0,Zx=Re(()=>{_s(),j0(),Yx(),Ku=()=>{(typeof jt.wasm.initTimeout!="number"||jt.wasm.initTimeout<0)&&(jt.wasm.initTimeout=0);let e=jt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),jt.wasm.simd=!1),typeof jt.wasm.proxy!="boolean"&&(jt.wasm.proxy=!1),typeof jt.wasm.trace!="boolean"&&(jt.wasm.trace=!1),typeof jt.wasm.numThreads!="number"||!Number.isInteger(jt.wasm.numThreads)||jt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)jt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Rv("node:os").cpus().length:navigator.hardwareConcurrency;jt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},Hu=class{async init(e){Ku(),await F0(),await O0(e)}async createInferenceSessionHandler(e,r){let t=new N0;return await t.loadModel(e,r),t}},U0=new Hu});_s();_s();_s();var eT="1.22.0-dev.20250409-89f8206ba4",tT=Eb;{let e=(Zx(),Jo(V0)).wasmBackend;Fn("webgpu",e,5),Fn("webnn",e,5),Fn("cpu",e,10),Fn("wasm",e,10)}Object.defineProperty(jt.versions,"web",{value:eT,enumerable:!0});/** -* @license -* Copyright 2021 Google LLC. All Rights Reserved. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============================================================================= -*//** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - *//** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */const rT=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Qu},get TRACE(){return Yo},get TRACE_FUNC_BEGIN(){return fs},get TRACE_FUNC_END(){return Jr},get Tensor(){return hs},default:tT,get env(){return jt},get registerBackend(){return Fn}},Symbol.toStringTag,{value:"Module"}));var As={},sT={"onnxruntime-common":e=>{e.exports=Dv},"onnxruntime-web":e=>{e.exports=rT},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Se,Interpreter:()=>Ae,Template:()=>Ve,parse:()=>V,tokenize:()=>d});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",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,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(O,Y){this.value=O,this.type=Y}};function i(O){return/\w/.test(O)}function a(O){return/[0-9]/.test(O)}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]],u=new Map([["n",` -`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(O,Y={}){return O.endsWith(` -`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),Y.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),Y.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function d(O,Y={}){var Ee,ke,Ie;const z=[],J=p(O,Y);let le=0;const ye=Be=>{let Xe="";for(;Be(J[le]);){if(J[le]==="\\"){if(++le,le>=J.length)throw new SyntaxError("Unexpected end of input");const Ge=J[le++],lt=u.get(Ge);if(lt===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ge}`);Xe+=lt;continue}if(Xe+=J[le++],le>=J.length)throw new SyntaxError("Unexpected end of input")}return Xe};e:for(;le0){z.push(new n(Ge,s.Text));continue}}ye(Ge=>/\s/.test(Ge));const Xe=J[le];if(Xe==="-"||Xe==="+"){const Ge=(ke=z.at(-1))==null?void 0:ke.type;if(Ge===s.Text||Ge===void 0)throw new SyntaxError(`Unexpected character: ${Xe}`);switch(Ge){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++le;const lt=ye(a);z.push(new n(`${Xe}${lt}`,lt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Ge,lt]of l)if(J.slice(le,le+Ge.length)===Ge){z.push(new n(Ge,lt)),le+=Ge.length;continue e}if(Xe==="'"||Xe==='"'){++le;const Ge=ye(lt=>lt!==Xe);z.push(new n(Ge,s.StringLiteral)),++le;continue}if(a(Xe)){const Ge=ye(a);z.push(new n(Ge,s.NumericLiteral));continue}if(i(Xe)){const Ge=ye(i),lt=Object.hasOwn(o,Ge)?o[Ge]:s.Identifier;lt===s.In&&((Ie=z.at(-1))==null?void 0:Ie.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Ge,lt));continue}throw new SyntaxError(`Unexpected character: ${Xe}`)}return z}var c=class{constructor(){te(this,"type","Statement")}},_=class extends c{constructor(Y){super();te(this,"type","Program");this.body=Y}},f=class extends c{constructor(Y,z,J){super();te(this,"type","If");this.test=Y,this.body=z,this.alternate=J}},v=class extends c{constructor(Y,z,J,le){super();te(this,"type","For");this.loopvar=Y,this.iterable=z,this.body=J,this.defaultBlock=le}},$=class extends c{constructor(Y,z,J){super();te(this,"type","Set");this.assignee=Y,this.value=z,this.body=J}},w=class extends c{constructor(Y,z,J){super();te(this,"type","Macro");this.name=Y,this.args=z,this.body=J}},g=class extends c{constructor(){super(...arguments);te(this,"type","Expression")}},C=class extends g{constructor(Y,z,J){super();te(this,"type","MemberExpression");this.object=Y,this.property=z,this.computed=J}},E=class extends g{constructor(Y,z){super();te(this,"type","CallExpression");this.callee=Y,this.args=z}},y=class extends g{constructor(Y){super();te(this,"type","Identifier");this.value=Y}},b=class extends g{constructor(Y){super();te(this,"type","Literal");this.value=Y}},x=class extends b{constructor(){super(...arguments);te(this,"type","NumericLiteral")}},S=class extends b{constructor(){super(...arguments);te(this,"type","StringLiteral")}},A=class extends b{constructor(){super(...arguments);te(this,"type","BooleanLiteral")}},B=class extends b{constructor(){super(...arguments);te(this,"type","NullLiteral")}},K=class extends b{constructor(){super(...arguments);te(this,"type","ArrayLiteral")}},G=class extends b{constructor(){super(...arguments);te(this,"type","TupleLiteral")}},j=class extends b{constructor(){super(...arguments);te(this,"type","ObjectLiteral")}},ee=class extends g{constructor(Y,z,J){super();te(this,"type","BinaryExpression");this.operator=Y,this.left=z,this.right=J}},H=class extends g{constructor(Y,z){super();te(this,"type","FilterExpression");this.operand=Y,this.filter=z}},Z=class extends g{constructor(Y,z){super();te(this,"type","SelectExpression");this.iterable=Y,this.test=z}},X=class extends g{constructor(Y,z,J){super();te(this,"type","TestExpression");this.operand=Y,this.negate=z,this.test=J}},oe=class extends g{constructor(Y,z){super();te(this,"type","UnaryExpression");this.operator=Y,this.argument=z}},me=class extends g{constructor(Y=void 0,z=void 0,J=void 0){super();te(this,"type","SliceExpression");this.start=Y,this.stop=z,this.step=J}},ae=class extends g{constructor(Y,z){super();te(this,"type","KeywordArgumentExpression");this.key=Y,this.value=z}};function V(O){const Y=new _([]);let z=0;function J(De,Qe){const et=O[z++];if(!et||et.type!==De)throw new Error(`Parser Error: ${Qe}. ${et.type} !== ${De}.`);return et}function le(){switch(O[z].type){case s.Text:return ke();case s.OpenStatement:return Ie();case s.OpenExpression:return Be();default:throw new SyntaxError(`Unexpected token type: ${O[z].type}`)}}function ye(...De){return z+De.length<=O.length&&De.some((Qe,et)=>Qe!==O[z+et].type)}function Ee(...De){return z+De.length<=O.length&&De.every((Qe,et)=>Qe===O[z+et].type)}function ke(){return new S(J(s.Text,"Expected text token").value)}function Ie(){J(s.OpenStatement,"Expected opening statement token");let De;switch(O[z].type){case s.Set:++z,De=Xe(),J(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,De=Ge(),J(s.OpenStatement,"Expected {% token"),J(s.EndIf,"Expected endif token"),J(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,De=lt(),J(s.OpenStatement,"Expected {% token"),J(s.EndMacro,"Expected endmacro token"),J(s.CloseStatement,"Expected %} token");break;case s.For:++z,De=Gt(),J(s.OpenStatement,"Expected {% token"),J(s.EndFor,"Expected endfor token"),J(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[z].type}`)}return De}function Be(){J(s.OpenExpression,"Expected opening expression token");const De=Ot();return J(s.CloseExpression,"Expected closing expression token"),De}function Xe(){var Qe,et;const De=Ot();if(Ee(s.Equals)){++z;const Bt=Ot();return new $(De,Bt,[])}else{const Bt=[];for(J(s.CloseStatement,"Expected %} token");!(((Qe=O[z])==null?void 0:Qe.type)===s.OpenStatement&&((et=O[z+1])==null?void 0:et.type)===s.EndSet);){const Or=le();Bt.push(Or)}return J(s.OpenStatement,"Expected {% token"),J(s.EndSet,"Expected endset token"),new $(De,null,Bt)}}function Ge(){var Bt,Or,Pr,rs,ss,Ur,ns,os;const De=Ot();J(s.CloseStatement,"Expected closing statement token");const Qe=[],et=[];for(;!(((Bt=O[z])==null?void 0:Bt.type)===s.OpenStatement&&(((Or=O[z+1])==null?void 0:Or.type)===s.ElseIf||((Pr=O[z+1])==null?void 0:Pr.type)===s.Else||((rs=O[z+1])==null?void 0:rs.type)===s.EndIf));)Qe.push(le());if(((ss=O[z])==null?void 0:ss.type)===s.OpenStatement&&((Ur=O[z+1])==null?void 0:Ur.type)!==s.EndIf)if(++z,Ee(s.ElseIf))J(s.ElseIf,"Expected elseif token"),et.push(Ge());else for(J(s.Else,"Expected else token"),J(s.CloseStatement,"Expected closing statement token");!(((ns=O[z])==null?void 0:ns.type)===s.OpenStatement&&((os=O[z+1])==null?void 0:os.type)===s.EndIf);)et.push(le());return new f(De,Qe,et)}function lt(){const De=Xt();if(De.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Qe=Zr();J(s.CloseStatement,"Expected closing statement token");const et=[];for(;ye(s.OpenStatement,s.EndMacro);)et.push(le());return new w(De,Qe,et)}function wt(De=!1){const Qe=De?Xt:Ot,et=[Qe()],Bt=Ee(s.Comma);for(;Bt&&(++z,et.push(Qe()),!!Ee(s.Comma)););return Bt?new G(et):et[0]}function Gt(){const De=wt(!0);if(!(De instanceof y||De instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${De.type} instead`);J(s.In,"Expected `in` keyword following loop variable");const Qe=Ot();J(s.CloseStatement,"Expected closing statement token");const et=[];for(;ye(s.OpenStatement,s.EndFor)&&ye(s.OpenStatement,s.Else);)et.push(le());const Bt=[];if(Ee(s.OpenStatement,s.Else))for(++z,++z,J(s.CloseStatement,"Expected closing statement token");ye(s.OpenStatement,s.EndFor);)Bt.push(le());return new v(De,Qe,et,Bt)}function Ot(){return lr()}function lr(){const De=Yr();if(Ee(s.If)){++z;const Qe=Yr();if(Ee(s.Else)){++z;const et=Yr();return new f(Qe,[De],[et])}else return new Z(De,Qe)}return De}function Yr(){let De=gs();for(;Ee(s.Or);){const Qe=O[z];++z;const et=gs();De=new ee(Qe,De,et)}return De}function gs(){let De=kr();for(;Ee(s.And);){const Qe=O[z];++z;const et=kr();De=new ee(Qe,De,et)}return De}function kr(){let De;for(;Ee(s.Not);){const Qe=O[z];++z;const et=kr();De=new oe(Qe,et)}return De??Ds()}function Ds(){let De=xs();for(;Ee(s.ComparisonBinaryOperator)||Ee(s.In)||Ee(s.NotIn);){const Qe=O[z];++z;const et=xs();De=new ee(Qe,De,et)}return De}function xs(){let De=es();for(;Ee(s.AdditiveBinaryOperator);){const Qe=O[z];++z;const et=es();De=new ee(Qe,De,et)}return De}function Ls(){const De=Ft(Xt());return Ee(s.OpenParen)?at(De):De}function at(De){let Qe=new E(De,Zr());return Qe=Ft(Qe),Ee(s.OpenParen)&&(Qe=at(Qe)),Qe}function Zr(){J(s.OpenParen,"Expected opening parenthesis for arguments list");const De=Ir();return J(s.CloseParen,"Expected closing parenthesis for arguments list"),De}function Ir(){const De=[];for(;!Ee(s.CloseParen);){let Qe=Ot();if(Ee(s.Equals)){if(++z,!(Qe instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const et=Ot();Qe=new ae(Qe,et)}De.push(Qe),Ee(s.Comma)&&++z}return De}function ws(){const De=[];let Qe=!1;for(;!Ee(s.CloseSquareBracket);)Ee(s.Colon)?(De.push(void 0),++z,Qe=!0):(De.push(Ot()),Ee(s.Colon)&&(++z,Qe=!0));if(De.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Qe){if(De.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new me(...De)}return De[0]}function Ft(De){for(;Ee(s.Dot)||Ee(s.OpenSquareBracket);){const Qe=O[z];++z;let et;const Bt=Qe.type!==s.Dot;if(Bt)et=ws(),J(s.CloseSquareBracket,"Expected closing square bracket");else if(et=Xt(),et.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");De=new C(De,et,Bt)}return De}function es(){let De=ts();for(;Ee(s.MultiplicativeBinaryOperator);){const Qe=O[z];++z;const et=ts();De=new ee(Qe,De,et)}return De}function ts(){let De=bs();for(;Ee(s.Is);){++z;const Qe=Ee(s.Not);Qe&&++z;let et=Xt();if(et instanceof A?et=new y(et.value.toString()):et instanceof B&&(et=new y("none")),!(et instanceof y))throw new SyntaxError("Expected identifier for the test");De=new X(De,Qe,et)}return De}function bs(){let De=Ls();for(;Ee(s.Pipe);){++z;let Qe=Xt();if(!(Qe instanceof y))throw new SyntaxError("Expected identifier for the filter");Ee(s.OpenParen)&&(Qe=at(Qe)),De=new H(De,Qe)}return De}function Xt(){const De=O[z];switch(De.type){case s.NumericLiteral:return++z,new x(Number(De.value));case s.StringLiteral:return++z,new S(De.value);case s.BooleanLiteral:return++z,new A(De.value.toLowerCase()==="true");case s.NullLiteral:return++z,new B(null);case s.Identifier:return++z,new y(De.value);case s.OpenParen:{++z;const Qe=wt();if(O[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[z].type} instead`);return++z,Qe}case s.OpenSquareBracket:{++z;const Qe=[];for(;!Ee(s.CloseSquareBracket);)Qe.push(Ot()),Ee(s.Comma)&&++z;return++z,new K(Qe)}case s.OpenCurlyBracket:{++z;const Qe=new Map;for(;!Ee(s.CloseCurlyBracket);){const et=Ot();J(s.Colon,"Expected colon between key and value in object literal");const Bt=Ot();Qe.set(et,Bt),Ee(s.Comma)&&++z}return++z,new j(Qe)}default:throw new SyntaxError(`Unexpected token: ${De.type}`)}}for(;z=0?(Y=(Y??(Y=0))<0?Math.max(O.length+Y,0):Math.min(Y,O.length),z=(z??(z=O.length))<0?Math.max(O.length+z,0):Math.min(z,O.length)):(Y=(Y??(Y=O.length-1))<0?Math.max(O.length+Y,-1):Math.min(Y,O.length-1),z=(z??(z=-1))<-1?Math.max(O.length+z,-1):Math.min(z,O.length-1));const ye=[];for(let Ee=Y;le*EeY.toUpperCase())}var fe=class{constructor(O=void 0){te(this,"type","RuntimeValue");te(this,"value");te(this,"builtins",new Map);this.value=O}__bool__(){return new $e(!!this.value)}},se=class extends fe{constructor(){super(...arguments);te(this,"type","NumericValue")}},ce=class extends fe{constructor(){super(...arguments);te(this,"type","StringValue");te(this,"builtins",new Map([["upper",new pe(()=>new ce(this.value.toUpperCase()))],["lower",new pe(()=>new ce(this.value.toLowerCase()))],["strip",new pe(()=>new ce(this.value.trim()))],["title",new pe(()=>new ce(re(this.value)))],["length",new se(this.value.length)],["rstrip",new pe(()=>new ce(this.value.trimEnd()))],["lstrip",new pe(()=>new ce(this.value.trimStart()))],["split",new pe(Y=>{const z=Y[0]??new xe;if(!(z instanceof ce||z instanceof xe))throw new Error("sep argument must be a string or null");const J=Y[1]??new se(-1);if(!(J instanceof se))throw new Error("maxsplit argument must be a number");let le=[];if(z instanceof xe){const ye=this.value.trimStart();for(const{0:Ee,index:ke}of ye.matchAll(/\S+/g)){if(J.value!==-1&&le.length>=J.value&&ke!==void 0){le.push(Ee+ye.slice(ke+Ee.length));break}le.push(Ee)}}else{if(z.value==="")throw new Error("empty separator");le=this.value.split(z.value),J.value!==-1&&le.length>J.value&&le.push(le.splice(J.value).join(z.value))}return new q(le.map(ye=>new ce(ye)))})]]))}},$e=class extends fe{constructor(){super(...arguments);te(this,"type","BooleanValue")}},Ue=class extends fe{constructor(){super(...arguments);te(this,"type","ObjectValue");te(this,"builtins",new Map([["get",new pe(([Y,z])=>{if(!(Y instanceof ce))throw new Error(`Object key must be a string: got ${Y.type}`);return this.value.get(Y.value)??z??new xe})],["items",new pe(()=>new q(Array.from(this.value.entries()).map(([Y,z])=>new q([new ce(Y),z]))))]]))}__bool__(){return new $e(this.value.size>0)}},we=class extends Ue{constructor(){super(...arguments);te(this,"type","KeywordArgumentsValue")}},q=class extends fe{constructor(){super(...arguments);te(this,"type","ArrayValue");te(this,"builtins",new Map([["length",new se(this.value.length)]]))}__bool__(){return new $e(this.value.length>0)}},R=class extends q{constructor(){super(...arguments);te(this,"type","TupleValue")}},pe=class extends fe{constructor(){super(...arguments);te(this,"type","FunctionValue")}},xe=class extends fe{constructor(){super(...arguments);te(this,"type","NullValue")}},Me=class extends fe{constructor(){super(...arguments);te(this,"type","UndefinedValue")}},Se=class{constructor(O){te(this,"variables",new Map([["namespace",new pe(O=>{if(O.length===0)return new Ue(new Map);if(O.length!==1||!(O[0]instanceof Ue))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));te(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof pe],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toLowerCase()}],["upper",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,Y)=>O.value===Y.value],["eq",(O,Y)=>O.value===Y.value]]));this.parent=O}set(O,Y){return this.declareVariable(O,Fe(Y))}declareVariable(O,Y){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,Y),Y}setVariable(O,Y){return this.variables.set(O,Y),Y}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new Me}catch{return new Me}}},Ae=class{constructor(O){te(this,"global");this.global=O??new Se}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,Y){const z=this.evaluate(O.left,Y);switch(O.operator.value){case"and":return z.__bool__().value?this.evaluate(O.right,Y):z;case"or":return z.__bool__().value?z:this.evaluate(O.right,Y)}const J=this.evaluate(O.right,Y);switch(O.operator.value){case"==":return new $e(z.value==J.value);case"!=":return new $e(z.value!=J.value)}if(z instanceof Me||J instanceof Me)throw new Error("Cannot perform operation on undefined values");if(z instanceof xe||J instanceof xe)throw new Error("Cannot perform operation on null values");if(z instanceof se&&J instanceof se)switch(O.operator.value){case"+":return new se(z.value+J.value);case"-":return new se(z.value-J.value);case"*":return new se(z.value*J.value);case"/":return new se(z.value/J.value);case"%":return new se(z.value%J.value);case"<":return new $e(z.value":return new $e(z.value>J.value);case">=":return new $e(z.value>=J.value);case"<=":return new $e(z.value<=J.value)}else if(z instanceof q&&J instanceof q)switch(O.operator.value){case"+":return new q(z.value.concat(J.value))}else if(J instanceof q){const le=J.value.find(ye=>ye.value===z.value)!==void 0;switch(O.operator.value){case"in":return new $e(le);case"not in":return new $e(!le)}}if(z instanceof ce||J instanceof ce)switch(O.operator.value){case"+":return new ce(z.value.toString()+J.value.toString())}if(z instanceof ce&&J instanceof ce)switch(O.operator.value){case"in":return new $e(J.value.includes(z.value));case"not in":return new $e(!J.value.includes(z.value))}if(z instanceof ce&&J instanceof Ue)switch(O.operator.value){case"in":return new $e(J.value.has(z.value));case"not in":return new $e(!J.value.has(z.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${z.type} and ${J.type}`)}evaluateArguments(O,Y){const z=[],J=new Map;for(const le of O)if(le.type==="KeywordArgumentExpression"){const ye=le;J.set(ye.key.value,this.evaluate(ye.value,Y))}else{if(J.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(le,Y))}return[z,J]}evaluateFilterExpression(O,Y){const z=this.evaluate(O.operand,Y);if(O.filter.type==="Identifier"){const J=O.filter;if(J.value==="tojson")return new ce(ze(z));if(z instanceof q)switch(J.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new se(z.value.length);case"reverse":return new q(z.value.reverse());case"sort":return new q(z.value.sort((le,ye)=>{if(le.type!==ye.type)throw new Error(`Cannot compare different types: ${le.type} and ${ye.type}`);switch(le.type){case"NumericValue":return le.value-ye.value;case"StringValue":return le.value.localeCompare(ye.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));case"join":return new ce(z.value.map(le=>le.value).join(""));case"string":return new ce(ze(z));default:throw new Error(`Unknown ArrayValue filter: ${J.value}`)}else if(z instanceof ce)switch(J.value){case"length":return new se(z.value.length);case"upper":return new ce(z.value.toUpperCase());case"lower":return new ce(z.value.toLowerCase());case"title":return new ce(re(z.value));case"capitalize":return new ce(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new ce(z.value.trim());case"indent":return new ce(z.value.split(` -`).map((le,ye)=>ye===0||le.length===0?le:" "+le).join(` -`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${J.value}`)}else if(z instanceof se)switch(J.value){case"abs":return new se(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${J.value}`)}else if(z instanceof Ue)switch(J.value){case"items":return new q(Array.from(z.value.entries()).map(([le,ye])=>new q([new ce(le),ye])));case"length":return new se(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${J.value}`)}throw new Error(`Cannot apply filter "${J.value}" to type: ${z.type}`)}else if(O.filter.type==="CallExpression"){const J=O.filter;if(J.callee.type!=="Identifier")throw new Error(`Unknown filter: ${J.callee.type}`);const le=J.callee.value;if(le==="tojson"){const[,ye]=this.evaluateArguments(J.args,Y),Ee=ye.get("indent")??new xe;if(!(Ee instanceof se||Ee instanceof xe))throw new Error("If set, indent must be a number");return new ce(ze(z,Ee.value))}else if(le==="join"){let ye;if(z instanceof ce)ye=Array.from(z.value);else if(z instanceof q)ye=z.value.map(Be=>Be.value);else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`);const[Ee,ke]=this.evaluateArguments(J.args,Y),Ie=Ee.at(0)??ke.get("separator")??new ce("");if(!(Ie instanceof ce))throw new Error("separator must be a string");return new ce(ye.join(Ie.value))}if(z instanceof q){switch(le){case"selectattr":case"rejectattr":{const ye=le==="selectattr";if(z.value.some(Ge=>!(Ge instanceof Ue)))throw new Error(`\`${le}\` can only be applied to array of objects`);if(J.args.some(Ge=>Ge.type!=="StringLiteral"))throw new Error(`arguments of \`${le}\` must be strings`);const[Ee,ke,Ie]=J.args.map(Ge=>this.evaluate(Ge,Y));let Be;if(ke){const Ge=Y.tests.get(ke.value);if(!Ge)throw new Error(`Unknown test: ${ke.value}`);Be=Ge}else Be=(...Ge)=>Ge[0].__bool__().value;const Xe=z.value.filter(Ge=>{const lt=Ge.value.get(Ee.value),wt=lt?Be(lt,Ie):!1;return ye?wt:!wt});return new q(Xe)}case"map":{const[,ye]=this.evaluateArguments(J.args,Y);if(ye.has("attribute")){const Ee=ye.get("attribute");if(!(Ee instanceof ce))throw new Error("attribute must be a string");const ke=ye.get("default"),Ie=z.value.map(Be=>{if(!(Be instanceof Ue))throw new Error("items in map must be an object");return Be.value.get(Ee.value)??ke??new Me});return new q(Ie)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(z instanceof ce){switch(le){case"indent":{const[ye,Ee]=this.evaluateArguments(J.args,Y),ke=ye.at(0)??Ee.get("width")??new se(4);if(!(ke instanceof se))throw new Error("width must be a number");const Ie=ye.at(1)??Ee.get("first")??new $e(!1),Be=ye.at(2)??Ee.get("blank")??new $e(!1),Xe=z.value.split(` -`),Ge=" ".repeat(ke.value),lt=Xe.map((wt,Gt)=>!Ie.value&&Gt===0||!Be.value&&wt.length===0?wt:Ge+wt);return new ce(lt.join(` -`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,Y){const z=this.evaluate(O.operand,Y),J=Y.tests.get(O.test.value);if(!J)throw new Error(`Unknown test: ${O.test.value}`);const le=J(z);return new $e(O.negate?!le:le)}evaluateUnaryExpression(O,Y){const z=this.evaluate(O.argument,Y);switch(O.operator.value){case"not":return new $e(!z.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,Y){return this.evaluateBlock(O.body,Y)}evaluateBlock(O,Y){let z="";for(const J of O){const le=this.evaluate(J,Y);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(z+=le.value)}return new ce(z)}evaluateIdentifier(O,Y){return Y.lookupVariable(O.value)}evaluateCallExpression(O,Y){const[z,J]=this.evaluateArguments(O.args,Y);J.size>0&&z.push(new we(J));const le=this.evaluate(O.callee,Y);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(z,Y)}evaluateSliceExpression(O,Y,z){if(!(O instanceof q||O instanceof ce))throw new Error("Slice object must be an array or string");const J=this.evaluate(Y.start,z),le=this.evaluate(Y.stop,z),ye=this.evaluate(Y.step,z);if(!(J instanceof se||J instanceof Me))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof se||le instanceof Me))throw new Error("Slice stop must be numeric or undefined");if(!(ye instanceof se||ye instanceof Me))throw new Error("Slice step must be numeric or undefined");return O instanceof q?new q(W(O.value,J.value,le.value,ye.value)):new ce(W(Array.from(O.value),J.value,le.value,ye.value).join(""))}evaluateMemberExpression(O,Y){const z=this.evaluate(O.object,Y);let J;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(z,O.property,Y);J=this.evaluate(O.property,Y)}else J=new ce(O.property.value);let le;if(z instanceof Ue){if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.value.get(J.value)??z.builtins.get(J.value)}else if(z instanceof q||z instanceof ce)if(J instanceof se)le=z.value.at(J.value),z instanceof ce&&(le=new ce(z.value.at(J.value)));else if(J instanceof ce)le=z.builtins.get(J.value);else throw new Error(`Cannot access property with non-string/non-number: got ${J.type}`);else{if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.builtins.get(J.value)}return le instanceof fe?le:new Me}evaluateSet(O,Y){const z=O.value?this.evaluate(O.value,Y):this.evaluateBlock(O.body,Y);if(O.assignee.type==="Identifier"){const J=O.assignee.value;Y.setVariable(J,z)}else if(O.assignee.type==="MemberExpression"){const J=O.assignee,le=this.evaluate(J.object,Y);if(!(le instanceof Ue))throw new Error("Cannot assign to member of non-object");if(J.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(J.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new xe}evaluateIf(O,Y){const z=this.evaluate(O.test,Y);return this.evaluateBlock(z.__bool__().value?O.body:O.alternate,Y)}evaluateFor(O,Y){const z=new Se(Y);let J,le;if(O.iterable.type==="SelectExpression"){const Be=O.iterable;le=this.evaluate(Be.iterable,z),J=Be.test}else le=this.evaluate(O.iterable,z);if(!(le instanceof q))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ye=[],Ee=[];for(let Be=0;Bewt.setVariable(O.loopvar.value,Ge);else if(O.loopvar.type==="TupleLiteral"){const wt=O.loopvar;if(Ge.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ge.type}`);const Gt=Ge;if(wt.value.length!==Gt.value.length)throw new Error(`Too ${wt.value.length>Gt.value.length?"few":"many"} items to unpack`);lt=Ot=>{for(let lr=0;lr0?ye[Be-1]:new Me],["nextitem",Be{var Ee;const le=new Se(J);z=z.slice();let ye;((Ee=z.at(-1))==null?void 0:Ee.type)==="KeywordArgumentsValue"&&(ye=z.pop());for(let ke=0;kethis.evaluate(z,Y)));case"TupleLiteral":return new R(O.value.map(z=>this.evaluate(z,Y)));case"ObjectLiteral":{const z=new Map;for(const[J,le]of O.value){const ye=this.evaluate(J,Y);if(!(ye instanceof ce))throw new Error(`Object keys must be strings: got ${ye.type}`);z.set(ye.value,this.evaluate(le,Y))}return new Ue(z)}case"Identifier":return this.evaluateIdentifier(O,Y);case"CallExpression":return this.evaluateCallExpression(O,Y);case"MemberExpression":return this.evaluateMemberExpression(O,Y);case"UnaryExpression":return this.evaluateUnaryExpression(O,Y);case"BinaryExpression":return this.evaluateBinaryExpression(O,Y);case"FilterExpression":return this.evaluateFilterExpression(O,Y);case"TestExpression":return this.evaluateTestExpression(O,Y);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function Fe(O){switch(typeof O){case"number":return new se(O);case"string":return new ce(O);case"boolean":return new $e(O);case"undefined":return new Me;case"object":return O===null?new xe:Array.isArray(O)?new q(O.map(Fe)):new Ue(new Map(Object.entries(O).map(([Y,z])=>[Y,Fe(z)])));case"function":return new pe((Y,z)=>{const J=O(...Y.map(le=>le.value))??null;return Fe(J)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function ze(O,Y,z){const J=z??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const le=Y?" ".repeat(Y):"",ye=` -`+le.repeat(J),Ee=ye+le;if(O.type==="ArrayValue"){const ke=O.value.map(Ie=>ze(Ie,Y,J+1));return Y?`[${Ee}${ke.join(`,${Ee}`)}${ye}]`:`[${ke.join(", ")}]`}else{const ke=Array.from(O.value.entries()).map(([Ie,Be])=>{const Xe=`"${Ie}": ${ze(Be,Y,J+1)}`;return Y?`${Ee}${Xe}`:Xe});return Y?`{${ke.join(",")}${ye}}`:`{${ke.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var Ve=class{constructor(O){te(this,"parsed");const Y=d(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=V(Y)}render(O){const Y=new Se;if(Y.set("false",!1),Y.set("true",!0),Y.set("raise_exception",le=>{throw new Error(le)}),Y.set("range",F),O)for(const[le,ye]of Object.entries(O))Y.set(le,ye);return new Ae(Y).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>$,deviceToExecutionProviders:()=>f,isONNXProxy:()=>C,isONNXTensor:()=>w});var o=t("./src/env.js"),n=t("?2ce3"),i=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"}}),u=[];let p,d;const c=Symbol.for("onnxruntime");if(c in globalThis)d=globalThis[c];else if(o.apis.IS_NODE_ENV){switch(d=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else d=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const _=d.InferenceSession;function f(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let v=null;async function $(E,y,b){v&&await v;const x=_.create(E,y);v??(v=x);const S=await x;return S.config=b,S}function w(E){return E instanceof d.Tensor}const g=d==null?void 0:d.env;g!=null&&g.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),g.wasm.proxy=!1),g!=null&&g.webgpu&&(g.webgpu.powerPreference="high-performance");function C(){var E;return(E=g==null?void 0:g.wasm)==null?void 0:E.proxy}o.env.backends.onnx=g},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const d=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} 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:()=>E,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>C,post_process_object_detection:()=>c,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>_});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(y,b,x=0,S=null){const A=y/b;let B=(0,n.bankers_round)(A)*b;return S!==null&&B>S&&(B=Math.floor(A)*b),Bb&&F.push(re)}else{let re=(0,n.max)(V.data)[1];if(re===j-1||(W=(0,n.softmax)(V.data),W[re]se*Z[(ce+1)%2])),X.boxes.push(fe),X.classes.push(re),X.scores.push(W[re])}}ee.push(X)}return ee}function _(y,b=null){const x=y.logits,S=x.dims[0];if(b!==null&&b.length!==S)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const A=[];for(let B=0;BZ[F]&&(Z[F]=V[F],X[F]=ae)}const oe=new Array(G.dims[0]);for(let ae=0;aeae!==void 0);A.push({segmentation:H,labels:me})}return A}function f(y,b,x,S){const A=[],B=[],K=[];for(let G=0;Gx&&(A.push(ee),B.push(X),K.push(H))}return[A,B,K]}function v(y,b,x,S=.5,A=.8){const B=[];let K=0,G=0;const j=b[x].data;for(let H=0;H=S&&++G;let ee=K>0&&G>0;return ee&&(ee=K/G>A),[ee,B]}function $(y,b,x,S,A,B=null,K=null){const[G,j]=K??y[0].dims,ee=new o.Tensor("int32",new Int32Array(G*j),[G,j]),H=[];if(K!==null)for(let ae=0;aeX[W]&&(Z[W]=ae,X[W]=F[W])}let oe=0;const me=ee.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,b)/Math.min(y,b)}`);let B=Math.round(y/x)*x,K=Math.round(b/x)*x;if(B*K>A){const G=Math.sqrt(y*b/A);B=Math.floor(y/G/x)*x,K=Math.floor(b/G/x)*x}else if(B*KB?ee=Math.floor(B*j/A):B>A&&(j=Math.floor(A*ee/B)),await b.resize(ee,j,{resample:S}))}async crop_margin(b,x=200){const S=b.clone().grayscale(),A=(0,n.min)(S.data)[0],K=(0,n.max)(S.data)[0]-A;if(K===0)return b;const G=x/255;let j=S.width,ee=S.height,H=0,Z=0;const X=S.data;for(let oe=0;oethis.preprocess(B)));return{pixel_values:(0,o.stack)(S.map(B=>B.pixel_values),0),original_sizes:S.map(B=>B.original_size),reshaped_input_sizes:S.map(B=>B.reshaped_input_size)}}static async from_pretrained(b,x){const S=await(0,a.getModelJSON)(b,l.IMAGE_PROCESSOR_NAME,!0,x);return new this(S)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,u){super(),this.config=l,this.components=u}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,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}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,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,d]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(c=>c in this).map(async c=>{const _=await this[c].from_pretrained(l,u);return[c.replace(/_class$/,""),_]})).then(Object.fromEntries)]);return new this(p,d)}}te(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),te(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,d){return await(0,o.getModelJSON)(p,"config.json",!0,d)}function i(p){const d={};let c={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":c=i(p.text_config);break;case"moondream1":c=i(p.phi_config);break;case"musicgen":c=i(p.decoder);break;case"multi_modality":c=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":d.num_heads="num_attention_heads",d.num_layers="num_hidden_layers",d.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":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.hidden_size="hidden_size",d.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.dim_kv="head_dim";break;case"openelm":d.num_heads="num_kv_heads",d.num_layers="num_transformer_layers",d.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":d.num_heads="num_heads",d.num_layers="num_layers",d.hidden_size="hidden_size";break;case"bloom":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="hidden_size";break;case"mpt":d.num_heads="n_heads",d.num_layers="n_layers",d.hidden_size="d_model";break;case"exaone":d.num_heads="num_key_value_heads",d.num_layers="num_layers",d.dim_kv="head_dim",d.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":d.num_decoder_layers="num_decoder_layers",d.num_decoder_heads="num_heads",d.decoder_dim_kv="d_kv",d.num_encoder_layers="num_layers",d.num_encoder_heads="num_heads",d.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":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="d_model",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="d_model";break;case"speecht5":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="hidden_size",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="hidden_size";break;case"trocr":d.num_encoder_layers=d.num_decoder_layers="decoder_layers",d.num_encoder_heads=d.num_decoder_heads="decoder_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="d_model";break;case"musicgen_decoder":d.num_encoder_layers=d.num_decoder_layers="num_hidden_layers",d.num_encoder_heads=d.num_decoder_heads="num_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"moonshine":d.num_decoder_layers="decoder_num_hidden_layers",d.num_decoder_heads="decoder_num_key_value_heads",d.num_encoder_layers="encoder_num_hidden_layers",d.num_encoder_heads="encoder_num_key_value_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const f=i(p.decoder),v="num_decoder_layers"in f,$=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return v?($.num_decoder_layers=f.num_decoder_layers,$.num_decoder_heads=f.num_decoder_heads,$.decoder_hidden_size=f.decoder_hidden_size,$.num_encoder_layers=f.num_encoder_layers,$.num_encoder_heads=f.num_encoder_heads,$.encoder_hidden_size=f.encoder_hidden_size):($.num_layers=f.num_layers,$.num_heads=f.num_heads,$.hidden_size=f.hidden_size),$}const _={...c,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const f in d)_[f]=p[d[f]];return _}function a(p,{prefix:d="past_key_values",batch_size:c=1}={}){const _={},f=p.normalized_config;if(f.is_encoder_decoder&&"num_encoder_heads"in f&&"num_decoder_heads"in f){const v=f.encoder_dim_kv??f.encoder_hidden_size/f.num_encoder_heads,$=f.decoder_dim_kv??f.decoder_hidden_size/f.num_decoder_heads,w=[c,f.num_encoder_heads,0,v],g=[c,f.num_decoder_heads,0,$];for(let C=0;C{var S,A;t.r(r),t.d(r,{apis:()=>$,env:()=>b});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((S=self.constructor)==null?void 0:S.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,c=typeof process<"u",_=c&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node",f=!x(s),v=!x(o),$=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:c,IS_NODE_ENV:_,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:v}),w=f&&v;let g="./";if(w){const B=Object(import.meta).url;B?g=o.dirname(o.dirname(n.fileURLToPath(B))):typeof __dirname<"u"&&(g=o.dirname(__dirname))}const C=w?o.join(g,"/.cache/"):null,E="/models/",y=w?o.join(g,E):E,b={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:y,useFS:f,useBrowserCache:u,useFSCache:f,cacheDir:C,useCustomCache:!1,customCache:null};function x(B){return Object.keys(B).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){te(this,"max_length",20);te(this,"max_new_tokens",null);te(this,"min_length",0);te(this,"min_new_tokens",null);te(this,"early_stopping",!1);te(this,"max_time",null);te(this,"do_sample",!1);te(this,"num_beams",1);te(this,"num_beam_groups",1);te(this,"penalty_alpha",null);te(this,"use_cache",!0);te(this,"temperature",1);te(this,"top_k",50);te(this,"top_p",1);te(this,"typical_p",1);te(this,"epsilon_cutoff",0);te(this,"eta_cutoff",0);te(this,"diversity_penalty",0);te(this,"repetition_penalty",1);te(this,"encoder_repetition_penalty",1);te(this,"length_penalty",1);te(this,"no_repeat_ngram_size",0);te(this,"bad_words_ids",null);te(this,"force_words_ids",null);te(this,"renormalize_logits",!1);te(this,"constraints",null);te(this,"forced_bos_token_id",null);te(this,"forced_eos_token_id",null);te(this,"remove_invalid_values",!1);te(this,"exponential_decay_length_penalty",null);te(this,"suppress_tokens",null);te(this,"streamer",null);te(this,"begin_suppress_tokens",null);te(this,"forced_decoder_ids",null);te(this,"guidance_scale",null);te(this,"num_return_sequences",1);te(this,"output_attentions",!1);te(this,"output_hidden_states",!1);te(this,"output_scores",!1);te(this,"return_dict_in_generate",!1);te(this,"pad_token_id",null);te(this,"bos_token_id",null);te(this,"eos_token_id",null);te(this,"encoder_no_repeat_ngram_size",0);te(this,"decoder_start_token_id",null);te(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>v,NoBadWordsLogitsProcessor:()=>$,NoRepeatNGramLogitsProcessor:()=>c,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>C,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(b,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(b,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(b){this.processors.push(b)}extend(b){this.processors.push(...b)}_call(b,x){let S=x;for(const A of this.processors)S=A(b,S);return S}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(b){super(),this.bos_token_id=b}_call(b,x){for(let S=0;S=1&&B[B.length-1]>=this.timestamp_begin,G=B.length<2||B[B.length-2]>=this.timestamp_begin;if(K&&(G?A.subarray(this.timestamp_begin).fill(-1/0):A.subarray(0,this.eos_token_id).fill(-1/0)),b[S].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Z=this.timestamp_begin+this.max_initial_timestamp_index;A.subarray(Z+1).fill(-1/0)}const j=(0,o.log_softmax)(A),ee=Math.log(j.subarray(this.timestamp_begin).map(Math.exp).reduce((Z,X)=>Z+X)),H=(0,o.max)(j.subarray(0,this.timestamp_begin))[0];ee>H&&A.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class c extends n{constructor(b){super(),this.no_repeat_ngram_size=b}getNgrams(b){const x=b.length,S=[];for(let B=0;B1 to use the classifier free guidance processor, got guidance scale ${b}.`);this.guidance_scale=b}_call(b,x){if(x.dims[0]!==2*b.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 ${x.dims[0]} for the logits and ${b.length} for the input ids.`);const S=b.length,A=x.slice([0,S],null),B=x.slice([S,x.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${b}`);if(!Number.isInteger(S)||S<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${S}`);this.top_p=b,this.filter_value=x,this.min_tokens_to_keep=S}}class E extends i{constructor(b,{filter_value:x=-1/0,min_tokens_to_keep:S=1}={}){if(super(),!Number.isInteger(b)||b<0)throw new Error(`\`top_k\` must be a positive integer, but is ${b}`);this.top_k=Math.max(b,S),this.filter_value=x}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,c){let _=d.dims.at(-1),f=d.data;if(c===-1)f=f.slice(-_);else{let v=c*_;f=f.slice(v,v+_)}return f}randomSelect(d){let c=0;for(let f=0;f1)return new u(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const c=(0,n.max)(d.data)[1];return[[BigInt(c),0]]}}class l extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[_,f]=await(0,o.topk)(d,c),v=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},()=>{const $=this.randomSelect(v);return[f.data[$],Math.log(v[$])]})}}class u extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[_,f]=await(0,o.topk)(d,c),v=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},($,w)=>[f.data[w],Math.log(v[w])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,d){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 o&&(p=[p]),this.criteria.push(...p)}_call(p,d){const c=new Array(p.length).fill(!1);for(const _ of this.criteria){const f=_(p,d);for(let v=0;vd.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(c=>{const _=c.at(-1);return this.eos_token_id.some(f=>_==f)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(d){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 i{constructor(d,{skip_prompt:c=!1,callback_function:_=null,token_callback_function:f=null,skip_special_tokens:v=!0,decode_kwargs:$={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=c,this.callback_function=_??a,this.token_callback_function=f,this.decode_kwargs={skip_special_tokens:v,...$,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){var $;if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const c=this.next_tokens_are_prompt;if(c&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const _=d[0];($=this.token_callback_function)==null||$.call(this,_),this.token_cache=(0,s.mergeArrays)(this.token_cache,_);const f=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let v;c||f.endsWith(` -`)?(v=f.slice(this.print_len),this.token_cache=[],this.print_len=0):f.length>0&&(0,o.is_chinese_char)(f.charCodeAt(f.length-1))?(v=f.slice(this.print_len),this.print_len+=v.length):(v=f.slice(this.print_len,f.lastIndexOf(" ")+1),this.print_len+=v.length),this.on_finalized_text(v,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,c){var _,f;d.length>0&&((_=this.callback_function)==null||_.call(this,d)),c&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((f=this.callback_function)==null||f.call(this,` -`))}}class u extends l{constructor(d,{skip_prompt:c=!1,callback_function:_=null,token_callback_function:f=null,on_chunk_start:v=null,on_chunk_end:$=null,on_finalize:w=null,time_precision:g=.02,skip_special_tokens:C=!0,decode_kwargs:E={}}={}){super(d,{skip_prompt:c,skip_special_tokens:C,callback_function:_,token_callback_function:f,decode_kwargs:E}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=v,this.on_chunk_end=$,this.on_finalize=w,this.time_precision=g,this.waiting_for_timestamp=!1}put(d){var _,f;if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const c=d[0];if(c.length===1){const v=Number(c[0])-this.timestamp_begin;if(v>=0){const $=v*this.time_precision;this.waiting_for_timestamp?(_=this.on_chunk_end)==null||_.call(this,$):(f=this.on_chunk_start)==null||f.call(this,$),this.waiting_for_timestamp=!this.waiting_for_timestamp,d=[[]]}}return super.put(d)}end(){var d;super.end(),(d=this.on_finalize)==null||d.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>ui,ASTModel:()=>li,ASTPreTrainedModel:()=>lo,AlbertForMaskedLM:()=>N,AlbertForQuestionAnswering:()=>k,AlbertForSequenceClassification:()=>he,AlbertModel:()=>dn,AlbertPreTrainedModel:()=>ys,AutoModel:()=>xl,AutoModelForAudioClassification:()=>tf,AutoModelForAudioFrameClassification:()=>sf,AutoModelForAudioTextToText:()=>hf,AutoModelForCTC:()=>ef,AutoModelForCausalLM:()=>Um,AutoModelForDepthEstimation:()=>lf,AutoModelForDocumentQuestionAnswering:()=>nf,AutoModelForImageClassification:()=>Hm,AutoModelForImageFeatureExtraction:()=>cf,AutoModelForImageMatting:()=>of,AutoModelForImageSegmentation:()=>qm,AutoModelForImageTextToText:()=>pf,AutoModelForImageToImage:()=>af,AutoModelForMaskGeneration:()=>Zm,AutoModelForMaskedLM:()=>Wm,AutoModelForNormalEstimation:()=>uf,AutoModelForObjectDetection:()=>Jm,AutoModelForPoseEstimation:()=>df,AutoModelForQuestionAnswering:()=>Gm,AutoModelForSemanticSegmentation:()=>Xm,AutoModelForSeq2SeqLM:()=>Rm,AutoModelForSequenceClassification:()=>zm,AutoModelForSpeechSeq2Seq:()=>jm,AutoModelForTextToSpectrogram:()=>Nm,AutoModelForTextToWaveform:()=>Vm,AutoModelForTokenClassification:()=>Bm,AutoModelForUniversalSegmentation:()=>Qm,AutoModelForVision2Seq:()=>Km,AutoModelForXVector:()=>rf,AutoModelForZeroShotObjectDetection:()=>Ym,BartForConditionalGeneration:()=>Rt,BartForSequenceClassification:()=>kt,BartModel:()=>Et,BartPretrainedModel:()=>vt,BaseModelOutput:()=>xe,BeitForImageClassification:()=>yc,BeitModel:()=>Mc,BeitPreTrainedModel:()=>Na,BertForMaskedLM:()=>Ae,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Fe,BertForTokenClassification:()=>ze,BertModel:()=>Se,BertPreTrainedModel:()=>Me,BlenderbotForConditionalGeneration:()=>rr,BlenderbotModel:()=>Dt,BlenderbotPreTrainedModel:()=>Kr,BlenderbotSmallForConditionalGeneration:()=>Lr,BlenderbotSmallModel:()=>Hr,BlenderbotSmallPreTrainedModel:()=>gr,BloomForCausalLM:()=>Ud,BloomModel:()=>Vd,BloomPreTrainedModel:()=>$a,CLIPModel:()=>bi,CLIPPreTrainedModel:()=>Ss,CLIPSegForImageSegmentation:()=>vo,CLIPSegModel:()=>yo,CLIPSegPreTrainedModel:()=>Vn,CLIPTextModel:()=>ba,CLIPTextModelWithProjection:()=>Mi,CLIPVisionModel:()=>Ma,CLIPVisionModelWithProjection:()=>yi,CamembertForMaskedLM:()=>Ft,CamembertForQuestionAnswering:()=>bs,CamembertForSequenceClassification:()=>es,CamembertForTokenClassification:()=>ts,CamembertModel:()=>ws,CamembertPreTrainedModel:()=>Ir,CausalLMOutput:()=>bn,CausalLMOutputWithPast:()=>nv,ChineseCLIPModel:()=>xi,ChineseCLIPPreTrainedModel:()=>vi,ClapAudioModelWithProjection:()=>bh,ClapModel:()=>gh,ClapPreTrainedModel:()=>Fi,ClapTextModelWithProjection:()=>wh,CodeGenForCausalLM:()=>gn,CodeGenModel:()=>ko,CodeGenPreTrainedModel:()=>Hn,CohereForCausalLM:()=>Ed,CohereModel:()=>Td,CoherePreTrainedModel:()=>ya,ConvBertForMaskedLM:()=>Ot,ConvBertForQuestionAnswering:()=>gs,ConvBertForSequenceClassification:()=>lr,ConvBertForTokenClassification:()=>Yr,ConvBertModel:()=>Gt,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>hp,ConvNextModel:()=>pp,ConvNextPreTrainedModel:()=>tl,ConvNextV2ForImageClassification:()=>fp,ConvNextV2Model:()=>mp,ConvNextV2PreTrainedModel:()=>rl,DPTForDepthEstimation:()=>qc,DPTModel:()=>Hc,DPTPreTrainedModel:()=>Ya,DacDecoderModel:()=>am,DacDecoderOutput:()=>nm,DacEncoderModel:()=>im,DacEncoderOutput:()=>sm,DacModel:()=>om,DacPreTrainedModel:()=>ji,DebertaForMaskedLM:()=>Qe,DebertaForQuestionAnswering:()=>Or,DebertaForSequenceClassification:()=>et,DebertaForTokenClassification:()=>Bt,DebertaModel:()=>De,DebertaPreTrainedModel:()=>Xt,DebertaV2ForMaskedLM:()=>ss,DebertaV2ForQuestionAnswering:()=>os,DebertaV2ForSequenceClassification:()=>Ur,DebertaV2ForTokenClassification:()=>ns,DebertaV2Model:()=>rs,DebertaV2PreTrainedModel:()=>Pr,DecisionTransformerModel:()=>jh,DecisionTransformerPreTrainedModel:()=>Rh,DeiTForImageClassification:()=>zc,DeiTModel:()=>Lc,DeiTPreTrainedModel:()=>qa,DepthAnythingForDepthEstimation:()=>Qc,DepthAnythingPreTrainedModel:()=>Xc,DepthProForDepthEstimation:()=>tp,DepthProPreTrainedModel:()=>ep,DetrForObjectDetection:()=>xc,DetrForSegmentation:()=>Va,DetrModel:()=>vc,DetrObjectDetectionOutput:()=>Ua,DetrPreTrainedModel:()=>Pi,DetrSegmentationOutput:()=>Tc,Dinov2ForImageClassification:()=>gp,Dinov2Model:()=>_p,Dinov2PreTrainedModel:()=>sl,Dinov2WithRegistersForImageClassification:()=>bp,Dinov2WithRegistersModel:()=>wp,Dinov2WithRegistersPreTrainedModel:()=>nl,DistilBertForMaskedLM:()=>Es,DistilBertForQuestionAnswering:()=>Ts,DistilBertForSequenceClassification:()=>Ys,DistilBertForTokenClassification:()=>vr,DistilBertModel:()=>yr,DistilBertPreTrainedModel:()=>Wr,DonutSwinModel:()=>cp,DonutSwinPreTrainedModel:()=>dp,EfficientNetForImageClassification:()=>Ph,EfficientNetModel:()=>Eh,EfficientNetPreTrainedModel:()=>ml,ElectraForMaskedLM:()=>xs,ElectraForQuestionAnswering:()=>Zr,ElectraForSequenceClassification:()=>Ls,ElectraForTokenClassification:()=>at,ElectraModel:()=>Ds,ElectraPreTrainedModel:()=>kr,EsmForMaskedLM:()=>Zs,EsmForSequenceClassification:()=>Ar,EsmForTokenClassification:()=>en,EsmModel:()=>zs,EsmPreTrainedModel:()=>fr,ExaoneForCausalLM:()=>L,ExaoneModel:()=>I,ExaonePreTrainedModel:()=>T,FalconForCausalLM:()=>_h,FalconModel:()=>fh,FalconPreTrainedModel:()=>cl,FastViTForImageClassification:()=>uc,FastViTModel:()=>lc,FastViTPreTrainedModel:()=>La,Florence2ForConditionalGeneration:()=>fo,Florence2PreTrainedModel:()=>mi,GLPNForDepthEstimation:()=>up,GLPNModel:()=>lp,GLPNPreTrainedModel:()=>el,GPT2LMHeadModel:()=>xo,GPT2Model:()=>Ti,GPT2PreTrainedModel:()=>Un,GPTBigCodeForCausalLM:()=>$o,GPTBigCodeModel:()=>Kn,GPTBigCodePreTrainedModel:()=>Gn,GPTJForCausalLM:()=>So,GPTJModel:()=>Co,GPTJPreTrainedModel:()=>_n,GPTNeoForCausalLM:()=>Po,GPTNeoModel:()=>Eo,GPTNeoPreTrainedModel:()=>To,GPTNeoXForCausalLM:()=>fn,GPTNeoXModel:()=>Br,GPTNeoXPreTrainedModel:()=>Ws,Gemma2ForCausalLM:()=>$d,Gemma2Model:()=>Sd,Gemma2PreTrainedModel:()=>xa,Gemma3ForCausalLM:()=>Id,Gemma3Model:()=>kd,Gemma3PreTrainedModel:()=>Ta,GemmaForCausalLM:()=>Cd,GemmaModel:()=>Pd,GemmaPreTrainedModel:()=>va,GlmForCausalLM:()=>h,GlmModel:()=>Oo,GlmPreTrainedModel:()=>Qn,GraniteForCausalLM:()=>Ei,GraniteModel:()=>$s,GranitePreTrainedModel:()=>sr,GroundingDinoForObjectDetection:()=>yp,GroundingDinoPreTrainedModel:()=>Mp,GroupViTModel:()=>ac,GroupViTPreTrainedModel:()=>ic,HeliumForCausalLM:()=>Fo,HeliumModel:()=>Ao,HeliumPreTrainedModel:()=>Xn,HieraForImageClassification:()=>Rc,HieraModel:()=>Bc,HieraPreTrainedModel:()=>Xa,HubertForCTC:()=>Jp,HubertForSequenceClassification:()=>Yp,HubertModel:()=>Qp,HubertPreTrainedModel:()=>W0,IJepaForImageClassification:()=>Jd,IJepaModel:()=>Qd,IJepaPreTrainedModel:()=>Fa,Idefics3ForConditionalGeneration:()=>Ns,Idefics3PreTrainedModel:()=>gi,ImageMattingOutput:()=>ff,JAISLMHeadModel:()=>nt,JAISModel:()=>mn,JAISPreTrainedModel:()=>Wn,JinaCLIPModel:()=>Nn,JinaCLIPPreTrainedModel:()=>Us,JinaCLIPTextModel:()=>bo,JinaCLIPVisionModel:()=>Mo,LiteWhisperForConditionalGeneration:()=>ci,LlamaForCausalLM:()=>Io,LlamaModel:()=>qn,LlamaPreTrainedModel:()=>wn,LlavaForConditionalGeneration:()=>pn,LlavaOnevisionForConditionalGeneration:()=>mo,LlavaPreTrainedModel:()=>hi,LongT5ForConditionalGeneration:()=>He,LongT5Model:()=>je,LongT5PreTrainedModel:()=>ve,M2M100ForConditionalGeneration:()=>Ip,M2M100Model:()=>kp,M2M100PreTrainedModel:()=>al,MBartForCausalLM:()=>Nt,MBartForConditionalGeneration:()=>dr,MBartForSequenceClassification:()=>cr,MBartModel:()=>Mr,MBartPreTrainedModel:()=>Kt,MPNetForMaskedLM:()=>rn,MPNetForQuestionAnswering:()=>on,MPNetForSequenceClassification:()=>sn,MPNetForTokenClassification:()=>nn,MPNetModel:()=>tn,MPNetPreTrainedModel:()=>Dr,MT5ForConditionalGeneration:()=>dt,MT5Model:()=>Je,MT5PreTrainedModel:()=>We,MarianMTModel:()=>$p,MarianModel:()=>Sp,MarianPreTrainedModel:()=>il,MaskFormerForInstanceSegmentation:()=>ap,MaskFormerModel:()=>ip,MaskFormerPreTrainedModel:()=>Za,MaskedLMOutput:()=>wr,Metric3DForDepthEstimation:()=>sp,Metric3DPreTrainedModel:()=>rp,Metric3Dv2ForDepthEstimation:()=>op,Metric3Dv2PreTrainedModel:()=>np,MgpstrForSceneTextRecognition:()=>Gh,MgpstrModelOutput:()=>Uh,MgpstrPreTrainedModel:()=>Wh,MimiDecoderModel:()=>rm,MimiDecoderOutput:()=>Zh,MimiEncoderModel:()=>tm,MimiEncoderOutput:()=>Yh,MimiModel:()=>em,MimiPreTrainedModel:()=>Ri,MistralForCausalLM:()=>ph,MistralModel:()=>ch,MistralPreTrainedModel:()=>ul,MobileBertForMaskedLM:()=>Ps,MobileBertForQuestionAnswering:()=>_r,MobileBertForSequenceClassification:()=>ur,MobileBertModel:()=>xr,MobileBertPreTrainedModel:()=>Gr,MobileLLMForCausalLM:()=>Te,MobileLLMModel:()=>ue,MobileLLMPreTrainedModel:()=>U,MobileNetV1ForImageClassification:()=>Sh,MobileNetV1ForSemanticSegmentation:()=>$h,MobileNetV1Model:()=>Ch,MobileNetV1PreTrainedModel:()=>Di,MobileNetV2ForImageClassification:()=>Ih,MobileNetV2ForSemanticSegmentation:()=>Ah,MobileNetV2Model:()=>kh,MobileNetV2PreTrainedModel:()=>Li,MobileNetV3ForImageClassification:()=>Oh,MobileNetV3ForSemanticSegmentation:()=>Dh,MobileNetV3Model:()=>Fh,MobileNetV3PreTrainedModel:()=>zi,MobileNetV4ForImageClassification:()=>zh,MobileNetV4ForSemanticSegmentation:()=>Bh,MobileNetV4Model:()=>Lh,MobileNetV4PreTrainedModel:()=>Bi,MobileViTForImageClassification:()=>hc,MobileViTModel:()=>pc,MobileViTPreTrainedModel:()=>za,MobileViTV2ForImageClassification:()=>fc,MobileViTV2Model:()=>mc,MobileViTV2PreTrainedModel:()=>Ba,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>J,ModernBertForTokenClassification:()=>le,ModernBertModel:()=>Y,ModernBertPreTrainedModel:()=>O,Moondream1ForConditionalGeneration:()=>js,MoonshineForConditionalGeneration:()=>po,MoonshineModel:()=>pi,MoonshinePreTrainedModel:()=>Rn,MptForCausalLM:()=>Gd,MptModel:()=>Wd,MptPreTrainedModel:()=>ka,MultiModalityCausalLM:()=>Vh,MultiModalityPreTrainedModel:()=>Nh,MusicgenForCausalLM:()=>q0,MusicgenForConditionalGeneration:()=>_l,MusicgenModel:()=>H0,MusicgenPreTrainedModel:()=>fl,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>ye,OPTForCausalLM:()=>Hd,OPTModel:()=>Kd,OPTPreTrainedModel:()=>Ia,Olmo2ForCausalLM:()=>It,Olmo2Model:()=>xt,Olmo2PreTrainedModel:()=>ht,OlmoForCausalLM:()=>Ye,OlmoModel:()=>Ke,OlmoPreTrainedModel:()=>Oe,OpenELMForCausalLM:()=>Fd,OpenELMModel:()=>Ad,OpenELMPreTrainedModel:()=>Ea,OwlViTForObjectDetection:()=>gc,OwlViTModel:()=>_c,OwlViTPreTrainedModel:()=>Ra,Owlv2ForObjectDetection:()=>bc,Owlv2Model:()=>wc,Owlv2PreTrainedModel:()=>ja,PaliGemmaForConditionalGeneration:()=>_i,PaliGemmaPreTrainedModel:()=>fi,PatchTSMixerForPrediction:()=>Xh,PatchTSMixerModel:()=>qh,PatchTSMixerPreTrainedModel:()=>wl,PatchTSTForPrediction:()=>Hh,PatchTSTModel:()=>Kh,PatchTSTPreTrainedModel:()=>gl,Phi3ForCausalLM:()=>Nd,Phi3Model:()=>jd,Phi3PreTrainedModel:()=>Sa,Phi3VForCausalLM:()=>_o,Phi3VPreTrainedModel:()=>wi,PhiForCausalLM:()=>Rd,PhiModel:()=>Bd,PhiPreTrainedModel:()=>Ca,PreTrainedModel:()=>R,PretrainedMixin:()=>Pt,PvtForImageClassification:()=>tc,PvtModel:()=>ec,PvtPreTrainedModel:()=>Oa,PyAnnoteForAudioFrameClassification:()=>zp,PyAnnoteModel:()=>Lp,PyAnnotePreTrainedModel:()=>ll,QuestionAnsweringModelOutput:()=>Tr,Qwen2ForCausalLM:()=>Dd,Qwen2Model:()=>Od,Qwen2PreTrainedModel:()=>Pa,Qwen2VLForConditionalGeneration:()=>zd,Qwen2VLPreTrainedModel:()=>Ld,RFDetrForObjectDetection:()=>Ic,RFDetrModel:()=>kc,RFDetrObjectDetectionOutput:()=>Ac,RFDetrPreTrainedModel:()=>Ka,RTDetrForObjectDetection:()=>Pc,RTDetrModel:()=>Ec,RTDetrObjectDetectionOutput:()=>Ci,RTDetrPreTrainedModel:()=>Wa,RTDetrV2ForObjectDetection:()=>Sc,RTDetrV2Model:()=>Cc,RTDetrV2ObjectDetectionOutput:()=>$c,RTDetrV2PreTrainedModel:()=>Ga,ResNetForImageClassification:()=>Nc,ResNetModel:()=>jc,ResNetPreTrainedModel:()=>Qa,RoFormerForMaskedLM:()=>Be,RoFormerForQuestionAnswering:()=>lt,RoFormerForSequenceClassification:()=>Xe,RoFormerForTokenClassification:()=>Ge,RoFormerModel:()=>Ie,RoFormerPreTrainedModel:()=>ke,RobertaForMaskedLM:()=>or,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Vt,RobertaForTokenClassification:()=>Zt,RobertaModel:()=>zr,RobertaPreTrainedModel:()=>Yt,SamImageSegmentationOutput:()=>Cp,SamModel:()=>Pp,SamPreTrainedModel:()=>Ep,SapiensForDepthEstimation:()=>Yc,SapiensForNormalEstimation:()=>Zc,SapiensForSemanticSegmentation:()=>Jc,SapiensPreTrainedModel:()=>$i,SegformerForImageClassification:()=>yh,SegformerForSemanticSegmentation:()=>vh,SegformerModel:()=>K0,SegformerPreTrainedModel:()=>Oi,Seq2SeqLMOutput:()=>sv,SequenceClassifierOutput:()=>mt,SiglipModel:()=>hn,SiglipPreTrainedModel:()=>go,SiglipTextModel:()=>Vs,SiglipVisionModel:()=>wo,SmolVLMForConditionalGeneration:()=>jn,SnacDecoderModel:()=>dm,SnacEncoderModel:()=>um,SnacModel:()=>lm,SnacPreTrainedModel:()=>Ni,SpeechT5ForSpeechToText:()=>ih,SpeechT5ForTextToSpeech:()=>ah,SpeechT5HifiGan:()=>lh,SpeechT5Model:()=>G0,SpeechT5PreTrainedModel:()=>Ai,SqueezeBertForMaskedLM:()=>Bs,SqueezeBertForQuestionAnswering:()=>un,SqueezeBertForSequenceClassification:()=>ln,SqueezeBertModel:()=>an,SqueezeBertPreTrainedModel:()=>Ms,StableLmForCausalLM:()=>Th,StableLmModel:()=>xh,StableLmPreTrainedModel:()=>hl,Starcoder2ForCausalLM:()=>mh,Starcoder2Model:()=>hh,Starcoder2PreTrainedModel:()=>dl,StyleTextToSpeech2Model:()=>oh,StyleTextToSpeech2PreTrainedModel:()=>nh,Swin2SRForImageSuperResolution:()=>Kc,Swin2SRModel:()=>Gc,Swin2SRPreTrainedModel:()=>Ja,SwinForImageClassification:()=>Uc,SwinForSemanticSegmentation:()=>Wc,SwinModel:()=>Vc,SwinPreTrainedModel:()=>Si,T5ForConditionalGeneration:()=>de,T5Model:()=>ie,T5PreTrainedModel:()=>Q,TableTransformerForObjectDetection:()=>Oc,TableTransformerModel:()=>Fc,TableTransformerObjectDetectionOutput:()=>Dc,TableTransformerPreTrainedModel:()=>Ha,TokenClassifierOutput:()=>pr,TrOCRForCausalLM:()=>dh,TrOCRPreTrainedModel:()=>uh,UltravoxModel:()=>Jh,UltravoxPreTrainedModel:()=>Qh,UniSpeechForCTC:()=>Np,UniSpeechForSequenceClassification:()=>Vp,UniSpeechModel:()=>jp,UniSpeechPreTrainedModel:()=>ki,UniSpeechSatForAudioFrameClassification:()=>Kp,UniSpeechSatForCTC:()=>Wp,UniSpeechSatForSequenceClassification:()=>Gp,UniSpeechSatModel:()=>Up,UniSpeechSatPreTrainedModel:()=>Do,ViTForImageClassification:()=>Xd,ViTMAEModel:()=>sc,ViTMAEPreTrainedModel:()=>rc,ViTMSNForImageClassification:()=>oc,ViTMSNModel:()=>nc,ViTMSNPreTrainedModel:()=>Da,ViTModel:()=>qd,ViTPreTrainedModel:()=>Aa,VisionEncoderDecoderModel:()=>ho,VitMatteForImageMatting:()=>cc,VitMattePreTrainedModel:()=>dc,VitPoseForPoseEstimation:()=>Zd,VitPosePreTrainedModel:()=>Yd,VitsModel:()=>pl,VitsModelOutput:()=>_f,VitsPreTrainedModel:()=>Mh,Wav2Vec2BertForCTC:()=>qp,Wav2Vec2BertForSequenceClassification:()=>Xp,Wav2Vec2BertModel:()=>Hp,Wav2Vec2BertPreTrainedModel:()=>Ii,Wav2Vec2ForAudioFrameClassification:()=>Dp,Wav2Vec2ForCTC:()=>Fp,Wav2Vec2ForSequenceClassification:()=>Op,Wav2Vec2Model:()=>Ap,Wav2Vec2PreTrainedModel:()=>Gs,WavLMForAudioFrameClassification:()=>sh,WavLMForCTC:()=>eh,WavLMForSequenceClassification:()=>th,WavLMForXVector:()=>rh,WavLMModel:()=>Zp,WavLMPreTrainedModel:()=>Jn,WeSpeakerResNetModel:()=>Rp,WeSpeakerResNetPreTrainedModel:()=>Bp,WhisperForConditionalGeneration:()=>co,WhisperModel:()=>di,WhisperPreTrainedModel:()=>uo,XLMForQuestionAnswering:()=>ri,XLMForSequenceClassification:()=>ei,XLMForTokenClassification:()=>ti,XLMModel:()=>Rs,XLMPreTrainedModel:()=>tr,XLMRobertaForMaskedLM:()=>ni,XLMRobertaForQuestionAnswering:()=>ai,XLMRobertaForSequenceClassification:()=>oi,XLMRobertaForTokenClassification:()=>ii,XLMRobertaModel:()=>si,XLMRobertaPreTrainedModel:()=>Cs,XLMWithLMHeadModel:()=>cn,XVectorOutput:()=>mf,YolosForObjectDetection:()=>xp,YolosModel:()=>vp,YolosObjectDetectionOutput:()=>Tp,YolosPreTrainedModel:()=>ol});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),c=t("./src/utils/tensor.js"),_=t("./src/utils/image.js"),f=t("./src/utils/maths.js"),v=t("./src/generation/stopping_criteria.js"),$=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),g=t("./src/models/whisper/generation_whisper.js"),C=t("./src/models/whisper/common_whisper.js");const E={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},y=new Map,b=new Map,x=new Map;async function S(M,P,D){var hr;let ne=((hr=D.config)==null?void 0:hr["transformers.js_config"])??{},ge=D.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const _e=ge??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ce=(0,o.deviceToExecutionProviders)(_e),Le=ne.device_config??{};Le.hasOwnProperty(_e)&&(ne={...ne,...Le[_e]});let Ne=D.dtype??ne.dtype;if(typeof Ne!="string"&&(Ne&&Ne.hasOwnProperty(P)?Ne=Ne[P]:(Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${Ne}) for this device (${_e}).`))),Ne===n.DATA_TYPES.auto){let Mt=ne.dtype;typeof Mt!="string"&&(Mt=Mt==null?void 0:Mt[P]),Mt&&Mt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Mt)?Ne=Mt:Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??n.DATA_TYPES.fp32}const qe=Ne;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(qe)){if(qe===n.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${qe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const it=ne.kv_cache_dtype,pt=it?typeof it=="string"?it:it[qe]??"float32":void 0;if(pt&&!["float32","float16"].includes(pt))throw new Error(`Invalid kv_cache_dtype: ${pt}. Should be one of: float32, float16`);const ot={dtype:qe,kv_cache_dtype:pt},bt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[qe],ct=`${P}${bt}.onnx`,gt=`${D.subfolder??""}/${ct}`,tt={...D.session_options};tt.executionProviders??(tt.executionProviders=Ce);const yt=ne.free_dimension_overrides;yt?tt.freeDimensionOverrides??(tt.freeDimensionOverrides=yt):_e.startsWith("webnn")&&!tt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${_e}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Lt=w.apis.IS_NODE_ENV&&w.env.useFSCache,Ut=(0,l.getModelFile)(M,gt,!0,D,Lt),Qt=D.use_external_data_format??ne.use_external_data_format;let Ht=[];if(Qt){let Mt;typeof Qt=="object"?Qt.hasOwnProperty(ct)?Mt=Qt[ct]:Qt.hasOwnProperty(P)?Mt=Qt[P]:Mt=!1:Mt=Qt;const ir=+Mt;if(ir>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${ir}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Rr=0;Rr{const yn=await(0,l.getModelFile)(M,Cr,!0,D,Lt);qr(yn instanceof Uint8Array?{path:Mn,data:yn}:Mn)}))}}else tt.externalData!==void 0&&(Ht=tt.externalData.map(async Mt=>{if(typeof Mt.data=="string"){const ir=await(0,l.getModelFile)(M,Mt.data,!0,D);return{...Mt,data:ir}}return Mt}));if(Ht.length>0){const Mt=await Promise.all(Ht);w.apis.IS_NODE_ENV||(tt.externalData=Mt)}if(_e==="webgpu"){const Mt=(0,s.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(Mt).length>0&&!(0,o.isONNXProxy)()){const ir={};for(const Rr in Mt)ir[Rr]="gpu-buffer";tt.preferredOutputLocation=ir}}return{buffer_or_path:await Ut,session_options:tt,session_config:ot}}async function A(M,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:_e,session_config:Ce}=await S(M,P[ne],D),Le=await(0,o.createInferenceSession)(ge,_e,Ce);return[ne,Le]})))}async function B(M,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(M,P[ne],!1,D);return[ne,ge]})))}function K(M,P){const D=Object.create(null),ne=[];for(const Ce of M.inputNames){const Le=P[Ce];if(!(Le instanceof c.Tensor)){ne.push(Ce);continue}D[Ce]=(0,o.isONNXProxy)()?Le.clone():Le}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,_e=M.inputNames.length;if(ge>_e){let Ce=Object.keys(P).filter(Le=>!M.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${ge} > ${_e}). The following inputs will be ignored: "${Ce.join(", ")}".`)}return D}async function G(M,P){const D=K(M,P);try{const ne=Object.fromEntries(Object.entries(D).map(([_e,Ce])=>[_e,Ce.ort_tensor]));let ge=await M.run(ne);return ge=j(ge),ge}catch(ne){const ge=Object.fromEntries(Object.entries(D).map(([_e,{type:Ce,dims:Le,data:Ne}])=>[_e,{type:Ce,dims:Le,data:Ne}]));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function j(M){for(let P in M)(0,o.isONNXTensor)(M[P])?M[P]=new c.Tensor(M[P]):typeof M[P]=="object"&&j(M[P]);return M}function ee(M){if(M instanceof c.Tensor)return M;if(M.length===0)throw Error("items must be non-empty");if(Array.isArray(M[0])){if(M.some(P=>P.length!==M[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 c.Tensor("int64",BigInt64Array.from(M.flat().map(P=>BigInt(P))),[M.length,M[0].length])}else return new c.Tensor("int64",BigInt64Array.from(M.map(P=>BigInt(P))),[1,M.length])}function H(M){return new c.Tensor("bool",[M],[1])}async function Z(M,P){let{encoder_outputs:D,input_ids:ne,decoder_input_ids:ge,..._e}=P;if(!D){const Le=(0,a.pick)(P,M.sessions.model.inputNames);D=(await X(M,Le)).last_hidden_state}return _e.input_ids=ge,_e.encoder_hidden_states=D,M.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=P.attention_mask),await me(M,_e,!0)}async function X(M,P){const D=M.sessions.model,ne=(0,a.pick)(P,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await M.encode_text({input_ids:P.input_ids})}if(D.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,c.zeros_like)(ne.input_ids)}if(D.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=ne.pixel_values.dims;ne.pixel_mask=(0,c.ones)([ge[0],ge[2],ge[3]])}return await G(D,ne)}async function oe(M,P){const D=await M.encode(P);return await M.decode(D)}async function me(M,P,D=!1){const ne=M.sessions[D?"decoder_model_merged":"model"],{past_key_values:ge,..._e}=P;if(ne.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=H(!!ge)),ne.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(M.config.model_type)?1:0;_e.position_ids=ce(_e,ge,Le)}M.addPastKeyValues(_e,ge);const Ce=(0,a.pick)(_e,ne.inputNames);return await G(ne,Ce)}function ae({modality_token_id:M,inputs_embeds:P,modality_features:D,input_ids:ne,attention_mask:ge}){const _e=ne.tolist().map(qe=>qe.reduce((it,pt,ot)=>(pt==M&&it.push(ot),it),[])),Ce=_e.reduce((qe,it)=>qe+it.length,0),Le=D.dims[0];if(Ce!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ce}, features ${Le}`);let Ne=0;for(let qe=0;qe<_e.length;++qe){const it=_e[qe],pt=P[qe];for(let ot=0;ot_e.dims[1])){if(ge<_e.dims[1])D.input_ids=_e.slice(null,[ge,null]);else if(M.config.image_token_index!=null&&_e.data.some(Le=>Le==M.config.image_token_index)){const Le=M.config.num_image_tokens;if(!Le)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ne=_e.dims[1]-(ge-Le);D.input_ids=_e.slice(null,[-Ne,null]),D.attention_mask=(0,c.ones)([1,ge+Ne])}}}return D}function Ue(M,P,D,ne){return D.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...D,decoder_input_ids:ee(P)}}function we(M,...P){return M.config.is_encoder_decoder?Ue(M,...P):$e(M,...P)}function q(M,P,D,ne){const ge=!!D.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?D.input_ids=(0,c.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,c.cat)([D.input_ids,(0,c.full_like)(D.input_ids,BigInt(ne.pad_token_id))],0),D.attention_mask=(0,c.cat)([D.attention_mask,(0,c.full_like)(D.attention_mask,0n)],0))),(ge||!D.pixel_values)&&(D.pixel_values=(0,c.full)([0,0,3,384,384],1)),ge&&(D.images_seq_mask=new c.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new c.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class R extends i.Callable{constructor(D,ne,ge){super();te(this,"main_input_name","input_ids");te(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=ne,this.configs=ge;const _e=x.get(this.constructor),Ce=y.get(_e);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ce){case E.DecoderOnly:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=$e;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=Ue;break;case E.EncoderDecoder:this._forward=Z;break;case E.ImageTextToText:this.can_generate=!0,this._forward=fe,this._prepare_inputs_for_generation=we;break;case E.AudioTextToText:this.can_generate=!0,this._forward=re,this._prepare_inputs_for_generation=we;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=we;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=q;break;case E.AutoEncoder:this._forward=oe;break;default:this._forward=X;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const D=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&D.push(ge.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:ne=null,config:ge=null,cache_dir:_e=null,local_files_only:Ce=!1,revision:Le="main",model_file_name:Ne=null,subfolder:qe="onnx",device:it=null,dtype:pt=null,use_external_data_format:ot=null,session_options:bt={}}={}){let ct={progress_callback:ne,config:ge,cache_dir:_e,local_files_only:Ce,revision:Le,model_file_name:Ne,subfolder:qe,device:it,dtype:pt,use_external_data_format:ot,session_options:bt};const gt=x.get(this),tt=y.get(gt);ge=ct.config=await s.AutoConfig.from_pretrained(D,ct);let yt;if(tt===E.DecoderOnly)yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.Seq2Seq||tt===E.Vision2Seq)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.MaskGeneration)yt=await Promise.all([A(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},ct)]);else if(tt===E.EncoderDecoder)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct)]);else if(tt===E.ImageTextToText){const Lt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(Lt.model="encoder_model"),yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(tt===E.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(tt===E.Musicgen)yt=await Promise.all([A(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.MultiModality)yt=await Promise.all([A(D,{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"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.Phi3V)yt=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.AutoEncoder)yt=await Promise.all([A(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},ct)]);else{if(tt!==E.EncoderOnly){const Lt=gt??(ge==null?void 0:ge.model_type);Lt!=="custom"&&console.warn(`Model type for '${Lt}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct)])}return new this(ge,...yt)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const ne=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&ne.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&ne.push(new p.TopPLogitsWarper(D.top_p)),ne}_get_logits_processor(D,ne,ge=null){const _e=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&_e.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&_e.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&_e.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&_e.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&_e.push(new p.MinNewTokensLengthLogitsProcessor(ne,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&_e.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&_e.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ce=ne>1||D.forced_bos_token_id===null?ne:ne+1;_e.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce))}return D.guidance_scale!==null&&D.guidance_scale>1&&_e.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),ge!==null&&_e.extend(ge),_e}_prepare_generation_config(D,ne,ge=d.GenerationConfig){const _e={...this.config};for(const Le of["decoder","generator","text_config"])Le in _e&&Object.assign(_e,_e[Le]);const Ce=new ge(_e);return Object.assign(Ce,this.generation_config??{}),D&&Object.assign(Ce,D),ne&&Object.assign(Ce,(0,a.pick)(ne,Object.getOwnPropertyNames(Ce))),Ce}_get_stopping_criteria(D,ne=null){const ge=new v.StoppingCriteriaList;return D.max_length!==null&&ge.push(new v.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&ge.push(new v.EosTokenCriteria(D.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const D=[yl,vl,Ml,bl],ne=x.get(this.constructor),ge=new Set,_e=this.config.model_type;for(const Le of D){const Ne=Le.get(_e);Ne&&ge.add(Ne[0])}let Ce=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ce+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ce)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:ne,model_inputs:ge,is_encoder_decoder:_e}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new c.Tensor("int64",D.flat(),[D.length,1]),_e||(ge.attention_mask=(0,c.cat)([ge.attention_mask,(0,c.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:D,bos_token_id:ne,model_kwargs:ge}){const _e=(0,a.pick)(ge,this.forward_params),Ce=this.main_input_name;if(Ce in _e){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else _e[Ce]=D;return{inputs_tensor:_e[Ce],model_inputs:_e,model_input_name:Ce}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:ne,model_input_name:ge,generation_config:_e}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Le,pixel_values:Ne,attention_mask:qe,...it}=ne,pt=await this._prepare_inputs_embeds(ne);ne={...it,...(0,a.pick)(pt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ce}=await X(this,ne);if(_e.guidance_scale!==null&&_e.guidance_scale>1)Ce=(0,c.cat)([Ce,(0,c.full_like)(Ce,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,c.cat)([ne.attention_mask,(0,c.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const Le=ee(ne.decoder_input_ids).dims[0];if(Le!==Ce.dims[0]){if(Ce.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ce.dims[0]}) than the decoder inputs (${Le}).`);Ce=(0,c.cat)(Array.from({length:Le},()=>Ce),0)}}return ne.encoder_outputs=Ce,ne}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:_e,bos_token_id:Ce,generation_config:Le}){let{decoder_input_ids:Ne,...qe}=ge;if(!(Ne instanceof c.Tensor)){if(Ne)Array.isArray(Ne[0])||(Ne=Array.from({length:D},()=>Ne));else if(_e??(_e=Ce),this.config.model_type==="musicgen")Ne=Array.from({length:D*this.config.decoder.num_codebooks},()=>[_e]);else if(Array.isArray(_e)){if(_e.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${_e.length}`);Ne=_e}else Ne=Array.from({length:D},()=>[_e]);Ne=ee(Ne)}return ge.decoder_attention_mask=(0,c.ones_like)(Ne),{input_ids:Ne,model_inputs:qe}}async generate({inputs:D=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:_e=null,streamer:Ce=null,...Le}){this._validate_model_class(),ne=this._prepare_generation_config(ne,Le);let{inputs_tensor:Ne,model_inputs:qe,model_input_name:it}=this._prepare_model_inputs({inputs:D,model_kwargs:Le});const pt=this.config.is_encoder_decoder;pt&&("encoder_outputs"in qe||(qe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ne,model_inputs:qe,model_input_name:it,generation_config:ne})));let ot;pt?{input_ids:ot,model_inputs:qe}=this._prepare_decoder_input_ids_for_generation({batch_size:qe[it].dims.at(0),model_input_name:it,model_kwargs:qe,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):ot=qe[it];let bt=ot.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=bt+ne.max_new_tokens);const ct=this._get_logits_processor(ne,bt,ge),gt=this._get_stopping_criteria(ne,_e),tt=qe[it].dims.at(0),yt=$.LogitsSampler.getSampler(ne),Lt=new Array(tt).fill(0),Ut=ot.tolist();Ce&&Ce.put(Ut);let Qt,Ht={};for(;;){if(qe=this.prepare_inputs_for_generation(Ut,qe,ne),Qt=await this.forward(qe),ne.output_attentions&&ne.return_dict_in_generate){const Cr=this.getAttentions(Qt);for(const qr in Cr)qr in Ht||(Ht[qr]=[]),Ht[qr].push(Cr[qr])}const Mt=Qt.logits.slice(null,-1,null),ir=ct(Ut,Mt),Rr=[];for(let Cr=0;CrCr))break;qe=this._update_model_kwargs_for_generation({generated_input_ids:Rr,outputs:Qt,model_inputs:qe,is_encoder_decoder:pt})}Ce&&Ce.end();const nr=this.getPastKeyValues(Qt,qe.past_key_values,!0),hr=new c.Tensor("int64",Ut.flat(),[Ut.length,Ut[0].length]);if(ne.return_dict_in_generate)return{sequences:hr,past_key_values:nr,...Ht};for(const Mt of Object.values(Qt))Mt.location==="gpu-buffer"&&Mt.dispose();return hr}getPastKeyValues(D,ne,ge=!1){const _e=Object.create(null);for(const Ce in D)if(Ce.startsWith("present")){const Le=Ce.replace("present","past_key_values"),Ne=Ce.includes("encoder");if(Ne&&ne?_e[Le]=ne[Le]:_e[Le]=D[Ce],ne&&(!Ne||ge)){const qe=ne[Le];qe.location==="gpu-buffer"&&qe.dispose()}}return _e}getAttentions(D){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const _e in D)_e.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(D[_e]));return ne}addPastKeyValues(D,ne){var ge,_e,Ce;if(ne)Object.assign(D,ne);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,Ne=((ge=Le==null?void 0:Le.config)==null?void 0:ge.kv_cache_dtype)??"float32",qe=Ne==="float16"?new c.DataTypeMap.float16:[],it=((Ce=(_e=D[this.main_input_name]??D.attention_mask)==null?void 0:_e.dims)==null?void 0:Ce[0])??1,pt=(0,s.getKeyValueShapes)(this.config,{batch_size:it});for(const ot in pt)D[ot]=new c.Tensor(Ne,qe,pt[ot])}}async encode_image({pixel_values:D}){const ne=(await G(this.sessions.vision_encoder,{pixel_values:D})).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 (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:D}){return(await G(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await G(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class pe{}class xe extends pe{constructor({last_hidden_state:P,hidden_states:D=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=D,this.attentions=ne}}class Me extends R{}class Se extends Me{}class Ae extends Me{async _call(P){return new wr(await super._call(P))}}class Fe extends Me{async _call(P){return new mt(await super._call(P))}}class ze extends Me{async _call(P){return new pr(await super._call(P))}}class Ve extends Me{async _call(P){return new Tr(await super._call(P))}}class O extends R{}class Y extends O{}class z extends O{async _call(P){return new wr(await super._call(P))}}class J extends O{async _call(P){return new mt(await super._call(P))}}class le extends O{async _call(P){return new pr(await super._call(P))}}class ye extends R{}class Ee extends ye{}class ke extends R{}class Ie extends ke{}class Be extends ke{async _call(P){return new wr(await super._call(P))}}class Xe extends ke{async _call(P){return new mt(await super._call(P))}}class Ge extends ke{async _call(P){return new pr(await super._call(P))}}class lt extends ke{async _call(P){return new Tr(await super._call(P))}}class wt extends R{}class Gt extends wt{}class Ot extends wt{async _call(P){return new wr(await super._call(P))}}class lr extends wt{async _call(P){return new mt(await super._call(P))}}class Yr extends wt{async _call(P){return new pr(await super._call(P))}}class gs extends wt{async _call(P){return new Tr(await super._call(P))}}class kr extends R{}class Ds extends kr{}class xs extends kr{async _call(P){return new wr(await super._call(P))}}class Ls extends kr{async _call(P){return new mt(await super._call(P))}}class at extends kr{async _call(P){return new pr(await super._call(P))}}class Zr extends kr{async _call(P){return new Tr(await super._call(P))}}class Ir extends R{}class ws extends Ir{}class Ft extends Ir{async _call(P){return new wr(await super._call(P))}}class es extends Ir{async _call(P){return new mt(await super._call(P))}}class ts extends Ir{async _call(P){return new pr(await super._call(P))}}class bs extends Ir{async _call(P){return new Tr(await super._call(P))}}class Xt extends R{}class De extends Xt{}class Qe extends Xt{async _call(P){return new wr(await super._call(P))}}class et extends Xt{async _call(P){return new mt(await super._call(P))}}class Bt extends Xt{async _call(P){return new pr(await super._call(P))}}class Or extends Xt{async _call(P){return new Tr(await super._call(P))}}class Pr extends R{}class rs extends Pr{}class ss extends Pr{async _call(P){return new wr(await super._call(P))}}class Ur extends Pr{async _call(P){return new mt(await super._call(P))}}class ns extends Pr{async _call(P){return new pr(await super._call(P))}}class os extends Pr{async _call(P){return new Tr(await super._call(P))}}class Wr extends R{}class yr extends Wr{}class Ys extends Wr{async _call(P){return new mt(await super._call(P))}}class vr extends Wr{async _call(P){return new pr(await super._call(P))}}class Ts extends Wr{async _call(P){return new Tr(await super._call(P))}}class Es extends Wr{async _call(P){return new wr(await super._call(P))}}class fr extends R{}class zs extends fr{}class Zs extends fr{async _call(P){return new wr(await super._call(P))}}class Ar extends fr{async _call(P){return new mt(await super._call(P))}}class en extends fr{async _call(P){return new pr(await super._call(P))}}class Gr extends R{}class xr extends Gr{}class Ps extends Gr{async _call(P){return new wr(await super._call(P))}}class ur extends Gr{async _call(P){return new mt(await super._call(P))}}class _r extends Gr{async _call(P){return new Tr(await super._call(P))}}class Dr extends R{}class tn extends Dr{}class rn extends Dr{async _call(P){return new wr(await super._call(P))}}class sn extends Dr{async _call(P){return new mt(await super._call(P))}}class nn extends Dr{async _call(P){return new pr(await super._call(P))}}class on extends Dr{async _call(P){return new Tr(await super._call(P))}}class Ms extends R{}class an extends Ms{}class Bs extends Ms{async _call(P){return new wr(await super._call(P))}}class ln extends Ms{async _call(P){return new mt(await super._call(P))}}class un extends Ms{async _call(P){return new Tr(await super._call(P))}}class ys extends R{}class dn extends ys{}class he extends ys{async _call(P){return new mt(await super._call(P))}}class k extends ys{async _call(P){return new Tr(await super._call(P))}}class N extends ys{async _call(P){return new wr(await super._call(P))}}class Q extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ie extends Q{}class de extends Q{}class ve extends R{}class je extends ve{}class He extends ve{}class We extends R{}class Je extends We{}class dt extends We{}class vt extends R{}class Et extends vt{}class Rt extends vt{}class kt extends vt{async _call(P){return new mt(await super._call(P))}}class Kt extends R{}class Mr extends Kt{}class dr extends Kt{}class cr extends Kt{async _call(P){return new mt(await super._call(P))}}class Nt extends Kt{}class Kr extends R{}class Dt extends Kr{}class rr extends Kr{}class gr extends R{}class Hr extends gr{}class Lr extends gr{}class Yt extends R{}class zr extends Yt{}class or extends Yt{async _call(P){return new wr(await super._call(P))}}class Vt extends Yt{async _call(P){return new mt(await super._call(P))}}class Zt extends Yt{async _call(P){return new pr(await super._call(P))}}class er extends Yt{async _call(P){return new Tr(await super._call(P))}}class tr extends R{}class Rs extends tr{}class cn extends tr{async _call(P){return new wr(await super._call(P))}}class ei extends tr{async _call(P){return new mt(await super._call(P))}}class ti extends tr{async _call(P){return new pr(await super._call(P))}}class ri extends tr{async _call(P){return new Tr(await super._call(P))}}class Cs extends R{}class si extends Cs{}class ni extends Cs{async _call(P){return new wr(await super._call(P))}}class oi extends Cs{async _call(P){return new mt(await super._call(P))}}class ii extends Cs{async _call(P){return new pr(await super._call(P))}}class ai extends Cs{async _call(P){return new Tr(await super._call(P))}}class lo extends R{}class li extends lo{}class ui extends lo{}class uo extends R{constructor(){super(...arguments);te(this,"requires_attention_mask",!1);te(this,"main_input_name","input_features");te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class di extends uo{}class co extends uo{_prepare_generation_config(P,D){return super._prepare_generation_config(P,D,g.WhisperGenerationConfig)}_retrieve_init_tokens(P){const D=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ce=`<|${(0,C.whisper_language_to_code)(ne)}|>`;D.push(P.lang_to_id[Ce]),D.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)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!P.return_timestamps&&P.no_timestamps_token_id&&D.at(-1)!==P.no_timestamps_token_id?D.push(P.no_timestamps_token_id):P.return_timestamps&&D.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(_e=>_e!=null)}async generate({inputs:P=null,generation_config:D=null,logits_processor:ne=null,stopping_criteria:ge=null,..._e}){D=this._prepare_generation_config(D,_e);const Ce=_e.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(D,Ce))),D.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce.length))),D.return_token_timestamps){if(!D.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.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Le=await super.generate({inputs:P,generation_config:D,logits_processor:ne,decoder_input_ids:Ce,..._e});return D.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,D.alignment_heads,D.num_frames)),Le}_extract_token_timestamps(P,D,ne=null,ge=.02){if(!P.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`.");ne==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 _e=this.config.median_filter_width;_e===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),_e=7);const Ce=P.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(gt,tt)=>(0,c.cat)(Ce.map(yt=>yt[tt]),2)),Ne=(0,c.stack)(D.map(([gt,tt])=>{if(gt>=Le.length)throw new Error(`Layer index ${gt} is out of bounds for cross attentions (length ${Le.length}).`);return ne?Le[gt].slice(null,tt,null,[0,ne]):Le[gt].slice(null,tt)})).transpose(1,0,2,3),[qe,it]=(0,c.std_mean)(Ne,-2,0,!0),pt=Ne.clone();for(let gt=0;gtyt[hr+1]-yt[hr]),Qt=(0,a.mergeArrays)([1],Ut).map(nr=>!!nr),Ht=[];for(let nr=0;nrot.findIndex(bt=>bt==_e)),Ne=Le.every(ot=>ot===-1),qe=Le.every(ot=>ot!==-1);if(!Ne&&!qe)throw new Error("Every input should contain either 0 or 1 image token.");if(Ne)return{inputs_embeds:P,attention_mask:ge};const it=[],pt=[];for(let ot=0;otArray.from({length:P.dims[0]},Ut=>Array.from({length:P.dims[1]},Qt=>1))),ct=D?D.tolist():[],gt=ne?ne.tolist():[];let tt=0,yt=0;for(let Lt=0;Ltot[Lt][ar]==1),Ht=Ut.reduce((Wt,ar,Ks)=>(ar==Ne&&Wt.push(Ks),Wt),[]).map(Wt=>Ut[Wt+1]),nr=Ht.filter(Wt=>Wt==Ce).length,hr=Ht.filter(Wt=>Wt==Le).length;let Mt=[],ir=0,Rr=nr,Mn=hr;for(let Wt=0;Wtis>ir&&xn==Ce),Ks=Ut.findIndex((xn,is)=>is>ir&&xn==Le),vn=Rr>0&&ar!==-1?ar:Ut.length+1,Zn=Mn>0&&Ks!==-1?Ks:Ut.length+1;let Gi,Tl,El,Pl;vn0?(0,f.max)(Mt.at(-1))[0]+1:0;Mt.push(Array.from({length:3*Sl},(xn,is)=>gf+is%Sl));const $l=Sl+gf,Hi=ov*Cl*Ki,iv=Array.from({length:Hi},(xn,is)=>$l+Math.floor(is/(Cl*Ki))),av=Array.from({length:Hi},(xn,is)=>$l+Math.floor(is/Ki)%Cl),lv=Array.from({length:Hi},(xn,is)=>$l+is%Ki);Mt.push([iv,av,lv].flat()),ir=Gi+Hi}if(ir0?(0,f.max)(Mt.at(-1))[0]+1:0,ar=Ut.length-ir;Mt.push(Array.from({length:3*ar},(Ks,vn)=>Wt+vn%ar))}const Cr=Mt.reduce((Wt,ar)=>Wt+ar.length,0),qr=new Array(Cr);let Vi=0;for(let Wt=0;Wt<3;++Wt)for(let ar=0;arpt[tt%pt.length]),ct=Array.from({length:ot[0]},(gt,tt)=>(0,f.max)(pt.subarray(ot[1]*tt,ot[1]*(tt+1)))[0]+1n+BigInt(ot[1]));return[new c.Tensor("int64",bt,[3,...ot]),new c.Tensor("int64",ct,[ct.length,1])]}else{const[pt,ot]=P.dims,bt=BigInt64Array.from({length:3*pt*ot},(ct,gt)=>BigInt(Math.floor(gt%ot/pt)));return[new c.Tensor("int64",bt,[3,...P.dims]),(0,c.zeros)([pt,1])]}}async encode_image({pixel_values:P,image_grid_thw:D}){return(await G(this.sessions.vision_encoder,{pixel_values:P,grid_thw:D})).image_features}_merge_input_ids_with_image_features(P){return V({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,D,ne){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const ge=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),_e=D.rope_deltas.map(Ce=>ge+Ce);D.position_ids=(0,c.stack)([_e,_e,_e],0)}return D}}class Ca extends R{}class Bd extends Ca{}class Rd extends Ca{}class Sa extends R{}class jd extends Sa{}class Nd extends Sa{}class $a extends R{}class Vd extends $a{}class Ud extends $a{}class ka extends R{}class Wd extends ka{}class Gd extends ka{}class Ia extends R{}class Kd extends Ia{}class Hd extends Ia{}class Aa extends R{}class qd extends Aa{}class Xd extends Aa{async _call(P){return new mt(await super._call(P))}}class Fa extends R{}class Qd extends Fa{}class Jd extends Fa{async _call(P){return new mt(await super._call(P))}}class Yd extends R{}class Zd extends Yd{}class Oa extends R{}class ec extends Oa{}class tc extends Oa{async _call(P){return new mt(await super._call(P))}}class rc extends R{}class sc extends rc{}class Da extends R{}class nc extends Da{}class oc extends Da{async _call(P){return new mt(await super._call(P))}}class ic extends R{}class ac extends ic{}class La extends R{}class lc extends La{}class uc extends La{async _call(P){return new mt(await super._call(P))}}class dc extends R{}class cc extends dc{async _call(P){return new ff(await super._call(P))}}class za extends R{}class pc extends za{}class hc extends za{async _call(P){return new mt(await super._call(P))}}class Ba extends R{}class mc extends Ba{}class fc extends Ba{async _call(P){return new mt(await super._call(P))}}class Ra extends R{}class _c extends Ra{}class gc extends Ra{}class ja extends R{}class wc extends ja{}class bc extends ja{}class Na extends R{}class Mc extends Na{}class yc extends Na{async _call(P){return new mt(await super._call(P))}}class Pi extends R{}class vc extends Pi{}class xc extends Pi{async _call(P){return new Ua(await super._call(P))}}class Va extends Pi{async _call(P){return new Tc(await super._call(P))}}class Ua extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Tc extends pe{constructor({logits:P,pred_boxes:D,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=D,this.pred_masks=ne}}class Wa extends R{}class Ec extends Wa{}class Pc extends Wa{async _call(P){return new Ci(await super._call(P))}}class Ci extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Ga extends R{}class Cc extends Ga{}class Sc extends Ga{async _call(P){return new $c(await super._call(P))}}class $c extends Ci{}class Ka extends R{}class kc extends Ka{}class Ic extends Ka{async _call(P){return new Ac(await super._call(P))}}class Ac extends Ci{}class Ha extends R{}class Fc extends Ha{}class Oc extends Ha{async _call(P){return new Dc(await super._call(P))}}class Dc extends Ua{}class qa extends R{}class Lc extends qa{}class zc extends qa{async _call(P){return new mt(await super._call(P))}}class Xa extends R{}class Bc extends Xa{}class Rc extends Xa{async _call(P){return new mt(await super._call(P))}}class Qa extends R{}class jc extends Qa{}class Nc extends Qa{async _call(P){return new mt(await super._call(P))}}class Si extends R{}class Vc extends Si{}class Uc extends Si{async _call(P){return new mt(await super._call(P))}}class Wc extends Si{}class Ja extends R{}class Gc extends Ja{}class Kc extends Ja{}class Ya extends R{}class Hc extends Ya{}class qc extends Ya{}class Xc extends R{}class Qc extends Xc{}class $i extends R{}class Jc extends $i{}class Yc extends $i{}class Zc extends $i{}class ep extends R{}class tp extends ep{}class rp extends R{}class sp extends rp{}class np extends R{}class op extends np{}class Za extends R{}class ip extends Za{}class ap extends Za{}class el extends R{}class lp extends el{}class up extends el{}class dp extends R{}class cp extends dp{}class tl extends R{}class pp extends tl{}class hp extends tl{async _call(P){return new mt(await super._call(P))}}class rl extends R{}class mp extends rl{}class fp extends rl{async _call(P){return new mt(await super._call(P))}}class sl extends R{}class _p extends sl{}class gp extends sl{async _call(P){return new mt(await super._call(P))}}class nl extends R{}class wp extends nl{}class bp extends nl{async _call(P){return new mt(await super._call(P))}}class Mp extends R{}class yp extends Mp{}class ol extends R{}class vp extends ol{}class xp extends ol{async _call(P){return new Tp(await super._call(P))}}class Tp extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Ep extends R{}class Pp extends Ep{async get_image_embeddings({pixel_values:P}){return await X(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((_e,Ce)=>_e*Ce,1);P.input_labels=new c.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const D={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(D.input_points=P.input_points),P.input_labels&&(D.input_labels=P.input_labels),P.input_boxes&&(D.input_boxes=P.input_boxes),await G(this.sessions.prompt_encoder_mask_decoder,D)}async _call(P){return new Cp(await super._call(P))}}class Cp extends pe{constructor({iou_scores:P,pred_masks:D}){super(),this.iou_scores=P,this.pred_masks=D}}class il extends R{}class Sp extends il{}class $p extends il{}class al extends R{}class kp extends al{}class Ip extends al{}class Gs extends R{}class Ap extends Gs{}class Fp extends Gs{async _call(P){return new bn(await super._call(P))}}class Op extends Gs{async _call(P){return new mt(await super._call(P))}}class Dp extends Gs{async _call(P){return new pr(await super._call(P))}}class ll extends R{}class Lp extends ll{}class zp extends ll{async _call(P){return new pr(await super._call(P))}}class Bp extends R{}class Rp extends Bp{}class ki extends R{}class jp extends ki{}class Np extends ki{async _call(P){return new bn(await super._call(P))}}class Vp extends ki{async _call(P){return new mt(await super._call(P))}}class Do extends R{}class Up extends Do{}class Wp extends Do{async _call(P){return new bn(await super._call(P))}}class Gp extends Do{async _call(P){return new mt(await super._call(P))}}class Kp extends Do{async _call(P){return new pr(await super._call(P))}}class Ii extends R{}class Hp extends Ii{}class qp extends Ii{async _call(P){return new bn(await super._call(P))}}class Xp extends Ii{async _call(P){return new mt(await super._call(P))}}class W0 extends R{}class Qp extends Gs{}class Jp extends Gs{async _call(P){return new bn(await super._call(P))}}class Yp extends Gs{async _call(P){return new mt(await super._call(P))}}class Jn extends R{}class Zp extends Jn{}class eh extends Jn{async _call(P){return new bn(await super._call(P))}}class th extends Jn{async _call(P){return new mt(await super._call(P))}}class rh extends Jn{async _call(P){return new mf(await super._call(P))}}class sh extends Jn{async _call(P){return new pr(await super._call(P))}}class nh extends R{}class oh extends nh{}class Ai extends R{}class G0 extends Ai{}class ih extends Ai{}class ah extends Ai{async generate_speech(P,D,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:_e=20,vocoder:Ce=null}={}){const Le={input_ids:P},{encoder_outputs:Ne,encoder_attention_mask:qe}=await X(this,Le),it=Ne.dims[1]/this.config.reduction_factor,pt=Math.floor(it*_e),ot=Math.floor(it*ge),bt=this.config.num_mel_bins;let ct=[],gt=null,tt=null,yt=0;for(;;){++yt;const Qt=H(!!tt);let Ht;tt?Ht=tt.output_sequence_out:Ht=new c.Tensor("float32",new Float32Array(bt),[1,1,bt]);let nr={use_cache_branch:Qt,output_sequence:Ht,encoder_attention_mask:qe,speaker_embeddings:D,encoder_hidden_states:Ne};this.addPastKeyValues(nr,gt),tt=await G(this.sessions.decoder_model_merged,nr),gt=this.getPastKeyValues(tt,gt);const{prob:hr,spectrum:Mt}=tt;if(ct.push(Mt),yt>=ot&&(Array.from(hr.data).filter(ir=>ir>=ne).length>0||yt>=pt))break}const Lt=(0,c.cat)(ct),{waveform:Ut}=await G(Ce.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Ut}}}class lh extends R{constructor(){super(...arguments);te(this,"main_input_name","spectrogram")}}class uh extends R{}class dh extends uh{}class ul extends R{}class ch extends ul{}class ph extends ul{}class dl extends R{}class hh extends dl{}class mh extends dl{}class cl extends R{}class fh extends cl{}class _h extends cl{}class Fi extends R{}class gh extends Fi{}class wh extends Fi{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"text_model"})}}class bh extends Fi{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"audio_model"})}}class Mh extends R{}class pl extends Mh{async _call(P){return new _f(await super._call(P))}}class Oi extends R{}class K0 extends Oi{}class yh extends Oi{}class vh extends Oi{}class hl extends R{}class xh extends hl{}class Th extends hl{}class ml extends R{}class Eh extends ml{}class Ph extends ml{async _call(P){return new mt(await super._call(P))}}class fl extends R{}class H0 extends fl{}class q0 extends fl{}class _l extends R{constructor(){super(...arguments);te(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(D){const[ne,ge]=D.dims,_e=this.config.decoder.num_codebooks,Ce=ge-_e;let Le=0;for(let it=0;it0&&bt<=Ce&&(D.data[Le++]=D.data[it])}const Ne=Math.floor(ne/_e),qe=Le/(Ne*_e);return new c.Tensor(D.type,D.data.slice(0,Le),[Ne,_e,qe])}prepare_inputs_for_generation(D,ne,ge){let _e=structuredClone(D);for(let Le=0;Le<_e.length;++Le)for(let Ne=0;Ne<_e[Le].length;++Ne)Le%this.config.decoder.num_codebooks>=Ne&&(_e[Le][Ne]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(_e=_e.concat(_e)),super.prepare_inputs_for_generation(_e,ne,ge)}async generate(D){const ne=await super.generate(D),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:_e}=await G(this.sessions.encodec_decode,{audio_codes:ge});return _e}}class Di extends R{}class Ch extends Di{}class Sh extends Di{async _call(P){return new mt(await super._call(P))}}class $h extends Di{}class Li extends R{}class kh extends Li{}class Ih extends Li{async _call(P){return new mt(await super._call(P))}}class Ah extends Li{}class zi extends R{}class Fh extends zi{}class Oh extends zi{async _call(P){return new mt(await super._call(P))}}class Dh extends zi{}class Bi extends R{}class Lh extends Bi{}class zh extends Bi{async _call(P){return new mt(await super._call(P))}}class Bh extends Bi{}class Rh extends R{}class jh extends Rh{}class Nh extends R{}class Vh extends Nh{constructor(...D){super(...D);te(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(D){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!D.past_key_values){const qe=this.sessions.prepare_inputs_embeds,it=(0,a.pick)(D,qe.inputNames);ge=await G(qe,it)}else{const qe=this.sessions.gen_img_embeds,it=(0,a.pick)({image_ids:D.input_ids},qe.inputNames);ge=await G(qe,it)}const _e={...D,...ge},Ce=await me(this,_e),Le=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!Le)throw new Error(`Unable to find "${Le}" generation head`);const Ne=await G(Le,(0,a.pick)(Ce,Le.inputNames));return{...ge,...Ce,...Ne}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const ne=(D.inputs??D[this.main_input_name]).dims[1],_e=(await super.generate(D)).slice(null,[ne,null]),Ce=this.sessions.image_decode,{decoded_image:Le}=await G(Ce,{generated_tokens:_e}),Ne=Le.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),qe=[];for(const it of Ne){const pt=_.RawImage.fromTensor(it);qe.push(pt)}return qe}}class Uh extends pe{constructor({char_logits:P,bpe_logits:D,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=D,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Wh extends R{}class Gh extends Wh{async _call(P){return new Uh(await super._call(P))}}class gl extends R{}class Kh extends gl{}class Hh extends gl{}class wl extends R{}class qh extends wl{}class Xh extends wl{}class Qh extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class Jh extends Qh{_merge_input_ids_with_audio_features(P){const D=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,D);return F({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class Ri extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class Yh extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class Zh extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class em extends Ri{async encode(P){return new Yh(await G(this.sessions.encoder_model,P))}async decode(P){return new Zh(await G(this.sessions.decoder_model,P))}}class tm extends Ri{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class rm extends Ri{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ji extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class sm extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class nm extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class om extends ji{async encode(P){return new sm(await G(this.sessions.encoder_model,P))}async decode(P){return new nm(await G(this.sessions.decoder_model,P))}}class im extends ji{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class am extends ji{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class Ni extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class lm extends Ni{async encode(P){return await G(this.sessions.encoder_model,P)}async decode(P){return await G(this.sessions.decoder_model,P)}}class um extends Ni{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class dm extends Ni{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class Pt{static async from_pretrained(P,{progress_callback:D=null,config:ne=null,cache_dir:ge=null,local_files_only:_e=!1,revision:Ce="main",model_file_name:Le=null,subfolder:Ne="onnx",device:qe=null,dtype:it=null,use_external_data_format:pt=null,session_options:ot={}}={}){const bt={progress_callback:D,config:ne,cache_dir:ge,local_files_only:_e,revision:Ce,model_file_name:Le,subfolder:Ne,device:qe,dtype:it,use_external_data_format:pt,session_options:ot};if(bt.config=await s.AutoConfig.from_pretrained(P,bt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const ct=bt.config.model_type;for(const gt of this.MODEL_CLASS_MAPPINGS){let tt=gt.get(ct);if(!tt){for(const yt of gt.values())if(yt[0]===ct){tt=yt;break}if(!tt)continue}return await tt[1].from_pretrained(P,bt)}if(this.BASE_IF_FAIL)return Lm.has(ct)||console.warn(`Unknown model class "${ct}", attempting to construct from base class.`),await R.from_pretrained(P,bt);throw Error(`Unsupported model type: ${ct}`)}}te(Pt,"MODEL_CLASS_MAPPINGS",null),te(Pt,"BASE_IF_FAIL",!1);const X0=new Map([["bert",["BertModel",Se]],["modernbert",["ModernBertModel",Y]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",Ie]],["electra",["ElectraModel",Ds]],["esm",["EsmModel",zs]],["convbert",["ConvBertModel",Gt]],["camembert",["CamembertModel",ws]],["deberta",["DebertaModel",De]],["deberta-v2",["DebertaV2Model",rs]],["mpnet",["MPNetModel",tn]],["albert",["AlbertModel",dn]],["distilbert",["DistilBertModel",yr]],["roberta",["RobertaModel",zr]],["xlm",["XLMModel",Rs]],["xlm-roberta",["XLMRobertaModel",si]],["clap",["ClapModel",gh]],["clip",["CLIPModel",bi]],["clipseg",["CLIPSegModel",yo]],["chinese_clip",["ChineseCLIPModel",xi]],["siglip",["SiglipModel",hn]],["jina_clip",["JinaCLIPModel",Nn]],["mobilebert",["MobileBertModel",xr]],["squeezebert",["SqueezeBertModel",an]],["wav2vec2",["Wav2Vec2Model",Ap]],["wav2vec2-bert",["Wav2Vec2BertModel",Hp]],["unispeech",["UniSpeechModel",jp]],["unispeech-sat",["UniSpeechSatModel",Up]],["hubert",["HubertModel",Qp]],["wavlm",["WavLMModel",Zp]],["audio-spectrogram-transformer",["ASTModel",li]],["vits",["VitsModel",pl]],["pyannote",["PyAnnoteModel",Lp]],["wespeaker-resnet",["WeSpeakerResNetModel",Rp]],["detr",["DetrModel",vc]],["rt_detr",["RTDetrModel",Ec]],["rt_detr_v2",["RTDetrV2Model",Cc]],["rf_detr",["RFDetrModel",kc]],["table-transformer",["TableTransformerModel",Fc]],["vit",["ViTModel",qd]],["ijepa",["IJepaModel",Qd]],["pvt",["PvtModel",ec]],["vit_msn",["ViTMSNModel",nc]],["vit_mae",["ViTMAEModel",sc]],["groupvit",["GroupViTModel",ac]],["fastvit",["FastViTModel",lc]],["mobilevit",["MobileViTModel",pc]],["mobilevitv2",["MobileViTV2Model",mc]],["owlvit",["OwlViTModel",_c]],["owlv2",["Owlv2Model",wc]],["beit",["BeitModel",Mc]],["deit",["DeiTModel",Lc]],["hiera",["HieraModel",Bc]],["convnext",["ConvNextModel",pp]],["convnextv2",["ConvNextV2Model",mp]],["dinov2",["Dinov2Model",_p]],["dinov2_with_registers",["Dinov2WithRegistersModel",wp]],["resnet",["ResNetModel",jc]],["swin",["SwinModel",Vc]],["swin2sr",["Swin2SRModel",Gc]],["donut-swin",["DonutSwinModel",cp]],["yolos",["YolosModel",vp]],["dpt",["DPTModel",Hc]],["glpn",["GLPNModel",lp]],["hifigan",["SpeechT5HifiGan",lh]],["efficientnet",["EfficientNetModel",Eh]],["decision_transformer",["DecisionTransformerModel",jh]],["patchtst",["PatchTSTForPrediction",Kh]],["patchtsmixer",["PatchTSMixerForPrediction",qh]],["mobilenet_v1",["MobileNetV1Model",Ch]],["mobilenet_v2",["MobileNetV2Model",kh]],["mobilenet_v3",["MobileNetV3Model",Fh]],["mobilenet_v4",["MobileNetV4Model",Lh]],["maskformer",["MaskFormerModel",ip]],["mgp-str",["MgpstrForSceneTextRecognition",Gh]],["style_text_to_speech_2",["StyleTextToSpeech2Model",oh]]]),Q0=new Map([["t5",["T5Model",ie]],["longt5",["LongT5Model",je]],["mt5",["MT5Model",Je]],["bart",["BartModel",Et]],["mbart",["MBartModel",Mr]],["marian",["MarianModel",Sp]],["whisper",["WhisperModel",di]],["m2m_100",["M2M100Model",kp]],["blenderbot",["BlenderbotModel",Dt]],["blenderbot-small",["BlenderbotSmallModel",Hr]]]),J0=new Map([["mimi",["MimiModel",em]],["dac",["DacModel",om]],["snac",["SnacModel",lm]]]),Y0=new Map([["bloom",["BloomModel",Vd]],["jais",["JAISModel",mn]],["gpt2",["GPT2Model",Ti]],["gptj",["GPTJModel",Co]],["gpt_bigcode",["GPTBigCodeModel",Kn]],["gpt_neo",["GPTNeoModel",Eo]],["gpt_neox",["GPTNeoXModel",Br]],["codegen",["CodeGenModel",ko]],["llama",["LlamaModel",qn]],["exaone",["ExaoneModel",I]],["olmo",["OlmoModel",Ke]],["olmo2",["Olmo2Model",xt]],["mobilellm",["MobileLLMModel",ue]],["granite",["GraniteModel",$s]],["cohere",["CohereModel",Td]],["gemma",["GemmaModel",Pd]],["gemma2",["Gemma2Model",Sd]],["gemma3_text",["Gemma3Model",kd]],["helium",["HeliumModel",Ao]],["glm",["GlmModel",Oo]],["openelm",["OpenELMModel",Ad]],["qwen2",["Qwen2Model",Od]],["phi",["PhiModel",Bd]],["phi3",["Phi3Model",jd]],["mpt",["MptModel",Wd]],["opt",["OPTModel",Kd]],["mistral",["MistralModel",ch]],["starcoder2",["Starcoder2Model",hh]],["falcon",["FalconModel",fh]],["stablelm",["StableLmModel",xh]]]),bl=new Map([["speecht5",["SpeechT5ForSpeechToText",ih]],["whisper",["WhisperForConditionalGeneration",co]],["lite-whisper",["LiteWhisperForConditionalGeneration",ci]],["moonshine",["MoonshineForConditionalGeneration",po]]]),cm=new Map([["speecht5",["SpeechT5ForTextToSpeech",ah]]]),pm=new Map([["vits",["VitsModel",pl]],["musicgen",["MusicgenForConditionalGeneration",_l]]]),hm=new Map([["bert",["BertForSequenceClassification",Fe]],["modernbert",["ModernBertForSequenceClassification",J]],["roformer",["RoFormerForSequenceClassification",Xe]],["electra",["ElectraForSequenceClassification",Ls]],["esm",["EsmForSequenceClassification",Ar]],["convbert",["ConvBertForSequenceClassification",lr]],["camembert",["CamembertForSequenceClassification",es]],["deberta",["DebertaForSequenceClassification",et]],["deberta-v2",["DebertaV2ForSequenceClassification",Ur]],["mpnet",["MPNetForSequenceClassification",sn]],["albert",["AlbertForSequenceClassification",he]],["distilbert",["DistilBertForSequenceClassification",Ys]],["roberta",["RobertaForSequenceClassification",Vt]],["xlm",["XLMForSequenceClassification",ei]],["xlm-roberta",["XLMRobertaForSequenceClassification",oi]],["bart",["BartForSequenceClassification",kt]],["mbart",["MBartForSequenceClassification",cr]],["mobilebert",["MobileBertForSequenceClassification",ur]],["squeezebert",["SqueezeBertForSequenceClassification",ln]]]),mm=new Map([["bert",["BertForTokenClassification",ze]],["modernbert",["ModernBertForTokenClassification",le]],["roformer",["RoFormerForTokenClassification",Ge]],["electra",["ElectraForTokenClassification",at]],["esm",["EsmForTokenClassification",en]],["convbert",["ConvBertForTokenClassification",Yr]],["camembert",["CamembertForTokenClassification",ts]],["deberta",["DebertaForTokenClassification",Bt]],["deberta-v2",["DebertaV2ForTokenClassification",ns]],["mpnet",["MPNetForTokenClassification",nn]],["distilbert",["DistilBertForTokenClassification",vr]],["roberta",["RobertaForTokenClassification",Zt]],["xlm",["XLMForTokenClassification",ti]],["xlm-roberta",["XLMRobertaForTokenClassification",ii]]]),Ml=new Map([["t5",["T5ForConditionalGeneration",de]],["longt5",["LongT5ForConditionalGeneration",He]],["mt5",["MT5ForConditionalGeneration",dt]],["bart",["BartForConditionalGeneration",Rt]],["mbart",["MBartForConditionalGeneration",dr]],["marian",["MarianMTModel",$p]],["m2m_100",["M2M100ForConditionalGeneration",Ip]],["blenderbot",["BlenderbotForConditionalGeneration",rr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Lr]]]),yl=new Map([["bloom",["BloomForCausalLM",Ud]],["gpt2",["GPT2LMHeadModel",xo]],["jais",["JAISLMHeadModel",nt]],["gptj",["GPTJForCausalLM",So]],["gpt_bigcode",["GPTBigCodeForCausalLM",$o]],["gpt_neo",["GPTNeoForCausalLM",Po]],["gpt_neox",["GPTNeoXForCausalLM",fn]],["codegen",["CodeGenForCausalLM",gn]],["llama",["LlamaForCausalLM",Io]],["exaone",["ExaoneForCausalLM",L]],["olmo",["OlmoForCausalLM",Ye]],["olmo2",["Olmo2ForCausalLM",It]],["mobilellm",["MobileLLMForCausalLM",Te]],["granite",["GraniteForCausalLM",Ei]],["cohere",["CohereForCausalLM",Ed]],["gemma",["GemmaForCausalLM",Cd]],["gemma2",["Gemma2ForCausalLM",$d]],["gemma3_text",["Gemma3ForCausalLM",Id]],["helium",["HeliumForCausalLM",Fo]],["glm",["GlmForCausalLM",h]],["openelm",["OpenELMForCausalLM",Fd]],["qwen2",["Qwen2ForCausalLM",Dd]],["phi",["PhiForCausalLM",Rd]],["phi3",["Phi3ForCausalLM",Nd]],["mpt",["MptForCausalLM",Gd]],["opt",["OPTForCausalLM",Hd]],["mbart",["MBartForCausalLM",Nt]],["mistral",["MistralForCausalLM",ph]],["starcoder2",["Starcoder2ForCausalLM",mh]],["falcon",["FalconForCausalLM",_h]],["trocr",["TrOCRForCausalLM",dh]],["stablelm",["StableLmForCausalLM",Th]],["phi3_v",["Phi3VForCausalLM",_o]]]),Z0=new Map([["multi_modality",["MultiModalityCausalLM",Vh]]]),fm=new Map([["bert",["BertForMaskedLM",Ae]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",Be]],["electra",["ElectraForMaskedLM",xs]],["esm",["EsmForMaskedLM",Zs]],["convbert",["ConvBertForMaskedLM",Ot]],["camembert",["CamembertForMaskedLM",Ft]],["deberta",["DebertaForMaskedLM",Qe]],["deberta-v2",["DebertaV2ForMaskedLM",ss]],["mpnet",["MPNetForMaskedLM",rn]],["albert",["AlbertForMaskedLM",N]],["distilbert",["DistilBertForMaskedLM",Es]],["roberta",["RobertaForMaskedLM",or]],["xlm",["XLMWithLMHeadModel",cn]],["xlm-roberta",["XLMRobertaForMaskedLM",ni]],["mobilebert",["MobileBertForMaskedLM",Ps]],["squeezebert",["SqueezeBertForMaskedLM",Bs]]]),_m=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",lt]],["electra",["ElectraForQuestionAnswering",Zr]],["convbert",["ConvBertForQuestionAnswering",gs]],["camembert",["CamembertForQuestionAnswering",bs]],["deberta",["DebertaForQuestionAnswering",Or]],["deberta-v2",["DebertaV2ForQuestionAnswering",os]],["mpnet",["MPNetForQuestionAnswering",on]],["albert",["AlbertForQuestionAnswering",k]],["distilbert",["DistilBertForQuestionAnswering",Ts]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",ri]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ai]],["mobilebert",["MobileBertForQuestionAnswering",_r]],["squeezebert",["SqueezeBertForQuestionAnswering",un]]]),vl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ho]],["idefics3",["Idefics3ForConditionalGeneration",Ns]],["smolvlm",["SmolVLMForConditionalGeneration",jn]]]),gm=new Map([["llava",["LlavaForConditionalGeneration",pn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",mo]],["moondream1",["Moondream1ForConditionalGeneration",js]],["florence2",["Florence2ForConditionalGeneration",fo]],["qwen2-vl",["Qwen2VLForConditionalGeneration",zd]],["idefics3",["Idefics3ForConditionalGeneration",Ns]],["smolvlm",["SmolVLMForConditionalGeneration",jn]],["paligemma",["PaliGemmaForConditionalGeneration",_i]]]),wm=new Map([["ultravox",["UltravoxModel",Jh]]]),ev=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ho]]]),bm=new Map([["vit",["ViTForImageClassification",Xd]],["ijepa",["IJepaForImageClassification",Jd]],["pvt",["PvtForImageClassification",tc]],["vit_msn",["ViTMSNForImageClassification",oc]],["fastvit",["FastViTForImageClassification",uc]],["mobilevit",["MobileViTForImageClassification",hc]],["mobilevitv2",["MobileViTV2ForImageClassification",fc]],["beit",["BeitForImageClassification",yc]],["deit",["DeiTForImageClassification",zc]],["hiera",["HieraForImageClassification",Rc]],["convnext",["ConvNextForImageClassification",hp]],["convnextv2",["ConvNextV2ForImageClassification",fp]],["dinov2",["Dinov2ForImageClassification",gp]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",bp]],["resnet",["ResNetForImageClassification",Nc]],["swin",["SwinForImageClassification",Uc]],["segformer",["SegformerForImageClassification",yh]],["efficientnet",["EfficientNetForImageClassification",Ph]],["mobilenet_v1",["MobileNetV1ForImageClassification",Sh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ih]],["mobilenet_v3",["MobileNetV3ForImageClassification",Oh]],["mobilenet_v4",["MobileNetV4ForImageClassification",zh]]]),Mm=new Map([["detr",["DetrForObjectDetection",xc]],["rt_detr",["RTDetrForObjectDetection",Pc]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Sc]],["rf_detr",["RFDetrForObjectDetection",Ic]],["table-transformer",["TableTransformerForObjectDetection",Oc]],["yolos",["YolosForObjectDetection",xp]]]),ym=new Map([["owlvit",["OwlViTForObjectDetection",gc]],["owlv2",["Owlv2ForObjectDetection",bc]],["grounding-dino",["GroundingDinoForObjectDetection",yp]]]),Yn=new Map([["detr",["DetrForSegmentation",Va]],["clipseg",["CLIPSegForImageSegmentation",vo]]]),vm=new Map([["segformer",["SegformerForSemanticSegmentation",vh]],["sapiens",["SapiensForSemanticSegmentation",Jc]],["swin",["SwinForSemanticSegmentation",Wc]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",$h]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Ah]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Dh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Bh]]]),xm=new Map([["detr",["DetrForSegmentation",Va]],["maskformer",["MaskFormerForInstanceSegmentation",ap]]]),Tm=new Map([["sam",["SamModel",Pp]]]),Em=new Map([["wav2vec2",["Wav2Vec2ForCTC",Fp]],["wav2vec2-bert",["Wav2Vec2BertForCTC",qp]],["unispeech",["UniSpeechForCTC",Np]],["unispeech-sat",["UniSpeechSatForCTC",Wp]],["wavlm",["WavLMForCTC",eh]],["hubert",["HubertForCTC",Jp]]]),Pm=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Op]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Xp]],["unispeech",["UniSpeechForSequenceClassification",Vp]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Gp]],["wavlm",["WavLMForSequenceClassification",th]],["hubert",["HubertForSequenceClassification",Yp]],["audio-spectrogram-transformer",["ASTForAudioClassification",ui]]]),Cm=new Map([["wavlm",["WavLMForXVector",rh]]]),Sm=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Kp]],["wavlm",["WavLMForAudioFrameClassification",sh]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Dp]],["pyannote",["PyAnnoteForAudioFrameClassification",zp]]]),$m=new Map([["vitmatte",["VitMatteForImageMatting",cc]]]),tv=new Map([["patchtst",["PatchTSTForPrediction",Hh]],["patchtsmixer",["PatchTSMixerForPrediction",Xh]]]),km=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Kc]]]),Im=new Map([["dpt",["DPTForDepthEstimation",qc]],["depth_anything",["DepthAnythingForDepthEstimation",Qc]],["glpn",["GLPNForDepthEstimation",up]],["sapiens",["SapiensForDepthEstimation",Yc]],["depth_pro",["DepthProForDepthEstimation",tp]],["metric3d",["Metric3DForDepthEstimation",sp]],["metric3dv2",["Metric3Dv2ForDepthEstimation",op]]]),Am=new Map([["sapiens",["SapiensForNormalEstimation",Zc]]]),Fm=new Map([["vitpose",["VitPoseForPoseEstimation",Zd]]]),Om=new Map([["clip",["CLIPVisionModelWithProjection",yi]],["siglip",["SiglipVisionModel",wo]],["jina_clip",["JinaCLIPVisionModel",Mo]]]),Dm=[[X0,E.EncoderOnly],[Q0,E.EncoderDecoder],[Y0,E.DecoderOnly],[J0,E.AutoEncoder],[hm,E.EncoderOnly],[mm,E.EncoderOnly],[Ml,E.Seq2Seq],[bl,E.Seq2Seq],[yl,E.DecoderOnly],[Z0,E.MultiModality],[fm,E.EncoderOnly],[_m,E.EncoderOnly],[vl,E.Vision2Seq],[gm,E.ImageTextToText],[wm,E.AudioTextToText],[bm,E.EncoderOnly],[Yn,E.EncoderOnly],[xm,E.EncoderOnly],[vm,E.EncoderOnly],[$m,E.EncoderOnly],[tv,E.EncoderOnly],[km,E.EncoderOnly],[Im,E.EncoderOnly],[Am,E.EncoderOnly],[Fm,E.EncoderOnly],[Mm,E.EncoderOnly],[ym,E.EncoderOnly],[Tm,E.MaskGeneration],[Em,E.EncoderOnly],[Pm,E.EncoderOnly],[cm,E.Seq2Seq],[pm,E.EncoderOnly],[Cm,E.EncoderOnly],[Sm,E.EncoderOnly],[Om,E.EncoderOnly]];for(const[M,P]of Dm)for(const[D,ne]of M.values())y.set(D,P),x.set(ne,D),b.set(D,ne);const rv=[["MusicgenForConditionalGeneration",_l,E.Musicgen],["Phi3VForCausalLM",_o,E.Phi3V],["CLIPTextModelWithProjection",Mi,E.EncoderOnly],["SiglipTextModel",Vs,E.EncoderOnly],["JinaCLIPTextModel",bo,E.EncoderOnly],["ClapTextModelWithProjection",wh,E.EncoderOnly],["ClapAudioModelWithProjection",bh,E.EncoderOnly],["DacEncoderModel",im,E.EncoderOnly],["DacDecoderModel",am,E.EncoderOnly],["MimiEncoderModel",tm,E.EncoderOnly],["MimiDecoderModel",rm,E.EncoderOnly],["SnacEncoderModel",um,E.EncoderOnly],["SnacDecoderModel",dm,E.EncoderOnly]];for(const[M,P,D]of rv)y.set(M,D),x.set(P,M),b.set(M,P);const Lm=new Map([["modnet",Yn],["birefnet",Yn],["isnet",Yn],["ben",Yn]]);for(const[M,P]of Lm.entries())P.set(M,["PreTrainedModel",R]),y.set(M,E.EncoderOnly),x.set(R,M),b.set(M,R);class xl extends Pt{}te(xl,"MODEL_CLASS_MAPPINGS",Dm.map(P=>P[0])),te(xl,"BASE_IF_FAIL",!0);class zm extends Pt{}te(zm,"MODEL_CLASS_MAPPINGS",[hm]);class Bm extends Pt{}te(Bm,"MODEL_CLASS_MAPPINGS",[mm]);class Rm extends Pt{}te(Rm,"MODEL_CLASS_MAPPINGS",[Ml]);class jm extends Pt{}te(jm,"MODEL_CLASS_MAPPINGS",[bl]);class Nm extends Pt{}te(Nm,"MODEL_CLASS_MAPPINGS",[cm]);class Vm extends Pt{}te(Vm,"MODEL_CLASS_MAPPINGS",[pm]);class Um extends Pt{}te(Um,"MODEL_CLASS_MAPPINGS",[yl]);class Wm extends Pt{}te(Wm,"MODEL_CLASS_MAPPINGS",[fm]);class Gm extends Pt{}te(Gm,"MODEL_CLASS_MAPPINGS",[_m]);class Km extends Pt{}te(Km,"MODEL_CLASS_MAPPINGS",[vl]);class Hm extends Pt{}te(Hm,"MODEL_CLASS_MAPPINGS",[bm]);class qm extends Pt{}te(qm,"MODEL_CLASS_MAPPINGS",[Yn]);class Xm extends Pt{}te(Xm,"MODEL_CLASS_MAPPINGS",[vm]);class Qm extends Pt{}te(Qm,"MODEL_CLASS_MAPPINGS",[xm]);class Jm extends Pt{}te(Jm,"MODEL_CLASS_MAPPINGS",[Mm]);class Ym extends Pt{}te(Ym,"MODEL_CLASS_MAPPINGS",[ym]);class Zm extends Pt{}te(Zm,"MODEL_CLASS_MAPPINGS",[Tm]);class ef extends Pt{}te(ef,"MODEL_CLASS_MAPPINGS",[Em]);class tf extends Pt{}te(tf,"MODEL_CLASS_MAPPINGS",[Pm]);class rf extends Pt{}te(rf,"MODEL_CLASS_MAPPINGS",[Cm]);class sf extends Pt{}te(sf,"MODEL_CLASS_MAPPINGS",[Sm]);class nf extends Pt{}te(nf,"MODEL_CLASS_MAPPINGS",[ev]);class of extends Pt{}te(of,"MODEL_CLASS_MAPPINGS",[$m]);class af extends Pt{}te(af,"MODEL_CLASS_MAPPINGS",[km]);class lf extends Pt{}te(lf,"MODEL_CLASS_MAPPINGS",[Im]);class uf extends Pt{}te(uf,"MODEL_CLASS_MAPPINGS",[Am]);class df extends Pt{}te(df,"MODEL_CLASS_MAPPINGS",[Fm]);class cf extends Pt{}te(cf,"MODEL_CLASS_MAPPINGS",[Om]);class pf extends Pt{}te(pf,"MODEL_CLASS_MAPPINGS",[gm]);class hf extends Pt{}te(hf,"MODEL_CLASS_MAPPINGS",[wm]);class sv extends pe{constructor({logits:P,past_key_values:D,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:_e=null}){super(),this.logits=P,this.past_key_values=D,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=_e}}class mt extends pe{constructor({logits:P,...D}){super(),this.logits=P;const ne=Object.values(D);ne.length>0&&(this.attentions=ne)}}class mf extends pe{constructor({logits:P,embeddings:D}){super(),this.logits=P,this.embeddings=D}}class pr extends pe{constructor({logits:P}){super(),this.logits=P}}class wr extends pe{constructor({logits:P}){super(),this.logits=P}}class Tr extends pe{constructor({start_logits:P,end_logits:D}){super(),this.start_logits=P,this.end_logits=D}}class bn extends pe{constructor({logits:P}){super(),this.logits=P}}class nv extends pe{constructor({logits:P,past_key_values:D}){super(),this.logits=P,this.past_key_values=D}}class ff extends pe{constructor({alphas:P}){super(),this.alphas=P}}class _f extends pe{constructor({waveform:P,spectrogram:D}){super(),this.waveform=P,this.spectrogram=D}}},"./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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.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,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const u=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),d=p.feature_extractor_type,c=n[d];if(!c)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new c(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"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const d=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),c=d.image_processor_type??d.feature_extractor_type;let _=i[c];return _||(c!==void 0&&console.warn(`Image processor type '${c}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),_=n.ImageProcessor),new _(d)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class u{static async from_pretrained(d,c={}){const _=await(0,o.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,c),{image_processor_type:f,feature_extractor_type:v,processor_class:$}=_;if($&&i[$])return i[$].from_pretrained(d,c);if(!f&&!v)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(f){const C=a[f];if(!C)throw new Error(`Unknown image_processor_type: '${f}'.`);w.image_processor=new C(_)}if(v){const C=a[v];if(C)w.image_processor=new C(_);else{const E=l[v];if(!E)throw new Error(`Unknown feature_extractor_type: '${v}'.`);w.feature_extractor=new E(_)}}const g={};return new n.Processor(g,w)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.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,o.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,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let d;const c=a.length-l;if(c>0)if(u==="rand_trunc"){const _=Math.floor(Math.random()*(c+1));a=a.subarray(_,_+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(c<0){let _=new Float64Array(l);if(_.set(a),p==="repeat")for(let f=a.length;f{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var u;const l=(u=this.size)==null?void 0:u.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),[d,c]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(d,c,{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 o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const u=await super._call(l),p=[u.pixel_values.dims[0],64,64],d=(0,o.full)(p,1n);return{...u,pixel_mask:d}}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 i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[d,c,_]=l;let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(_).fill(f));let v=this.image_std;Array.isArray(v)||(v=new Array(_).fill(f));const $=f.map((w,g)=>-w/v[g]);return super.pad_image(a,l,u,{center:!0,constant_values:$,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),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"),o=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 u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>c.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>f.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=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"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),d=t("./src/models/speecht5/feature_extraction_speecht5.js"),c=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),f=t("./src/models/whisper/feature_extraction_whisper.js"),v=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:d,task_prompts_with_input:c}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(d??{})),this.task_prompts_with_input=new Map(Object.entries(c??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[d,c]of this.task_prompts_with_input)if(p.includes(d)){u.push(c.replaceAll("{input}",p).replaceAll(d,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const d=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let c;switch(d){case"pure_text":c=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const _=d==="ocr"?"quad_boxes":"bboxes",f=l.matchAll(this.regexes[_]),v=[],$=[];for(const[w,g,...C]of f)v.push(g?g.trim():v.at(-1)??""),$.push(C.map((E,y)=>(Number(E)+.5)/this.size_per_bin*p[y%2]));c={labels:v,[_]:$};break;default:throw new Error(`Task "${u}" (of type "${d}") not yet implemented.`)}return{[u]:c}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),c=u?this.tokenizer(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(u,p){const c=u.dims.at(-1)-1,_=u.tolist();_.fill(!1,0,1),_.fill(!1,c);const f=p.tolist();return _.map((v,$)=>v?$:null).filter(v=>v!==null).map(v=>f[v])}class l extends s.Processor{async _call(p,d,c={}){const _=p?await this.image_processor(p,c):{};return{...d?this.tokenizer(d,c):{},..._}}post_process_grounded_object_detection(p,d,{box_threshold:c=.25,text_threshold:_=.25,target_sizes:f=null}={}){const{logits:v,pred_boxes:$}=p,w=v.dims[0];if(f!==null&&f.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=v.dims.at(1),C=v.sigmoid(),E=C.max(-1).tolist(),y=$.tolist().map(x=>x.map(S=>(0,i.center_to_corners_format)(S))),b=[];for(let x=0;xj.map((ee,H)=>ee*S[(H+1)%2])));const A=E[x],B=[],K=[],G=[];for(let j=0;j{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=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[u,p]=a.dims.slice(-2);const d=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/d),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*d),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!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 d=[],c=[],_=[];const f=[],v=[];for(const x of p){let S=await Promise.all(x.map(K=>this.preprocess(K)));f.push(...S.map(K=>K.original_size)),v.push(...S.map(K=>K.reshaped_input_size)),S.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:A}=this.max_image_size;let B;if(l??this.do_image_splitting){let K=new Array(S.length),G=new Array(S.length);B=await Promise.all(S.map(async(j,ee)=>{const H=this.get_resize_for_vision_encoder(j.pixel_values,A),Z=await(0,o.interpolate_4d)(j.pixel_values,{size:[H.height,H.width]}),{frames:X,num_splits_h:oe,num_splits_w:me}=await this.split_image(Z,this.max_image_size);return K[ee]=oe,G[ee]=me,(0,o.cat)(X,0)})),c.push(K),_.push(G)}else{const K=[A,A];B=await Promise.all(S.map(G=>(0,o.interpolate_4d)(G.pixel_values,{size:K}))),c.push(new Array(S.length).fill(0)),_.push(new Array(S.length).fill(0))}d.push((0,o.cat)(B,0))}const $=d.length,[w,g,C,E]=d[0].dims;let y,b;if($===1)y=d[0].unsqueeze_(0),b=(0,o.full)([$,w,C,E],!0);else{const x=Math.max(...d.map(B=>B.dims.at(0)));b=(0,o.full)([$,x,C,E],!0);const S=b.data,A=x*C*E;for(let B=0;B<$;++B){const K=d[B].dims[0];if(Ku||_>p){f=Math.ceil(c/u),v=Math.ceil(_/p);const $=Math.ceil(c/f),w=Math.ceil(_/v);for(let E=0;E{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,c,_,f,v,$){let w="";for(let g=0;g`+v.repeat(d);w+=` -`}return w+=` -${f}${$}`+v.repeat(d)+`${f}`,w}function l(d,c,_,f){return`${c}${f}`+_.repeat(d)+`${c}`}function u(d,c,_,f,v,$){return d===0&&c===0?l(_,f,v,$):a(_,d,c,f,v,$)}class p extends s.Processor{constructor(){super(...arguments);te(this,"fake_image_token","");te(this,"image_token","");te(this,"global_img_token","")}async _call(_,f=null,v={}){v.return_row_col_info??(v.return_row_col_info=!0);let $;f&&($=await this.image_processor(f,v)),Array.isArray(_)||(_=[_]);const w=$.rows??[new Array(_.length).fill(0)],g=$.cols??[new Array(_.length).fill(0)],C=this.config.image_seq_len,E=[],y=[];for(let x=0;x<_.length;++x){const S=_[x],A=w[x],B=g[x];E.push((0,i.count)(S,this.image_token));const K=A.map((ee,H)=>u(ee,B[H],C,this.fake_image_token,this.image_token,this.global_img_token)),G=S.split(this.image_token);if(G.length===0)throw new Error("The image token should be present in the text.");let j=G[0];for(let ee=0;ee{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTImageProcessor:()=>d.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>c.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>v.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>w.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>C.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>b.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>b.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>S.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>S.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>A.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>A.MobileViTImageProcessor,NougatImageProcessor:()=>B.NougatImageProcessor,OwlViTFeatureExtractor:()=>G.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>G.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>j.Phi3VImageProcessor,PvtImageProcessor:()=>ee.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Z.RTDetrImageProcessor,SamImageProcessor:()=>X.SamImageProcessor,SegformerFeatureExtractor:()=>oe.SegformerFeatureExtractor,SegformerImageProcessor:()=>oe.SegformerImageProcessor,SiglipImageProcessor:()=>me.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>$.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>W.VitMatteImageProcessor,VitPoseImageProcessor:()=>re.VitPoseImageProcessor,YolosFeatureExtractor:()=>fe.YolosFeatureExtractor,YolosImageProcessor:()=>fe.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=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"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),d=t("./src/models/dpt/image_processing_dpt.js"),c=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),f=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),v=t("./src/models/idefics3/image_processing_idefics3.js"),$=t("./src/models/janus/image_processing_janus.js"),w=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),C=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),b=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),S=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),A=t("./src/models/mobilevit/image_processing_mobilevit.js"),B=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),G=t("./src/models/owlvit/image_processing_owlvit.js"),j=t("./src/models/phi3_v/image_processing_phi3_v.js"),ee=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Z=t("./src/models/rt_detr/image_processing_rt_detr.js"),X=t("./src/models/sam/image_processing_sam.js"),oe=t("./src/models/segformer/image_processing_segformer.js"),me=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),W=t("./src/models/vitmatte/image_processing_vitmatte.js"),re=t("./src/models/vitpose/image_processing_vitpose.js"),fe=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:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(d,c){super(d,c),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(d,{images:c=null,chat_template:_="default"}={}){c?Array.isArray(c)||(c=[c]):c=await Promise.all(d.filter(B=>B.images).flatMap(B=>B.images).map(B=>l.RawImage.read(B)));const f=this.tokenizer,v=f.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:_}),$=B=>f.encode(B,{add_special_tokens:!1}),w=v.split(this.image_tag),g=w.length-1;if(c.length!==g)throw new Error(`Number of images provided (${c.length}) does not match number of "${this.image_tag}" image tags (${g})`);const[C,E,y]=f.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let b=$(w[0]),x=new Array(b.length).fill(!1);for(let B=1;B0){const B=await this.image_processor(c);return B.pixel_values.unsqueeze_(0),{...A,...B}}return A}}te(u,"image_processor_class",o.AutoImageProcessor),te(u,"tokenizer_class",n.AutoTokenizer),te(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...d}=i,c=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},_=u==="bicubic"?3:2;super({...d,size:c,resample:_,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:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},c=u?await this.image_processor(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o{}},"./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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=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,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[c,_]=a[d],f=this[c].bind(this),[v,$]=p.dims,w=[],g=[],C=p.tolist();for(let y=0;y0?S.reduce((B,K)=>B*K,1):0;g.push(x),w.push(A)}return[f(g),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,c]){const[_,f]=this._decode_helper(p,"char"),[v,$]=this._decode_helper(d,"bpe"),[w,g]=this._decode_helper(c,"wp"),C=[],E=[];for(let y=0;y<_.length;++y){const[b,x]=(0,i.max)([f[y],$[y],g[y]]);C.push([_[y],v[y],w[y]][x]),E.push(b)}return{generated_text:C,scores:E,char_preds:_,bpe_preds:v,wp_preds:w}}static async from_pretrained(...p){const d=await super.from_pretrained(...p),c=await n.AutoTokenizer.from_pretrained("Xenova/gpt2"),_=await n.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return d.components={image_processor:d.image_processor,char_tokenizer:d.tokenizer,bpe_tokenizer:c,wp_tokenizer:_},d}async _call(p,d=null){const c=await this.image_processor(p);return d&&(c.labels=this.tokenizer(d).input_ids),c}}te(l,"tokenizer_class",n.AutoTokenizer),te(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(u,p,d,c,_){return`${c.repeat(d*_)}${p}${u} -`}class l extends s.Processor{async _call(p,d=null,c={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const _=this.tokenizer.bos_token,f=this.image_processor.config.image_seq_length;let v;d.some(g=>g.includes(i))?v=d.map(g=>{const C=g.replaceAll(i,i.repeat(f)),E=C.lastIndexOf(i),y=E===-1?0:E+i.length;return C.slice(0,y)+_+C.slice(y)+` -`}):(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."),v=d.map(g=>a(g,_,f,i,p.length)));const $=this.tokenizer(v,c);return{...await this.image_processor(p,c),...$}}}te(l,"tokenizer_class",n.AutoTokenizer),te(l,"image_processor_class",o.AutoImageProcessor),te(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"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(c){super({...c,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=c.num_crops}calc_num_image_tokens_from_image_size(c,_){const{num_img_tokens:f}=this.config;return l((l(_/n)*l(c/n)+1)*f+1+(l(_/n)+1)*u(f))}get_resize_output_image_size(c,_){const f=this._num_crops,[v,$]=c.size;let w=v/$,g=1;for(;g*Math.ceil(g/w)<=f;)g+=1;g-=1;const C=Math.floor(g*336),E=Math.floor(C/w);return[C,E]}pad_image(c,_,f,v={}){const[$,w]=_,g=n*a($/n),C=n*a(w/n),E=[1,1,1].map((y,b)=>(y-this.image_mean[b])/this.image_std[b]);return super.pad_image(c,_,{width:C,height:g},{center:!0,constant_values:E,...v})}async _call(c,{num_crops:_=null}={}){if(this._num_crops=_??(_=this.config.num_crops),_<4||u(_)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(c)||(c=[c]);const f=c.length,v=await Promise.all(c.map(x=>this.preprocess(x))),$=v.map(x=>x.original_size),w=v.map(x=>x.reshaped_input_size),g=[];for(const{pixel_values:x}of v){x.unsqueeze_(0);const[S,A]=x.dims.slice(-2),B=await(0,o.interpolate_4d)(x,{size:[n,n],mode:"bicubic"});if(_>0){const K=[],G=u(_),j=l(A/G),ee=l(S/G);for(let Z=0;Zx.map(S=>n*a(S/n))),y=new o.Tensor("int64",E.flat(),[f,2]),b=E.map(([x,S])=>this.calc_num_image_tokens_from_image_size(S,x));return{pixel_values:C,original_sizes:$,reshaped_input_sizes:w,image_sizes:y,num_img_tokens:b}}}},"./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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,d=null,{padding:c=!0,truncation:_=!0,num_crops:f=null}={}){Array.isArray(p)||(p=[p]);let v,$;if(d){$=await this.image_processor(d,{num_crops:f});const{num_img_tokens:w}=$,g=p.map((E,y)=>E.split(a).join(i.repeat(w[y])));v=this.tokenizer(g,{padding:c,truncation:_});const C=this.tokenizer.model.convert_tokens_to_ids([i])[0];v.input_ids.map_(E=>E==C?-E:E)}else v=this.tokenizer(p);return{...v,...$}}}te(l,"image_processor_class",o.AutoImageProcessor),te(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>c.PaliGemmaProcessor,Phi3VProcessor:()=>d.Phi3VProcessor,PyAnnoteProcessor:()=>_.PyAnnoteProcessor,Qwen2VLProcessor:()=>f.Qwen2VLProcessor,SamProcessor:()=>v.SamProcessor,SmolVLMProcessor:()=>$.SmolVLMProcessor,SpeechT5Processor:()=>w.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>C.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>y.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=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"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),d=t("./src/models/phi3_v/processing_phi3_v.js"),c=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/pyannote/processing_pyannote.js"),f=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),v=t("./src/models/sam/processing_sam.js"),$=t("./src/models/smolvlm/processing_smolvlm.js"),w=t("./src/models/speecht5/processing_speecht5.js"),g=t("./src/models/ultravox/processing_ultravox.js"),C=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),y=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,d=[];for(const c of l.tolist()){const _=[];let f=-1;for(let v=0;v({id:v,start:$*p,end:w*p,confidence:g/(w-$)})))}return d}}},"./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"),o=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}}te(n,"feature_extractor_class",o.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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let c=u;const{temporal_patch_size:_,merge_size:f,patch_size:v}=this.config;c.dims[0]===1&&(c=(0,o.cat)(Array.from({length:_},()=>c),0));const $=c.dims[0]/_,w=c.dims[1],g=Math.floor(c.dims[2]/v),C=Math.floor(c.dims[3]/v),E=c.view($,_,w,Math.floor(g/f),f,v,Math.floor(C/f),f,v).permute(0,3,6,4,7,2,1,5,8).view($*g*C,w*_*v*v),y=new o.Tensor("int64",[$,g,C],[1,3]);return{pixel_values:E,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:d}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let d,c;if(u&&(d=await this.image_processor(u),c=d.image_grid_thw),c){let f=this.image_processor.config.merge_size**2,v=0;const $=c.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const g=Number($[v++].reduce((C,E)=>C*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/f)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}te(i,"image_processor_class",o.AutoImageProcessor),te(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,u,p,d=!1){l=structuredClone(l);let c=(0,o.calculateDimensions)(l);if(c.length===3)d||(c=[1,...c]),l=[l];else if(c.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 _=0;_d!==u.dims[c]))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:u=null,input_labels:p=null,input_boxes:d=null}={}){const c=await super._call(l);if(u&&(c.input_points=this.reshape_input_points(u,c.original_sizes,c.reshaped_input_sizes)),p){if(!c.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");c.input_labels=this.add_input_labels(p,c.input_points)}return d&&(c.input_boxes=this.reshape_input_points(d,c.original_sizes,c.reshaped_input_sizes,!0)),c}async post_process_masks(l,u,p,{mask_threshold:d=0,binarize:c=!0,pad_size:_=null}={}){const f=[];_=_??this.pad_size;const v=[_.height,_.width];for(let $=0;$d&&(y[b]=1);C=new n.Tensor("bool",y,C.dims)}f.push(C)}return f}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:c=32,crop_n_points_downscale_factor:_=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"),o=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)}}te(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){return l=l.map(p=>p*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:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:c=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let _=await this._extract_fbank_features(l,this.config.max_length);if(d){const[y,b]=_.dims,x=_.data;for(let S=0;S0){const A=new Float32Array(b*(y+S));A.set(x),A.fill(this.config.padding_value,x.length);const B=y+S;_=new o.Tensor(_.type,A,[B,b]),c&&(f=new o.Tensor("int64",new BigInt64Array(B),[1,B]),f.data.fill(1n,0,y))}}const[v,$]=_.dims,w=this.config.stride;if(v%w!==0)throw new Error(`The number of frames (${v}) must be a multiple of the stride (${w}).`);const C=_.view(1,Math.floor(v/w),$*w),E={input_features:C};if(c){const y=C.dims[1],b=new BigInt64Array(y);if(f){const x=f.data;for(let S=1,A=0;S{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,u={}){const[p,d,c]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...u})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(u){const _=u.length,{input_features:f}=await this.feature_extractor(u,{...p,max_length:_}),v=Math.round(_/this.config.encoder_ds_factor+1e-4),$=1+Math.ceil(v/this.config.stack_factor);d.audio_token_len=[$],d.audio_values=f;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat($))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor),te(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 u=await Promise.all(a.map(c=>this.preprocess(c))),p=await Promise.all(l.map(c=>this.preprocess(c,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(u.map((c,_)=>(0,o.cat)([c.pixel_values,p[_].pixel_values],0)),0),original_sizes:u.map(c=>c.original_size),reshaped_input_sizes:u.map(c=>c.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const u=i.tolist(),[p,d,c,_]=i.dims,f=[];for(let v=0;v{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((d,c)=>d+c,0)/a.length,p=a.reduce((d,c)=>d+(c-u)**2,0)/a.length;return a.map(d=>(d-u)/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 u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",s.AutoTokenizer),te(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",s.AutoTokenizer),te(i,"feature_extractor_class",o.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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.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 u=l.mean(1).data,p=l.data,[d,c,_]=l.dims;for(let f=0;f{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});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"]],o=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 i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[1]),o.has(a))l=a;else{const d=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,o.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,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,o.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=u.data,d=(0,n.max)(p)[0];for(let c=0;cd?(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,d)):(p=new Float32Array(d),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:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);te(this,"return_timestamps",null);te(this,"return_token_timestamps",null);te(this,"num_frames",null);te(this,"alignment_heads",null);te(this,"task",null);te(this,"language",null);te(this,"no_timestamps_token_id",null);te(this,"prompt_ids",null);te(this,"is_multilingual",null);te(this,"lang_to_id",null);te(this,"task_to_id",null);te(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,d)=>{const c=await(0,s.createInferenceSession)(new Uint8Array(u),p);let _=Promise.resolve();return async f=>{const v=(0,s.isONNXProxy)(),$=Object.fromEntries(Object.entries(f).map(([g,C])=>[g,(v?C.clone():C).ort_tensor])),w=await(_=i?_.then(()=>c.run($)):c.run($));return Array.isArray(d)?d.map(g=>new o.Tensor(w[g])):new o.Tensor(w[d])}};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}}te(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>G,AutomaticSpeechRecognitionPipeline:()=>ee,BackgroundRemovalPipeline:()=>oe,DepthEstimationPipeline:()=>fe,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>B,FillMaskPipeline:()=>C,ImageClassificationPipeline:()=>Z,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>X,ImageToImagePipeline:()=>re,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>v,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>$,TextGenerationPipeline:()=>S,TextToAudioPipeline:()=>W,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>b,ZeroShotAudioClassificationPipeline:()=>j,ZeroShotClassificationPipeline:()=>A,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>$e});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function c(we){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(q=>d.RawImage.read(q)))}async function _(we,q){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(R=>typeof R=="string"||R instanceof URL?(0,u.read_audio)(R,q):R instanceof Float64Array?new Float32Array(R):R))}function f(we,q){q&&(we=we.map(Se=>Se|0));const[R,pe,xe,Me]=we;return{xmin:R,ymin:pe,xmax:xe,ymax:Me}}class v extends i.Callable{constructor({task:q,model:R,tokenizer:pe=null,processor:xe=null}){super(),this.task=q,this.model=R,this.tokenizer=pe,this.processor=xe}async dispose(){await this.model.dispose()}}class $ extends v{constructor(q){super(q)}async _call(q,{top_k:R=1}={}){const pe=this.tokenizer(q,{padding:!0,truncation:!0}),xe=await this.model(pe),Me=this.model.config.problem_type==="multi_label_classification"?Fe=>Fe.sigmoid():Fe=>new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),Se=this.model.config.id2label,Ae=[];for(const Fe of xe.logits){const ze=Me(Fe),Ve=await(0,p.topk)(ze,R),O=Ve[0].tolist(),z=Ve[1].tolist().map((J,le)=>({label:Se?Se[J]:`LABEL_${J}`,score:O[le]}));R===1?Ae.push(...z):Ae.push(z)}return Array.isArray(q)||R===1?Ae:Ae[0]}}class w extends v{constructor(q){super(q)}async _call(q,{ignore_labels:R=["O"]}={}){const pe=Array.isArray(q),xe=this.tokenizer(pe?q:[q],{padding:!0,truncation:!0}),Se=(await this.model(xe)).logits,Ae=this.model.config.id2label,Fe=[];for(let ze=0;zeIe==this.tokenizer.sep_token_id);Fe[O].map((Ie,Be)=>Ie==1&&(Be===0||Be>z&&ze.findIndex(Xe=>Xe==Y[Be])===-1));const J=Me[O].tolist(),le=Se[O].tolist();for(let Ie=1;IeBe==Y[Ie])!==-1)&&(J[Ie]=-1/0,le[Ie]=-1/0);const ye=(0,l.softmax)(J).map((Ie,Be)=>[Ie,Be]),Ee=(0,l.softmax)(le).map((Ie,Be)=>[Ie,Be]);ye[0][0]=0,Ee[0][0]=0;const ke=(0,a.product)(ye,Ee).filter(Ie=>Ie[0][1]<=Ie[1][1]).map(Ie=>[Ie[0][1],Ie[1][1],Ie[0][0]*Ie[1][0]]).sort((Ie,Be)=>Be[2]-Ie[2]);for(let Ie=0;IeJ==this.tokenizer.mask_token_id);if(ze===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=xe[Ae][ze],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),z=O[1].tolist();Me.push(z.map((J,le)=>{const ye=Fe.slice();return ye[ze]=J,{score:Y[le],token:Number(J),token_str:this.tokenizer.decode([J]),sequence:this.tokenizer.decode(ye,{skip_special_tokens:!0})}}))}return Array.isArray(q)?Me:Me[0]}}class E extends v{constructor(R){super(R);te(this,"_key","generated_text")}async _call(R,pe={}){Array.isArray(R)||(R=[R]),this.model.config.prefix&&(R=R.map(ze=>this.model.config.prefix+ze));const xe=this.model.config.task_specific_params;xe&&xe[this.task]&&xe[this.task].prefix&&(R=R.map(ze=>xe[this.task].prefix+ze));const Me=this.tokenizer,Se={padding:!0,truncation:!0};let Ae;this instanceof b&&"_build_translation_inputs"in Me?Ae=Me._build_translation_inputs(R,Se,pe):Ae=Me(R,Se);const Fe=await this.model.generate({...Ae,...pe});return Me.batch_decode(Fe,{skip_special_tokens:!0}).map(ze=>({[this._key]:ze}))}}class y extends E{constructor(R){super(R);te(this,"_key","summary_text")}}class b extends E{constructor(R){super(R);te(this,"_key","translation_text")}}function x(we){return Array.isArray(we)&&we.every(q=>"role"in q&&"content"in q)}class S extends v{constructor(q){super(q)}async _call(q,R={}){let pe=!1,xe=!1,Me;if(typeof q=="string")Me=q=[q];else if(Array.isArray(q)&&q.every(z=>typeof z=="string"))pe=!0,Me=q;else{if(x(q))q=[q];else if(Array.isArray(q)&&q.every(x))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");xe=!0,Me=q.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Se=R.add_special_tokens??!1,Ae=xe?!1:R.return_full_text??!0;this.tokenizer.padding_side="left";const Fe=this.tokenizer(Me,{add_special_tokens:Se,padding:!0,truncation:!0}),ze=await this.model.generate({...Fe,...R}),Ve=this.tokenizer.batch_decode(ze,{skip_special_tokens:!0});let O;!Ae&&Fe.input_ids.dims.at(-1)>0&&(O=this.tokenizer.batch_decode(Fe.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Y=Array.from({length:q.length},z=>[]);for(let z=0;z[R.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(q,R,{hypothesis_template:pe="This example is {}.",multi_label:xe=!1}={}){const Me=Array.isArray(q);Me||(q=[q]),Array.isArray(R)||(R=[R]);const Se=R.map(ze=>pe.replace("{}",ze)),Ae=xe||R.length===1,Fe=[];for(const ze of q){const Ve=[];for(const z of Se){const J=this.tokenizer(ze,{text_pair:z,padding:!0,truncation:!0}),le=await this.model(J);Ae?Ve.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):Ve.push(le.logits.data[this.entailment_id])}const Y=(Ae?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,J)=>[z,J]).sort((z,J)=>J[0]-z[0]);Fe.push({sequence:ze,labels:Y.map(z=>R[z[1]]),scores:Y.map(z=>z[0])})}return Me?Fe:Fe[0]}}class B extends v{constructor(q){super(q)}async _call(q,{pooling:R="none",normalize:pe=!1,quantize:xe=!1,precision:Me="binary"}={}){const Se=this.tokenizer(q,{padding:!0,truncation:!0}),Ae=await this.model(Se);let Fe=Ae.last_hidden_state??Ae.logits??Ae.token_embeddings;if(R!=="none")if(R==="mean")Fe=(0,p.mean_pooling)(Fe,Se.attention_mask);else if(R==="cls")Fe=Fe.slice(null,0);else throw Error(`Pooling method '${R}' not supported.`);return pe&&(Fe=Fe.normalize(2,-1)),xe&&(Fe=(0,p.quantize_embeddings)(Fe,Me)),Fe}}class K extends v{constructor(q){super(q)}async _call(q,{pool:R=null}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),Me=await this.model({pixel_values:xe});let Se;if(R){if(!("pooler_output"in Me))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=Me.pooler_output}else Se=Me.last_hidden_state??Me.logits??Me.image_embeds;return Se}}class G extends v{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,xe=await _(q,pe),Me=this.model.config.id2label,Se=[];for(const Ae of xe){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),J=O[1].tolist().map((le,ye)=>({label:Me?Me[le]:`LABEL_${le}`,score:Y[ye]}));Se.push(J)}return Array.isArray(q)?Se:Se[0]}}class j extends v{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a sound of {}."}={}){const xe=!Array.isArray(q);xe&&(q=[q]);const Me=R.map(Ve=>pe.replace("{}",Ve)),Se=this.tokenizer(Me,{padding:!0,truncation:!0}),Ae=this.processor.feature_extractor.config.sampling_rate,Fe=await _(q,Ae),ze=[];for(const Ve of Fe){const O=await this.processor(Ve),Y=await this.model({...Se,...O}),z=(0,l.softmax)(Y.logits_per_audio.data);ze.push([...z].map((J,le)=>({score:J,label:R[le]})))}return xe?ze[0]:ze}}class ee extends v{constructor(q){super(q)}async _call(q,R={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(q,R);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(q,R);case"moonshine":return this._call_moonshine(q,R);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(q,R){R.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),R.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,Me=await _(q,xe),Se=[];for(const Ae of Me){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=[];for(const z of Ve)O.push((0,l.max)(z.data)[1]);const Y=this.tokenizer.decode(O);Se.push({text:Y})}return pe?Se[0]:Se}async _call_whisper(q,R){const pe=R.return_timestamps??!1,xe=R.chunk_length_s??0,Me=R.force_full_sequences??!1;let Se=R.stride_length_s??null;const Ae={...R};pe==="word"&&(Ae.return_token_timestamps=!0,Ae.return_timestamps=!1);const Fe=!Array.isArray(q);Fe&&(q=[q]);const ze=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,O=this.processor.feature_extractor.config.sampling_rate,Y=await _(q,O),z=[];for(const J of Y){let le=[];if(xe>0){if(Se===null)Se=xe/6;else if(xe<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ke=O*xe,Ie=O*Se,Be=ke-2*Ie;let Xe=0;for(;;){const Ge=Xe+ke,lt=J.subarray(Xe,Ge),wt=await this.processor(lt),Gt=Xe===0,Ot=Ge>=J.length;if(le.push({stride:[lt.length,Gt?0:Ie,Ot?0:Ie],input_features:wt.input_features,is_last:Ot}),Ot)break;Xe+=Be}}else le=[{stride:[J.length,0,0],input_features:(await this.processor(J)).input_features,is_last:!0}];for(const ke of le){Ae.num_frames=Math.floor(ke.stride[0]/Ve);const Ie=await this.model.generate({inputs:ke.input_features,...Ae});pe==="word"?(ke.tokens=Ie.sequences.tolist()[0],ke.token_timestamps=Ie.token_timestamps.tolist()[0].map(Be=>(0,l.round)(Be,2))):ke.tokens=Ie[0].tolist(),ke.stride=ke.stride.map(Be=>Be/O)}const[ye,Ee]=this.tokenizer._decode_asr(le,{time_precision:ze,return_timestamps:pe,force_full_sequences:Me});z.push({text:ye,...Ee})}return Fe?z[0]:z}async _call_moonshine(q,R){const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,Me=await _(q,xe),Se=[];for(const Ae of Me){const Fe=await this.processor(Ae),ze=Math.floor(Ae.length/xe)*6,Ve=await this.model.generate({max_new_tokens:ze,...R,...Fe}),O=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Se.push({text:O})}return pe?Se[0]:Se}}class H extends v{constructor(q){super(q)}async _call(q,R={}){const pe=Array.isArray(q),xe=await c(q),{pixel_values:Me}=await this.processor(xe),Se=[];for(const Ae of Me){Ae.dims=[1,...Ae.dims];const Fe=await this.model.generate({inputs:Ae,...R}),ze=this.tokenizer.batch_decode(Fe,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Se.push(ze)}return pe?Se:Se[0]}}class Z extends v{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),Me=await this.model({pixel_values:xe}),Se=this.model.config.id2label,Ae=[];for(const Fe of Me.logits){const ze=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),R),Ve=ze[0].tolist(),Y=ze[1].tolist().map((z,J)=>({label:Se?Se[z]:`LABEL_${z}`,score:Ve[J]}));Ae.push(Y)}return Array.isArray(q)?Ae:Ae[0]}}class X extends v{constructor(q){super(q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(q,{threshold:R=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:xe=.8,label_ids_to_fuse:Me=null,target_sizes:Se=null,subtask:Ae=null}={}){if(Array.isArray(q)&&q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ze=await c(q),Ve=ze.map(ke=>[ke.height,ke.width]),O=await this.processor(ze),{inputNames:Y,outputNames:z}=this.model.sessions.model;if(!Y.includes("pixel_values")){if(Y.length!==1)throw Error(`Expected a single input name, but got ${Y.length} inputs: ${Y}.`);const ke=Y[0];if(ke in O)throw Error(`Input name ${ke} already exists in the inputs.`);O[ke]=O.pixel_values}const J=await this.model(O);let le=null;if(Ae!==null)le=this.subtasks_mapping[Ae];else if(this.processor.image_processor){for(const[ke,Ie]of Object.entries(this.subtasks_mapping))if(Ie in this.processor.image_processor){le=this.processor.image_processor[Ie].bind(this.processor.image_processor),Ae=ke;break}}const ye=this.model.config.id2label,Ee=[];if(Ae)if(Ae==="panoptic"||Ae==="instance"){const ke=le(J,R,pe,xe,Me,Se??Ve)[0],Ie=ke.segmentation;for(const Be of ke.segments_info){const Xe=new Uint8ClampedArray(Ie.data.length);for(let lt=0;ltwt<-1e-5||wt>1+1e-5)&&Ge.sigmoid_();const lt=await d.RawImage.fromTensor(Ge.mul_(255).to("uint8")).resize(Xe[1],Xe[0]);Ee.push({label:null,score:null,mask:lt})}}return Ee}}class oe extends X{constructor(q){super(q)}async _call(q,R={}){if(Array.isArray(q)&&q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const xe=await c(q),Me=await super._call(q,R);return xe.map((Ae,Fe)=>{const ze=Ae.clone();return ze.putAlpha(Me[Fe].mask),ze})}}class me extends v{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a photo of {}"}={}){const xe=Array.isArray(q),Me=await c(q),Se=R.map(Y=>pe.replace("{}",Y)),Ae=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Fe}=await this.processor(Me),ze=await this.model({...Ae,pixel_values:Fe}),Ve=this.model.config.model_type==="siglip"?Y=>Y.sigmoid().data:Y=>(0,l.softmax)(Y.data),O=[];for(const Y of ze.logits_per_image){const J=[...Ve(Y)].map((le,ye)=>({score:le,label:R[ye]}));J.sort((le,ye)=>ye.score-le.score),O.push(J)}return xe?O:O[0]}}class ae extends v{constructor(q){super(q)}async _call(q,{threshold:R=.9,percentage:pe=!1}={}){const xe=Array.isArray(q);if(xe&&q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Me=await c(q),Se=pe?null:Me.map(z=>[z.height,z.width]),{pixel_values:Ae,pixel_mask:Fe}=await this.processor(Me),ze=await this.model({pixel_values:Ae,pixel_mask:Fe}),Ve=this.processor.image_processor.post_process_object_detection(ze,R,Se),O=this.model.config.id2label,Y=Ve.map(z=>z.boxes.map((J,le)=>({score:z.scores[le],label:O[z.classes[le]],box:f(J,!pe)})));return xe?Y:Y[0]}}class V extends v{constructor(q){super(q)}async _call(q,R,{threshold:pe=.1,top_k:xe=null,percentage:Me=!1}={}){const Se=Array.isArray(q),Ae=await c(q),Fe=this.tokenizer(R,{padding:!0,truncation:!0}),ze=await this.processor(Ae),Ve=[];for(let O=0;O({score:Ee.scores[Ie],label:Ee.labels[Ie],box:f(ke,!Me)}))}else{const Ee=this.processor.image_processor.post_process_object_detection(le,pe,z,!0)[0];ye=Ee.boxes.map((ke,Ie)=>({score:Ee.scores[Ie],label:R[Ee.classes[Ie]],box:f(ke,!Me)}))}ye.sort((Ee,ke)=>ke.score-Ee.score),xe!==null&&(ye=ye.slice(0,xe)),Ve.push(ye)}return Se?Ve:Ve[0]}}class F extends v{constructor(q){super(q)}async _call(q,R,pe={}){const xe=(await c(q))[0],{pixel_values:Me}=await this.processor(xe),Se=`${R}`,Ae=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Fe=await this.model.generate({inputs:Me,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ae,...pe}),Ve=this.tokenizer.batch_decode(Fe)[0].match(/(.*?)<\/s_answer>/);let O=null;return Ve&&Ve.length>=2&&(O=Ve[1].trim()),[{answer:O}]}}class W extends v{constructor(R){super(R);te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=R.vocoder??null}async _call(R,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(R,{speaker_embeddings:pe}):this._call_text_to_waveform(R)}async _call_text_to_waveform(R){const pe=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:xe}=await this.model(pe),Me=this.model.config.sampling_rate;return new u.RawAudio(xe.data,Me)}async _call_text_to_spectrogram(R,{speaker_embeddings:pe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.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:xe}=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:Me}=await this.model.generate_speech(xe,pe,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(Me.data,Se)}}class re extends v{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),xe=await this.model(pe),Me=[];for(const Se of xe.reconstruction){const Ae=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Me.push(d.RawImage.fromTensor(Ae))}return Me.length>1?Me:Me[0]}}class fe extends v{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),{predicted_depth:xe}=await this.model(pe),Me=[];for(let Se=0;Se1?Me:Me[0]}}const se=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:$,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:b,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:S,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:G,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:j,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:ee,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:W,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Z,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:X,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:oe,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:me,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:re,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:fe,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:B,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ce=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $e(we,q=null,{progress_callback:R=null,config:pe=null,cache_dir:xe=null,local_files_only:Me=!1,revision:Se="main",device:Ae=null,dtype:Fe=null,subfolder:ze="onnx",use_external_data_format:Ve=null,model_file_name:O=null,session_options:Y={}}={}){we=ce[we]??we;const z=se[we.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${we}. Must be one of [${Object.keys(se)}]`);q||(q=z.default.model,console.log(`No model specified. Using default model: "${q}".`));const J={progress_callback:R,config:pe,cache_dir:xe,local_files_only:Me,revision:Se,device:Ae,dtype:Fe,subfolder:ze,use_external_data_format:Ve,model_file_name:O,session_options:Y},le=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),ye=await Ue(le,q,J);ye.task=we,(0,a.dispatchCallback)(R,{status:"ready",task:we,model:q});const Ee=z.pipeline;return new Ee(ye)}async function Ue(we,q,R){const pe=Object.create(null),xe=[];for(const[Me,Se]of we.entries()){if(!Se)continue;let Ae;Array.isArray(Se)?Ae=new Promise(async(Fe,ze)=>{var O,Y;let Ve;for(const z of Se){if(z===null){Fe(null);return}try{Fe(await z.from_pretrained(q,R));return}catch(J){if((O=J.message)!=null&&O.includes("Unsupported model type"))Ve=J;else if((Y=J.message)!=null&&Y.includes("Could not locate file"))Ve=J;else{ze(J);return}}}ze(Ve)}):Ae=Se.from_pretrained(q,R),pe[Me]=Ae,xe.push(Ae)}await Promise.all(xe);for(const[Me,Se]of Object.entries(pe))pe[Me]=await Se;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ir,AutoTokenizer:()=>dn,BartTokenizer:()=>ss,BertTokenizer:()=>Zr,BlenderbotSmallTokenizer:()=>Ms,BlenderbotTokenizer:()=>on,BloomTokenizer:()=>Wr,CLIPTokenizer:()=>tn,CamembertTokenizer:()=>et,CodeGenTokenizer:()=>Dr,CodeLlamaTokenizer:()=>vr,CohereTokenizer:()=>un,ConvBertTokenizer:()=>Xt,DebertaTokenizer:()=>es,DebertaV2Tokenizer:()=>ts,DistilBertTokenizer:()=>Qe,ElectraTokenizer:()=>Or,EsmTokenizer:()=>Zs,FalconTokenizer:()=>fr,GPT2Tokenizer:()=>rs,GPTNeoXTokenizer:()=>zs,GemmaTokenizer:()=>en,Grok1Tokenizer:()=>Gr,HerbertTokenizer:()=>bs,LlamaTokenizer:()=>Ys,M2M100Tokenizer:()=>ur,MBart50Tokenizer:()=>ns,MBartTokenizer:()=>Ur,MPNetTokenizer:()=>Es,MarianTokenizer:()=>sn,MgpstrTokenizer:()=>ys,MobileBertTokenizer:()=>ws,NllbTokenizer:()=>Ps,NougatTokenizer:()=>Bs,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ar,RoFormerTokenizer:()=>De,RobertaTokenizer:()=>os,SiglipTokenizer:()=>rn,SpeechT5Tokenizer:()=>an,SqueezeBertTokenizer:()=>Ft,T5Tokenizer:()=>Pr,TokenizerModel:()=>K,VitsTokenizer:()=>ln,Wav2Vec2CTCTokenizer:()=>nn,WhisperTokenizer:()=>_r,XLMRobertaTokenizer:()=>Ts,XLMTokenizer:()=>Bt,is_chinese_char:()=>C});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(he,k){const N=await Promise.all([(0,n.getModelJSON)(he,"tokenizer.json",!0,k),(0,n.getModelJSON)(he,"tokenizer_config.json",!0,k)]);return k.legacy!==null&&(N[1].legacy=k.legacy),N}function c(he,k){const N=[];let Q=0;for(const ie of he.matchAll(k)){const de=ie[0];Q0&&N.push(de),Q=ie.index+de.length}return Q=19968&&he<=40959||he>=13312&&he<=19903||he>=131072&&he<=173791||he>=173824&&he<=177983||he>=177984&&he<=178207||he>=178208&&he<=183983||he>=63744&&he<=64255||he>=194560&&he<=195103}function E(he,k,N){const Q=[];let ie=0;for(;iethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens(k){return k.map(N=>this.vocab[N]??this.unk_token)}}class G extends K{constructor(k){super(k),this.tokens_to_ids=f(k.vocab),this.unk_token_id=this.tokens_to_ids.get(k.unk_token),this.unk_token=k.unk_token,this.max_input_chars_per_word=k.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,Q]of this.tokens_to_ids)this.vocab[Q]=N}encode(k){const N=[];for(const Q of k){const ie=[...Q];if(ie.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let de=!1,ve=0;const je=[];for(;ve0&&(Je=this.config.continuing_subword_prefix+Je),this.tokens_to_ids.has(Je)){We=Je;break}--He}if(We===null){de=!0;break}je.push(We),ve=He}de?N.push(this.unk_token):N.push(...je)}return N}}class j extends K{constructor(k,N){super(k);const Q=k.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let ie=0;ie[ie,de])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.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,i.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(k){const N=k.chars,Q=1;let ie=0;for(;ie{const he=[...Array.from({length:94},(ie,de)=>de+33),...Array.from({length:12},(ie,de)=>de+161),...Array.from({length:82},(ie,de)=>de+174)],k=he.slice();let N=0;for(let ie=0;ie<256;++ie)he.includes(ie)||(he.push(ie),k.push(256+N),N+=1);const Q=k.map(ie=>String.fromCharCode(ie));return Object.fromEntries(he.map((ie,de)=>[ie,Q[de]]))})(),H=(0,o.reverseDictionary)(ee);class Z extends K{constructor(k){super(k),this.tokens_to_ids=f(k.vocab),this.unk_token_id=this.tokens_to_ids.get(k.unk_token),this.unk_token=k.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q;const N=Array.isArray(k.merges[0]);this.merges=N?k.merges:k.merges.map(Q=>Q.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Q,ie)=>[JSON.stringify(Q),ie])),this.end_of_word_suffix=k.end_of_word_suffix,this.continuing_subword_suffix=k.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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(k){if(k.length===0)return[];const N=this.cache.get(k);if(N!==void 0)return N;const Q=Array.from(k);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let ie=[];if(Q.length>1){const de=new l.PriorityQueue((He,We)=>He.score`<0x${je.toString(16).toUpperCase().padStart(2,"0")}>`);ve.every(je=>this.tokens_to_ids.has(je))?N.push(...ve):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class X extends K{constructor(k,N){super(k),this.tokens_to_ids=f(N.target_lang?k.vocab[N.target_lang]:k.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.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[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q}encode(k){return k}}class oe extends s.Callable{constructor(k){super(),this.config=k}static fromConfig(k){if(k===null)return null;switch(k.type){case"BertNormalizer":return new we(k);case"Precompiled":return new Ot(k);case"Sequence":return new Ue(k);case"Replace":return new me(k);case"NFC":return new V(k);case"NFD":return new F(k);case"NFKC":return new W(k);case"NFKD":return new re(k);case"Strip":return new fe(k);case"StripAccents":return new se(k);case"Lowercase":return new ce(k);case"Prepend":return new $e(k);default:throw new Error(`Unknown Normalizer type: ${k.type}`)}}normalize(k){throw Error("normalize should be implemented in subclass.")}_call(k){return this.normalize(k)}}class me extends oe{normalize(k){const N=_(this.config.pattern);return N===null?k:k.replaceAll(N,this.config.content)}}class ae extends oe{constructor(){super(...arguments);te(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class V extends ae{constructor(){super(...arguments);te(this,"form","NFC")}}class F extends ae{constructor(){super(...arguments);te(this,"form","NFD")}}class W extends ae{constructor(){super(...arguments);te(this,"form","NFKC")}}class re extends ae{constructor(){super(...arguments);te(this,"form","NFKD")}}class fe extends oe{normalize(k){return this.config.strip_left&&this.config.strip_right?k=k.trim():(this.config.strip_left&&(k=k.trimStart()),this.config.strip_right&&(k=k.trimEnd())),k}}class se extends oe{normalize(k){return k=w(k),k}}class ce extends oe{normalize(k){return k=k.toLowerCase(),k}}class $e extends oe{normalize(k){return k=this.config.prepend+k,k}}class Ue extends oe{constructor(k){super(k),this.normalizers=k.normalizers.map(N=>oe.fromConfig(N))}normalize(k){return this.normalizers.reduce((N,Q)=>Q.normalize(N),k)}}class we extends oe{_tokenize_chinese_chars(k){const N=[];for(let Q=0;Qthis.pre_tokenize_text(Q,N)):this.pre_tokenize_text(k,N)).flat()}_call(k,N){return this.pre_tokenize(k,N)}}class R extends q{constructor(k){super(),this.pattern=new RegExp(`[^\\s${b}]+|[${b}]`,"gu")}pre_tokenize_text(k,N){return k.trim().match(this.pattern)||[]}}class pe extends q{constructor(k){super(),this.config=k,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=ee,this.text_encoder=new TextEncoder}pre_tokenize_text(k,N){return this.add_prefix_space&&!k.startsWith(" ")&&(k=" "+k),(this.use_regex?k.match(this.pattern)||[]:[k]).map(ie=>Array.from(this.text_encoder.encode(ie),de=>this.byte_encoder[de]).join(""))}}class xe extends q{constructor(k){super(),this.config=k,this.pattern=_(this.config.pattern,this.config.invert)}pre_tokenize_text(k,N){var Q;return this.pattern===null?[]:this.config.invert?k.match(this.pattern)||[]:((Q=this.config.behavior)==null?void 0:Q.toLowerCase())==="removed"?k.split(this.pattern).filter(ie=>ie):c(k,this.pattern)}}class Me extends q{constructor(k){super(),this.config=k,this.pattern=new RegExp(`[^${b}]+|[${b}]+`,"gu")}pre_tokenize_text(k,N){return k.match(this.pattern)||[]}}class Se extends q{constructor(k){super(),this.config=k;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text(k,N){return k.match(this.pattern)||[]}}class Ae extends s.Callable{constructor(k){super(),this.config=k}static fromConfig(k){if(k===null)return null;switch(k.type){case"TemplateProcessing":return new Ve(k);case"ByteLevel":return new O(k);case"RobertaProcessing":return new ze(k);case"BertProcessing":return new Fe(k);case"Sequence":return new Y(k);default:throw new Error(`Unknown PostProcessor type: ${k.type}`)}}post_process(k,...N){throw Error("post_process should be implemented in subclass.")}_call(k,...N){return this.post_process(k,...N)}}class Fe extends Ae{constructor(k){super(k),this.cls=k.cls[0],this.sep=k.sep[0]}post_process(k,N=null,{add_special_tokens:Q=!0}={}){Q&&(k=(0,o.mergeArrays)([this.cls],k,[this.sep]));let ie=new Array(k.length).fill(0);if(N!==null){const de=Q&&this instanceof ze?[this.sep]:[],ve=Q?[this.sep]:[];k=(0,o.mergeArrays)(k,de,N,ve),ie=(0,o.mergeArrays)(ie,new Array(N.length+de.length+ve.length).fill(1))}return{tokens:k,token_type_ids:ie}}}class ze extends Fe{}class Ve extends Ae{constructor(k){super(k),this.single=k.single,this.pair=k.pair}post_process(k,N=null,{add_special_tokens:Q=!0}={}){const ie=N===null?this.single:this.pair;let de=[],ve=[];for(const je of ie)"SpecialToken"in je?Q&&(de.push(je.SpecialToken.id),ve.push(je.SpecialToken.type_id)):"Sequence"in je&&(je.Sequence.id==="A"?(de=(0,o.mergeArrays)(de,k),ve=(0,o.mergeArrays)(ve,new Array(k.length).fill(je.Sequence.type_id))):je.Sequence.id==="B"&&(de=(0,o.mergeArrays)(de,N),ve=(0,o.mergeArrays)(ve,new Array(N.length).fill(je.Sequence.type_id))));return{tokens:de,token_type_ids:ve}}}class O extends Ae{post_process(k,N=null){return N&&(k=(0,o.mergeArrays)(k,N)),{tokens:k}}}class Y extends Ae{constructor(k){super(k),this.processors=k.processors.map(N=>Ae.fromConfig(N))}post_process(k,N=null,Q={}){let ie;for(const de of this.processors)if(de instanceof O)k=de.post_process(k).tokens,N&&(N=de.post_process(N).tokens);else{const ve=de.post_process(k,N,Q);k=ve.tokens,ie=ve.token_type_ids}return{tokens:k,token_type_ids:ie}}}class z extends s.Callable{constructor(k){super(),this.config=k,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=k.trim_offsets}static fromConfig(k){if(k===null)return null;switch(k.type){case"WordPiece":return new ke(k);case"Metaspace":return new Gt(k);case"ByteLevel":return new Ie(k);case"Replace":return new J(k);case"ByteFallback":return new le(k);case"Fuse":return new ye(k);case"Strip":return new Ee(k);case"Sequence":return new Xe(k);case"CTC":return new Be(k);case"BPEDecoder":return new Ge(k);default:throw new Error(`Unknown Decoder type: ${k.type}`)}}_call(k){return this.decode(k)}decode(k){return this.decode_chain(k).join("")}decode_chain(k){throw Error("`decode_chain` should be implemented in subclass.")}}class J extends z{decode_chain(k){const N=_(this.config.pattern);return N===null?k:k.map(Q=>Q.replaceAll(N,this.config.content))}}class le extends z{constructor(k){super(k),this.text_decoder=new TextDecoder}decode_chain(k){const N=[];let Q=[];for(const ie of k){let de=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const ve=parseInt(ie.slice(3,5),16);isNaN(ve)||(de=ve)}if(de!==null)Q.push(de);else{if(Q.length>0){const ve=this.text_decoder.decode(Uint8Array.from(Q));N.push(ve),Q=[]}N.push(ie)}}if(Q.length>0){const ie=this.text_decoder.decode(Uint8Array.from(Q));N.push(ie),Q=[]}return N}}class ye extends z{decode_chain(k){return[k.join("")]}}class Ee extends z{constructor(k){super(k),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(k){return k.map(N=>{let Q=0;for(let de=0;de(Q!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=$(N)),N))}}class Ie extends z{constructor(k){super(k),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(k){const N=k.join(""),Q=new Uint8Array([...N].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Q)}decode_chain(k){const N=[];let Q=[];for(const ie of k)this.added_tokens.find(de=>de.content===ie)!==void 0?(Q.length>0&&(N.push(this.convert_tokens_to_string(Q)),Q=[]),N.push(ie)):Q.push(ie);return Q.length>0&&N.push(this.convert_tokens_to_string(Q)),N}}class Be extends z{constructor(k){super(k),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(k){if(k.length===0)return"";const N=[k[0]];for(let de=1;dede!==this.pad_token).join("");return this.cleanup&&(ie=$(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain(k){return[this.convert_tokens_to_string(k)]}}class Xe extends z{constructor(k){super(k),this.decoders=k.decoders.map(N=>z.fromConfig(N))}decode_chain(k){return this.decoders.reduce((N,Q)=>Q.decode_chain(N),k)}}class Ge extends z{constructor(k){super(k),this.suffix=this.config.suffix}decode_chain(k){return k.map((N,Q)=>N.replaceAll(this.suffix,Q===k.length-1?"":" "))}}class lt extends z{decode_chain(k){let N="";for(let Q=1;QQ.normalize("NFKC")).join("~"):k=k.normalize("NFKC"),k}}class lr extends q{constructor(k){super(),this.tokenizers=k.pretokenizers.map(N=>q.fromConfig(N))}pre_tokenize_text(k,N){return this.tokenizers.reduce((Q,ie)=>ie.pre_tokenize(Q,N),[k])}}class Yr extends q{constructor(k){super()}pre_tokenize_text(k,N){return k.match(/\w+|[^\w\s]+/g)||[]}}class gs extends q{constructor(k){super()}pre_tokenize_text(k,N){return y(k)}}class kr extends q{constructor(k){super(),this.config=k,this.pattern=_(this.config.pattern),this.content=this.config.content}pre_tokenize_text(k,N){return this.pattern===null?[k]:[k.replaceAll(this.pattern,this.config.content)]}}const Ds=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function xs(he,k,N,Q){for(const ie of Object.keys(he)){const de=k-he[ie].length,ve=N(ie),je=new Array(de).fill(ve);he[ie]=Q==="right"?(0,o.mergeArrays)(he[ie],je):(0,o.mergeArrays)(je,he[ie])}}function Ls(he,k){for(const N of Object.keys(he))he[N].length=k}class at extends s.Callable{constructor(N,Q){super();te(this,"return_token_type_ids",!1);te(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=oe.fromConfig(N.normalizer),this.pre_tokenizer=q.fromConfig(N.pre_tokenizer),this.model=K.fromConfig(N.model,Q),this.post_processor=Ae.fromConfig(N.post_processor),this.decoder=z.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of N.added_tokens){const de=new B(ie);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Q.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_splitter=new l.DictionarySplitter(this.added_tokens.map(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),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=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:de,template:ve}of this.chat_template){if(typeof de!="string"||typeof ve!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[de]=ve}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...N){for(const Q of N){const ie=this._tokenizer_config[Q];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(N,{progress_callback:Q=null,config:ie=null,cache_dir:de=null,local_files_only:ve=!1,revision:je="main",legacy:He=null}={}){const We=await d(N,{progress_callback:Q,config:ie,cache_dir:de,local_files_only:ve,revision:je,legacy:He});return new this(...We)}_call(N,{text_pair:Q=null,add_special_tokens:ie=!0,padding:de=!1,truncation:ve=null,max_length:je=null,return_tensor:He=!0,return_token_type_ids:We=null}={}){const Je=Array.isArray(N);let dt;if(Je){if(N.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(N.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");dt=N.map((Et,Rt)=>this._encode_plus(Et,{text_pair:Q[Rt],add_special_tokens:ie,return_token_type_ids:We}))}else dt=N.map(Et=>this._encode_plus(Et,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");dt=[this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:We})]}if(je===null?de==="max_length"?je=this.model_max_length:je=(0,i.max)(dt.map(Et=>Et.input_ids.length))[0]:ve||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."),je=Math.min(je,this.model_max_length??1/0),de||ve)for(let Et=0;Etje?ve&&Ls(dt[Et],je):de&&xs(dt[Et],je,Rt=>Rt==="input_ids"?this.pad_token_id:0,this.padding_side));const vt={};if(He){if(!(de&&ve)&&dt.some(Rt=>{var kt;for(const Kt of Object.keys(Rt))if(Rt[Kt].length!==((kt=dt[0][Kt])==null?void 0:kt.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 Et=[dt.length,dt[0].input_ids.length];for(const Rt of Object.keys(dt[0]))vt[Rt]=new a.Tensor("int64",BigInt64Array.from(dt.flatMap(kt=>kt[Rt]).map(BigInt)),Et)}else{for(const Et of Object.keys(dt[0]))vt[Et]=dt.map(Rt=>Rt[Et]);if(!Je)for(const Et of Object.keys(vt))vt[Et]=vt[Et][0]}return vt}_encode_text(N){if(N===null)return null;const Q=this.added_tokens_splitter.split(N);for(let de=0;de0&&(Q[de-1]=Q[de-1].trimEnd()),ve.rstrip&&de{if(de.length===0)return[];if(this.added_tokens_map.has(de))return[de];if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=g(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const je=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:ve}):[de];return this.model(je)})}_encode_plus(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){const{tokens:ve,token_type_ids:je}=this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}),He=this.model.convert_tokens_to_ids(ve),We={input_ids:He,attention_mask:new Array(He.length).fill(1)};return(de??this.return_token_type_ids)&&je&&(We.token_type_ids=je),We}_tokenize_helper(N,{pair:Q=null,add_special_tokens:ie=!1}={}){const de=this._encode_text(N),ve=this._encode_text(Q);return this.post_processor?this.post_processor(de,ve,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(de??[],ve??[])}}tokenize(N,{pair:Q=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}).tokens}encode(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){return this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:de}).input_ids}batch_decode(N,Q={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(ie=>this.decode(ie,Q))}decode(N,Q={}){if(N instanceof a.Tensor&&(N=v(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,Q)}decode_single(N,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:ie=null}){let de=this.model.convert_ids_to_tokens(N);Q&&(de=de.filter(je=>!this.special_tokens.includes(je)));let ve=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ve=ve.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(ve=ve.trim())),(ie??this.clean_up_tokenization_spaces)&&(ve=$(ve)),ve}get_chat_template({chat_template:N=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(N!==null&&Object.hasOwn(ie,N))N=ie[N];else if(N===null)if(Q!==null&&"tool_use"in ie)N=ie.tool_use;else if("default"in ie)N=ie.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(ie).sort()}.`)}else if(N===null)if(this.chat_template)N=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 N}apply_chat_template(N,{tools:Q=null,documents:ie=null,chat_template:de=null,add_generation_prompt:ve=!1,tokenize:je=!0,padding:He=!1,truncation:We=!1,max_length:Je=null,return_tensor:dt=!0,return_dict:vt=!1,tokenizer_kwargs:Et={},...Rt}={}){if(de=this.get_chat_template({chat_template:de,tools:Q}),typeof de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let kt=this._compiled_template_cache.get(de);kt===void 0&&(kt=new u.Template(de),this._compiled_template_cache.set(de,kt));const Kt=Object.create(null);for(const dr of Ds){const cr=this.getToken(dr);cr&&(Kt[dr]=cr)}const Mr=kt.render({messages:N,add_generation_prompt:ve,tools:Q,documents:ie,...Kt,...Rt});if(je){const dr=this._call(Mr,{add_special_tokens:!1,padding:He,truncation:We,max_length:Je,return_tensor:dt,...Et});return vt?dr:dr.input_ids}return Mr}}class Zr extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ir extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ws extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ft extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class es extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ts extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class bs extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Xt extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class De extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Qe extends at{}class et extends at{}class Bt extends at{constructor(N,Q){super(N,Q);te(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 Or extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Pr extends at{}class rs extends at{}class ss extends at{}class Ur extends at{constructor(k,N){super(k,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(k,N,Q){return xr(this,k,N,Q)}}class ns extends Ur{}class os extends at{}class Wr extends at{}const yr="▁";class Ys extends at{constructor(N,Q){super(N,Q);te(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new wt({replacement:yr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let Q=super._encode_text(yr+N.replaceAll(yr," "));return Q.length>1&&Q[0]===yr&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class vr extends at{}class Ts extends at{}class Es extends at{}class fr extends at{}class zs extends at{}class Zs extends at{}class Ar extends at{}class en extends at{}class Gr extends at{}function xr(he,k,N,Q){if(!("language_codes"in he)||!Array.isArray(he.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in he)||!(he.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in he)||typeof he.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=Q.src_lang,de=Q.tgt_lang;if(!he.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);if(ie!==void 0){if(!he.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);for(const ve of he.post_processor.config.single)if("SpecialToken"in ve&&he.languageRegex.test(ve.SpecialToken.id)){ve.SpecialToken.id=he.lang_to_token(ie);break}}return Q.forced_bos_token_id=he.model.convert_tokens_to_ids([he.lang_to_token(de)])[0],he._call(k,N)}class Ps extends at{constructor(k,N){super(k,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(k,N,Q){return xr(this,k,N,Q)}}class ur extends at{constructor(k,N){super(k,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs(k,N,Q){return xr(this,k,N,Q)}}class _r extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(k,{return_timestamps:N=!1,return_language:Q=!1,time_precision:ie=null,force_full_sequences:de=!0}={}){if(ie===null)throw Error("Must specify time_precision");let ve=null;const je=N==="word";function He(){return{language:ve,timestamp:[null,null],text:""}}const We=[];let Je=He(),dt=0;const vt=this.timestamp_begin,Rt=vt+1500;let kt=[],Kt=[],Mr=!1,dr=null;const cr=new Set(this.all_special_ids);for(const Dt of k){const rr=Dt.tokens,gr=je?Dt.token_timestamps:null;let Hr=null,Lr=vt;if("stride"in Dt){const[or,Vt,Zt]=Dt.stride;if(dt-=Vt,dr=or-Zt,Vt&&(Lr=Vt/ie+vt),Zt)for(let er=rr.length-1;er>=0;--er){const tr=Number(rr[er]);if(tr>=vt){if(Hr!==null&&(tr-vt)*ie=vt&&Vt<=Rt){const Zt=(Vt-vt)*ie+dt,er=(0,i.round)(Zt,2);if(Hr!==null&&Vt>=Hr)Mr=!0;else if(Mr||kt.length>0&&Vt0?(kt.push(Yt),je&&Kt.push(zr)):kt.every(or=>or.length===0)&&(Je=He(),kt=[],Yt=[],Kt=[],zr=[])}if(kt.length>0){if(de&&N)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[Dt,rr]=this.findLongestCommonSequence(kt,Kt),gr=this.decode(Dt);Je.text=gr,je&&(Je.words=this.collateWordTimestamps(Dt,rr,ve)),We.push(Je)}let Nt=Object.create(null);const Kr=We.map(Dt=>Dt.text).join("");if(N||Q){for(let Dt=0;Dt0;let je=ve?[]:null,He=ve?N[0]:null;for(let We=1;WeVt===Lr[Zt]&&He[Kr+Zt]<=N[We][gr+Zt]).length:Yt=rr.filter((Vt,Zt)=>Vt===Lr[Zt]).length;const zr=Nt/1e4,or=Yt/Nt+zr;Yt>1&&or>dt&&(dt=or,vt=[Kr,Dt,gr,Hr])}const[Rt,kt,Kt,Mr]=vt,dr=Math.floor((kt+Rt)/2),cr=Math.floor((Mr+Kt)/2);de.push(...Q.slice(0,dr)),Q=Je.slice(cr),ie=Q.length,ve&&(je.push(...He.slice(0,dr)),He=N[We].slice(cr))}return de.push(...Q),ve?(je.push(...He),[de,je]):[de,[]]}collateWordTimestamps(k,N,Q){const[ie,de,ve]=this.combineTokensIntoWords(k,Q),je=[];for(let He=0;He=ie){const je=((ve-ie)*Q).toFixed(2);de.push(`<|${je}|>`),de.push([])}else de[de.length-1].push(ve);return de=de.map(ve=>typeof ve=="string"?ve:super.decode(ve,N)),de.join("")}splitTokensOnUnicode(k){const N=this.decode(k,{decode_with_timestamps:!0}),Q="�",ie=[],de=[],ve=[];let je=[],He=[],We=0;for(let Je=0;Je=this.model.tokens_to_ids.get("<|endoftext|>"),Rt=Je.startsWith(" "),kt=Je.trim(),Kt=He.test(kt);if(Et||Rt||Kt||de.length===0)de.push(Je),ve.push(dt),je.push(vt);else{const Mr=de.length-1;de[Mr]+=Je,ve[Mr].push(...dt),je[Mr].push(...vt)}}return[de,ve,je]}mergePunctuations(k,N,Q,ie,de){const ve=structuredClone(k),je=structuredClone(N),He=structuredClone(Q);let We=ve.length-2,Je=ve.length-1;for(;We>=0;)ve[We].startsWith(" ")&&ie.includes(ve[We].trim())?(ve[Je]=ve[We]+ve[Je],je[Je]=(0,o.mergeArrays)(je[We],je[Je]),He[Je]=(0,o.mergeArrays)(He[We],He[Je]),ve[We]="",je[We]=[],He[We]=[]):Je=We,--We;for(We=0,Je=1;Jedt),je.filter(dt=>dt.length>0),He.filter(dt=>dt.length>0)]}}class Dr extends at{}class tn extends at{}class rn extends at{}class sn extends at{constructor(k,N){super(k,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(k){if(k===null)return null;const[N,...Q]=k.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(N);if(Q.length===2){const[ie,de]=Q;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(de))}}}class nn extends at{}class on extends at{}class Ms extends at{}class an extends at{}class Bs extends at{}class ln extends at{constructor(k,N){super(k,N),this.decoder=new lt({})}}class un extends at{}class ys extends at{}class dn{static async from_pretrained(k,{progress_callback:N=null,config:Q=null,cache_dir:ie=null,local_files_only:de=!1,revision:ve="main",legacy:je=null}={}){var vt;const[He,We]=await d(k,{progress_callback:N,config:Q,cache_dir:ie,local_files_only:de,revision:ve,legacy:je}),Je=((vt=We.tokenizer_class)==null?void 0:vt.replace(/Fast$/,""))??"PreTrainedTokenizer";let dt=this.TOKENIZER_CLASS_MAPPING[Je];return dt||(console.warn(`Unknown tokenizer class "${Je}", attempting to construct from base class.`),dt=at),new dt(He,We)}}te(dn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Pr,DistilBertTokenizer:Qe,CamembertTokenizer:et,DebertaTokenizer:es,DebertaV2Tokenizer:ts,BertTokenizer:Zr,HerbertTokenizer:bs,ConvBertTokenizer:Xt,RoFormerTokenizer:De,XLMTokenizer:Bt,ElectraTokenizer:Or,MobileBertTokenizer:ws,SqueezeBertTokenizer:Ft,AlbertTokenizer:Ir,GPT2Tokenizer:rs,BartTokenizer:ss,MBartTokenizer:Ur,MBart50Tokenizer:ns,RobertaTokenizer:os,WhisperTokenizer:_r,CodeGenTokenizer:Dr,CLIPTokenizer:tn,SiglipTokenizer:rn,MarianTokenizer:sn,BloomTokenizer:Wr,NllbTokenizer:Ps,M2M100Tokenizer:ur,LlamaTokenizer:Ys,CodeLlamaTokenizer:vr,XLMRobertaTokenizer:Ts,MPNetTokenizer:Es,FalconTokenizer:fr,GPTNeoXTokenizer:zs,EsmTokenizer:Zs,Wav2Vec2CTCTokenizer:nn,BlenderbotTokenizer:on,BlenderbotSmallTokenizer:Ms,SpeechT5Tokenizer:an,NougatTokenizer:Bs,VitsTokenizer:ln,Qwen2Tokenizer:Ar,GemmaTokenizer:en,Grok1Tokenizer:Gr,CohereTokenizer:un,MgpstrTokenizer:ys,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>G,hamming:()=>c,hanning:()=>d,mel_filter_bank:()=>C,read_audio:()=>u,spectrogram:()=>S,window_function:()=>A});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(j,ee){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)(j)).arrayBuffer(),Z=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${Z.sampleRate}Hz.`);const X=await Z.decodeAudioData(H);let oe;if(X.numberOfChannels===2){const me=Math.sqrt(2),ae=X.getChannelData(0),V=X.getChannelData(1);oe=new Float32Array(ae.length);for(let F=0;F2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,ee=1e3,H=15,Z=27/Math.log(6.4))=>j>=ee?H+Math.log(j/ee)*Z:3*j/200};function f(j,ee="htk"){const H=_[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}const v={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,ee=1e3,H=15,Z=Math.log(6.4)/27)=>j>=H?ee*Math.exp(Z*(j-H)):200*j/3};function $(j,ee="htk"){const H=v[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}function w(j,ee){const H=Float64Array.from({length:ee.length-1},(me,ae)=>ee[ae+1]-ee[ae]),Z=Array.from({length:j.length},()=>new Array(ee.length));for(let me=0;menew Array(j.length));for(let me=0;mej+Z*oe)}function C(j,ee,H,Z,X,oe=null,me="htk",ae=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(j<2)throw new Error(`Require num_frequency_bins: ${j} >= 2`);if(H>Z)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${Z}`);const V=f(H,me),F=f(Z,me),W=g(V,F,ee+2);let re=$(W,me),fe;if(ae){const ce=X/((j-1)*2);fe=f(Float64Array.from({length:j},($e,Ue)=>Ue*ce),me),re=W}else fe=g(0,Math.floor(X/2),j);const se=w(fe,re);if(oe!==null&&oe==="slaney")for(let ce=0;ceX)throw Error(`frame_length (${H}) may not be larger than fft_length (${X})`);if(xe!==H)throw new Error(`Length of the window (${xe}) must equal frame_length (${H})`);if(Z<=0)throw new Error("hop_length must be greater than zero");if(oe===null&&W!==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(me){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const ye=Math.floor((X-1)/2)+1;j=E(j,ye,ye)}let Me=Math.floor(1+Math.floor((j.length-H)/Z));we!==null&&MeMe?R&&(Fe=q):Fe=Ae=q);const ze=new o.FFT(X),Ve=new Float64Array(X),O=new Float64Array(ze.outputBufferSize),Y=new Float32Array(Se*Fe);for(let ye=0;ye=1;--Ie)Ve[Ie]-=F*Ve[Ie-1];Ve[0]*=1-F}for(let Ie=0;IeMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(H&&(me=me.subarray(0,j)),Z===null)return me;if(j>Z)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${Z})`);return me}function B(j,ee){let H=44;const Z=new ArrayBuffer(H+j.length*4),X=new DataView(Z);K(X,0,"RIFF"),X.setUint32(4,36+j.length*4,!0),K(X,8,"WAVE"),K(X,12,"fmt "),X.setUint32(16,16,!0),X.setUint16(20,3,!0),X.setUint16(22,1,!0),X.setUint32(24,ee,!0),X.setUint32(28,ee*4,!0),X.setUint16(32,4,!0),X.setUint16(34,32,!0),K(X,36,"data"),X.setUint32(40,j.length*4,!0);for(let oe=0;oe{let oe=await X.arrayBuffer();a.writeFileSync(Z,Buffer.from(oe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(ee,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>_,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>$,mergeArrays:()=>d,pick:()=>v,pop:()=>p,product:()=>c,reverseDictionary:()=>o,saveBlob:()=>f});function s(g,C){g&&g(C)}function o(g){return Object.fromEntries(Object.entries(g).map(([C,E])=>[E,C]))}function n(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(g){var C,E,y;return((y=(E=(C=g==null?void 0:g.prototype)==null?void 0:C.__proto__)==null?void 0:E.constructor)==null?void 0:y.name)==="TypedArray"}function a(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function u(g){const C=[];let E=g;for(;Array.isArray(E);)C.push(E.length),E=E[0];return C}function p(g,C,E=void 0){const y=g[C];if(y!==void 0)return delete g[C],y;if(E===void 0)throw Error(`Key ${C} does not exist in object.`);return E}function d(...g){return Array.prototype.concat.apply([],g)}function c(...g){return g.reduce((C,E)=>C.flatMap(y=>E.map(b=>[y,b])))}function _(g,C){return Math.abs((g+C)%(2*C)-C)}function f(g,C){const E=URL.createObjectURL(C),y=document.createElement("a");y.href=E,y.download=g,y.click(),y.remove(),URL.revokeObjectURL(E)}function v(g,C){return Object.assign({},...C.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function $(g){let C=0;for(const E of g)++C;return C}function w(g,C){let E=0;for(const y of g)y===C&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(_,f)=>_>f,c=1/0){this._heap=[],this._comparator=d,this._maxSize=c}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 c of d)if(this.size0&&this._swap(0,c),this._heap.pop(),this._siftDown(),d}replace(d){const c=this.peek();return this._heap[0]=d,this._siftDown(),c}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,c){return this._comparator(this._heap[d],this._heap[c])}_swap(d,c){const _=this._heap[d];this._heap[d]=this._heap[c],this._heap[c]=_}_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 f=new a(this.bosTokenId,0,0,0,0),v=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(f.clone()),this.nodes.push(v.clone()),this.beginNodes[this.len].push(v),this.endNodes[0].push(f)}insert(d,c,_,f){const v=this.nodes.length,$=new a(f,v,d,c,_);this.beginNodes[d].push($),this.endNodes[d+c].push($),this.nodes.push($)}viterbi(){const d=this.len;let c=0;for(;c<=d;){if(this.beginNodes[c].length==0)return[];for(let w of this.beginNodes[c]){w.prev=null;let g=0,C=null;for(let E of this.endNodes[c]){const y=E.backtraceScore+w.score;(C===null||y>g)&&(C=E.clone(),g=y)}if(C!==null)w.prev=C,w.backtraceScore=g;else return[]}++c}const _=[],v=this.beginNodes[d][0].prev;if(v===null)return[];let $=v.clone();for(;$.prev!==null;)_.push($.clone()),$=$.clone().prev.clone();return _.reverse(),_}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(c=>this.piece(c))}tokenIds(){return this.viterbi().map(c=>c.tokenId)}}class a{constructor(d,c,_,f,v){this.tokenId=d,this.nodeId=c,this.pos=_,this.length=f,this.score=v,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}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){var _;const c=Object.create(null);for(const f of d){let v=c;for(let $=0;$f&&c.push(d.slice(f,v)),c.push(w),v+=w.length,f=v):++v}return f<_&&c.push(d.slice(f)),c}}class u{constructor(d){this.capacity=d,this.cache=new Map}get(d){if(!this.cache.has(d))return;const c=this.cache.get(d);return this.cache.delete(d),this.cache.set(d,c),c}put(d,c){this.cache.has(d)&&this.cache.delete(d),this.cache.set(d,c),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./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:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){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:()=>_,getModelFile:()=>g,getModelJSON:()=>C});var s=t("?7a2c"),o=t("?a42a"),n=t("./src/env.js"),i=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 u{constructor(x){if(this.filePath=x,this.headers=new Headers,this.exists=s.existsSync(x),this.exists){this.status=200,this.statusText="OK";let S=s.statSync(x);this.headers.set("content-length",S.size.toString()),this.updateContentType();const A=s.createReadStream(x);this.body=new ReadableStream({start(B){A.on("data",K=>B.enqueue(K)),A.on("end",()=>B.close()),A.on("error",K=>B.error(K))},cancel(){A.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const x=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[x]??"application/octet-stream")}clone(){let x=new u(this.filePath);return x.exists=this.exists,x.status=this.status,x.statusText=this.statusText,x.headers=new Headers(this.headers),x}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const x=await s.promises.readFile(this.filePath);return new Blob([x],{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(b,x=null,S=null){let A;try{A=new URL(b)}catch{return!1}return!(x&&!x.includes(A.protocol)||S&&!S.includes(A.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function c(b){return!(!d.test(b)||b.includes("..")||b.includes("--")||b.endsWith(".git")||b.endsWith(".ipynb"))}async function _(b){var x;if(n.env.useFS&&!p(b,["http:","https:","blob:"]))return new u(b.toString());if(typeof process<"u"&&((x=process==null?void 0:process.release)==null?void 0:x.name)==="node"){const S=!!(As!=null&&As.TESTING_REMOTELY),A=n.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${A}; is_ci/${S};`),p(b,["http:","https:"],["huggingface.co","hf.co"])){const G=(As==null?void 0:As.HF_TOKEN)??(As==null?void 0:As.HF_ACCESS_TOKEN);G&&B.set("Authorization",`Bearer ${G}`)}return fetch(b,{headers:B})}else return fetch(b)}const f={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 v(b,x,S){if(!S)return null;const A=f[b]??`Error (${b}) occurred while trying to load file`;throw Error(`${A}: "${x}".`)}class ${constructor(x){this.path=x}async match(x){let S=o.join(this.path,x),A=new u(S);if(A.exists)return A}async put(x,S,A=void 0){let B=o.join(this.path,x);try{const K=S.headers.get("Content-Length"),G=parseInt(K??"0");let j=0;await s.promises.mkdir(o.dirname(B),{recursive:!0});const ee=s.createWriteStream(B),H=S.body.getReader();for(;;){const{done:Z,value:X}=await H.read();if(Z)break;await new Promise((me,ae)=>{ee.write(X,V=>{if(V){ae(V);return}me()})}),j+=X.length;const oe=G?j/G*100:0;A==null||A({progress:oe,loaded:j,total:G})}ee.close()}catch(K){try{await s.promises.unlink(B)}catch{}throw K}}}async function w(b,...x){for(let S of x)try{let A=await b.match(S);if(A)return A}catch{continue}}async function g(b,x,S=!0,A={},B=!1){if(!n.env.allowLocalModels){if(A.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,i.dispatchCallback)(A.progress_callback,{status:"initiate",name:b,file:x});let K;if(!K&&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");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(re){console.warn("An error occurred while opening the browser cache:",re)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new $(A.cache_dir??n.env.cacheDir)}const G=A.revision??"main",j=y(b,x),ee=c(b),H=ee?y(n.env.localModelPath,j):j,Z=y(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",b).replaceAll("{revision}",encodeURIComponent(G)),x);let X;const oe=K instanceof $?G==="main"?j:y(b,G,x):Z;let me=!1,ae;K&&(ae=await w(K,H,oe));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(j,["http:","https:"])){if(A.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${j}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${j}.`)}else try{ae=await _(H),X=H}catch(fe){console.warn(`Unable to load from local path "${H}": "${fe}"`)}if(ae===void 0||ae.status===404){if(A.local_files_only||!n.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!ee)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${b}".`);if(ae=await _(Z),ae.status!==200)return v(ae.status,Z,S);X=oe}me=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(A.progress_callback,{status:"download",name:b,file:x});let F;if(!(n.apis.IS_NODE_ENV&&B)){let re;A.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(re=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:b,file:x,progress:100,loaded:re.length,total:re.length})):re=await E(ae,fe=>{(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:b,file:x,...fe})}):re=new Uint8Array(await ae.arrayBuffer()),F=re}if(me&&X&&await K.match(X)===void 0&&(F?await K.put(X,new Response(F,{headers:ae.headers})).catch(re=>{console.warn(`Unable to add response to browser cache: ${re}.`)}):await K.put(X,ae,A.progress_callback)),(0,i.dispatchCallback)(A.progress_callback,{status:"done",name:b,file:x}),F){if(!n.apis.IS_NODE_ENV&&B)throw new Error("Cannot return path in a browser environment.");return F}if(ae instanceof u)return ae.filePath;const W=await(K==null?void 0:K.match(X));if(W instanceof u)return W.filePath;if(W instanceof Response)return new Uint8Array(await W.arrayBuffer());if(typeof W=="string")return W;throw new Error("Unable to get model file path or buffer.")}async function C(b,x,S=!0,A={}){const B=await g(b,x,S,A,!1);if(B===null)return{};const G=new TextDecoder("utf-8").decode(B);return JSON.parse(G)}async function E(b,x){const S=b.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let A=parseInt(S??"0"),B=new Uint8Array(A),K=0;const G=b.body.getReader();async function j(){const{done:ee,value:H}=await G.read();if(ee)return;const Z=K+H.length;if(Z>A){A=Z;const oe=new Uint8Array(A);oe.set(B),B=oe}B.set(H,K),K=Z;const X=K/A*100;return x({progress:X,loaded:K,total:A}),j()}return await j(),B}function y(...b){return b=b.map((x,S)=>(S&&(x=x.replace(new RegExp("^/"),"")),S!==b.length-1&&(x=x.replace(new RegExp("/$"),"")),x)),b.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>f,load_image:()=>v});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const d=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(d)l=($,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas($,w)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async $=>{const g=(await $.metadata()).channels,{data:C,info:E}=await $.rotate().raw().toBuffer({resolveWithObject:!0}),y=new f(new Uint8ClampedArray(C),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&y.convert(g),y};else throw new Error("Unable to load image processing library.");const c={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(w,g,C,E){this.data=w,this.width=g,this.height=C,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof f)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const C=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new f(C,w.width,w.height,4)}static async fromURL(w){const g=await(0,o.getFile)(w);if(g.status!==200)throw new Error(`Unable to read image from "${w}" (${g.status} ${g.statusText})`);const C=await g.blob();return this.fromBlob(C)}static async fromBlob(w){if(d){const g=await p(w),C=l(g.width,g.height).getContext("2d");return C.drawImage(g,0,0),new this(C.getImageData(0,0,g.width,g.height).data,g.width,g.height,4)}else{const g=a(await w.arrayBuffer());return await p(g)}}static fromTensor(w,g="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(g==="CHW")w=w.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new f(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let g=0,C=0;g=0?S=C:B=-C,E>=0?A=E:K=-E,x.drawImage(b,S,A,w,g,B,K,w,g),new f(x.getImageData(0,0,w,g).data,w,g,4).convert(y)}else{let y=this.toSharp();if(C>=0&&E>=0)y=y.extract({left:Math.floor(C),top:Math.floor(E),width:w,height:g});else if(C<=0&&E<=0){const b=Math.floor(-E),x=Math.floor(-C);y=y.extend({top:b,left:x,right:w-this.width-x,bottom:g-this.height-b})}else{let b=[0,0],x=0;E<0?(b[0]=Math.floor(-E),b[1]=g-this.height-b[0]):x=Math.floor(E);let S=[0,0],A=0;C<0?(S[0]=Math.floor(-C),S[1]=w-this.width-S[0]):A=Math.floor(C),y=y.extend({top:b[0],bottom:b[1],left:S[0],right:S[1]}).extract({left:A,top:x,width:w,height:g})}return await p(y)}}async toBlob(w="image/png",g=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:g})}toTensor(w="CHW"){let g=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return g}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),g=l(w.width,w.height),C=new u(w.data,w.width,w.height);return g.getContext("2d").putImageData(C,0,0),g}split(){const{data:w,width:g,height:C,channels:E}=this,y=w.constructor,b=w.length/E,x=Array.from({length:E},()=>new y(b));for(let S=0;Snew f(S,g,C,1))}_update(w,g,C,E=null){return this.data=w,this.width=g,this.height=C,E!==null&&(this.channels=E),this}clone(){return new f(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){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(w){if(d){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const g=w.split(".").pop().toLowerCase(),C=_.get(g)??"image/png",E=await this.toBlob(C);(0,s.saveBlob)(w,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)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 v=f.read.bind(f)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>v,bankers_round:()=>g,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>C,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>d,medianFilter:()=>$,min:()=>p,permute_data:()=>o,round:()=>w,softmax:()=>n});function s(E,[y,b,x],[S,A],B="bilinear",K=!1){const G=A/x,j=S/b,ee=new E.constructor(S*A*y),H=b*x,Z=S*A;for(let X=0;X=0;--K)S[K]=G,x[K]=y[b[K]],G*=x[K];const A=b.map((K,G)=>S[b.indexOf(G)]),B=new E.constructor(E.length);for(let K=0;K=0;--j)G+=ee%y[j]*A[j],ee=Math.floor(ee/y[j]);B[G]=E[K]}return[B,x]}function n(E){const y=d(E)[0],b=E.map(A=>Math.exp(A-y)),x=b.reduce((A,B)=>A+B,0);return b.map(A=>A/x)}function i(E){const y=d(E)[0];let b=0;for(let A=0;AA-y-x)}function a(E,y){let b=0;for(let x=0;xy+b*b,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let y=E[0],b=0;for(let x=1;xy&&(y=E[x],b=x);return[y,b]}function c(E){return E>0&&(E&E-1)===0}class _{constructor(y){if(this.size=y|0,this.size<=1||!c(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++b;this._width=b%2===0?b-1:b,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=y[S];return x}toComplexArray(y,b){const x=b||this.createComplexArray();for(let S=0;S>>1],x[S+1]=0;return x}transform(y,b){if(y===b)throw new Error("Input and output buffers must be different");this._transform4(y,b,1)}realTransform(y,b){if(y===b)throw new Error("Input and output buffers must be different");this._realTransform4(y,b,1)}inverseTransform(y,b){if(y===b)throw new Error("Input and output buffers must be different");this._transform4(y,b,-1);for(let x=0;x>=2;B>=2;B>>=2){K=S/B<<1;const Z=K>>>2;for(G=0;G>>1,B>>>1)}else for(G=0,j=0;G>>1,B>>>1,x)}const H=this.table;for(B>>=2;B>=2;B>>=2){K=S/B<<1;const X=K>>>1,oe=X>>>1,me=oe>>>1;for(G=0;G>>1;for(let X=2;X>1;++ee){const H=(ee+1-y)**2/2,Z=Math.sqrt(G**2+j**2)**H,X=H*Math.atan2(j,G),oe=2*ee;A[oe]=Z*Math.cos(X),A[oe+1]=Z*Math.sin(X),B[oe]=A[oe],B[oe+1]=-A[oe+1]}this._slicedChirpBuffer=A.subarray(b,x),this._f=new _(S>>1),this._f.transform(this._chirpBuffer,B)}_transform(y,b,x){const S=this._buffer1,A=this._buffer2,B=this._outBuffer1,K=this._outBuffer2,G=this._chirpBuffer,j=this._slicedChirpBuffer,ee=this._a;if(x)for(let H=0;H>1,oe=b[X];S[H]=oe*j[H],S[Z]=oe*j[Z]}else for(let H=0;H=E.length&&(G=2*(E.length-1)-G),x[B++]=E[G]}x.sort(),b[A]=x[S]}return b}function w(E,y){const b=Math.pow(10,y);return Math.round(E*b)/b}function g(E){const y=Math.round(E);return Math.abs(E)%1===.5?y%2===0?y:y-1:y}function C(E){const y=E.length,b=E[0].length,x=[y+1,b+1],S=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));S[0][0]=0;const A=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let ee=1;ee0||K>0;)switch(G.push(B-1),j.push(K-1),A[B][K]){case 0:--B,--K;break;case 1:--B;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${B}, ${K}]. Please file a bug report.`)}return G.reverse(),j.reverse(),[G,j]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>b,full:()=>j,full_like:()=>ee,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>g,matmul:()=>c,mean:()=>B,mean_pooling:()=>w,ones:()=>H,ones_like:()=>Z,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>me,rfft:()=>_,slice:()=>$,stack:()=>x,std_mean:()=>A,topk:()=>f,zeros:()=>X,zeros_like:()=>oe});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=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(...F){te(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(W,re)=>{if(typeof re=="string"){let fe=Number(re);if(Number.isInteger(fe))return W._getitem(fe)}return W[re]},set:(W,re,fe)=>W[re]=fe})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}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[F,...W]=this.dims;if(W.length>0){const re=W.reduce((fe,se)=>fe*se);for(let fe=0;fe0){const fe=re.reduce((se,ce)=>se*ce);return this._subarray(F,fe,re)}else return new a(this.type,[this.data[F]],re)}indexOf(F){const W=this.data;for(let re=0;repe)throw new Error(`Invalid slice: ${q}`);const xe=[Math.max(R,0),Math.min(pe,this.dims[we])];re.push(xe),W.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${q}`)}const fe=re.map(([we,q])=>q-we),se=fe.reduce((we,q)=>we*q),ce=this.data,$e=new ce.constructor(se),Ue=this.stride();for(let we=0;we=0;--R){const xe=fe[R];q+=(pe%xe+re[R][0])*Ue[R],pe=Math.floor(pe/xe)}$e[we]=ce[q]}return new a(this.type,$e,W)}permute(...F){return u(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,W=!1){return this.norm(1,F,W)}norm(F="fro",W=null,re=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const fe=this.data,se=(we,q)=>we+q**F;if(W===null){const we=fe.reduce(se,0)**(1/F);return new a(this.type,[we],[])}const[ce,$e,Ue]=S(se,this,W,re);if(F!==1)for(let we=0;we<$e.length;++we)$e[we]=$e[we]**(1/F);return new a(ce,$e,Ue)}normalize_(F=2,W=1){W=y(W,this.dims.length);const re=this.norm(F,W,!0),fe=this.data,se=re.data;for(let ce=0;ce=0;--Ue){const R=this.dims[Ue];if(Ue!==W){const pe=we%R;$e+=pe*q,q*=this.dims[Ue]}we=Math.floor(we/R)}fe[ce]/=se[$e]}return this}normalize(F=2,W=1){return this.clone().normalize_(F,W)}stride(){return K(this.dims)}squeeze(F=null){return new a(this.type,this.data,C(this.dims,F))}squeeze_(F=null){return this.dims=C(this.dims,F),this}unsqueeze(F=null){return new a(this.type,this.data,E(this.dims,F))}unsqueeze_(F=null){return this.dims=E(this.dims,F),this}flatten_(F=0,W=-1){W=(W+this.dims.length)%this.dims.length;let re=this.dims.slice(0,F),fe=this.dims.slice(F,W+1),se=this.dims.slice(W+1);return this.dims=[...re,fe.reduce((ce,$e)=>ce*$e,1),...se],this}flatten(F=0,W=-1){return this.clone().flatten_(F,W)}view(...F){let W=-1;for(let fe=0;fe$e!==W?se*ce:se,1);F[W]=re.length/fe}return new a(this.type,re,F)}neg_(){const F=this.data;for(let W=0;WF?1:0;return new a("bool",W,this.dims)}lt(F){const W=new Uint8Array(this.data.length),re=this.data;for(let fe=0;feMath.min(ce,$e),this,F,W,1/0);return new a(re,fe,se)}max(F=null,W=!1){if(F===null){const ce=(0,s.max)(this.data)[0];return new a(this.type,[ce],[])}const[re,fe,se]=S((ce,$e)=>Math.max(ce,$e),this,F,W,-1/0);return new a(re,fe,se)}argmin(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.min)(this.data)[1];return new a("int64",[BigInt(re)],[])}argmax(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.max)(this.data)[1];return new a("int64",[BigInt(re)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let W;const re=["int64","uint64"].includes(this.type),fe=["int64","uint64"].includes(F);return re&&!fe?W=Number:!re&&fe&&(W=BigInt),new a(F,i[F].from(this.data,W),this.dims)}}function l(V,F){const W=V.length,re=F.reduce((se,ce)=>se*ce);if(W!==re)throw Error(`cannot reshape array of size ${W} into shape (${F})`);let fe=V;for(let se=F.length-1;se>=0;se--)fe=fe.reduce((ce,$e)=>{let Ue=ce[ce.length-1];return Ue.lengthnew a("int64",V,[V.length]);async function $(V,F,W,re,fe){return await(await n.TensorOpRegistry.slice)({x:V,s:v(F),e:v(W),a:v(re),t:v(fe??new Array(re.length).fill(1))})}function w(V,F){const W=V.data,re=F.data,fe=[V.dims[0],V.dims[2]],se=new W.constructor(fe[0]*fe[1]),[ce,$e,Ue]=V.dims;let we=0;for(let q=0;qW!==1):typeof F=="number"?V[F]===1&&V.splice(F,1):Array.isArray(F)&&(V=V.filter((W,re)=>W!==1||!F.includes(re))),V}function E(V,F){return F=y(F,V.length+1),V=V.slice(),V.splice(F,0,1),V}function y(V,F,W=null,re=!0){if(V<-F||V>=F){if(re)throw new Error(`IndexError: index ${V} is out of bounds for dimension${W===null?"":" "+W} with size ${F}`);return V<-F?0:F}return V<0&&(V=(V%F+F)%F),V}function b(V,F=0){F=y(F,V[0].dims.length);const W=V[0].dims.slice();W[F]=V.reduce((ce,$e)=>ce+$e.dims[F],0);const re=W.reduce((ce,$e)=>ce*$e,1),fe=new V[0].data.constructor(re),se=V[0].type;if(F===0){let ce=0;for(const $e of V){const Ue=$e.data;fe.set(Ue,ce),ce+=Ue.length}}else{let ce=0;for(let $e=0;$e=0;--pe){const Se=we[pe];let Ae=xe%Se;pe===F&&(Ae+=ce),R+=Ae*Me,Me*=W[pe],xe=Math.floor(xe/Se)}fe[R]=Ue[q]}ce+=we[F]}}return new a(se,fe,W)}function x(V,F=0){return b(V.map(W=>W.unsqueeze(F)),F)}function S(V,F,W=null,re=!1,fe=null){const se=F.data,ce=F.dims;W=y(W,ce.length);const $e=ce.slice();$e[W]=1;const Ue=new se.constructor(se.length/ce[W]);fe!==null&&Ue.fill(fe);for(let we=0;we=0;--R){const Me=ce[R];if(R!==W){const Se=pe%Me;q+=Se*xe,xe*=$e[R]}pe=Math.floor(pe/Me)}Ue[q]=V(Ue[q],se[we],we,q)}return re||$e.splice(W,1),[F.type,Ue,$e]}function A(V,F=null,W=1,re=!1){const fe=V.data,se=V.dims;if(F===null){const xe=fe.reduce((Fe,ze)=>Fe+ze,0)/fe.length,Me=Math.sqrt(fe.reduce((Fe,ze)=>Fe+(ze-xe)**2,0)/(fe.length-W)),Se=new a(V.type,[xe],[]);return[new a(V.type,[Me],[]),Se]}F=y(F,se.length);const ce=B(V,F,re),$e=ce.data,[Ue,we,q]=S((pe,xe,Me,Se)=>pe+(xe-$e[Se])**2,V,F,re);for(let pe=0;pewe+q,0);return new a(V.type,[Ue/fe.length],[])}F=y(F,re.length);const[se,ce,$e]=S((Ue,we)=>Ue+we,V,F,W);if(re[F]!==1)for(let Ue=0;Ue=0;--W)F[W]=re,re*=V[W];return F}function G(V,F,W,re){const fe=V.reduce((se,ce)=>se*ce,1);return new a(W,new re(fe).fill(F),V)}function j(V,F){let W,re;if(typeof F=="number")W="float32",re=Float32Array;else if(typeof F=="bigint")W="int64",re=BigInt64Array;else if(typeof F=="boolean")W="bool",re=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return G(V,F,W,re)}function ee(V,F){return j(V.dims,F)}function H(V){return G(V,1n,"int64",BigInt64Array)}function Z(V){return H(V.dims)}function X(V){return G(V,0n,"int64",BigInt64Array)}function oe(V){return X(V.dims)}function me(V){const F=V.reduce((W,re)=>W*re,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),V)}function ae(V,F){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const W=F==="binary",re=W?"int8":"uint8",fe=W?Int8Array:Uint8Array,se=V.data,ce=new fe(se.length/8);for(let $e=0;$e0?1:0,we=Math.floor($e/8),q=$e%8;ce[we]|=Ue<<7-q,W&&q===0&&(ce[we]-=128)}return new a(re,ce,[V.dims[0],V.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((d,c)=>new n(d,(c+1)/(u.length+1)*p))),this.frames=u,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:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],c=document.createElement("video");if(c.crossOrigin="anonymous",c.muted=!0,typeof l=="string")c.src=l;else if(l instanceof Blob)c.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)c.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(C=>c.onloadedmetadata=C),c.seekable.start(0)===c.seekable.end(0)){const E=await(await fetch(c.src)).blob();c.src=URL.createObjectURL(E),await new Promise(y=>c.onloadedmetadata=y)}const _=c.duration;let f,v;u!=null?(f=u,v=u===1?0:_/(u-1)):(v=1/p,f=Math.floor(_/v));let $=[];for(let C=0;C{c.onseeked=x}),g.drawImage(c,0,0,w.width,w.height);const E=g.getImageData(0,0,w.width,w.height),y=new s.RawImage(E.data,w.width,w.height,4),b=new n(y,C);d.push(b)}return c.remove(),new i(d,_)}}},rb={};function St(e){var r=rb[e];if(r!==void 0)return r.exports;var t=rb[e]={exports:{}};return sT[e](t,t.exports,St),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;St.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 o=Object.create(null);St.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,St.d(o,n),o}})();St.d=(e,r)=>{for(var t in r)St.o(r,t)&&!St.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};St.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);St.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ - !*** ./src/transformers.js ***! - \*****************************/St.r(m),St.d(m,{ASTFeatureExtractor:()=>d.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:()=>o.AutoConfig,AutoFeatureExtractor:()=>c.AutoFeatureExtractor,AutoImageProcessor:()=>v.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:()=>g.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:()=>C.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:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.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:()=>d.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:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>E.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:()=>u.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:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.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:()=>w.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:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>_.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.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:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.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:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.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:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.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:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.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:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>f.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.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:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>$.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>f.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.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:()=>w.Qwen2VLProcessor,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>f.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.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:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.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:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.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:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.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:()=>y.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>C.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.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:()=>w.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:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>C.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.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:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.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=St("./src/env.js"),r=St("./src/pipelines.js"),t=St("./src/models.js"),s=St("./src/tokenizers.js"),o=St("./src/configs.js"),n=St("./src/utils/audio.js"),i=St("./src/utils/image.js"),a=St("./src/utils/video.js"),l=St("./src/utils/tensor.js"),u=St("./src/utils/maths.js"),p=St("./src/base/feature_extraction_utils.js"),d=St("./src/models/feature_extractors.js"),c=St("./src/models/auto/feature_extraction_auto.js"),_=St("./src/base/image_processors_utils.js"),f=St("./src/models/image_processors.js"),v=St("./src/models/auto/image_processing_auto.js"),$=St("./src/base/processing_utils.js"),w=St("./src/models/processors.js"),g=St("./src/models/auto/processing_auto.js"),C=St("./src/generation/streamers.js"),E=St("./src/generation/stopping_criteria.js"),y=St("./src/generation/logits_process.js")})();m.ASTFeatureExtractor;m.ASTForAudioClassification;m.ASTModel;m.ASTPreTrainedModel;m.AlbertForMaskedLM;m.AlbertForQuestionAnswering;m.AlbertForSequenceClassification;m.AlbertModel;m.AlbertPreTrainedModel;m.AlbertTokenizer;m.AudioClassificationPipeline;m.AutoConfig;m.AutoFeatureExtractor;m.AutoImageProcessor;var nT=m.AutoModel;m.AutoModelForAudioClassification;m.AutoModelForAudioFrameClassification;m.AutoModelForAudioTextToText;m.AutoModelForCTC;m.AutoModelForCausalLM;m.AutoModelForDepthEstimation;m.AutoModelForDocumentQuestionAnswering;m.AutoModelForImageClassification;m.AutoModelForImageFeatureExtraction;m.AutoModelForImageMatting;m.AutoModelForImageSegmentation;m.AutoModelForImageTextToText;m.AutoModelForImageToImage;m.AutoModelForMaskGeneration;m.AutoModelForMaskedLM;m.AutoModelForNormalEstimation;m.AutoModelForObjectDetection;m.AutoModelForPoseEstimation;m.AutoModelForQuestionAnswering;m.AutoModelForSemanticSegmentation;m.AutoModelForSeq2SeqLM;m.AutoModelForSequenceClassification;m.AutoModelForSpeechSeq2Seq;m.AutoModelForTextToSpectrogram;m.AutoModelForTextToWaveform;m.AutoModelForTokenClassification;m.AutoModelForUniversalSegmentation;m.AutoModelForVision2Seq;m.AutoModelForXVector;m.AutoModelForZeroShotObjectDetection;var oT=m.AutoProcessor;m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline;m.BackgroundRemovalPipeline;m.BartForConditionalGeneration;m.BartForSequenceClassification;m.BartModel;m.BartPretrainedModel;m.BartTokenizer;m.BaseModelOutput;m.BaseStreamer;m.BeitFeatureExtractor;m.BeitForImageClassification;m.BeitModel;m.BeitPreTrainedModel;m.BertForMaskedLM;m.BertForQuestionAnswering;m.BertForSequenceClassification;m.BertForTokenClassification;m.BertModel;m.BertPreTrainedModel;m.BertTokenizer;m.BitImageProcessor;m.BlenderbotForConditionalGeneration;m.BlenderbotModel;m.BlenderbotPreTrainedModel;m.BlenderbotSmallForConditionalGeneration;m.BlenderbotSmallModel;m.BlenderbotSmallPreTrainedModel;m.BlenderbotSmallTokenizer;m.BlenderbotTokenizer;m.BloomForCausalLM;m.BloomModel;m.BloomPreTrainedModel;m.BloomTokenizer;m.CLIPFeatureExtractor;m.CLIPImageProcessor;m.CLIPModel;m.CLIPPreTrainedModel;m.CLIPSegForImageSegmentation;m.CLIPSegModel;m.CLIPSegPreTrainedModel;m.CLIPTextModel;m.CLIPTextModelWithProjection;m.CLIPTokenizer;m.CLIPVisionModel;m.CLIPVisionModelWithProjection;m.CamembertForMaskedLM;m.CamembertForQuestionAnswering;m.CamembertForSequenceClassification;m.CamembertForTokenClassification;m.CamembertModel;m.CamembertPreTrainedModel;m.CamembertTokenizer;m.CausalLMOutput;m.CausalLMOutputWithPast;m.ChineseCLIPFeatureExtractor;m.ChineseCLIPModel;m.ChineseCLIPPreTrainedModel;m.ClapAudioModelWithProjection;m.ClapFeatureExtractor;m.ClapModel;m.ClapPreTrainedModel;m.ClapTextModelWithProjection;m.ClassifierFreeGuidanceLogitsProcessor;m.CodeGenForCausalLM;m.CodeGenModel;m.CodeGenPreTrainedModel;m.CodeGenTokenizer;m.CodeLlamaTokenizer;m.CohereForCausalLM;m.CohereModel;m.CoherePreTrainedModel;m.CohereTokenizer;m.ConvBertForMaskedLM;m.ConvBertForQuestionAnswering;m.ConvBertForSequenceClassification;m.ConvBertForTokenClassification;m.ConvBertModel;m.ConvBertPreTrainedModel;m.ConvBertTokenizer;m.ConvNextFeatureExtractor;m.ConvNextForImageClassification;m.ConvNextImageProcessor;m.ConvNextModel;m.ConvNextPreTrainedModel;m.ConvNextV2ForImageClassification;m.ConvNextV2Model;m.ConvNextV2PreTrainedModel;m.DPTFeatureExtractor;m.DPTForDepthEstimation;m.DPTImageProcessor;m.DPTModel;m.DPTPreTrainedModel;m.DacDecoderModel;m.DacDecoderOutput;m.DacEncoderModel;m.DacEncoderOutput;m.DacFeatureExtractor;m.DacModel;m.DacPreTrainedModel;m.DataTypeMap;m.DebertaForMaskedLM;m.DebertaForQuestionAnswering;m.DebertaForSequenceClassification;m.DebertaForTokenClassification;m.DebertaModel;m.DebertaPreTrainedModel;m.DebertaTokenizer;m.DebertaV2ForMaskedLM;m.DebertaV2ForQuestionAnswering;m.DebertaV2ForSequenceClassification;m.DebertaV2ForTokenClassification;m.DebertaV2Model;m.DebertaV2PreTrainedModel;m.DebertaV2Tokenizer;m.DecisionTransformerModel;m.DecisionTransformerPreTrainedModel;m.DeiTFeatureExtractor;m.DeiTForImageClassification;m.DeiTImageProcessor;m.DeiTModel;m.DeiTPreTrainedModel;m.DepthAnythingForDepthEstimation;m.DepthAnythingPreTrainedModel;m.DepthEstimationPipeline;m.DepthProForDepthEstimation;m.DepthProPreTrainedModel;m.DetrFeatureExtractor;m.DetrForObjectDetection;m.DetrForSegmentation;m.DetrImageProcessor;m.DetrModel;m.DetrObjectDetectionOutput;m.DetrPreTrainedModel;m.DetrSegmentationOutput;m.Dinov2ForImageClassification;m.Dinov2Model;m.Dinov2PreTrainedModel;m.Dinov2WithRegistersForImageClassification;m.Dinov2WithRegistersModel;m.Dinov2WithRegistersPreTrainedModel;m.DistilBertForMaskedLM;m.DistilBertForQuestionAnswering;m.DistilBertForSequenceClassification;m.DistilBertForTokenClassification;m.DistilBertModel;m.DistilBertPreTrainedModel;m.DistilBertTokenizer;m.DocumentQuestionAnsweringPipeline;m.DonutFeatureExtractor;m.DonutImageProcessor;m.DonutSwinModel;m.DonutSwinPreTrainedModel;m.EfficientNetForImageClassification;m.EfficientNetImageProcessor;m.EfficientNetModel;m.EfficientNetPreTrainedModel;m.ElectraForMaskedLM;m.ElectraForQuestionAnswering;m.ElectraForSequenceClassification;m.ElectraForTokenClassification;m.ElectraModel;m.ElectraPreTrainedModel;m.ElectraTokenizer;m.EncodecFeatureExtractor;m.EosTokenCriteria;m.EsmForMaskedLM;m.EsmForSequenceClassification;m.EsmForTokenClassification;m.EsmModel;m.EsmPreTrainedModel;m.EsmTokenizer;m.ExaoneForCausalLM;m.ExaoneModel;m.ExaonePreTrainedModel;m.FFT;m.FalconForCausalLM;m.FalconModel;m.FalconPreTrainedModel;m.FalconTokenizer;m.FastViTForImageClassification;m.FastViTModel;m.FastViTPreTrainedModel;m.FeatureExtractionPipeline;m.FeatureExtractor;m.FillMaskPipeline;m.Florence2ForConditionalGeneration;m.Florence2PreTrainedModel;m.Florence2Processor;m.ForcedBOSTokenLogitsProcessor;m.ForcedEOSTokenLogitsProcessor;m.GLPNFeatureExtractor;m.GLPNForDepthEstimation;m.GLPNModel;m.GLPNPreTrainedModel;m.GPT2LMHeadModel;m.GPT2Model;m.GPT2PreTrainedModel;m.GPT2Tokenizer;m.GPTBigCodeForCausalLM;m.GPTBigCodeModel;m.GPTBigCodePreTrainedModel;m.GPTJForCausalLM;m.GPTJModel;m.GPTJPreTrainedModel;m.GPTNeoForCausalLM;m.GPTNeoModel;m.GPTNeoPreTrainedModel;m.GPTNeoXForCausalLM;m.GPTNeoXModel;m.GPTNeoXPreTrainedModel;m.GPTNeoXTokenizer;m.Gemma2ForCausalLM;m.Gemma2Model;m.Gemma2PreTrainedModel;m.Gemma3ForCausalLM;m.Gemma3Model;m.Gemma3PreTrainedModel;m.GemmaForCausalLM;m.GemmaModel;m.GemmaPreTrainedModel;m.GemmaTokenizer;m.GlmForCausalLM;m.GlmModel;m.GlmPreTrainedModel;m.GraniteForCausalLM;m.GraniteModel;m.GranitePreTrainedModel;m.Grok1Tokenizer;m.GroundingDinoForObjectDetection;m.GroundingDinoImageProcessor;m.GroundingDinoPreTrainedModel;m.GroundingDinoProcessor;m.GroupViTModel;m.GroupViTPreTrainedModel;m.HeliumForCausalLM;m.HeliumModel;m.HeliumPreTrainedModel;m.HerbertTokenizer;m.HieraForImageClassification;m.HieraModel;m.HieraPreTrainedModel;m.HubertForCTC;m.HubertForSequenceClassification;m.HubertModel;m.HubertPreTrainedModel;m.IJepaForImageClassification;m.IJepaModel;m.IJepaPreTrainedModel;m.Idefics3ForConditionalGeneration;m.Idefics3ImageProcessor;m.Idefics3PreTrainedModel;m.Idefics3Processor;m.ImageClassificationPipeline;m.ImageFeatureExtractionPipeline;m.ImageFeatureExtractor;m.ImageMattingOutput;m.ImageProcessor;m.ImageSegmentationPipeline;m.ImageToImagePipeline;m.ImageToTextPipeline;m.InterruptableStoppingCriteria;m.JAISLMHeadModel;m.JAISModel;m.JAISPreTrainedModel;m.JinaCLIPImageProcessor;m.JinaCLIPModel;m.JinaCLIPPreTrainedModel;m.JinaCLIPProcessor;m.JinaCLIPTextModel;m.JinaCLIPVisionModel;m.LiteWhisperForConditionalGeneration;m.LlamaForCausalLM;m.LlamaModel;m.LlamaPreTrainedModel;m.LlamaTokenizer;m.LlavaForConditionalGeneration;m.LlavaOnevisionForConditionalGeneration;m.LlavaOnevisionImageProcessor;m.LlavaPreTrainedModel;m.LogitsProcessor;m.LogitsProcessorList;m.LogitsWarper;m.LongT5ForConditionalGeneration;m.LongT5Model;m.LongT5PreTrainedModel;m.M2M100ForConditionalGeneration;m.M2M100Model;m.M2M100PreTrainedModel;m.M2M100Tokenizer;m.MBart50Tokenizer;m.MBartForCausalLM;m.MBartForConditionalGeneration;m.MBartForSequenceClassification;m.MBartModel;m.MBartPreTrainedModel;m.MBartTokenizer;m.MPNetForMaskedLM;m.MPNetForQuestionAnswering;m.MPNetForSequenceClassification;m.MPNetForTokenClassification;m.MPNetModel;m.MPNetPreTrainedModel;m.MPNetTokenizer;m.MT5ForConditionalGeneration;m.MT5Model;m.MT5PreTrainedModel;m.MarianMTModel;m.MarianModel;m.MarianPreTrainedModel;m.MarianTokenizer;m.Mask2FormerImageProcessor;m.MaskFormerFeatureExtractor;m.MaskFormerForInstanceSegmentation;m.MaskFormerImageProcessor;m.MaskFormerModel;m.MaskFormerPreTrainedModel;m.MaskedLMOutput;m.MaxLengthCriteria;m.Metric3DForDepthEstimation;m.Metric3DPreTrainedModel;m.Metric3Dv2ForDepthEstimation;m.Metric3Dv2PreTrainedModel;m.MgpstrForSceneTextRecognition;m.MgpstrModelOutput;m.MgpstrPreTrainedModel;m.MgpstrProcessor;m.MgpstrTokenizer;m.MimiDecoderModel;m.MimiDecoderOutput;m.MimiEncoderModel;m.MimiEncoderOutput;m.MimiModel;m.MimiPreTrainedModel;m.MinLengthLogitsProcessor;m.MinNewTokensLengthLogitsProcessor;m.MistralForCausalLM;m.MistralModel;m.MistralPreTrainedModel;m.MobileBertForMaskedLM;m.MobileBertForQuestionAnswering;m.MobileBertForSequenceClassification;m.MobileBertModel;m.MobileBertPreTrainedModel;m.MobileBertTokenizer;m.MobileLLMForCausalLM;m.MobileLLMModel;m.MobileLLMPreTrainedModel;m.MobileNetV1FeatureExtractor;m.MobileNetV1ForImageClassification;m.MobileNetV1ForSemanticSegmentation;m.MobileNetV1ImageProcessor;m.MobileNetV1Model;m.MobileNetV1PreTrainedModel;m.MobileNetV2FeatureExtractor;m.MobileNetV2ForImageClassification;m.MobileNetV2ForSemanticSegmentation;m.MobileNetV2ImageProcessor;m.MobileNetV2Model;m.MobileNetV2PreTrainedModel;m.MobileNetV3FeatureExtractor;m.MobileNetV3ForImageClassification;m.MobileNetV3ForSemanticSegmentation;m.MobileNetV3ImageProcessor;m.MobileNetV3Model;m.MobileNetV3PreTrainedModel;m.MobileNetV4FeatureExtractor;m.MobileNetV4ForImageClassification;m.MobileNetV4ForSemanticSegmentation;m.MobileNetV4ImageProcessor;m.MobileNetV4Model;m.MobileNetV4PreTrainedModel;m.MobileViTFeatureExtractor;m.MobileViTForImageClassification;m.MobileViTImageProcessor;m.MobileViTModel;m.MobileViTPreTrainedModel;m.MobileViTV2ForImageClassification;m.MobileViTV2Model;m.MobileViTV2PreTrainedModel;m.ModelOutput;m.ModernBertForMaskedLM;m.ModernBertForSequenceClassification;m.ModernBertForTokenClassification;m.ModernBertModel;m.ModernBertPreTrainedModel;m.Moondream1ForConditionalGeneration;m.MoonshineFeatureExtractor;m.MoonshineForConditionalGeneration;m.MoonshineModel;m.MoonshinePreTrainedModel;m.MoonshineProcessor;m.MptForCausalLM;m.MptModel;m.MptPreTrainedModel;m.MultiModalityCausalLM;m.MultiModalityPreTrainedModel;m.MusicgenForCausalLM;m.MusicgenForConditionalGeneration;m.MusicgenModel;m.MusicgenPreTrainedModel;m.NllbTokenizer;m.NoBadWordsLogitsProcessor;m.NoRepeatNGramLogitsProcessor;m.NomicBertModel;m.NomicBertPreTrainedModel;m.NougatImageProcessor;m.NougatTokenizer;m.OPTForCausalLM;m.OPTModel;m.OPTPreTrainedModel;m.ObjectDetectionPipeline;m.Olmo2ForCausalLM;m.Olmo2Model;m.Olmo2PreTrainedModel;m.OlmoForCausalLM;m.OlmoModel;m.OlmoPreTrainedModel;m.OpenELMForCausalLM;m.OpenELMModel;m.OpenELMPreTrainedModel;m.OwlViTFeatureExtractor;m.OwlViTForObjectDetection;m.OwlViTImageProcessor;m.OwlViTModel;m.OwlViTPreTrainedModel;m.OwlViTProcessor;m.Owlv2ForObjectDetection;m.Owlv2ImageProcessor;m.Owlv2Model;m.Owlv2PreTrainedModel;m.PaliGemmaForConditionalGeneration;m.PaliGemmaPreTrainedModel;m.PaliGemmaProcessor;m.PatchTSMixerForPrediction;m.PatchTSMixerModel;m.PatchTSMixerPreTrainedModel;m.PatchTSTForPrediction;m.PatchTSTModel;m.PatchTSTPreTrainedModel;m.Phi3ForCausalLM;m.Phi3Model;m.Phi3PreTrainedModel;m.Phi3VForCausalLM;m.Phi3VImageProcessor;m.Phi3VPreTrainedModel;m.Phi3VProcessor;m.PhiForCausalLM;m.PhiModel;m.PhiPreTrainedModel;m.Pipeline;m.PreTrainedModel;m.PreTrainedTokenizer;m.PretrainedConfig;m.PretrainedMixin;m.Processor;m.PvtForImageClassification;m.PvtImageProcessor;m.PvtModel;m.PvtPreTrainedModel;m.PyAnnoteFeatureExtractor;m.PyAnnoteForAudioFrameClassification;m.PyAnnoteModel;m.PyAnnotePreTrainedModel;m.PyAnnoteProcessor;m.QuestionAnsweringModelOutput;m.QuestionAnsweringPipeline;m.Qwen2ForCausalLM;m.Qwen2Model;m.Qwen2PreTrainedModel;m.Qwen2Tokenizer;m.Qwen2VLForConditionalGeneration;m.Qwen2VLImageProcessor;m.Qwen2VLPreTrainedModel;m.Qwen2VLProcessor;m.RFDetrForObjectDetection;m.RFDetrModel;m.RFDetrObjectDetectionOutput;m.RFDetrPreTrainedModel;m.RTDetrForObjectDetection;m.RTDetrImageProcessor;m.RTDetrModel;m.RTDetrObjectDetectionOutput;m.RTDetrPreTrainedModel;m.RTDetrV2ForObjectDetection;m.RTDetrV2Model;m.RTDetrV2ObjectDetectionOutput;m.RTDetrV2PreTrainedModel;m.RawAudio;var sb=m.RawImage;m.RawVideo;m.RawVideoFrame;m.RepetitionPenaltyLogitsProcessor;m.ResNetForImageClassification;m.ResNetModel;m.ResNetPreTrainedModel;m.RoFormerForMaskedLM;m.RoFormerForQuestionAnswering;m.RoFormerForSequenceClassification;m.RoFormerForTokenClassification;m.RoFormerModel;m.RoFormerPreTrainedModel;m.RoFormerTokenizer;m.RobertaForMaskedLM;m.RobertaForQuestionAnswering;m.RobertaForSequenceClassification;m.RobertaForTokenClassification;m.RobertaModel;m.RobertaPreTrainedModel;m.RobertaTokenizer;m.SamImageProcessor;m.SamImageSegmentationOutput;m.SamModel;m.SamPreTrainedModel;m.SamProcessor;m.SapiensForDepthEstimation;m.SapiensForNormalEstimation;m.SapiensForSemanticSegmentation;m.SapiensPreTrainedModel;m.SeamlessM4TFeatureExtractor;m.SegformerFeatureExtractor;m.SegformerForImageClassification;m.SegformerForSemanticSegmentation;m.SegformerImageProcessor;m.SegformerModel;m.SegformerPreTrainedModel;m.Seq2SeqLMOutput;m.SequenceClassifierOutput;m.SiglipImageProcessor;m.SiglipModel;m.SiglipPreTrainedModel;m.SiglipTextModel;m.SiglipTokenizer;m.SiglipVisionModel;m.SmolVLMForConditionalGeneration;m.SmolVLMImageProcessor;m.SmolVLMProcessor;m.SnacDecoderModel;m.SnacEncoderModel;m.SnacFeatureExtractor;m.SnacModel;m.SnacPreTrainedModel;m.SpeechT5FeatureExtractor;m.SpeechT5ForSpeechToText;m.SpeechT5ForTextToSpeech;m.SpeechT5HifiGan;m.SpeechT5Model;m.SpeechT5PreTrainedModel;m.SpeechT5Processor;m.SpeechT5Tokenizer;m.SqueezeBertForMaskedLM;m.SqueezeBertForQuestionAnswering;m.SqueezeBertForSequenceClassification;m.SqueezeBertModel;m.SqueezeBertPreTrainedModel;m.SqueezeBertTokenizer;m.StableLmForCausalLM;m.StableLmModel;m.StableLmPreTrainedModel;m.Starcoder2ForCausalLM;m.Starcoder2Model;m.Starcoder2PreTrainedModel;m.StoppingCriteria;m.StoppingCriteriaList;m.StyleTextToSpeech2Model;m.StyleTextToSpeech2PreTrainedModel;m.SummarizationPipeline;m.SuppressTokensAtBeginLogitsProcessor;m.Swin2SRForImageSuperResolution;m.Swin2SRImageProcessor;m.Swin2SRModel;m.Swin2SRPreTrainedModel;m.SwinForImageClassification;m.SwinForSemanticSegmentation;m.SwinModel;m.SwinPreTrainedModel;m.T5ForConditionalGeneration;m.T5Model;m.T5PreTrainedModel;m.T5Tokenizer;m.TableTransformerForObjectDetection;m.TableTransformerModel;m.TableTransformerObjectDetectionOutput;m.TableTransformerPreTrainedModel;m.TemperatureLogitsWarper;m.Tensor;m.Text2TextGenerationPipeline;m.TextClassificationPipeline;m.TextGenerationPipeline;m.TextStreamer;m.TextToAudioPipeline;m.TokenClassificationPipeline;m.TokenClassifierOutput;m.TokenizerModel;m.TopKLogitsWarper;m.TopPLogitsWarper;m.TrOCRForCausalLM;m.TrOCRPreTrainedModel;m.TranslationPipeline;m.UltravoxModel;m.UltravoxPreTrainedModel;m.UltravoxProcessor;m.UniSpeechForCTC;m.UniSpeechForSequenceClassification;m.UniSpeechModel;m.UniSpeechPreTrainedModel;m.UniSpeechSatForAudioFrameClassification;m.UniSpeechSatForCTC;m.UniSpeechSatForSequenceClassification;m.UniSpeechSatModel;m.UniSpeechSatPreTrainedModel;m.VLChatProcessor;m.VLMImageProcessor;m.ViTFeatureExtractor;m.ViTForImageClassification;m.ViTImageProcessor;m.ViTMAEModel;m.ViTMAEPreTrainedModel;m.ViTMSNForImageClassification;m.ViTMSNModel;m.ViTMSNPreTrainedModel;m.ViTModel;m.ViTPreTrainedModel;m.VisionEncoderDecoderModel;m.VitMatteForImageMatting;m.VitMatteImageProcessor;m.VitMattePreTrainedModel;m.VitPoseForPoseEstimation;m.VitPoseImageProcessor;m.VitPosePreTrainedModel;m.VitsModel;m.VitsModelOutput;m.VitsPreTrainedModel;m.VitsTokenizer;m.Wav2Vec2BertForCTC;m.Wav2Vec2BertForSequenceClassification;m.Wav2Vec2BertModel;m.Wav2Vec2BertPreTrainedModel;m.Wav2Vec2CTCTokenizer;m.Wav2Vec2FeatureExtractor;m.Wav2Vec2ForAudioFrameClassification;m.Wav2Vec2ForCTC;m.Wav2Vec2ForSequenceClassification;m.Wav2Vec2Model;m.Wav2Vec2PreTrainedModel;m.Wav2Vec2Processor;m.Wav2Vec2ProcessorWithLM;m.WavLMForAudioFrameClassification;m.WavLMForCTC;m.WavLMForSequenceClassification;m.WavLMForXVector;m.WavLMModel;m.WavLMPreTrainedModel;m.WeSpeakerFeatureExtractor;m.WeSpeakerResNetModel;m.WeSpeakerResNetPreTrainedModel;m.WhisperFeatureExtractor;m.WhisperForConditionalGeneration;m.WhisperModel;m.WhisperPreTrainedModel;m.WhisperProcessor;m.WhisperTextStreamer;m.WhisperTimeStampLogitsProcessor;m.WhisperTokenizer;m.XLMForQuestionAnswering;m.XLMForSequenceClassification;m.XLMForTokenClassification;m.XLMModel;m.XLMPreTrainedModel;m.XLMRobertaForMaskedLM;m.XLMRobertaForQuestionAnswering;m.XLMRobertaForSequenceClassification;m.XLMRobertaForTokenClassification;m.XLMRobertaModel;m.XLMRobertaPreTrainedModel;m.XLMRobertaTokenizer;m.XLMTokenizer;m.XLMWithLMHeadModel;m.XVectorOutput;m.YolosFeatureExtractor;m.YolosForObjectDetection;m.YolosImageProcessor;m.YolosModel;m.YolosObjectDetectionOutput;m.YolosPreTrainedModel;m.ZeroShotAudioClassificationPipeline;m.ZeroShotClassificationPipeline;m.ZeroShotImageClassificationPipeline;m.ZeroShotObjectDetectionPipeline;m.bankers_round;m.cat;m.cos_sim;m.dot;m.dynamic_time_warping;var iT=m.env;m.full;m.full_like;m.getKeyValueShapes;m.hamming;m.hanning;m.interpolate;m.interpolate_4d;m.interpolate_data;m.is_chinese_char;m.layer_norm;m.load_image;m.load_video;m.log_softmax;m.magnitude;m.matmul;m.max;m.mean;m.mean_pooling;m.medianFilter;m.mel_filter_bank;m.min;m.ones;m.ones_like;m.permute;m.permute_data;m.pipeline;m.quantize_embeddings;m.rand;m.read_audio;m.rfft;m.round;m.slice;m.softmax;m.spectrogram;m.stack;m.std_mean;m.topk;m.window_function;m.zeros;m.zeros_like;async function aT(){try{if(lT())return{supported:!1,isNode:!0,reason:"",fp16Supported:!1};if(typeof navigator>"u"||!navigator.gpu)return{supported:!1,isNode:!1,reason:"WebGPU is not available (navigator.gpu is undefined)",fp16Supported:!1};const e=await navigator.gpu.requestAdapter();return e?{supported:!0,isNode:!1,reason:"",adapter:e,fp16Supported:e.features.has("shader-f16")}:{supported:!1,isNode:!1,reason:"WebGPU is not supported (no adapter found)",fp16Supported:!1}}catch(e){return{supported:!1,isNode:!1,reason:e instanceof Error?e.toString():String(e),fp16Supported:!1}}}function lT(){return typeof process<"u"&&"versions"in process&&process.versions!=null&&typeof process.versions=="object"&&"node"in process.versions&&process.versions.node!=null}const uT={flex:"","flex-col":"","items-center":"","gap-4":""},dT=["disabled"],cT={"h-full":"","w-full":"",flex:"","gap-2":""},pT={w:"[50%]",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","min-h":"120",h:"auto","overflow-hidden":"","rounded-lg":""},hT=["src"],mT={w:"[50%]",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","min-h":"120",h:"auto",relative:"","overflow-hidden":"","rounded-lg":""},fT={key:0,bg:"black/50",absolute:"","inset-0":"","z-10":"",flex:"","flex-col":"","items-center":"","justify-center":""},_T={"mb-4":"","text-white":"","font-medium":""},gT={bg:"gray-200/30",w:"70%","h-2":"","overflow-hidden":"","rounded-full":""},wT=["src"],bT={bg:"black/0 group-hover:black/20",absolute:"","inset-0":"",flex:"","items-center":"","justify-center":"","transition-all":"","duration-200":""},MT=["onClick"],yT={key:1,absolute:"","bottom-2":"","right-2":""},ST=pv({__name:"background-remove",setup(e){const r=ks(),t=ks(),s=ks(),o=ks(),n=ks(!1),i=ks(0),a=ks(),l=ks(),u=ks([]),p=hv(()=>u.value.map(f=>URL.createObjectURL(f)));mv(async()=>{try{if(!(await aT()).supported)throw new Error("WebGPU is not supported in this browser.");const f="Xenova/modnet";iT.backends.onnx.wasm.proxy=!1,r.value??(r.value=await nT.from_pretrained(f,{device:"webgpu"})),t.value??(t.value=await oT.from_pretrained(f,{}))}catch(f){s.value=f}o.value=!1});async function d(){if(!r.value||!t.value)return;n.value=!0,i.value=0,a.value=[];const f=p.value.length;for(let v=0;v=a.value.length||!u.value[f])return;const v=u.value[f].name,$=v.substring(0,v.lastIndexOf("."))||v,w=v.substring(v.lastIndexOf("."))||".png",g=`${$}-background-removed${w}`,C=document.createElement("a");C.href=a.value[f],C.download=g,document.body.appendChild(C),C.click(),document.body.removeChild(C)}function _(){!a.value||a.value.length===0||a.value.forEach((f,v)=>{setTimeout(()=>c(v),v*100)})}return(f,v)=>(En(),Tn("div",uT,[Sr("button",{bg:"neutral-100 dark:neutral-800","w-full":"","cursor-pointer":"","rounded-lg":"","px-3":"","py-2":"",disabled:n.value,onClick:d},wf(n.value?"Processing...":"Process"),9,dT),Sr("div",cT,[Sr("div",pT,[(En(!0),Tn(bf,null,Mf(p.value,($,w)=>(En(),Tn("img",{key:w,src:$,"h-full":"","w-full":"","object-cover":""},null,8,hT))),128))]),Sr("div",mT,[n.value?(En(),Tn("div",fT,[Sr("div",_T,wf(i.value)+"% ",1),Sr("div",gT,[Sr("div",{bg:"emerald-500","h-full":"",style:_v({width:`${i.value}%`}),"transition-all":"","duration-200":""},null,4)])])):yf("",!0),(En(!0),Tn(bf,null,Mf(a.value,($,w)=>(En(),Tn("div",{key:w,relative:"",class:"group","h-full":"","w-full":""},[Sr("img",{src:$,"h-full":"","w-full":"","object-cover":""},null,8,wT),Sr("div",bT,[Sr("button",{bg:"emerald-500 hover:emerald-600","rounded-full":"","p-2":"","text-white":"","opacity-0":"","transition-all":"","duration-200":"","group-hover:opacity-100":"",onClick:g=>c(w)},v[1]||(v[1]=[Sr("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[Sr("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1)]),8,MT)])]))),128)),a.value&&a.value.length>1?(En(),Tn("div",yT,[Sr("button",{bg:"emerald-500 hover:emerald-600","rounded-full":"","p-2":"","text-white":"",onClick:_},v[2]||(v[2]=[Sr("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[Sr("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"})],-1)]))])):yf("",!0)])]),fv(gv(cv),{modelValue:u.value,"onUpdate:modelValue":v[0]||(v[0]=$=>u.value=$),"w-full":""},null,8,["modelValue"])]))}});export{ST as default}; diff --git a/assets/chat-7V8Q9Hlp.js b/assets/chat-C6ApJPfV.js similarity index 94% rename from assets/chat-7V8Q9Hlp.js rename to assets/chat-C6ApJPfV.js index 33fbb68a3a2629a8113c54243cc8e80000350d78..dc50f223b9e865a7b165d36f4be38c874fa38f6f 100644 --- a/assets/chat-7V8Q9Hlp.js +++ b/assets/chat-C6ApJPfV.js @@ -1 +1 @@ -import{d as D,q as W,r as S,c as h,o as y,e as i,x as C,y as E,b as M,Q as A,F as N,l as P,bD as z,j as U,t as $}from"./index-BQKiy4UR.js";import{s as K}from"./index-C4mUnpiM.js";import"./index-LHmcipjy.js";var q=()=>{let e=null;return{getStore:()=>(e===null&&console.warn("Woops! Looks like you are calling `getContext` after `await fn()`. Please move `getContext` to top level of handler."),e),run(r,o){e=r;try{return o()}finally{e=null}}}},H=new WeakMap,F=new WeakMap,I=0,T=0,_=e=>{const r=`${I++}`,o={include:t=>n.has(t),with:t=>{const d=`${T++}`,l={[Symbol.toStringTag]:`WorkflowEvent(${r}.${d})`,toString:()=>`WorkflowEvent(${r}.${d})`,toJSON:()=>({event:r,data:t}),get data(){return t}};return n.add(l),Object.freeze(l),F.set(l,o),l}},n=new WeakSet;return H.set(o,n),Object.defineProperty(o,Symbol.toStringTag,{get:()=>`WorkflowEvent<${r}>`}),Object.defineProperty(o,"displayName",{value:`WorkflowEvent<${r}>`}),o.toString=()=>`WorkflowEvent<${r}>`,Object.freeze(o),o},j=e=>e!=null&&typeof e=="object"&&"data"in e,J=e=>e!=null&&typeof e.then=="function";function R(e,r){const o=new Array(e.length);for(const n of r)for(let t=0;t{const r=[],o=(a,f,p)=>{let c;const g={get abortController(){return c||(c=new AbortController),c},handler:a,inputs:f,outputs:[],prev:p,next:new Set};g.prev.next.add(g);const v=d(g);Q.run(g,()=>{const s=[...new Set([...x.__internal__call_context,...v.__internal__call_context])];B.run(v,()=>{let u=0;const b=()=>{if(u===s.length){let k;try{k=a(...f)}catch(m){if(c??l)(c??l).abort(m);else throw console.error("unhandled error in handler",m),m}J(k)?k.then(m=>{j(m)&&v.sendEvent(m)}):j(k)&&v.sendEvent(k)}const L=s[u];L&&(u++,L(v,f,b))};b()})})},n=a=>{const f=[...r];[...e].filter(([p])=>R(p,f).length===p.length).map(([p,c])=>{const g=R(p,f);g.forEach(v=>{r.splice(r.indexOf(v),1)});for(const v of c)o(v.handler,g,a)})},t=[],d=a=>({get stream(){let f;return new ReadableStream({start:async p=>{f=c=>{let g=O.get(c);for(;g;){if(g===a){p.enqueue(c);break}g=g.prev}},t.push(f)}})},get signal(){return a.abortController.signal},sendEvent:(...f)=>{f.forEach(p=>{O.set(p,a),a.outputs.push(p),r.push(p),t.forEach(c=>c(p)),n(a)})},__internal__call_context:new Set});let l=new AbortController;const x=d({get abortController(){return l||(l=new AbortController),l},inputs:[],outputs:[],handler:null,prev:null,next:new Set});return x};function X(){const e={steps:new Map};return{handle:(r,o)=>{if(e.steps.has(r)){const n=e.steps.get(r),t={get handler(){return o},unsubscribe:()=>{n.delete(t),n.size===0&&e.steps.delete(r)}};return n.add(t),t}else{const n=new Set,t={get handler(){return o},unsubscribe:()=>{n.delete(t),n.size===0&&e.steps.delete(r)}};return n.add(t),e.steps.set(r,n),t}},createContext(){return G({listeners:e.steps})}}}async function Y(e,r,o){const{stream:n,sendEvent:t}=e.createContext();t(r);for await(const d of n)if(o.include(d))return d;throw new Error("Workflow did not return a stop event")}function Z(e,r){const o=(...n)=>{const t=r.filter(([w])=>w.every((x,a)=>x.include(n[a]))).map(([w,x])=>x),l=V().sendEvent;return(...w)=>{let x=!1;for(let a=0;ap.include(w[c]))){x=!0;break}}return x&&console.warn("Invalid input detected [%s]",w.map(a=>a.data).join(", ")),l(...w)}};return{...e,handle:(n,t)=>{const d=(...l)=>{const w=V();return t(w.safeSendEvent,...l)};return e.handle(n,d)},createContext(){const n=e.createContext();return n.__internal__call_context.add((t,d,l)=>{t.safeSendEvent=o(...d),l()}),n}}}const ee={flex:"","flex-col":"","gap-2":""},te={flex:"~ col","gap-2":""},ne={flex:"","flex-col":"","gap-2":""},re={grid:"","grid-cols-2":"","gap-2":""},oe={flex:"","items-center":"","gap-2":""},ae={flex:"","items-center":"","gap-2":""},le={flex:"","items-center":"","gap-2":""},se={key:0},ue={key:1},fe=D({__name:"chat",setup(e){const r=W("settings/llm/baseUrl","https://openrouter.ai/api/v1/"),o=W("settings/llm/apiKey",""),n=W("settings/llm/model","openai/gpt-4o-mini"),t=S(""),d=S([]),l=S({role:"assistant",content:""}),w=S(!1),x=_(),a=_(),f=_(),p=_(),c=_();async function g(){w.value=!0;try{const v=Z(X(),[[[x],[a,c]],[[a],[f]],[[f],[p]]]);v.handle([x],async s=>{l.value={role:"assistant",content:""},d.value.push({role:"user",content:t.value}),d.value.push(l.value);const u=await K({baseURL:r.value,apiKey:o.value,model:n.value,messages:d.value.slice(0,d.value.length-1).map(b=>z(b))});for await(const b of u.chunkStream)s(a.with(b.choices[0].delta.content||""));return c.with()}),v.handle([a],async(s,u)=>{l.value.content?l.value.content+=u.data:l.value.content=u.data}),await Y(v,x.with(),c)}catch(v){console.error(v)}finally{w.value=!1}}return(v,s)=>(y(),h("div",ee,[i("div",te,[i("div",ne,[s[7]||(s[7]=i("div",null,[i("span",{"text-neutral-500":"","dark:text-neutral-400":""},"LLM")],-1)),i("div",re,[i("label",oe,[s[4]||(s[4]=i("span",{"text-nowrap":""}," Base URL ",-1)),C(i("input",{"onUpdate:modelValue":s[0]||(s[0]=u=>A(r)?r.value=u:null),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,512),[[E,M(r)]])]),i("label",ae,[s[5]||(s[5]=i("span",{"text-nowrap":""}," API Key ",-1)),C(i("input",{"onUpdate:modelValue":s[1]||(s[1]=u=>A(o)?o.value=u:null),type:"password",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,512),[[E,M(o)]])]),i("label",le,[s[6]||(s[6]=i("span",{"text-nowrap":""}," Model ",-1)),C(i("input",{"onUpdate:modelValue":s[2]||(s[2]=u=>A(n)?n.value=u:null),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,512),[[E,M(n)]])])])]),i("div",null,[C(i("textarea",{"onUpdate:modelValue":s[3]||(s[3]=u=>t.value=u),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,512),[[E,t.value]])]),i("button",{"rounded-lg":"",bg:"blue-100 dark:blue-900","px-4":"","py-2":"",onClick:g}," Send "),i("div",null,[(y(!0),h(N,null,P(d.value,(u,b)=>(y(),h("div",{key:b},[u.role==="user"?(y(),h("div",se,[i("span",null,$(u.content),1)])):U("",!0),u.role==="assistant"?(y(),h("div",ue,[i("span",null,$(u.content),1)])):U("",!0)]))),128))])])]))}});export{fe as default}; +import{d as N,q as W,r as S,c as h,o as y,e as i,x as C,y as E,b as M,Q as A,F as P,l as z,b6 as D,j as U,t as $}from"./index-CQudhZin.js";import{s as K}from"./index-C4mUnpiM.js";import"./index-LHmcipjy.js";var q=()=>{let e=null;return{getStore:()=>(e===null&&console.warn("Woops! Looks like you are calling `getContext` after `await fn()`. Please move `getContext` to top level of handler."),e),run(r,o){e=r;try{return o()}finally{e=null}}}},H=new WeakMap,F=new WeakMap,I=0,T=0,_=e=>{const r=`${I++}`,o={include:t=>n.has(t),with:t=>{const d=`${T++}`,l={[Symbol.toStringTag]:`WorkflowEvent(${r}.${d})`,toString:()=>`WorkflowEvent(${r}.${d})`,toJSON:()=>({event:r,data:t}),get data(){return t}};return n.add(l),Object.freeze(l),F.set(l,o),l}},n=new WeakSet;return H.set(o,n),Object.defineProperty(o,Symbol.toStringTag,{get:()=>`WorkflowEvent<${r}>`}),Object.defineProperty(o,"displayName",{value:`WorkflowEvent<${r}>`}),o.toString=()=>`WorkflowEvent<${r}>`,Object.freeze(o),o},j=e=>e!=null&&typeof e=="object"&&"data"in e,J=e=>e!=null&&typeof e.then=="function";function R(e,r){const o=new Array(e.length);for(const n of r)for(let t=0;t{const r=[],o=(a,f,p)=>{let c;const g={get abortController(){return c||(c=new AbortController),c},handler:a,inputs:f,outputs:[],prev:p,next:new Set};g.prev.next.add(g);const v=d(g);Q.run(g,()=>{const s=[...new Set([...x.__internal__call_context,...v.__internal__call_context])];B.run(v,()=>{let u=0;const b=()=>{if(u===s.length){let k;try{k=a(...f)}catch(m){if(c??l)(c??l).abort(m);else throw console.error("unhandled error in handler",m),m}J(k)?k.then(m=>{j(m)&&v.sendEvent(m)}):j(k)&&v.sendEvent(k)}const L=s[u];L&&(u++,L(v,f,b))};b()})})},n=a=>{const f=[...r];[...e].filter(([p])=>R(p,f).length===p.length).map(([p,c])=>{const g=R(p,f);g.forEach(v=>{r.splice(r.indexOf(v),1)});for(const v of c)o(v.handler,g,a)})},t=[],d=a=>({get stream(){let f;return new ReadableStream({start:async p=>{f=c=>{let g=O.get(c);for(;g;){if(g===a){p.enqueue(c);break}g=g.prev}},t.push(f)}})},get signal(){return a.abortController.signal},sendEvent:(...f)=>{f.forEach(p=>{O.set(p,a),a.outputs.push(p),r.push(p),t.forEach(c=>c(p)),n(a)})},__internal__call_context:new Set});let l=new AbortController;const x=d({get abortController(){return l||(l=new AbortController),l},inputs:[],outputs:[],handler:null,prev:null,next:new Set});return x};function X(){const e={steps:new Map};return{handle:(r,o)=>{if(e.steps.has(r)){const n=e.steps.get(r),t={get handler(){return o},unsubscribe:()=>{n.delete(t),n.size===0&&e.steps.delete(r)}};return n.add(t),t}else{const n=new Set,t={get handler(){return o},unsubscribe:()=>{n.delete(t),n.size===0&&e.steps.delete(r)}};return n.add(t),e.steps.set(r,n),t}},createContext(){return G({listeners:e.steps})}}}async function Y(e,r,o){const{stream:n,sendEvent:t}=e.createContext();t(r);for await(const d of n)if(o.include(d))return d;throw new Error("Workflow did not return a stop event")}function Z(e,r){const o=(...n)=>{const t=r.filter(([w])=>w.every((x,a)=>x.include(n[a]))).map(([w,x])=>x),l=V().sendEvent;return(...w)=>{let x=!1;for(let a=0;ap.include(w[c]))){x=!0;break}}return x&&console.warn("Invalid input detected [%s]",w.map(a=>a.data).join(", ")),l(...w)}};return{...e,handle:(n,t)=>{const d=(...l)=>{const w=V();return t(w.safeSendEvent,...l)};return e.handle(n,d)},createContext(){const n=e.createContext();return n.__internal__call_context.add((t,d,l)=>{t.safeSendEvent=o(...d),l()}),n}}}const ee={flex:"","flex-col":"","gap-2":""},te={flex:"~ col","gap-2":""},ne={flex:"","flex-col":"","gap-2":""},re={grid:"","grid-cols-2":"","gap-2":""},oe={flex:"","items-center":"","gap-2":""},ae={flex:"","items-center":"","gap-2":""},le={flex:"","items-center":"","gap-2":""},se={key:0},ue={key:1},fe=N({__name:"chat",setup(e){const r=W("settings/llm/baseUrl","https://openrouter.ai/api/v1/"),o=W("settings/llm/apiKey",""),n=W("settings/llm/model","openai/gpt-4o-mini"),t=S(""),d=S([]),l=S({role:"assistant",content:""}),w=S(!1),x=_(),a=_(),f=_(),p=_(),c=_();async function g(){w.value=!0;try{const v=Z(X(),[[[x],[a,c]],[[a],[f]],[[f],[p]]]);v.handle([x],async s=>{l.value={role:"assistant",content:""},d.value.push({role:"user",content:t.value}),d.value.push(l.value);const u=await K({baseURL:r.value,apiKey:o.value,model:n.value,messages:d.value.slice(0,d.value.length-1).map(b=>D(b))});for await(const b of u.chunkStream)s(a.with(b.choices[0].delta.content||""));return c.with()}),v.handle([a],async(s,u)=>{l.value.content?l.value.content+=u.data:l.value.content=u.data}),await Y(v,x.with(),c)}catch(v){console.error(v)}finally{w.value=!1}}return(v,s)=>(y(),h("div",ee,[i("div",te,[i("div",ne,[s[7]||(s[7]=i("div",null,[i("span",{"text-neutral-500":"","dark:text-neutral-400":""},"LLM")],-1)),i("div",re,[i("label",oe,[s[4]||(s[4]=i("span",{"text-nowrap":""}," Base URL ",-1)),C(i("input",{"onUpdate:modelValue":s[0]||(s[0]=u=>A(r)?r.value=u:null),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,512),[[E,M(r)]])]),i("label",ae,[s[5]||(s[5]=i("span",{"text-nowrap":""}," API Key ",-1)),C(i("input",{"onUpdate:modelValue":s[1]||(s[1]=u=>A(o)?o.value=u:null),type:"password",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,512),[[E,M(o)]])]),i("label",le,[s[6]||(s[6]=i("span",{"text-nowrap":""}," Model ",-1)),C(i("input",{"onUpdate:modelValue":s[2]||(s[2]=u=>A(n)?n.value=u:null),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,512),[[E,M(n)]])])])]),i("div",null,[C(i("textarea",{"onUpdate:modelValue":s[3]||(s[3]=u=>t.value=u),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,512),[[E,t.value]])]),i("button",{"rounded-lg":"",bg:"blue-100 dark:blue-900","px-4":"","py-2":"",onClick:g}," Send "),i("div",null,[(y(!0),h(P,null,z(d.value,(u,b)=>(y(),h("div",{key:b},[u.role==="user"?(y(),h("div",se,[i("span",null,$(u.content),1)])):U("",!0),u.role==="assistant"?(y(),h("div",ue,[i("span",null,$(u.content),1)])):U("",!0)]))),128))])])]))}});export{fe as default}; diff --git a/assets/cloudflare-workers-ai-CJorqeuz.js b/assets/cloudflare-workers-ai-CmLRkAJ-.js similarity index 78% rename from assets/cloudflare-workers-ai-CJorqeuz.js rename to assets/cloudflare-workers-ai-CmLRkAJ-.js index 9b212b786e19f7ae4aca049c48bca0d57868a847..afd0f23d2ba17e98513e47c438b4bb49d826d996 100644 --- a/assets/cloudflare-workers-ai-CJorqeuz.js +++ b/assets/cloudflare-workers-ai-CmLRkAJ-.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as k,m as y,u as M,A as I,o as h,b as l,g as $,S as q,s as x,h as v,H as K,v as A,w as f,i as c}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as P}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as S}from"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import{_ as z}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as B,a as C}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as N}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as V}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const R=k({__name:"ProviderAccountIdInput",props:y({placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(p){const r=p,u=M(p,"modelValue");return(n,e)=>(h(),I(l(S),{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",U=k({__name:"cloudflare-workers-ai",setup(p){const{t:r}=$(),u=q(),n=P(),{providers:e}=x(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}});K(()=>{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)||""}),A([s,d],()=>{e.value[a]={...e.value[a],apiKey:s.value,accountId:d.value}});function w(){var o;e.value[a]={...(o=t.value)==null?void 0:o.defaultOptions}}return(o,i)=>{var _,g;return h(),I(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":w},{default:f(()=>{var b;return[c(l(z),{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"])}}});typeof V=="function"&&V(U);export{U as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as k,m as y,u as M,A as I,o as h,b as l,g as $,S as q,s as x,h as v,H as K,v as A,w as f,i as c}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as P}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as S}from"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import{_ as z}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as B,a as C}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as N}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as V}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const R=k({__name:"ProviderAccountIdInput",props:y({placeholder:null,required:{type:Boolean},label:null,description:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(p){const r=p,u=M(p,"modelValue");return(n,e)=>(h(),I(l(S),{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",U=k({__name:"cloudflare-workers-ai",setup(p){const{t:r}=$(),u=q(),n=P(),{providers:e}=x(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}});K(()=>{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)||""}),A([s,d],()=>{e.value[a]={...e.value[a],apiKey:s.value,accountId:d.value}});function w(){var o;e.value[a]={...(o=t.value)==null?void 0:o.defaultOptions}}return(o,i)=>{var _,g;return h(),I(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":w},{default:f(()=>{var b;return[c(l(z),{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"])}}});typeof V=="function"&&V(U);export{U as default}; diff --git a/assets/consciousness-DS3QILRV.js b/assets/consciousness-BmgC4h1A.js similarity index 90% rename from assets/consciousness-DS3QILRV.js rename to assets/consciousness-BmgC4h1A.js index 6e686de0248aee353a306a2d599d07bfe7818189..44c818221d2d07f46bc45dc70716cddf53f6d36a 100644 --- a/assets/consciousness-DS3QILRV.js +++ b/assets/consciousness-BmgC4h1A.js @@ -1 +1 @@ -import{p as P,q as n,r as M,h as r,v as L}from"./index-BQKiy4UR.js";import{u as w}from"./providers-kjOpfeNb.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)),p=r(()=>o.isLoadingModels[s.value]||!1),f=r(()=>o.modelLoadError[s.value]||null),g=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:p,activeProviderModelError:f,filteredModels:g,resetModelSelection:u,loadModelsForProvider:v}});export{h as u}; +import{p as P,q as n,r as M,h as r,v as L}from"./index-CQudhZin.js";import{u as w}from"./providers-Y3Mr8_DF.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)),p=r(()=>o.isLoadingModels[s.value]||!1),f=r(()=>o.modelLoadError[s.value]||null),g=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:p,activeProviderModelError:f,filteredModels:g,resetModelSelection:u,loadModelsForProvider:v}});export{h as u}; diff --git a/assets/consciousness-zgXn05x5.js b/assets/consciousness-CS4IBC4q.js similarity index 93% rename from assets/consciousness-zgXn05x5.js rename to assets/consciousness-CS4IBC4q.js index f313e1bdff79b82ad7cbfea86382964e718dcf17..158abdf619dd9e9dbd2e2914ff1c03dce8f24a03 100644 --- a/assets/consciousness-zgXn05x5.js +++ b/assets/consciousness-CS4IBC4q.js @@ -1 +1 @@ -import{d as R,s as h,g as U,H as z,K as B,c as r,o as n,e,x as b,j as f,t as i,b as s,F as k,l as D,i as j,w as q,P as F,A as y,Q as u,y as Q}from"./index-BQKiy4UR.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as T}from"./consciousness-DS3QILRV.js";import{u as A}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{R as E,a as G}from"./RadioCardSimple-DdnP6Fc5.js";import{b as M}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const H={bg:"neutral-50 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4"},I={flex:"~ col gap-4"},K={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-500"},J={text:"neutral-400 dark:neutral-400"},O={"max-w-full":""},W={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},X={key:1},Y={key:0},Z={flex:"~ col gap-4"},$={class:"text-lg md:text-2xl"},ee={text:"neutral-400 dark:neutral-400"},se={key:0,class:"flex items-center justify-center py-4"},te={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"},oe={class:"flex flex-col"},ie={class:"font-medium"},ne={class:"text-sm text-red-600 dark:text-red-400"},le={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"},re={class:"flex flex-col"},de={class:"font-medium"},ae={class:"text-sm text-amber-600 dark:text-amber-400"},ce={key:1},ue={flex:"~ col gap-4"},pe={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},me={text:"neutral-400 dark:neutral-500"},xe={class:"flex items-center gap-3 border border-primary-200 rounded-lg bg-primary-50 p-4 dark:border-primary-800 dark:bg-primary-900/20"},ve={class:"flex flex-col"},ge={class:"font-medium"},_e={class:"text-sm text-primary-600 dark:text-primary-400"},he={class:"mt-2"},be={class:"mb-1 block text-sm font-medium"},fe=["placeholder"],ke={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},ye=R({__name:"consciousness",setup(Me){const w=A(),m=T(),{availableProviders:V,availableTextGenerationsProvidersMetadata:C}=h(w),{activeProvider:d,activeModel:a,customModelName:P,modelSearchQuery:c,supportsModelListing:x,providerModels:p,isLoadingActiveProviderModels:v,activeProviderModelError:g}=h(m),{t}=U();z(async()=>{await m.loadModelsForProvider(d.value)});function S(_){P.value=_}return(_,o)=>{const N=B("motion");return n(),r(k,null,[e("div",H,[e("div",null,[e("div",I,[e("div",null,[e("h2",K,i(s(t)("settings.pages.providers.title")),1),e("div",J,[e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.description")),1)])]),e("div",O,[s(V).length>0?(n(),r("fieldset",W,[(n(!0),r(k,null,D(s(C),l=>(n(),y(s(G),{id:l.id,key:l.id,modelValue:s(d),"onUpdate:modelValue":o[0]||(o[0]=L=>u(d)?d.value=L:null),name:"provider",value:l.id,title:l.localizedName,description:l.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(n(),r("div",X,[j(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:q(()=>o[4]||(o[4]=[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)?(n(),r("div",Y,[e("div",Z,[e("div",null,[e("h2",$,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",ee,[e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),s(v)?(n(),r("div",se,[o[5]||(o[5]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):s(g)?(n(),r("div",te,[o[6]||(o[6]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",oe,[e("span",ie,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",ne,i(s(g)),1)])])):s(p).length===0&&!s(v)?(n(),r("div",le,[o[7]||(o[7]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",re,[e("span",de,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",ae,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):s(p).length>0?(n(),y(s(E),{key:3,modelValue:s(a),"onUpdate:modelValue":o[1]||(o[1]=l=>u(a)?a.value=l:null),"search-query":s(c),"onUpdate:searchQuery":o[2]||(o[2]=l=>u(c)?c.value=l:null),items:s(p),searchable:!0,"search-placeholder":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:s(c)}),"search-results-text":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":S},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)?(n(),r("div",ce,[e("div",ue,[e("div",null,[e("h2",pe,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",me,[e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),e("div",xe,[o[8]||(o[8]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-primary-500 dark:text-primary-400"},null,-1)),e("div",ve,[e("span",ge,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported")),1),e("span",_e,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported_description")),1)])]),e("div",he,[e("label",be,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_name")),1),b(e("input",{"onUpdate:modelValue":o[3]||(o[3]=l=>u(a)?a.value=l: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(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_placeholder")},null,8,fe),[[Q,s(a)]])])])])):f("",!0)]),b((n(),r("div",ke,o[9]||(o[9]=[e("div",{text:"60","i-solar:ghost-bold-duotone":""},null,-1)]))),[[N]])],64)}}});typeof M=="function"&&M(ye);export{ye as default}; +import{d as R,s as h,g as U,H as z,K as B,c as r,o as n,e,x as b,j as f,t as i,b as s,F as k,l as D,i as j,w as q,P as F,A as y,Q as u,y as Q}from"./index-CQudhZin.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as T}from"./consciousness-BmgC4h1A.js";import{u as A}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{R as E,a as G}from"./RadioCardSimple-B-Oog_Qf.js";import{b as M}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const H={bg:"neutral-50 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4"},I={flex:"~ col gap-4"},K={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-500"},J={text:"neutral-400 dark:neutral-400"},O={"max-w-full":""},W={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},X={key:1},Y={key:0},Z={flex:"~ col gap-4"},$={class:"text-lg md:text-2xl"},ee={text:"neutral-400 dark:neutral-400"},se={key:0,class:"flex items-center justify-center py-4"},te={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"},oe={class:"flex flex-col"},ie={class:"font-medium"},ne={class:"text-sm text-red-600 dark:text-red-400"},le={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"},re={class:"flex flex-col"},de={class:"font-medium"},ae={class:"text-sm text-amber-600 dark:text-amber-400"},ce={key:1},ue={flex:"~ col gap-4"},pe={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},me={text:"neutral-400 dark:neutral-500"},xe={class:"flex items-center gap-3 border border-primary-200 rounded-lg bg-primary-50 p-4 dark:border-primary-800 dark:bg-primary-900/20"},ve={class:"flex flex-col"},ge={class:"font-medium"},_e={class:"text-sm text-primary-600 dark:text-primary-400"},he={class:"mt-2"},be={class:"mb-1 block text-sm font-medium"},fe=["placeholder"],ke={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},ye=R({__name:"consciousness",setup(Me){const w=A(),m=T(),{availableProviders:V,availableTextGenerationsProvidersMetadata:C}=h(w),{activeProvider:d,activeModel:a,customModelName:P,modelSearchQuery:c,supportsModelListing:x,providerModels:p,isLoadingActiveProviderModels:v,activeProviderModelError:g}=h(m),{t}=U();z(async()=>{await m.loadModelsForProvider(d.value)});function S(_){P.value=_}return(_,o)=>{const N=B("motion");return n(),r(k,null,[e("div",H,[e("div",null,[e("div",I,[e("div",null,[e("h2",K,i(s(t)("settings.pages.providers.title")),1),e("div",J,[e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.description")),1)])]),e("div",O,[s(V).length>0?(n(),r("fieldset",W,[(n(!0),r(k,null,D(s(C),l=>(n(),y(s(G),{id:l.id,key:l.id,modelValue:s(d),"onUpdate:modelValue":o[0]||(o[0]=L=>u(d)?d.value=L:null),name:"provider",value:l.id,title:l.localizedName,description:l.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(n(),r("div",X,[j(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:q(()=>o[4]||(o[4]=[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)?(n(),r("div",Y,[e("div",Z,[e("div",null,[e("h2",$,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",ee,[e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),s(v)?(n(),r("div",se,[o[5]||(o[5]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):s(g)?(n(),r("div",te,[o[6]||(o[6]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",oe,[e("span",ie,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",ne,i(s(g)),1)])])):s(p).length===0&&!s(v)?(n(),r("div",le,[o[7]||(o[7]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",re,[e("span",de,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",ae,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):s(p).length>0?(n(),y(s(E),{key:3,modelValue:s(a),"onUpdate:modelValue":o[1]||(o[1]=l=>u(a)?a.value=l:null),"search-query":s(c),"onUpdate:searchQuery":o[2]||(o[2]=l=>u(c)?c.value=l:null),items:s(p),searchable:!0,"search-placeholder":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:s(c)}),"search-results-text":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":S},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)?(n(),r("div",ce,[e("div",ue,[e("div",null,[e("h2",pe,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",me,[e("span",null,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),e("div",xe,[o[8]||(o[8]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-primary-500 dark:text-primary-400"},null,-1)),e("div",ve,[e("span",ge,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported")),1),e("span",_e,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.not_supported_description")),1)])]),e("div",he,[e("label",be,i(s(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_name")),1),b(e("input",{"onUpdate:modelValue":o[3]||(o[3]=l=>u(a)?a.value=l: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(t)("settings.pages.modules.consciousness.sections.section.provider-model-selection.manual_model_placeholder")},null,8,fe),[[Q,s(a)]])])])])):f("",!0)]),b((n(),r("div",ke,o[9]||(o[9]=[e("div",{text:"60","i-solar:ghost-bold-duotone":""},null,-1)]))),[[N]])],64)}}});typeof M=="function"&&M(ye);export{ye as default}; diff --git a/assets/deepseek-J636LQ27.js b/assets/deepseek-Dhr9828c.js similarity index 66% rename from assets/deepseek-J636LQ27.js rename to assets/deepseek-Dhr9828c.js index d4b9e729a38db6e9c2c98fa5ae1b419e381ce3bc..fade1ff37ce8f9e91f8c533fb85bdbba2e6369a6 100644 --- a/assets/deepseek-J636LQ27.js +++ b/assets/deepseek-Dhr9828c.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as U,g as V,S as y,s as $,h as c,H as K,v as h,A as S,o as w,w as m,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const o="deepseek",B=U({__name:"deepseek",setup(I){const{t:u}=V(),b=y(),d=x(),{providers:a}=$(d),n=c(()=>d.getProviderMetadata(o)),r=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.apiKey)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].apiKey=e}}),s=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.baseUrl)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].baseUrl=e}});K(()=>{var e,i;d.initializeProvider(o),r.value=((e=a.value[o])==null?void 0:e.apiKey)||"",s.value=((i=a.value[o])==null?void 0:i.baseUrl)||""}),h([r,s],()=>{a.value[o]={...a.value[o],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;a.value[o]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var v,f;return w(),S(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(b).back()},{default:m(()=>[l(t(N),null,{default:m(()=>[l(t(P),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:m(()=>{var p;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=k=>r.value=k),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:m(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.deepseek.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as U,g as V,S as y,s as $,h as c,H as K,v as h,A as S,o as w,w as m,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const o="deepseek",B=U({__name:"deepseek",setup(I){const{t:u}=V(),b=y(),d=x(),{providers:a}=$(d),n=c(()=>d.getProviderMetadata(o)),r=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.apiKey)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].apiKey=e}}),s=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.baseUrl)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].baseUrl=e}});K(()=>{var e,i;d.initializeProvider(o),r.value=((e=a.value[o])==null?void 0:e.apiKey)||"",s.value=((i=a.value[o])==null?void 0:i.baseUrl)||""}),h([r,s],()=>{a.value[o]={...a.value[o],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;a.value[o]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var v,f;return w(),S(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(b).back()},{default:m(()=>[l(t(N),null,{default:m(()=>[l(t(P),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:m(()=>{var p;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=k=>r.value=k),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:m(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.deepseek.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; diff --git a/assets/default-BhVC5vRq.js b/assets/default-Uk3R33Mo.js similarity index 89% rename from assets/default-BhVC5vRq.js rename to assets/default-Uk3R33Mo.js index a97bf8840a438c5780ac0ea9460a490350b62cce..6cf5e37c4c289ea216c9c1012c2fa277c0fc958a 100644 --- a/assets/default-BhVC5vRq.js +++ b/assets/default-Uk3R33Mo.js @@ -1 +1 @@ -import{d as t,c as s,e,i as a,b as o,R as n,o as p}from"./index-BQKiy4UR.js";import{H as d}from"./HeaderLink-CnrAQmsl.js";const i={style:{paddingBottom:"env(safe-area-inset-bottom, 0px)",paddingTop:"env(safe-area-inset-top, 0px)",paddingRight:"env(safe-area-inset-right, 0px)",paddingLeft:"env(safe-area-inset-left, 0px)"}},r={class:"px-0 py-1 md:px-3 md:py-3","w-full":"","gap-2":"",bg:"$bg-color"},c={class:"px-3 py-2 md:px-5 md:py-5",flex:"~ col","mx-auto":"","max-w-screen-xl":""},g=t({__name:"default",setup(m){return(f,l)=>(p(),s("div",i,[e("div",r,[a(d)]),e("div",c,[a(o(n))])]))}});export{g as default}; +import{d as t,c as s,e,i as a,b as o,R as n,o as p}from"./index-CQudhZin.js";import{H as d}from"./HeaderLink-DVu0ldr4.js";const i={style:{paddingBottom:"env(safe-area-inset-bottom, 0px)",paddingTop:"env(safe-area-inset-top, 0px)",paddingRight:"env(safe-area-inset-right, 0px)",paddingLeft:"env(safe-area-inset-left, 0px)"}},r={class:"px-0 py-1 md:px-3 md:py-3","w-full":"","gap-2":"",bg:"$bg-color"},c={class:"px-3 py-2 md:px-5 md:py-5",flex:"~ col","mx-auto":"","max-w-screen-xl":""},g=t({__name:"default",setup(m){return(f,l)=>(p(),s("div",i,[e("div",r,[a(d)]),e("div",c,[a(o(n))])]))}});export{g as default}; diff --git a/assets/default-node-S5EYlj5_.js b/assets/default-node-DAs8YCRC.js similarity index 89% rename from assets/default-node-S5EYlj5_.js rename to assets/default-node-DAs8YCRC.js index b85a04b252dff3fdec71f0746a7558deb8abb689..0d211ba86ce1076831a35b6076c753f5c1ec03e0 100644 --- a/assets/default-node-S5EYlj5_.js +++ b/assets/default-node-DAs8YCRC.js @@ -1 +1 @@ -import{L as t}from"./index-BQKiy4UR.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:i}=await import("./__vite-browser-external-FmFgRqLi.js");return{dirname:o,resolve:i}},[]),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{L as t}from"./index-CQudhZin.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:i}=await import("./__vite-browser-external-FmFgRqLi.js");return{dirname:o,resolve:i}},[]),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-CflciaKu.js b/assets/delays-DJLByMTi.js similarity index 71% rename from assets/delays-CflciaKu.js rename to assets/delays-DJLByMTi.js index aeb217a4aac896bb89890d9da043cf39452ff407..483b691c3adf3b4368cdb377e5122f3d35e7d5a7 100644 --- a/assets/delays-CflciaKu.js +++ b/assets/delays-DJLByMTi.js @@ -1 +1 @@ -import"./index-DSso2JwG.js";import{u as g,l as _}from"./queues-C9_pVSeq.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as k}from"./Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js";import{d as b,r,c as n,o as t,e,i as y,b as x,t as i,F as f,l as m}from"./index-BQKiy4UR.js";import"./mini_xsschema-P_8cZcRg.js";import"./queue-DNS07_tB.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";const w={flex:"","flex-col":"","gap-2":"","p-2":""},h={flex:"","flex-row":"","gap-2":""},M={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},V={"w-full":"",flex:"","flex-row":"","gap-4":""},E={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},S={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},U=b({__name:"delays",setup(B){const s=r(""),c=r([]),p=r([]),u=r(!1),d=g();d.onHandlerEvent("delay",a=>{p.value.push(a)});function v(){u.value=!0;const a=s.value.split("");for(const o of a)d.add(o);d.add(_),s.value="",u.value=!1}return(a,o)=>(t(),n("div",w,[e("div",h,[y(x(k),{modelValue:s.value,"onUpdate:modelValue":o[0]||(o[0]=l=>s.value=l),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:v},null,8,["modelValue"]),e("button",M,i(u.value?"Processing...":"Send"),1)]),e("div",V,[e("div",E,[o[1]||(o[1]=e("h3",{"font-semibold":""}," Emotion Message ",-1)),(t(!0),n(f,null,m(c.value,l=>(t(),n("div",{key:l},[e("div",null,i(l),1)]))),128))]),e("div",S,[o[2]||(o[2]=e("h3",{"font-semibold":""}," Delays ",-1)),(t(!0),n(f,null,m(p.value,l=>(t(),n("div",{key:l},[e("div",null,i(l)+"s",1)]))),128))])])]))}});export{U as default}; +import"./index-DC4guwRc.js";import{u as g,l as _}from"./queues-B-17ADgG.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as k}from"./Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js";import{d as b,r,c as n,o as t,e,i as y,b as x,t as i,F as f,l as m}from"./index-CQudhZin.js";import"./mini_xsschema-P_8cZcRg.js";import"./queue-3c99Yq5f.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";const w={flex:"","flex-col":"","gap-2":"","p-2":""},h={flex:"","flex-row":"","gap-2":""},M={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},V={"w-full":"",flex:"","flex-row":"","gap-4":""},E={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},S={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},U=b({__name:"delays",setup(B){const s=r(""),c=r([]),p=r([]),u=r(!1),d=g();d.onHandlerEvent("delay",a=>{p.value.push(a)});function v(){u.value=!0;const a=s.value.split("");for(const o of a)d.add(o);d.add(_),s.value="",u.value=!1}return(a,o)=>(t(),n("div",w,[e("div",h,[y(x(k),{modelValue:s.value,"onUpdate:modelValue":o[0]||(o[0]=l=>s.value=l),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:v},null,8,["modelValue"]),e("button",M,i(u.value?"Processing...":"Send"),1)]),e("div",V,[e("div",E,[o[1]||(o[1]=e("h3",{"font-semibold":""}," Emotion Message ",-1)),(t(!0),n(f,null,m(c.value,l=>(t(),n("div",{key:l},[e("div",null,i(l),1)]))),128))]),e("div",S,[o[2]||(o[2]=e("h3",{"font-semibold":""}," Delays ",-1)),(t(!0),n(f,null,m(p.value,l=>(t(),n("div",{key:l},[e("div",null,i(l)+"s",1)]))),128))])])]))}});export{U as default}; diff --git a/assets/effect-AvyXEvwH-DIOBmVdI.js b/assets/effect-AvyXEvwH-DHZdf01Y.js similarity index 51% rename from assets/effect-AvyXEvwH-DIOBmVdI.js rename to assets/effect-AvyXEvwH-DHZdf01Y.js index 3c61f62e1d9d42556ca28a5f60b41c68ee6f64ad..a92fa19e484ad7380a35a82c3bd98fd39a09894d 100644 --- a/assets/effect-AvyXEvwH-DIOBmVdI.js +++ b/assets/effect-AvyXEvwH-DHZdf01Y.js @@ -1 +1 @@ -import{L as r}from"./index-BQKiy4UR.js";import{t as e}from"./mcp-DQCTu0C2.js";const _=async()=>{const{JSONSchema:t}=await e(r(()=>import("./__vite-optional-peer-dep_effect_xsschema-BIHI7g3E.js"),[]),"effect");return o=>t.make(o)};export{_ as getToJsonSchemaFn}; +import{L as r}from"./index-CQudhZin.js";import{t as e}from"./mcp-C9U4MroK.js";const _=async()=>{const{JSONSchema:t}=await e(r(()=>import("./__vite-optional-peer-dep_effect_xsschema-BIHI7g3E.js"),[]),"effect");return o=>t.make(o)};export{_ as getToJsonSchemaFn}; diff --git a/assets/elevenlabs-CHUs61J3.js b/assets/elevenlabs-CtF3mm-w.js similarity index 79% rename from assets/elevenlabs-CHUs61J3.js rename to assets/elevenlabs-CtF3mm-w.js index a44efcbc8e34e41a2d1889cf252701a7b8232f34..d0b88403f20306ee3f7eff1fab494d66f234a383 100644 --- a/assets/elevenlabs-CHUs61J3.js +++ b/assets/elevenlabs-CtF3mm-w.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as $,r as n,s as F,g as I,h as x,H as E,v as a,A as H,o as K,w as k,i as d,b as o,e as L}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as N}from"./providers-kjOpfeNb.js";import{u as T}from"./speech-Db_L6FBm.js";import{_ as p,a as z}from"./FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as A,a as G}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js";import{b as w}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";const R={flex:"~ col gap-4"},l="elevenlabs",_="eleven_multilingual_v2",j=$({__name:"elevenlabs",setup(q){const V={similarityBoost:.75,stability:.5,speed:1,style:0,useSpeakerBoost:!0},v=n(0),m=n(1),u=n(0),f=n(0),c=n(.5),g=n(.75),b=n(!1),y=T(),t=N(),{providers:C}=F(t),{t:r}=I(),B=x(()=>{var e;return!!((e=C.value[l])!=null&&e.apiKey)}),M=x(()=>y.availableVoices[l]||[]);async function U(e,i,s){const P=t.getProviderInstance(l);if(!P)throw new Error("Failed to initialize speech provider");const S=t.getProviderConfig(l),h=S.model||_;return await y.speech(P,h,e,i,{...S,...V})}return E(async()=>{const e=t.getProviderConfig(l);await t.getProviderMetadata(l).validators.validateProviderConfig(e)?await y.loadVoicesForProvider(l):console.error("Failed to validate provider config",e)}),a(v,async()=>{const e=t.getProviderConfig(l);e.pitch=v.value}),a(m,async()=>{const e=t.getProviderConfig(l);e.speed=m.value}),a(u,async()=>{const e=t.getProviderConfig(l);e.volume=u.value}),a(f,async()=>{const e=t.getProviderConfig(l);e.style=f.value}),a(c,async()=>{const e=t.getProviderConfig(l);e.stability=c.value}),a(g,async()=>{const e=t.getProviderConfig(l);e.similarityBoost=g.value}),a(b,async()=>{const e=t.getProviderConfig(l);e.useSpeakerBoost=b.value}),a(C,async()=>{const e=t.getProviderConfig(l);await t.getProviderMetadata(l).validators.validateProviderConfig(e)?await y.loadVoicesForProvider(l):console.error("Failed to validate provider config",e)},{immediate:!0}),(e,i)=>(K(),H(o(G),{"provider-id":l,"default-model":_,"additional-settings":V},{"voice-settings":k(()=>[L("div",R,[d(o(p),{modelValue:v.value,"onUpdate:modelValue":i[0]||(i[0]=s=>v.value=s),label:o(r)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":s=>`${s}%`},null,8,["modelValue","label","description","format-value"]),d(o(p),{modelValue:m.value,"onUpdate:modelValue":i[1]||(i[1]=s=>m.value=s),label:o(r)("settings.pages.providers.provider.common.fields.field.speed.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"]),d(o(p),{modelValue:u.value,"onUpdate:modelValue":i[2]||(i[2]=s=>u.value=s),label:o(r)("settings.pages.providers.provider.common.fields.field.volume.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":s=>`${s}%`},null,8,["modelValue","label","description","format-value"]),d(o(p),{modelValue:f.value,"onUpdate:modelValue":i[3]||(i[3]=s=>f.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.style.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.style.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"]),d(o(p),{modelValue:c.value,"onUpdate:modelValue":i[4]||(i[4]=s=>c.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.stability.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.stability.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"]),d(o(p),{modelValue:g.value,"onUpdate:modelValue":i[5]||(i[5]=s=>g.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"]),d(o(z),{modelValue:b.value,"onUpdate:modelValue":i[6]||(i[6]=s=>b.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.description")},null,8,["modelValue","label","description"])])]),playground:k(()=>[d(o(A),{"available-voices":M.value,"generate-speech":U,"api-key-configured":B.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof w=="function"&&w(j);export{j as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as $,r as n,s as F,g as I,h as x,H as E,v as a,A as H,o as K,w as k,i as d,b as o,e as L}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as N}from"./providers-Y3Mr8_DF.js";import{u as T}from"./speech-nVAae-rt.js";import{_ as p,a as z}from"./FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as A,a as G}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js";import{b as w}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";const R={flex:"~ col gap-4"},l="elevenlabs",_="eleven_multilingual_v2",j=$({__name:"elevenlabs",setup(q){const V={similarityBoost:.75,stability:.5,speed:1,style:0,useSpeakerBoost:!0},v=n(0),m=n(1),u=n(0),f=n(0),c=n(.5),g=n(.75),b=n(!1),y=T(),t=N(),{providers:C}=F(t),{t:r}=I(),B=x(()=>{var e;return!!((e=C.value[l])!=null&&e.apiKey)}),M=x(()=>y.availableVoices[l]||[]);async function U(e,i,s){const P=t.getProviderInstance(l);if(!P)throw new Error("Failed to initialize speech provider");const S=t.getProviderConfig(l),h=S.model||_;return await y.speech(P,h,e,i,{...S,...V})}return E(async()=>{const e=t.getProviderConfig(l);await t.getProviderMetadata(l).validators.validateProviderConfig(e)?await y.loadVoicesForProvider(l):console.error("Failed to validate provider config",e)}),a(v,async()=>{const e=t.getProviderConfig(l);e.pitch=v.value}),a(m,async()=>{const e=t.getProviderConfig(l);e.speed=m.value}),a(u,async()=>{const e=t.getProviderConfig(l);e.volume=u.value}),a(f,async()=>{const e=t.getProviderConfig(l);e.style=f.value}),a(c,async()=>{const e=t.getProviderConfig(l);e.stability=c.value}),a(g,async()=>{const e=t.getProviderConfig(l);e.similarityBoost=g.value}),a(b,async()=>{const e=t.getProviderConfig(l);e.useSpeakerBoost=b.value}),a(C,async()=>{const e=t.getProviderConfig(l);await t.getProviderMetadata(l).validators.validateProviderConfig(e)?await y.loadVoicesForProvider(l):console.error("Failed to validate provider config",e)},{immediate:!0}),(e,i)=>(K(),H(o(G),{"provider-id":l,"default-model":_,"additional-settings":V},{"voice-settings":k(()=>[L("div",R,[d(o(p),{modelValue:v.value,"onUpdate:modelValue":i[0]||(i[0]=s=>v.value=s),label:o(r)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":s=>`${s}%`},null,8,["modelValue","label","description","format-value"]),d(o(p),{modelValue:m.value,"onUpdate:modelValue":i[1]||(i[1]=s=>m.value=s),label:o(r)("settings.pages.providers.provider.common.fields.field.speed.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"]),d(o(p),{modelValue:u.value,"onUpdate:modelValue":i[2]||(i[2]=s=>u.value=s),label:o(r)("settings.pages.providers.provider.common.fields.field.volume.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":s=>`${s}%`},null,8,["modelValue","label","description","format-value"]),d(o(p),{modelValue:f.value,"onUpdate:modelValue":i[3]||(i[3]=s=>f.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.style.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.style.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"]),d(o(p),{modelValue:c.value,"onUpdate:modelValue":i[4]||(i[4]=s=>c.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.stability.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.stability.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"]),d(o(p),{modelValue:g.value,"onUpdate:modelValue":i[5]||(i[5]=s=>g.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.simularity-boost.description"),min:0,max:1,step:.01},null,8,["modelValue","label","description"]),d(o(z),{modelValue:b.value,"onUpdate:modelValue":i[6]||(i[6]=s=>b.value=s),label:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.label"),description:o(r)("settings.pages.providers.provider.elevenlabs.fields.field.speaker-boost.description")},null,8,["modelValue","label","description"])])]),playground:k(()=>[d(o(A),{"available-voices":M.value,"generate-speech":U,"api-key-configured":B.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof w=="function"&&w(j);export{j as default}; diff --git a/assets/emotions-T9t8Z2VX.js b/assets/emotions-COZF15gE.js similarity index 73% rename from assets/emotions-T9t8Z2VX.js rename to assets/emotions-COZF15gE.js index 7caad95073213911b8458cd1ca85e4b3fe2acad9..24f91cc599d6e84b7e879fee7728defbc9a96f96 100644 --- a/assets/emotions-T9t8Z2VX.js +++ b/assets/emotions-COZF15gE.js @@ -1 +1 @@ -import{u as _}from"./queue-DNS07_tB.js";import{a as k,l as b}from"./queues-C9_pVSeq.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as x}from"./Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js";import{d as h,r,c as s,o as t,e,i as w,b as M,t as d,F as p,l as f}from"./index-BQKiy4UR.js";import"./mini_xsschema-P_8cZcRg.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";const V={flex:"","flex-col":"","gap-2":"","p-2":""},y={flex:"","flex-row":"","gap-2":""},E={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},Q={"w-full":"",flex:"","flex-row":"","gap-4":""},S={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},B={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},$=h({__name:"emotions",setup(P){const l=r(""),c=r([]),i=r([]),u=r(!1),g=_({handlers:[async a=>{i.value.push(a.data)}]}),m=k(g);function v(){u.value=!0;const a=l.value.split("");for(const o of a)m.add(o);m.add(b),l.value="",u.value=!1}return(a,o)=>(t(),s("div",V,[e("div",y,[w(M(x),{modelValue:l.value,"onUpdate:modelValue":o[0]||(o[0]=n=>l.value=n),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:v},null,8,["modelValue"]),e("button",E,d(u.value?"Processing...":"Send"),1)]),e("div",Q,[e("div",S,[o[1]||(o[1]=e("h3",{"font-semibold":""}," Messages ",-1)),(t(!0),s(p,null,f(c.value,n=>(t(),s("div",{key:n},[e("div",null,d(n),1)]))),128))]),e("div",B,[o[2]||(o[2]=e("h3",{"font-semibold":""}," Emotions ",-1)),(t(!0),s(p,null,f(i.value,n=>(t(),s("div",{key:n},[e("div",null,d(n),1)]))),128))])])]))}});export{$ as default}; +import{u as _}from"./queue-3c99Yq5f.js";import{a as k,l as b}from"./queues-B-17ADgG.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as x}from"./Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js";import{d as h,r,c as s,o as t,e,i as w,b as M,t as d,F as p,l as f}from"./index-CQudhZin.js";import"./mini_xsschema-P_8cZcRg.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";const V={flex:"","flex-col":"","gap-2":"","p-2":""},y={flex:"","flex-row":"","gap-2":""},E={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},Q={"w-full":"",flex:"","flex-row":"","gap-4":""},S={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},B={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},$=h({__name:"emotions",setup(P){const l=r(""),c=r([]),i=r([]),u=r(!1),g=_({handlers:[async a=>{i.value.push(a.data)}]}),m=k(g);function v(){u.value=!0;const a=l.value.split("");for(const o of a)m.add(o);m.add(b),l.value="",u.value=!1}return(a,o)=>(t(),s("div",V,[e("div",y,[w(M(x),{modelValue:l.value,"onUpdate:modelValue":o[0]||(o[0]=n=>l.value=n),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:v},null,8,["modelValue"]),e("button",E,d(u.value?"Processing...":"Send"),1)]),e("div",Q,[e("div",S,[o[1]||(o[1]=e("h3",{"font-semibold":""}," Messages ",-1)),(t(!0),s(p,null,f(c.value,n=>(t(),s("div",{key:n},[e("div",null,d(n),1)]))),128))]),e("div",B,[o[2]||(o[2]=e("h3",{"font-semibold":""}," Emotions ",-1)),(t(!0),s(p,null,f(i.value,n=>(t(),s("div",{key:n},[e("div",null,d(n),1)]))),128))])])]))}});export{$ as default}; diff --git a/assets/featherless-ai-iViKpBby.js b/assets/featherless-ai-8Fh6lUDA.js similarity index 66% rename from assets/featherless-ai-iViKpBby.js rename to assets/featherless-ai-8Fh6lUDA.js index 955f76e9b528360a137d8426cc85d563f60afa06..b526be1f8ccf7bb1ff1fc235ef1e9939d87be443 100644 --- a/assets/featherless-ai-iViKpBby.js +++ b/assets/featherless-ai-8Fh6lUDA.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as U,g as V,S as k,s as y,h as v,H as $,v as K,A as w,o as S,w as u,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const a="featherless-ai",C=U({__name:"featherless-ai",setup(I){const{t:m}=V(),b=k(),d=x(),{providers:o}=y(d),n=v(()=>d.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}});$(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return S(),w(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:u(()=>[l(t(P),null,{default:u(()=>[l(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=h=>r.value=h),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"fw-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.featherless.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as U,g as V,S as k,s as y,h as v,H as $,v as K,A as w,o as S,w as u,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const a="featherless-ai",C=U({__name:"featherless-ai",setup(I){const{t:m}=V(),b=k(),d=x(),{providers:o}=y(d),n=v(()=>d.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}});$(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return S(),w(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:u(()=>[l(t(P),null,{default:u(()=>[l(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=h=>r.value=h),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"fw-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.featherless.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; diff --git a/assets/filter-message-CXNI-DZl.js b/assets/filter-message-DJVIgF-Z.js similarity index 75% rename from assets/filter-message-CXNI-DZl.js rename to assets/filter-message-DJVIgF-Z.js index cd55843afb900b2879a4c04044debc1fdc2f0b5d..1ab7c92c8fe862c153fd66ad681a9b85fa2e14c4 100644 --- a/assets/filter-message-CXNI-DZl.js +++ b/assets/filter-message-DJVIgF-Z.js @@ -1 +1 @@ -import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as m}from"./Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js";import{d as g,r as c,c as v,o as _,e as o,i as b,b as x,t as d}from"./index-BQKiy4UR.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";const S={flex:"","flex-col":"","gap-2":"","p-2":""},k={flex:"","flex-row":"","gap-2":""},w={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},V={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},C=g({__name:"filter-message",setup(M){const s=c(""),u=c(!1),r=c({content:""});async function f(i){return new Promise(e=>setTimeout(e,i))}async function p(){u.value=!0;const i=s.value.split("");let e;(a=>{a.Literal="literal",a.Special="special"})(e||(e={}));let t="literal",l="";for(const a of i){await f(50);let n=t;a==="<"?n="special":a===">"&&(n="literal"),t==="literal"&&n==="special"&&(r.value.content+=l,l=""),t==="special"&&n==="literal"&&(l=""),t==="literal"&&n==="literal"&&(r.value.content+=a,l=""),t=n}l&&(r.value.content+=l),s.value="",u.value=!1}return(i,e)=>(_(),v("div",S,[o("div",k,[b(x(m),{modelValue:s.value,"onUpdate:modelValue":e[0]||(e[0]=t=>s.value=t),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:p},null,8,["modelValue"]),o("button",w,d(u.value?"Processing...":"Send"),1)]),o("div",V,[e[1]||(e[1]=o("h3",{"font-semibold":""}," Streaming Message ",-1)),o("div",null,d(r.value.content),1)])]))}});export{C as default}; +import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as m}from"./Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js";import{d as g,r as c,c as v,o as _,e as o,i as b,b as x,t as d}from"./index-CQudhZin.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";const S={flex:"","flex-col":"","gap-2":"","p-2":""},k={flex:"","flex-row":"","gap-2":""},w={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},V={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},C=g({__name:"filter-message",setup(M){const s=c(""),u=c(!1),r=c({content:""});async function f(i){return new Promise(e=>setTimeout(e,i))}async function p(){u.value=!0;const i=s.value.split("");let e;(a=>{a.Literal="literal",a.Special="special"})(e||(e={}));let t="literal",l="";for(const a of i){await f(50);let n=t;a==="<"?n="special":a===">"&&(n="literal"),t==="literal"&&n==="special"&&(r.value.content+=l,l=""),t==="special"&&n==="literal"&&(l=""),t==="literal"&&n==="literal"&&(r.value.content+=a,l=""),t=n}l&&(r.value.content+=l),s.value="",u.value=!1}return(i,e)=>(_(),v("div",S,[o("div",k,[b(x(m),{modelValue:s.value,"onUpdate:modelValue":e[0]||(e[0]=t=>s.value=t),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:p},null,8,["modelValue"]),o("button",w,d(u.value?"Processing...":"Send"),1)]),o("div",V,[e[1]||(e[1]=o("h3",{"font-semibold":""}," Streaming Message ",-1)),o("div",null,d(r.value.content),1)])]))}});export{C as default}; diff --git a/assets/fireworks-ai-oUount_Y.js b/assets/fireworks-ai-Dd6lQOw3.js similarity index 66% rename from assets/fireworks-ai-oUount_Y.js rename to assets/fireworks-ai-Dd6lQOw3.js index 5db4688f34c04c82651c3172f85a475c4d953c30..368dfe6f88f4cdfab5cdbbc7486a5c9ce755f999 100644 --- a/assets/fireworks-ai-oUount_Y.js +++ b/assets/fireworks-ai-Dd6lQOw3.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as w,g as U,S as V,s as y,h as v,H as $,v as K,A as h,o as S,w as u,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const a="fireworks-ai",C=w({__name:"fireworks-ai",setup(I){const{t:m}=U(),b=V(),d=x(),{providers:o}=y(d),n=v(()=>d.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}});$(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return S(),h(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:u(()=>[l(t(P),null,{default:u(()=>[l(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=k=>r.value=k),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"fw-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.fireworks.ai/inference/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as w,g as U,S as V,s as y,h as v,H as $,v as K,A as h,o as S,w as u,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const a="fireworks-ai",C=w({__name:"fireworks-ai",setup(I){const{t:m}=U(),b=V(),d=x(),{providers:o}=y(d),n=v(()=>d.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}});$(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return S(),h(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:u(()=>[l(t(P),null,{default:u(()=>[l(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=k=>r.value=k),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"fw-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.fireworks.ai/inference/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; diff --git a/assets/google-generative-ai-w-KmjfIn.js b/assets/google-generative-ai-Cst0rdKi.js similarity index 69% rename from assets/google-generative-ai-w-KmjfIn.js rename to assets/google-generative-ai-Cst0rdKi.js index 12bbdff45d0d2750ffebf9ff2765fa29e2f46058..a540540d9a1f69bf3ee42bc8853d4ce7b13a340f 100644 --- a/assets/google-generative-ai-w-KmjfIn.js +++ b/assets/google-generative-ai-Cst0rdKi.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as U,g as k,S as V,s as y,h as v,H as $,v as K,A as S,o as w,w as p,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as G,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as R,a as z}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as f}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const e="google-generative-ai",C=U({__name:"google-generative-ai",setup(I){const{t:m}=k(),_=V(),c=x(),{providers:a}=y(c),u=v(()=>c.getProviderMetadata(e)),s=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://generativelanguage.googleapis.com/v1beta/openai/"},set:o=>{a.value[e]||(a.value[e]={}),a.value[e].baseUrl=o}});$(()=>{var o,i;a.value[e]||(a.value[e]={baseUrl:"https://api.anthropic.com/v1/"}),s.value=((o=a.value[e])==null?void 0:o.apiKey)||"",r.value=((i=a.value[e])==null?void 0:i.baseUrl)||"https://generativelanguage.googleapis.com/v1beta/openai/"}),K([s,r],()=>{a.value[e]={...a.value[e],apiKey:s.value,baseUrl:r.value||"https://generativelanguage.googleapis.com/v1beta/openai/"}});function b(){a.value[e]={baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai/"}}return(o,i)=>{var d,g;return w(),S(t(B),{"provider-name":((d=u.value)==null?void 0:d.localizedName)||"Google | Gemini","provider-icon":(g=u.value)==null?void 0:g.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(R),null,{default:p(()=>[l(t(z),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var n;return[l(t(N),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=h=>s.value=h),"provider-name":((n=u.value)==null?void 0:n.localizedName)||"Google",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(G),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=n=>r.value=n),placeholder:"https://generativelanguage.googleapis.com/v1beta/openai/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof f=="function"&&f(C);export{C as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as U,g as k,S as V,s as y,h as v,H as $,v as K,A as S,o as w,w as p,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as G,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as R,a as z}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as f}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const e="google-generative-ai",C=U({__name:"google-generative-ai",setup(I){const{t:m}=k(),_=V(),c=x(),{providers:a}=y(c),u=v(()=>c.getProviderMetadata(e)),s=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://generativelanguage.googleapis.com/v1beta/openai/"},set:o=>{a.value[e]||(a.value[e]={}),a.value[e].baseUrl=o}});$(()=>{var o,i;a.value[e]||(a.value[e]={baseUrl:"https://api.anthropic.com/v1/"}),s.value=((o=a.value[e])==null?void 0:o.apiKey)||"",r.value=((i=a.value[e])==null?void 0:i.baseUrl)||"https://generativelanguage.googleapis.com/v1beta/openai/"}),K([s,r],()=>{a.value[e]={...a.value[e],apiKey:s.value,baseUrl:r.value||"https://generativelanguage.googleapis.com/v1beta/openai/"}});function b(){a.value[e]={baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai/"}}return(o,i)=>{var d,g;return w(),S(t(B),{"provider-name":((d=u.value)==null?void 0:d.localizedName)||"Google | Gemini","provider-icon":(g=u.value)==null?void 0:g.icon,"on-back":()=>t(_).back()},{default:p(()=>[l(t(R),null,{default:p(()=>[l(t(z),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:p(()=>{var n;return[l(t(N),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=h=>s.value=h),"provider-name":((n=u.value)==null?void 0:n.localizedName)||"Google",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(G),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=n=>r.value=n),placeholder:"https://generativelanguage.googleapis.com/v1beta/openai/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof f=="function"&&f(C);export{C as default}; diff --git a/assets/image-BHbvwqTc.js b/assets/image-DmDCtZow.js similarity index 70% rename from assets/image-BHbvwqTc.js rename to assets/image-DmDCtZow.js index 2b93091c3dfb1f109b7b70f6df77732ed881ccc9..f66d6093457c14877661a1747de48ac9bf791c47 100644 --- a/assets/image-BHbvwqTc.js +++ b/assets/image-DmDCtZow.js @@ -1,2 +1,2 @@ -import{d as _,r as c,U as y,c as d,o as u,e as a,j as x,t as v,b,_ as w}from"./index-BQKiy4UR.js";const U={bg:"neutral-100",flex:"~ col","items-center":"","justify-center":"","rounded-lg":"","px-4":"","py-3":""},h={key:0},C=["src"],R={bg:"neutral-100",class:"text-wrap-any","max-h":"100","overflow-scroll":"","rounded-lg":"","text-wrap":"","text-black":"","font-mono":""},k=_({__name:"image",setup(D){const p=c(),n=c(""),{copy:g}=y({source:n});async function m(s){return new Promise((e,o)=>{const t=new FileReader;t.onload=r=>{var l,i;e(((i=(l=r.target)==null?void 0:l.result)==null?void 0:i.toString())||"")},t.onerror=r=>{o(r)},t.readAsDataURL(s)})}async function f(s){var t;const o=(t=s.target.files)==null?void 0:t[0];if(o){p.value=o;const r=await m(o);n.value=r}}return(s,e)=>(u(),d("div",null,[a("label",U,[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,C),a("pre",R," "+v(n.value)+` +import{d as _,r as c,W as y,c as d,o as u,e as a,j as x,t as v,b,_ as w}from"./index-CQudhZin.js";const h={bg:"neutral-100",flex:"~ col","items-center":"","justify-center":"","rounded-lg":"","px-4":"","py-3":""},C={key:0},U=["src"],R={bg:"neutral-100",class:"text-wrap-any","max-h":"100","overflow-scroll":"","rounded-lg":"","text-wrap":"","text-black":"","font-mono":""},k=_({__name:"image",setup(D){const p=c(),n=c(""),{copy:g}=y({source:n});async function m(s){return new Promise((e,o)=>{const t=new FileReader;t.onload=r=>{var l,i;e(((i=(l=r.target)==null?void 0:l.result)==null?void 0:i.toString())||"")},t.onerror=r=>{o(r)},t.readAsDataURL(s)})}async function f(s){var t;const o=(t=s.target.files)==null?void 0:t[0];if(o){p.value=o;const r=await m(o);n.value=r}}return(s,e)=>(u(),d("div",null,[a("label",h,[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",C,[a("img",{src:n.value,alt:"Uploaded Image","w-100":""},null,8,U),a("pre",R," "+v(n.value)+` `,1),a("button",{bg:"primary-500",text:"white","mt-4":"","rounded-lg":"","px-4":"","py-2":"",onClick:e[0]||(e[0]=()=>b(g)())}," Copy Data URL ")])):x("",!0)]))}}),B=w(k,[["__scopeId","data-v-7edd53e6"]]);export{B as default}; diff --git a/assets/index-BrQ5XatC.js b/assets/index-BWM8H6v1.js similarity index 90% rename from assets/index-BrQ5XatC.js rename to assets/index-BWM8H6v1.js index c3d942d1a2e5161c233baa23663cfc0ff2ea9ffa..889525b99afb0c293e747598a40399e1ab20fee9 100644 --- a/assets/index-BrQ5XatC.js +++ b/assets/index-BWM8H6v1.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as I,N as A,A as x,o as n,w as E,e as s,c as p,j as w,f as D,t as C,n as P,_ as R,S as j,r,g as L,G as N,h as q,K as F,x as _,F as V,l as G,b as y,z as K,b3 as O}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as H}from"./IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js";import{b as S}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";const J={"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=I({__name:"IconItem",props:{title:null,description:null,icon:null,iconTemplate:{type:Boolean},to:null},setup(o){return(m,g)=>{const f=A("RouterLink");return n(),x(f,{box:"border",flex:"~ row",bg:"neutral-50 dark:neutral-900",border:"neutral-100 dark:neutral-800/25 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:o.to},{default:E(()=>[s("div",J,[s("div",M,C(o.title),1),s("div",Q,[s("span",null,C(o.description),1)])]),typeof o.icon=="string"?(n(),p("div",{key:0,class:P(["menu-icon-item-icon",[o.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)):w("",!0),o.iconTemplate?D(m.$slots,"icon",{key:1},void 0,!0):w("",!0)]),_:3},8,["to"])}}}),W=R(U,[["__scopeId","data-v-656e0116"]]),X={flex:"~ col gap-4"},Y={flex:"~ col gap-4"},Z={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-12rem)]","bottom-0":"","right--10":"","z--1":"",initial:{scale:.9,opacity:0,rotate:180},enter:{scale:1,opacity:1,rotate:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},tt={text:"60","i-solar:settings-bold-duotone":""},et=I({__name:"index",setup(o){const m=j(),g=r(!1),f=r(),c=r(),{t}=L(),h=r(""),b=r(""),k=r(!1),d=N();function $(){var a;(a=c.value)==null||a.call(c)}async function z(a,l){const e=a.currentTarget.querySelector(".menu-icon-item-icon");if(!e)return;const u=e.getBoundingClientRect(),v=`${u.left}px, ${u.top}px`;h.value=l.icon,b.value=v,k.value=!0,await O(),g.value=!0}const T=m.beforeEach(async(a,l,i)=>{if(!d.usePageSpecificTransitions||d.disableTransitions){i();return}await new Promise(e=>{c.value=e}),T(),i()}),B=q(()=>[{title:t("settings.pages.card.title"),description:t("settings.pages.card.description"),icon:"i-solar:emoji-funny-square-bold-duotone",to:"/settings/airi-card"},{title:t("settings.pages.modules.title"),description:t("settings.pages.modules.description"),icon:"i-solar:layers-bold-duotone",to:"/settings/modules"},{title:t("settings.pages.scene.title"),description:t("settings.pages.scene.description"),icon:"i-solar:armchair-2-bold-duotone",to:"/settings/scene"},{title:t("settings.pages.models.title"),description:t("settings.pages.models.description"),icon:"i-solar:people-nearby-bold-duotone",to:"/settings/models"},{title:t("settings.pages.memory.title"),description:t("settings.pages.memory.description"),icon:"i-solar:leaf-bold-duotone",to:"/settings/memory"},{title:t("settings.pages.providers.title"),description:t("settings.pages.providers.description"),icon:"i-solar:box-minimalistic-bold-duotone",to:"/settings/providers"},{title:t("settings.pages.themes.title"),description:t("settings.pages.themes.description"),icon:"i-solar:filters-bold-duotone",to:"/settings/appearance"}]);return(a,l)=>{const i=F("motion");return n(),p("div",X,[l[0]||(l[0]=s("div",null,null,-1)),s("div",Y,[(n(!0),p(V,null,G(B.value,(e,u)=>_((n(),x(y(W),{key:e.to,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250,style:K({transitionDelay:`${u*50}ms`}),title:e.title,description:e.description,icon:e.icon,to:e.to,onClick:v=>z(v,e)},null,8,["style","title","description","icon","to","onClick"])),[[i]])),128))]),k.value&&!y(d).disableTransitions&&y(d).usePageSpecificTransitions?(n(),x(H,{key:0,ref_key:"iconAnimation",ref:f,icon:h.value,"icon-size":6*1.2,position:b.value,duration:1e3,"text-color":"text-neutral-400/50 dark:text-neutral-600/20",started:g.value,onAnimationEndedOnce:$},null,8,["icon","position","started"])):_((n(),p("div",Z,[_(s("div",tt,null,512),[[i]])])),[[i]])])}}});typeof S=="function"&&S(et);export{et as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as I,N as A,A as x,o as n,w as E,e as s,c as p,j as w,f as D,t as C,n as P,_ as R,S as j,r,g as L,G as N,h as q,K as F,x as _,F as V,l as G,b as y,z as K,ax as O}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as H}from"./IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js";import{b as S}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";const J={"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=I({__name:"IconItem",props:{title:null,description:null,icon:null,iconTemplate:{type:Boolean},to:null},setup(o){return(m,g)=>{const f=A("RouterLink");return n(),x(f,{box:"border",flex:"~ row",bg:"neutral-50 dark:neutral-900",border:"neutral-100 dark:neutral-800/25 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:o.to},{default:E(()=>[s("div",J,[s("div",M,C(o.title),1),s("div",Q,[s("span",null,C(o.description),1)])]),typeof o.icon=="string"?(n(),p("div",{key:0,class:P(["menu-icon-item-icon",[o.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)):w("",!0),o.iconTemplate?D(m.$slots,"icon",{key:1},void 0,!0):w("",!0)]),_:3},8,["to"])}}}),W=R(U,[["__scopeId","data-v-656e0116"]]),X={flex:"~ col gap-4"},Y={flex:"~ col gap-4"},Z={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-12rem)]","bottom-0":"","right--10":"","z--1":"",initial:{scale:.9,opacity:0,rotate:180},enter:{scale:1,opacity:1,rotate:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},tt={text:"60","i-solar:settings-bold-duotone":""},et=I({__name:"index",setup(o){const m=j(),g=r(!1),f=r(),c=r(),{t}=L(),h=r(""),b=r(""),k=r(!1),d=N();function $(){var a;(a=c.value)==null||a.call(c)}async function z(a,l){const e=a.currentTarget.querySelector(".menu-icon-item-icon");if(!e)return;const u=e.getBoundingClientRect(),v=`${u.left}px, ${u.top}px`;h.value=l.icon,b.value=v,k.value=!0,await O(),g.value=!0}const T=m.beforeEach(async(a,l,i)=>{if(!d.usePageSpecificTransitions||d.disableTransitions){i();return}await new Promise(e=>{c.value=e}),T(),i()}),B=q(()=>[{title:t("settings.pages.card.title"),description:t("settings.pages.card.description"),icon:"i-solar:emoji-funny-square-bold-duotone",to:"/settings/airi-card"},{title:t("settings.pages.modules.title"),description:t("settings.pages.modules.description"),icon:"i-solar:layers-bold-duotone",to:"/settings/modules"},{title:t("settings.pages.scene.title"),description:t("settings.pages.scene.description"),icon:"i-solar:armchair-2-bold-duotone",to:"/settings/scene"},{title:t("settings.pages.models.title"),description:t("settings.pages.models.description"),icon:"i-solar:people-nearby-bold-duotone",to:"/settings/models"},{title:t("settings.pages.memory.title"),description:t("settings.pages.memory.description"),icon:"i-solar:leaf-bold-duotone",to:"/settings/memory"},{title:t("settings.pages.providers.title"),description:t("settings.pages.providers.description"),icon:"i-solar:box-minimalistic-bold-duotone",to:"/settings/providers"},{title:t("settings.pages.themes.title"),description:t("settings.pages.themes.description"),icon:"i-solar:filters-bold-duotone",to:"/settings/appearance"}]);return(a,l)=>{const i=F("motion");return n(),p("div",X,[l[0]||(l[0]=s("div",null,null,-1)),s("div",Y,[(n(!0),p(V,null,G(B.value,(e,u)=>_((n(),x(y(W),{key:e.to,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250,style:K({transitionDelay:`${u*50}ms`}),title:e.title,description:e.description,icon:e.icon,to:e.to,onClick:v=>z(v,e)},null,8,["style","title","description","icon","to","onClick"])),[[i]])),128))]),k.value&&!y(d).disableTransitions&&y(d).usePageSpecificTransitions?(n(),x(H,{key:0,ref_key:"iconAnimation",ref:f,icon:h.value,"icon-size":6*1.2,position:b.value,duration:1e3,"text-color":"text-neutral-400/50 dark:text-neutral-600/20",started:g.value,onAnimationEndedOnce:$},null,8,["icon","position","started"])):_((n(),p("div",Z,[_(s("div",tt,null,512),[[i]])])),[[i]])])}}});typeof S=="function"&&S(et);export{et as default}; diff --git a/assets/index-C0MBzJvw.js b/assets/index-BsTlOxC-.js similarity index 91% rename from assets/index-C0MBzJvw.js rename to assets/index-BsTlOxC-.js index 8242065071b5715bc0804a738a195fbfdbfdf039..5efc5aa2d0ea93f189cda916b5af9bae19f245e4 100644 --- a/assets/index-C0MBzJvw.js +++ b/assets/index-BsTlOxC-.js @@ -1 +1 @@ -import{d as q,m as G,u as H,h as C,A as E,o as i,w as A,e as a,n as F,f as W,k as X,t as u,c,F as z,l as T,E as Y,b as r,g as Z,s as ee,r as x,v as te,K as ae,i as h,x as O,y as le,j as S}from"./index-BQKiy4UR.js";import"./mcp-DQCTu0C2.js";import{u as re}from"./airi-card-BqSQR9SZ.js";import{k as se}from"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as oe}from"./InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js";import{_ as ne}from"./CardDetailDialog.vue_vue_type_script_setup_true_lang-CmdVZPFO.js";import{_ as ie}from"./CardListItem.vue_vue_type_script_setup_true_lang-BYBvY3lt.js";import{a as de}from"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js";import{b as U}from"./route-block-B_A1xBdJ.js";import"./mini_xsschema-P_8cZcRg.js";import"./consciousness-DS3QILRV.js";import"./providers-kjOpfeNb.js";import"./index-LHmcipjy.js";import"./speech-Db_L6FBm.js";import"./floating-ui.core-CgBsuaUc.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./index-D1N6XcGk.js";const ue={class:"flex-1 truncate"},ce={class:"min-w-[160px] flex flex-col gap-0.5 border border-neutral-200 rounded-lg bg-white p-1 shadow-lg dark:border-neutral-800 dark:bg-neutral-900"},me=["onClick"],pe=q({__name:"Select",props:G({options:null,placeholder:null,disabled:{type:Boolean},title:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(V){const s=V,p=H(V,"modelValue"),y=C(()=>{const n=s.options.find(f=>f.value===p.value);return n?n.label:s.placeholder});function $(n){p.value=n}return(n,f)=>(i(),E(r(se),{"auto-size":"","auto-boundary-max-size":""},{popper:A(({hide:g})=>[a("div",ce,[(i(!0),c(z,null,T(s.options,d=>(i(),c("div",Y({ref_for:!0},{...n.$attrs,class:null,style:null},{key:d.value,class:["cursor-pointer rounded px-2 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-800",{"bg-neutral-100 dark:bg-neutral-800":p.value===d.value}],onClick:b=>{$(d.value),g()}}),u(d.label),17,me))),128))])]),default:A(()=>[a("div",{class:F(["min-w-[160px] flex cursor-pointer items-center justify-between gap-2 border rounded-lg bg-white p-2.5 text-xs text-neutral-700 shadow-sm outline-none transition-colors disabled:cursor-not-allowed dark:border-neutral-800 dark:bg-neutral-900 disabled:bg-neutral-100 hover:bg-neutral-50 dark:text-neutral-200 disabled:text-neutral-400 focus:ring-2 focus:ring-black/10 dark:disabled:bg-neutral-800 dark:hover:bg-neutral-800 dark:disabled:text-neutral-600",{"pointer-events-none":s.disabled}])},[a("div",ue,[W(n.$slots,"default",{label:y.value},()=>[X(u(y.value),1)])]),f[0]||(f[0]=a("div",{"i-solar:alt-arrow-down-bold-duotone":"",class:"h-3.5 w-3.5 text-neutral-500 dark:text-neutral-400"},null,-1))],2)]),_:3}))}}),fe={"rounded-xl":"","p-4":"",flex:"~ col gap-4"},ve={flex:"~ row","flex-wrap":"","items-center":"","justify-between":"","gap-4":""},xe={class:"relative min-w-[200px] flex-1","inline-flex":"~","w-full":"","items-center":""},ge=["placeholder"],be={class:"relative flex flex-row justify-start gap-2 lg:flex-col"},_e={class:"top-[-32px] whitespace-nowrap text-sm text-neutral-500 leading-10 lg:absolute dark:text-neutral-400"},ke={key:0,flex:"","flex-col":"","items-center":""},ye={"font-medium":"",text:"neutral-600 dark:neutral-300"},we={text:"neutral-500 dark:neutral-400","mt-2":"","text-sm":""},he={key:1,flex:"","flex-col":"","items-center":""},Ce={"font-medium":"",text:"primary-600 dark:primary-300"},Ve={key:1,class:"col-span-full rounded-xl p-8 text-center",border:"~ neutral-200/50 dark:neutral-700/30",bg:"neutral-50/50 dark:neutral-900/50"},$e={key:2,class:"col-span-full flex items-center gap-3 border-2 border-amber-200 rounded-xl bg-amber-50/80 p-4 dark:border-amber-800 dark:bg-amber-900/30"},De={class:"flex flex-col"},Se={class:"font-medium"},Ae={class:"text-sm text-amber-600 dark:text-amber-400"},ze={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},Ne=q({__name:"index",setup(V){const{t:s}=Z(),p=re(),{addCard:y,removeCard:$}=p,{cards:n,activeCardId:f}=ee(p),g=x(""),d=x(!1),b=x(""),_=x("nameAsc"),D=x([]);te(D,async l=>{const e=l[0];if(e)try{const o=await e.text(),m=JSON.parse(o);g.value=y(m),d.value=!0}catch(o){console.error("Error processing card file:",o)}});const N=C(()=>Array.from(n.value.entries()).map(([l,e])=>({id:l,name:e.name,description:e.description}))),I=C(()=>{if(!b.value)return N.value;const l=b.value.toLowerCase();return N.value.filter(e=>e.name.toLowerCase().includes(l)||e.description&&e.description.toLowerCase().includes(l))}),j=C(()=>{const l=[...I.value];return _.value==="nameAsc"?l.sort((e,o)=>e.name.localeCompare(o.name)):_.value==="nameDesc"?l.sort((e,o)=>o.name.localeCompare(e.name)):_.value==="recent"?l.sort((e,o)=>o.id.localeCompare(e.id)):l}),w=x(!1),v=x(null);function J(){v.value&&($(v.value),v.value=null,w.value=!1)}function K(l){v.value=l,w.value=!0}function P(l){g.value=l,d.value=!0}function Q(l){f.value=l}function R(l){const e=n.value.get(l);return(e==null?void 0:e.version)||"1.0.0"}function B(l,e){var t,k,L,M;const o=n.value.get(l);if(!o||!((k=(t=o.extensions)==null?void 0:t.airi)!=null&&k.modules))return"default";const m=o.extensions.airi.modules;return e==="consciousness"?(L=m.consciousness)!=null&&L.model&&m.consciousness.model.split("-").pop()||"default":e==="voice"&&((M=m.speech)==null?void 0:M.voice_id)||"default"}return(l,e)=>{var m;const o=ae("motion");return i(),c(z,null,[a("div",fe,[a("div",ve,[a("div",xe,[e[6]||(e[6]=a("div",{class:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"},[a("div",{"i-solar:magnifer-line-duotone":"",class:"text-neutral-500 dark:text-neutral-400"})],-1)),O(a("input",{"onUpdate:modelValue":e[0]||(e[0]=t=>b.value=t),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:r(s)("settings.pages.card.search")},null,8,ge),[[le,b.value]])]),a("div",be,[a("div",_e,u(r(s)("settings.pages.card.sort_by"))+": ",1),h(pe,{modelValue:_.value,"onUpdate:modelValue":e[1]||(e[1]=t=>_.value=t),options:[{value:"nameAsc",label:r(s)("settings.pages.card.name_asc")},{value:"nameDesc",label:r(s)("settings.pages.card.name_desc")},{value:"recent",label:r(s)("settings.pages.card.recent")}],placeholder:"Select sort option",class:"min-w-[150px]"},null,8,["modelValue","options"])])]),a("div",{class:F(["mt-4",{"grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4 grid-auto-rows-[minmax(min-content,max-content)] grid-auto-flow-dense sm:grid-cols-[repeat(auto-fill,minmax(240px,1fr))] sm:gap-5 md:grid-cols-[repeat(auto-fill,minmax(220px,1fr))] lg:grid-cols-[repeat(auto-fill,minmax(250px,1fr))]":r(n).size>0}])},[h(r(oe),{modelValue:D.value,"onUpdate:modelValue":e[2]||(e[2]=t=>D.value=t),accept:"*.json"},{default:A(({isDragging:t})=>[t?(i(),c("div",he,[e[8]||(e[8]=a("div",{"i-solar:upload-minimalistic-bold":"",class:"mb-2 text-5xl text-primary-500 dark:text-primary-400"},null,-1)),a("p",Ce,u(r(s)("settings.pages.card.drop_here")),1)])):(i(),c("div",ke,[e[7]||(e[7]=a("div",{"i-solar:upload-square-line-duotone":"","mb-4":"","text-5xl":"",text:"neutral-400 dark:neutral-500"},null,-1)),a("p",ye,u(r(s)("settings.pages.card.upload")),1),a("p",we,u(r(s)("settings.pages.card.upload_desc")),1)]))]),_:1},8,["modelValue"]),r(n).size>0?(i(!0),c(z,{key:0},T(j.value,t=>(i(),E(ie,{id:t.id,key:t.id,name:t.name,description:t.description,"is-active":t.id===r(f),"is-selected":t.id===g.value&&d.value,version:R(t.id),"consciousness-model":B(t.id,"consciousness"),"voice-model":B(t.id,"voice"),onSelect:k=>P(t.id),onActivate:k=>Q(t.id),onDelete:k=>K(t.id)},null,8,["id","name","description","is-active","is-selected","version","consciousness-model","voice-model","onSelect","onActivate","onDelete"]))),128)):S("",!0),r(n).size===0?(i(),c("div",Ve,[e[9]||(e[9]=a("div",{"i-solar:card-search-broken":"","mx-auto":"","mb-3":"","text-6xl":"","text-neutral-400":""},null,-1)),a("p",null,u(r(s)("settings.pages.card.no_cards")),1)])):S("",!0),b.value&&j.value.length===0?(i(),c("div",$e,[e[10]||(e[10]=a("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),a("div",De,[a("span",Se,u(r(s)("settings.pages.card.no_results")),1),a("span",Ae,u(r(s)("settings.pages.card.try_different_search")),1)])])):S("",!0)],2)]),h(de,{modelValue:w.value,"onUpdate:modelValue":e[3]||(e[3]=t=>w.value=t),"card-name":v.value?(m=r(p).getCard(v.value))==null?void 0:m.name:"",onConfirm:J,onCancel:e[4]||(e[4]=t=>v.value=null)},null,8,["modelValue","card-name"]),h(ne,{modelValue:d.value,"onUpdate:modelValue":e[5]||(e[5]=t=>d.value=t),"card-id":g.value},null,8,["modelValue","card-id"]),O((i(),c("div",ze,e[11]||(e[11]=[a("div",{text:"60","i-solar:emoji-funny-square-bold-duotone":""},null,-1)]))),[[o]])],64)}}});typeof U=="function"&&U(Ne);export{Ne as default}; +import{d as q,m as G,u as H,h as C,A as E,o as i,w as A,e as a,n as F,f as W,k as X,t as u,c,F as z,l as T,E as Y,b as r,g as Z,s as ee,r as x,v as te,K as ae,i as h,x as O,y as le,j as S}from"./index-CQudhZin.js";import"./mcp-C9U4MroK.js";import{u as re}from"./airi-card-Bpd1towy.js";import{k as se}from"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as oe}from"./InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js";import{_ as ne}from"./CardDetailDialog.vue_vue_type_script_setup_true_lang-BN5mx1Hz.js";import{_ as ie}from"./CardListItem.vue_vue_type_script_setup_true_lang-B94Ybzjh.js";import{a as de}from"./DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js";import{b as U}from"./route-block-B_A1xBdJ.js";import"./mini_xsschema-P_8cZcRg.js";import"./consciousness-BmgC4h1A.js";import"./providers-Y3Mr8_DF.js";import"./index-LHmcipjy.js";import"./speech-nVAae-rt.js";import"./floating-ui.core-CgBsuaUc.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./index-CAP_srMr.js";const ue={class:"flex-1 truncate"},ce={class:"min-w-[160px] flex flex-col gap-0.5 border border-neutral-200 rounded-lg bg-white p-1 shadow-lg dark:border-neutral-800 dark:bg-neutral-900"},me=["onClick"],pe=q({__name:"Select",props:G({options:null,placeholder:null,disabled:{type:Boolean},title:null},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(V){const s=V,p=H(V,"modelValue"),y=C(()=>{const n=s.options.find(f=>f.value===p.value);return n?n.label:s.placeholder});function $(n){p.value=n}return(n,f)=>(i(),E(r(se),{"auto-size":"","auto-boundary-max-size":""},{popper:A(({hide:g})=>[a("div",ce,[(i(!0),c(z,null,T(s.options,d=>(i(),c("div",Y({ref_for:!0},{...n.$attrs,class:null,style:null},{key:d.value,class:["cursor-pointer rounded px-2 py-1.5 text-sm text-neutral-700 hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-800",{"bg-neutral-100 dark:bg-neutral-800":p.value===d.value}],onClick:b=>{$(d.value),g()}}),u(d.label),17,me))),128))])]),default:A(()=>[a("div",{class:F(["min-w-[160px] flex cursor-pointer items-center justify-between gap-2 border rounded-lg bg-white p-2.5 text-xs text-neutral-700 shadow-sm outline-none transition-colors disabled:cursor-not-allowed dark:border-neutral-800 dark:bg-neutral-900 disabled:bg-neutral-100 hover:bg-neutral-50 dark:text-neutral-200 disabled:text-neutral-400 focus:ring-2 focus:ring-black/10 dark:disabled:bg-neutral-800 dark:hover:bg-neutral-800 dark:disabled:text-neutral-600",{"pointer-events-none":s.disabled}])},[a("div",ue,[W(n.$slots,"default",{label:y.value},()=>[X(u(y.value),1)])]),f[0]||(f[0]=a("div",{"i-solar:alt-arrow-down-bold-duotone":"",class:"h-3.5 w-3.5 text-neutral-500 dark:text-neutral-400"},null,-1))],2)]),_:3}))}}),fe={"rounded-xl":"","p-4":"",flex:"~ col gap-4"},ve={flex:"~ row","flex-wrap":"","items-center":"","justify-between":"","gap-4":""},xe={class:"relative min-w-[200px] flex-1","inline-flex":"~","w-full":"","items-center":""},ge=["placeholder"],be={class:"relative flex flex-row justify-start gap-2 lg:flex-col"},_e={class:"top-[-32px] whitespace-nowrap text-sm text-neutral-500 leading-10 lg:absolute dark:text-neutral-400"},ke={key:0,flex:"","flex-col":"","items-center":""},ye={"font-medium":"",text:"neutral-600 dark:neutral-300"},we={text:"neutral-500 dark:neutral-400","mt-2":"","text-sm":""},he={key:1,flex:"","flex-col":"","items-center":""},Ce={"font-medium":"",text:"primary-600 dark:primary-300"},Ve={key:1,class:"col-span-full rounded-xl p-8 text-center",border:"~ neutral-200/50 dark:neutral-700/30",bg:"neutral-50/50 dark:neutral-900/50"},$e={key:2,class:"col-span-full flex items-center gap-3 border-2 border-amber-200 rounded-xl bg-amber-50/80 p-4 dark:border-amber-800 dark:bg-amber-900/30"},De={class:"flex flex-col"},Se={class:"font-medium"},Ae={class:"text-sm text-amber-600 dark:text-amber-400"},ze={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},Ne=q({__name:"index",setup(V){const{t:s}=Z(),p=re(),{addCard:y,removeCard:$}=p,{cards:n,activeCardId:f}=ee(p),g=x(""),d=x(!1),b=x(""),_=x("nameAsc"),D=x([]);te(D,async l=>{const e=l[0];if(e)try{const o=await e.text(),m=JSON.parse(o);g.value=y(m),d.value=!0}catch(o){console.error("Error processing card file:",o)}});const N=C(()=>Array.from(n.value.entries()).map(([l,e])=>({id:l,name:e.name,description:e.description}))),I=C(()=>{if(!b.value)return N.value;const l=b.value.toLowerCase();return N.value.filter(e=>e.name.toLowerCase().includes(l)||e.description&&e.description.toLowerCase().includes(l))}),j=C(()=>{const l=[...I.value];return _.value==="nameAsc"?l.sort((e,o)=>e.name.localeCompare(o.name)):_.value==="nameDesc"?l.sort((e,o)=>o.name.localeCompare(e.name)):_.value==="recent"?l.sort((e,o)=>o.id.localeCompare(e.id)):l}),w=x(!1),v=x(null);function J(){v.value&&($(v.value),v.value=null,w.value=!1)}function K(l){v.value=l,w.value=!0}function P(l){g.value=l,d.value=!0}function Q(l){f.value=l}function R(l){const e=n.value.get(l);return(e==null?void 0:e.version)||"1.0.0"}function B(l,e){var t,k,L,M;const o=n.value.get(l);if(!o||!((k=(t=o.extensions)==null?void 0:t.airi)!=null&&k.modules))return"default";const m=o.extensions.airi.modules;return e==="consciousness"?(L=m.consciousness)!=null&&L.model&&m.consciousness.model.split("-").pop()||"default":e==="voice"&&((M=m.speech)==null?void 0:M.voice_id)||"default"}return(l,e)=>{var m;const o=ae("motion");return i(),c(z,null,[a("div",fe,[a("div",ve,[a("div",xe,[e[6]||(e[6]=a("div",{class:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"},[a("div",{"i-solar:magnifer-line-duotone":"",class:"text-neutral-500 dark:text-neutral-400"})],-1)),O(a("input",{"onUpdate:modelValue":e[0]||(e[0]=t=>b.value=t),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:r(s)("settings.pages.card.search")},null,8,ge),[[le,b.value]])]),a("div",be,[a("div",_e,u(r(s)("settings.pages.card.sort_by"))+": ",1),h(pe,{modelValue:_.value,"onUpdate:modelValue":e[1]||(e[1]=t=>_.value=t),options:[{value:"nameAsc",label:r(s)("settings.pages.card.name_asc")},{value:"nameDesc",label:r(s)("settings.pages.card.name_desc")},{value:"recent",label:r(s)("settings.pages.card.recent")}],placeholder:"Select sort option",class:"min-w-[150px]"},null,8,["modelValue","options"])])]),a("div",{class:F(["mt-4",{"grid grid-cols-[repeat(auto-fill,minmax(280px,1fr))] gap-4 grid-auto-rows-[minmax(min-content,max-content)] grid-auto-flow-dense sm:grid-cols-[repeat(auto-fill,minmax(240px,1fr))] sm:gap-5 md:grid-cols-[repeat(auto-fill,minmax(220px,1fr))] lg:grid-cols-[repeat(auto-fill,minmax(250px,1fr))]":r(n).size>0}])},[h(r(oe),{modelValue:D.value,"onUpdate:modelValue":e[2]||(e[2]=t=>D.value=t),accept:"*.json"},{default:A(({isDragging:t})=>[t?(i(),c("div",he,[e[8]||(e[8]=a("div",{"i-solar:upload-minimalistic-bold":"",class:"mb-2 text-5xl text-primary-500 dark:text-primary-400"},null,-1)),a("p",Ce,u(r(s)("settings.pages.card.drop_here")),1)])):(i(),c("div",ke,[e[7]||(e[7]=a("div",{"i-solar:upload-square-line-duotone":"","mb-4":"","text-5xl":"",text:"neutral-400 dark:neutral-500"},null,-1)),a("p",ye,u(r(s)("settings.pages.card.upload")),1),a("p",we,u(r(s)("settings.pages.card.upload_desc")),1)]))]),_:1},8,["modelValue"]),r(n).size>0?(i(!0),c(z,{key:0},T(j.value,t=>(i(),E(ie,{id:t.id,key:t.id,name:t.name,description:t.description,"is-active":t.id===r(f),"is-selected":t.id===g.value&&d.value,version:R(t.id),"consciousness-model":B(t.id,"consciousness"),"voice-model":B(t.id,"voice"),onSelect:k=>P(t.id),onActivate:k=>Q(t.id),onDelete:k=>K(t.id)},null,8,["id","name","description","is-active","is-selected","version","consciousness-model","voice-model","onSelect","onActivate","onDelete"]))),128)):S("",!0),r(n).size===0?(i(),c("div",Ve,[e[9]||(e[9]=a("div",{"i-solar:card-search-broken":"","mx-auto":"","mb-3":"","text-6xl":"","text-neutral-400":""},null,-1)),a("p",null,u(r(s)("settings.pages.card.no_cards")),1)])):S("",!0),b.value&&j.value.length===0?(i(),c("div",$e,[e[10]||(e[10]=a("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),a("div",De,[a("span",Se,u(r(s)("settings.pages.card.no_results")),1),a("span",Ae,u(r(s)("settings.pages.card.try_different_search")),1)])])):S("",!0)],2)]),h(de,{modelValue:w.value,"onUpdate:modelValue":e[3]||(e[3]=t=>w.value=t),"card-name":v.value?(m=r(p).getCard(v.value))==null?void 0:m.name:"",onConfirm:J,onCancel:e[4]||(e[4]=t=>v.value=null)},null,8,["modelValue","card-name"]),h(ne,{modelValue:d.value,"onUpdate:modelValue":e[5]||(e[5]=t=>d.value=t),"card-id":g.value},null,8,["modelValue","card-id"]),O((i(),c("div",ze,e[11]||(e[11]=[a("div",{text:"60","i-solar:emoji-funny-square-bold-duotone":""},null,-1)]))),[[o]])],64)}}});typeof U=="function"&&U(Ne);export{Ne as default}; diff --git a/assets/index-DychlYah.js b/assets/index-BvSR0QFl.js similarity index 96% rename from assets/index-DychlYah.js rename to assets/index-BvSR0QFl.js index 51e3a2f403e9653578869f27be505593358eef4f..d77216aa50219f7a7f7867a28ca1668c1dc17638 100644 --- a/assets/index-DychlYah.js +++ b/assets/index-BvSR0QFl.js @@ -1,4 +1,4 @@ -import{d as vs}from"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{p as Gn,r as W,h as Ue,s as Ke,bD as bs,d as Fe,bw as ws,bM as ks,bG as Zr,v as Be,H as Wt,c as oe,o as J,f as gn,by as Ts,g as Qt,G as Xt,A as Zt,w as Ye,i as _e,e as D,n as lt,x as Et,bu as Qr,j as at,t as be,b as H,bN as yt,bO as _t,b8 as Jr,bP as Yn,b4 as Yo,bQ as On,I as Ot,bR as _s,Y as ae,bS as Mi,a3 as Fn,bT as $t,X as Pe,bU as Mt,bV as Es,bW as Ko,bX as hn,bY as ei,W as ze,aj as qo,bZ as Wo,b_ as ti,ac as yn,a1 as Ms,ae as ni,b$ as As,a4 as Xo,$ as xt,c0 as ri,c1 as At,c2 as Ss,c3 as Zo,a2 as Dt,c4 as Qo,bm as Is,c5 as Rs,Q as Cs,c6 as Ns,B as Jo,a7 as Kn,b5 as Ls,b6 as Ps,ap as Ds,a8 as Pt,c7 as Os,c8 as Fs,c9 as Bs,ca as zs,cb as er,cc as Bn,cd as Cr,ah as Nt,ce as ea,cf as Nr,a6 as Vt,cg as Ai,ch as Lt,ci as Ht,cj as tr,ck as Us,cl as js,cm as Vs,cn as Hs,co as ta,cp as na,cq as zn,cr as ra,cs as ii,ct as Un,cu as ia,cv as $s,z as Lr,cw as Gs,cx as Pr,cy as oa,cz as Ys,cA as fn,cB as aa,cC as ft,cD as vt,cE as mn,cF as Ks,cG as qs,cH as Ws,cI as Xs,cJ as Zs,ag as oi,cK as Qs,cL as Js,cM as el,a0 as nr,a9 as tl,cN as sa,al as nl,aa as rl,ak as il,cO as ol,cP as al,a5 as rr,an as sl,aq as ll,cQ as ul,cR as Si,ar as Ii,as as Ri,cS as Ci,cT as cl,cU as fl,cV as dl,cW as pl,cX as hl,_ as qn,P as ml,cY as la,cZ as gl,bh as yl,c_ as xl,c$ as vl,d0 as ua,b3 as jn,K as ca,F as ai,l as si,d1 as bl,bH as ir,bt as wl}from"./index-BQKiy4UR.js";import{V as kl,a as Tl,c as _l,r as El,b as Dr,d as Ml}from"./three-vrm-animation.module-DtlqIxay.js";import{m as Al}from"./mcp-DQCTu0C2.js";import{c as Ni,d as Sl,e as Il,f as Rl,g as Cl}from"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{getImportUrlBundles as Nl}from"./import-url-browser-CPN8ipMD.js";import{s as Gt,c as Li,u as Ll,g as Pl}from"./speech-Db_L6FBm.js";import{u as or}from"./queue-DNS07_tB.js";import{b as Dl,a as Ol,u as Fl,l as Bl}from"./queues-C9_pVSeq.js";import{l as zl,u as li}from"./providers-kjOpfeNb.js";import{s as Ul}from"./index-C4mUnpiM.js";import{u as jl}from"./airi-card-BqSQR9SZ.js";import{_ as ui}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import{_ as Vl,a as Hl,r as an}from"./Model.vue_vue_type_script_setup_true_lang-Dx1Lxvvu.js";import{_ as Pi}from"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import{H as $l}from"./HeaderLink-CnrAQmsl.js";import{d as Di}from"./index-DSso2JwG.js";import{u as fa}from"./consciousness-DS3QILRV.js";import{_ as da}from"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";import{b as Oi}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";import"./duckdb-mvp-CaaD-olE.js";import"./index-LHmcipjy.js";async function*Gl(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 Yl(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 Kl(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 ql(t,e="linear"){switch(e){case"linear":return Yl(t);case"minmax":return Kl(t)}}const pa=Gn("AudioContext",()=>({audioContext:new AudioContext,calculateVolume:ql})),Wl=Gn("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 Xl(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)))}}}const Zl=Gn("llm",()=>{async function t(n,r,i,o){const a=o==null?void 0:o.headers;return await Ul({...r.chat(n),maxSteps:10,messages:i,headers:a,tools:[...await Al()]})}async function e(n,r){if(n==="")return[];try{return await zl({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=Gn("chat",()=>{const{stream:t}=Zl(),{systemPrompt:e}=Ke(jl()),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 y(h){a.value.push(h)}function x(h){s.value.push(h)}function v(h){l.value.push(h)}function k(h){u.value.push(h)}function S(h){c.value.push(h)}const E=W([{role:"system",content:e.value}]),C=W({role:"assistant",content:""});async function P(h,I){var b;try{if(n.value=!0,!h)return;for(const F of r.value)await F(h);C.value={role:"assistant",content:""},E.value.push({role:"user",content:h}),E.value.push(C.value);const g=E.value.slice(0,E.value.length-1).map(F=>bs(F));for(const F of i.value)await F(h);for(const F of o.value)await F(h);const m=((b=I.providerConfig)==null?void 0:b.headers)||{},T=await t(I.model,I.chatProvider,g,{headers:m});for(const F of a.value)await F(h);let M="";const j=Xl({onLiteral:async F=>{for(const z of s.value)await z(F);C.value.content+=F},onSpecial:async F=>{for(const z of l.value)await z(F)}});for await(const F of Gl(T.textStream,async z=>z))M+=F,await j.consume(F);await j.end();for(const F of u.value)await F();for(const F of c.value)await F(M);console.debug("LLM output:",M)}catch(g){throw console.error("Error sending message:",g),g}finally{n.value=!1}}return{sending:n,messages:E,streamingMessage:C,send:P,onBeforeMessageComposed:f,onAfterMessageComposed:p,onBeforeSend:d,onAfterSend:y,onTokenLiteral:x,onTokenSpecial:v,onStreamEnd:k,onAssistantResponseEnd:S}}),ha=Fe({__name:"Screen",setup(t){const e=W(),n=ws(Ts),{width:r,height:i}=ks(),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 Be([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}),Be([o.width,o.height],()=>{l.value||a.value||s.value?c.value=o.height.value:c.value=600}),Wt(async()=>{e.value&&o.update()}),(f,p)=>(J(),oe("div",{ref_key:"containerRef",ref:e,"h-full":"","w-full":""},[gn(f.$slots,"default",{width:u.value,height:c.value})],512))}}),Ql={absolute:"",bottom:"3",right:"3"},Jl={flex:"~ row","cursor-pointer":""},eu=["checked","aria-checked"],tu={key:0,"min-w":"50vw",z:"(J(),Zt(ha,{relative:""},{default:Ye(({width:a,height:s})=>[_e(Hl,{width:a,height:s},{default:Ye(({app:l})=>[_e(Vl,{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"]),D("div",Ql,[D("div",Jl,[D("label",{class:lt([n.value?"bg-neutral-300 dark:bg-neutral-200":"bg-neutral-100 dark:bg-neutral-700"]),transition:"all ease-in-out duration-500",text:"lg neutral-500 dark:neutral-400","m-1":"","h-fit":"","w-fit":"","cursor-pointer":"","appearance-none":"","gap-1":"","rounded-lg":"","rounded-md":"","border-none":"","p-2":"","outline-none":""},[Et(D("input",{"onUpdate:modelValue":o[0]||(o[0]=l=>n.value=l),checked:n.value,"aria-checked":n.value,name:"showLive2DViewerInspector",type:"checkbox","appearance-none":"","outline-none":"",hidden:""},null,8,eu),[[Qr,n.value]]),o[8]||(o[8]=D("div",{"select-none":""},[D("div",{"i-solar:bug-bold-duotone":""})],-1))],2)]),_e(H(ui),null,{default:Ye(()=>[n.value?(J(),oe("div",tu,[D("div",nu,[D("div",ru,[D("span",null,be(H(e)("stage.viewers.debug-menu.emotions")),1)]),D("div",iu,[D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[1]||(o[1]=l=>r.value={group:"Surprise",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.surprised")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[2]||(o[2]=l=>r.value={group:"Sad",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.sad")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[3]||(o[3]=l=>r.value={group:"Angry",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.angry")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[4]||(o[4]=l=>r.value={group:"Happy",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.happy")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[5]||(o[5]=l=>r.value={group:"Awkward",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.awkward")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[6]||(o[6]=l=>r.value={group:"Question",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.question")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[7]||(o[7]=l=>r.value={group:"Think",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.think")),1)])])])):at("",!0)]),_:1})])]),_:1}))}});var au=Object.defineProperty,su=(t,e,n)=>e in t?au(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lu=(t,e,n)=>su(t,e+"",n);function uu(t){return Ls()?(Ps(t),!0):!1}function ma(t){return typeof t=="function"?t():H(t)}const cu=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const fu=Object.prototype.toString,du=t=>fu.call(t)==="[object Object]",pu=()=>{},hu=cu?window:void 0;function mu(t){var e;const n=ma(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=hu):[e,n,r,i]=t,!e)return pu;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=Be(()=>[mu(e),ma(i)],([c,f])=>{if(a(),!c)return;const p=du(f)?{...f}:f;o.push(...n.flatMap(d=>r.map(y=>s(c,d,y,p))))},{immediate:!0,flush:"post"}),u=()=>{l(),a()};return uu(u),u}function ga(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=ni.clone({[l]:{value:u}});return{...s,...c}},{}),vertexShader:e,fragmentShader:n}),lu(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}ga({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},` +import{d as vs}from"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{p as Gn,r as W,h as Ue,s as Ke,b6 as bs,d as Fe,a$ as ws,bf as ks,b9 as Zr,v as Be,H as Wt,c as oe,o as J,f as gn,b1 as Ts,g as Qt,G as Xt,A as Zt,w as Ye,i as _e,e as D,n as lt,x as Et,aZ as Qr,j as at,t as be,b as H,bg as yt,bh as _t,aC as Jr,bi as Yn,ay as Yo,bj as On,I as Ot,bk as _s,$ as ae,bl as Mi,a5 as Fn,bm as $t,Z as Pe,bn as Mt,bo as Es,bp as Ko,bq as hn,br as ei,Y as ze,al as qo,bs as Wo,bt as ti,ae as yn,a3 as Ms,ag as ni,bu as As,a6 as Xo,a1 as xt,bv as ri,bw as At,bx as Ss,by as Zo,a4 as Dt,bz as Qo,aQ as Is,bA as Rs,Q as Cs,bB as Ns,B as Jo,a9 as Kn,az as Ls,aA as Ps,ar as Ds,aa as Pt,bC as Os,bD as Fs,bE as Bs,bF as zs,bG as er,bH as Bn,bI as Cr,aj as Nt,bJ as ea,bK as Nr,a8 as Vt,bL as Ai,bM as Lt,bN as Ht,bO as tr,bP as Us,bQ as js,bR as Vs,bS as Hs,bT as ta,bU as na,bV as zn,bW as ra,bX as ii,bY as Un,bZ as ia,b_ as $s,z as Lr,b$ as Gs,c0 as Pr,c1 as oa,c2 as Ys,c3 as fn,c4 as aa,c5 as ft,c6 as vt,c7 as mn,c8 as Ks,c9 as qs,ca as Ws,cb as Xs,cc as Zs,ai as oi,cd as Qs,ce as Js,cf as el,a2 as nr,ab as tl,cg as sa,an as nl,ac as rl,am as il,ch as ol,ci as al,a7 as rr,ap as sl,as as ll,cj as ul,ck as Si,at as Ii,au as Ri,cl as Ci,cm as cl,cn as fl,co as dl,cp as pl,cq as hl,_ as qn,P as ml,cr as la,cs as gl,aL as yl,ct as xl,cu as vl,cv as ua,ax as jn,K as ca,F as ai,l as si,cw as bl,ba as ir,aY as wl}from"./index-CQudhZin.js";import{V as kl,a as Tl,c as _l,r as El,b as Dr,d as Ml}from"./three-vrm-animation.module-Dklr5eVx.js";import{m as Al}from"./mcp-C9U4MroK.js";import{c as Ni,d as Sl,e as Il,f as Rl,g as Cl}from"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{getImportUrlBundles as Nl}from"./import-url-browser-CPN8ipMD.js";import{s as Gt,c as Li,u as Ll,g as Pl}from"./speech-nVAae-rt.js";import{u as or}from"./queue-3c99Yq5f.js";import{b as Dl,a as Ol,u as Fl,l as Bl}from"./queues-B-17ADgG.js";import{l as zl,u as li}from"./providers-Y3Mr8_DF.js";import{s as Ul}from"./index-C4mUnpiM.js";import{u as jl}from"./airi-card-Bpd1towy.js";import{_ as ui}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import{_ as Vl,a as Hl,r as an}from"./Model.vue_vue_type_script_setup_true_lang-PK96Pm-_.js";import{_ as Pi}from"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import{H as $l}from"./HeaderLink-DVu0ldr4.js";import{d as Di}from"./index-DC4guwRc.js";import{u as fa}from"./consciousness-BmgC4h1A.js";import{_ as da}from"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";import{b as Oi}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";import"./duckdb-mvp-CaaD-olE.js";import"./index-LHmcipjy.js";async function*Gl(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 Yl(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 Kl(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 ql(t,e="linear"){switch(e){case"linear":return Yl(t);case"minmax":return Kl(t)}}const pa=Gn("AudioContext",()=>({audioContext:new AudioContext,calculateVolume:ql})),Wl=Gn("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 Xl(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)))}}}const Zl=Gn("llm",()=>{async function t(n,r,i,o){const a=o==null?void 0:o.headers;return await Ul({...r.chat(n),maxSteps:10,messages:i,headers:a,tools:[...await Al()]})}async function e(n,r){if(n==="")return[];try{return await zl({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=Gn("chat",()=>{const{stream:t}=Zl(),{systemPrompt:e}=Ke(jl()),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 y(h){a.value.push(h)}function x(h){s.value.push(h)}function v(h){l.value.push(h)}function k(h){u.value.push(h)}function S(h){c.value.push(h)}const E=W([{role:"system",content:e.value}]),C=W({role:"assistant",content:""});async function P(h,I){var b;try{if(n.value=!0,!h)return;for(const F of r.value)await F(h);C.value={role:"assistant",content:""},E.value.push({role:"user",content:h}),E.value.push(C.value);const g=E.value.slice(0,E.value.length-1).map(F=>bs(F));for(const F of i.value)await F(h);for(const F of o.value)await F(h);const m=((b=I.providerConfig)==null?void 0:b.headers)||{},T=await t(I.model,I.chatProvider,g,{headers:m});for(const F of a.value)await F(h);let M="";const j=Xl({onLiteral:async F=>{for(const z of s.value)await z(F);C.value.content+=F},onSpecial:async F=>{for(const z of l.value)await z(F)}});for await(const F of Gl(T.textStream,async z=>z))M+=F,await j.consume(F);await j.end();for(const F of u.value)await F();for(const F of c.value)await F(M);console.debug("LLM output:",M)}catch(g){throw console.error("Error sending message:",g),g}finally{n.value=!1}}return{sending:n,messages:E,streamingMessage:C,send:P,onBeforeMessageComposed:f,onAfterMessageComposed:p,onBeforeSend:d,onAfterSend:y,onTokenLiteral:x,onTokenSpecial:v,onStreamEnd:k,onAssistantResponseEnd:S}}),ha=Fe({__name:"Screen",setup(t){const e=W(),n=ws(Ts),{width:r,height:i}=ks(),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 Be([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}),Be([o.width,o.height],()=>{l.value||a.value||s.value?c.value=o.height.value:c.value=600}),Wt(async()=>{e.value&&o.update()}),(f,p)=>(J(),oe("div",{ref_key:"containerRef",ref:e,"h-full":"","w-full":""},[gn(f.$slots,"default",{width:u.value,height:c.value})],512))}}),Ql={absolute:"",bottom:"3",right:"3"},Jl={flex:"~ row","cursor-pointer":""},eu=["checked","aria-checked"],tu={key:0,"min-w":"50vw",z:"(J(),Zt(ha,{relative:""},{default:Ye(({width:a,height:s})=>[_e(Hl,{width:a,height:s},{default:Ye(({app:l})=>[_e(Vl,{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"]),D("div",Ql,[D("div",Jl,[D("label",{class:lt([n.value?"bg-neutral-300 dark:bg-neutral-200":"bg-neutral-100 dark:bg-neutral-700"]),transition:"all ease-in-out duration-500",text:"lg neutral-500 dark:neutral-400","m-1":"","h-fit":"","w-fit":"","cursor-pointer":"","appearance-none":"","gap-1":"","rounded-lg":"","rounded-md":"","border-none":"","p-2":"","outline-none":""},[Et(D("input",{"onUpdate:modelValue":o[0]||(o[0]=l=>n.value=l),checked:n.value,"aria-checked":n.value,name:"showLive2DViewerInspector",type:"checkbox","appearance-none":"","outline-none":"",hidden:""},null,8,eu),[[Qr,n.value]]),o[8]||(o[8]=D("div",{"select-none":""},[D("div",{"i-solar:bug-bold-duotone":""})],-1))],2)]),_e(H(ui),null,{default:Ye(()=>[n.value?(J(),oe("div",tu,[D("div",nu,[D("div",ru,[D("span",null,be(H(e)("stage.viewers.debug-menu.emotions")),1)]),D("div",iu,[D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[1]||(o[1]=l=>r.value={group:"Surprise",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.surprised")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[2]||(o[2]=l=>r.value={group:"Sad",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.sad")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[3]||(o[3]=l=>r.value={group:"Angry",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.angry")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[4]||(o[4]=l=>r.value={group:"Happy",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.happy")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[5]||(o[5]=l=>r.value={group:"Awkward",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.awkward")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[6]||(o[6]=l=>r.value={group:"Question",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.question")),1),D("button",{"rounded-lg":"",bg:"neutral-100/70 dark:neutral-800/50","px-2":"","py-1":"","backdrop-blur-sm":"",onClick:o[7]||(o[7]=l=>r.value={group:"Think",index:0})},be(H(e)("stage.viewers.debug-menu.emotions-btn.think")),1)])])])):at("",!0)]),_:1})])]),_:1}))}});var au=Object.defineProperty,su=(t,e,n)=>e in t?au(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lu=(t,e,n)=>su(t,e+"",n);function uu(t){return Ls()?(Ps(t),!0):!1}function ma(t){return typeof t=="function"?t():H(t)}const cu=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const fu=Object.prototype.toString,du=t=>fu.call(t)==="[object Object]",pu=()=>{},hu=cu?window:void 0;function mu(t){var e;const n=ma(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=hu):[e,n,r,i]=t,!e)return pu;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=Be(()=>[mu(e),ma(i)],([c,f])=>{if(a(),!c)return;const p=du(f)?{...f}:f;o.push(...n.flatMap(d=>r.map(y=>s(c,d,y,p))))},{immediate:!0,flush:"post"}),u=()=>{l(),a()};return uu(u),u}function ga(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=ni.clone({[l]:{value:u}});return{...s,...c}},{}),vertexShader:e,fragmentShader:n}),lu(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}ga({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},` varying vec2 vUv; varying vec2 vPos; void main() { @@ -527,6 +527,6 @@ void main() { `});++r0&&n.push({type:"text",value:` `}),n}function zo(t){let e=0,n=t.charCodeAt(e);for(;n===9||n===32;)e++,n=t.charCodeAt(e);return t.slice(e)}function Uo(t,e){const n=Qm(t,e),r=n.one(t,void 0),i=Um(n),o=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return i&&o.children.push({type:"text",value:` -`},i),o}function rg(t,e){return t&&"run"in t?async function(n,r){const i=Uo(n,{file:r,...e});await t.run(i,r)}:function(n,r){return Uo(n,{file:r,...t||e})}}function jo(t){if(t)throw t}var Tr,Vo;function ig(){if(Vo)return Tr;Vo=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)},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 Tr=function l(){var u,c,f,p,d,y,x=arguments[0],v=1,k=arguments.length,S=!1;for(typeof x=="boolean"&&(S=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 Xe 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=pn(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}}Xe.prototype.file="";Xe.prototype.name="";Xe.prototype.reason="";Xe.prototype.message="";Xe.prototype.stack="";Xe.prototype.column=void 0;Xe.prototype.line=void 0;Xe.prototype.ancestors=void 0;Xe.prototype.cause=void 0;Xe.prototype.fatal=void 0;Xe.prototype.place=void 0;Xe.prototype.ruleId=void 0;Xe.prototype.source=void 0;const st={basename:lg,dirname:ug,extname:cg,join:fg,sep:"/"};function lg(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 ug(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 cg(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 fg(...t){let e=-1,n;for(;++e0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function pg(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 hg={cwd:mg};function mg(){return"/"}function Xr(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function gg(t){if(typeof t=="string")t=new URL(t);else if(!Xr(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 yg(t)}function yg(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,...y]=c;const x=r[p][1];Wr(x)&&Wr(d)&&(d=_r(!0,x,d)),r[p]=[u,d,...y]}}}}const kg=new Ti().freeze();function Sr(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Ir(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Rr(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 $o(t){if(!Wr(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Go(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function Nn(t){return Tg(t)?t:new xg(t)}function Tg(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function _g(t){return typeof t=="string"||Eg(t)}function Eg(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}function _i(){const t=kg().use(am).use(rg).use(ep);return{process:e=>t.processSync(e).toString()}}const Mg={relative:""},Ag={"h-full":"","w-full":""},Sg={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"},Ig={bg:"primary-50","rounded-xl":"","px-10":"","py-6":""},Rg=["innerHTML"],Cg=Fe({__name:"Stage",props:{paused:{type:Boolean,default:!1}},setup(t){const e=W(),n=W(),{stageView:r}=Ke(Xt()),{mouthOpenSize:i}=Ke(Wl()),{audioContext:o,calculateVolume:a}=pa(),{onBeforeMessageComposed:s,onBeforeSend:l,onTokenLiteral:u,onTokenSpecial:c,onStreamEnd:f,streamingMessage:p,onAssistantResponseEnd:d}=St(),{process:y}=_i(),x=li(),v=W(),k=W(!1),S=W(!1),E=or({handlers:[_=>new Promise(ee=>{const he=o.createBufferSource();he.buffer=_.data.audioBuffer,he.connect(o.destination),he.connect(v.value),k.value=!0,he.start(0),he.onended=()=>{k.value=!1,ee()}})]}),C=Ll(),{ssmlEnabled:P,activeSpeechProvider:h,activeSpeechModel:I,activeSpeechVoice:b,pitch:g}=Ke(C);async function m(_){try{if(!h.value){console.warn("No active speech provider configured");return}if(!b.value){console.warn("No active speech voice configured");return}const ee=x.getProviderInstance(h.value);if(!ee){console.error("Failed to initialize speech provider");return}const he=x.getProviderConfig(h.value),R=P.value?C.generateSSML(_.data,b.value,{...he,pitch:g.value}):_.data,me=await Pl({...ee.speech(I.value,he),input:R,voice:b.value.id}),ke=await o.decodeAudioData(me);await E.add({audioBuffer:ke,text:_.data})}catch(ee){console.error("Speech generation failed:",ee)}}const T=or({handlers:[m]});T.on("add",_=>{console.debug("ttsQueue added",_)});const M=Dl(T),{live2dCurrentMotion:j}=Ke(Xt()),F=or({handlers:[async _=>{if(r.value==="3d"){const ee=Rl[_.data];if(!ee)return;await n.value.setExpression(ee)}else r.value==="2d"&&(j.value={group:Cl[_.data]})}]}),z=Ol(F);z.onHandlerEvent("emotion",_=>{console.debug("emotion detected",_)});const U=Fl();U.onHandlerEvent("delay",_=>{console.debug("delay detected",_)});function Q(){requestAnimationFrame(Q),k.value&&(i.value=a(v.value,"linear"))}function ie(){S.value||(Q(),o.resume(),S.value=!0)}function Z(){v.value||(v.value=o.createAnalyser())}return s(async()=>{Z(),ie()}),l(async()=>{j.value={group:Ni}}),u(async _=>{await M.add(_)}),c(async _=>{await U.add(_),await z.add(_)}),f(async()=>{await U.add(Bl)}),d(async _=>{}),Ot(()=>{var ee,he,R;S.value=!1;const _=window;(ee=_.electron)==null||ee.ipcRenderer.removeAllListeners("before-hide"),(he=_.electron)==null||he.ipcRenderer.removeAllListeners("after-show"),(R=_.electron)==null||R.ipcRenderer.removeAllListeners("before-quit")}),Wt(()=>{var ee,he,R;const _=window;(ee=_.electron)==null||ee.ipcRenderer.on("before-hide",()=>{j.value={group:Sl}}),(he=_.electron)==null||he.ipcRenderer.on("after-show",()=>{j.value={group:Il}}),(R=_.electron)==null||R.ipcRenderer.on("before-quit",()=>{j.value={group:Ni}})}),Wt(async()=>{e.value=vs({connection:{bundles:Nl()}}),await e.value.execute("CREATE TABLE memory_test (vec FLOAT[768]);")}),(_,ee)=>(J(),oe("div",Mg,[D("div",Ag,[H(r)==="2d"?(J(),Zt(ou,{key:0,"mouth-open-size":H(i),"min-w":"50% (J(),oe("header",Fg,[D("div",Bg,[_e($l)]),_e(H(ml),{class:"m-1 block max-h-[10lh] min-h-[1lh] rounded-lg bg-neutral-100 p-2 text-lg text-neutral-500 outline-none dark:bg-neutral-800 dark:text-neutral-400",to:"/settings"},{default:Ye(()=>n[0]||(n[0]=[D("div",{"i-solar:settings-minimalistic-bold-duotone":""},null,-1)])),_:1})]))}});function xs(t,e){const n=la(e??{},{...Di.getDefaultRealTimeVADOptions("v5"),preSpeechPadFrames:30,positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,minSpeechFrames:30,auto:!0}),r=W(),i=gl("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 Di.MicVAD.new({...n,stream:s}),n.auto&&r.value.start()}return Be(i,o,{immediate:!0}),Be(yl(t),o,{immediate:!0}),xl(o),Ot(()=>{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 Ug(t,e){const n=la(e,{onLoading:()=>{},onInitiate:()=>{},onProgress:()=>{},onDone:()=>{},onReady:()=>{},onStart:()=>{},onUpdate:()=>{},onComplete:()=>{}}),{post:r,data:i,terminate:o}=vl(t,{type:"module"}),a=W(null),s=W(""),l=W([]),u=W(!1),c=W(0),f=W("");return Be(i,p=>{var d,y,x,v,k,S,E,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),(y=n.onInitiate)==null||y.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",(k=n.onReady)==null||k.call(n);break;case"start":u.value=!0,(S=n.onStart)==null||S.call(n);break;case"update":c.value=p.tps,(E=n.onUpdate)==null||E.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}}),Ot(()=>{o()}),{transcribe:p=>r(p),status:a,loadingMessage:s,loadingProgress:l,transcribing:u,tps:c,result:f,load:()=>r({type:"load"}),terminate:o}}const jg="/assets/worker-i3yLSyEt.js";async function Vg(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),Hg(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=ca("auto-animate");return J(),oe("div",$g,[f[2]||(f[2]=D("div",{"flex-1":""},null,-1)),Et((J(),oe("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"",flex:"~ col","overflow-scroll":""},[f[1]||(f[1]=D("div",{"flex-1":""},null,-1)),(J(!0),oe(ai,null,si(H(n),(d,y)=>(J(),oe("div",{key:y,"mb-2":""},[d.role==="error"?(J(),oe("div",Gg,[D("div",Yg,[D("div",Kg,[D("div",qg,[D("span",Wg,be(H(a)("stage.chat.message.character-name.core-system")),1)]),f[0]||(f[0]=D("div",{"i-solar:danger-triangle-bold-duotone":"","text-violet-500":""},null,-1))]),H(r)&&y===H(n).length-1?(J(),oe("div",Xg)):(J(),oe("div",{key:1,class:"markdown-content break-words text-violet-500",text:"base {if(!m||!m.trim())return;const T=o.getProviderConfig(a.value);await y(m,{chatProvider:o.getProviderInstance(a.value),model:s.value,providerConfig:T})}});async function P(){if(e.value.trim())try{const m=o.getProviderConfig(a.value);await y(e.value,{chatProvider:o.getProviderInstance(a.value),model:s.value,providerConfig:m})}catch(m){v.value.pop(),v.value.push({role:"error",content:m.message})}}const{destroy:h,start:I}=xs(d,{onSpeechStart:()=>{n.value=!0},onVADMisfire:()=>{n.value=!1},onSpeechEnd:m=>{n.value=!1,b(m)},auto:!1});async function b(m){await k.resume();const T=await Vg(m,k.sampleRate);E({type:"generate",data:{audio:T,language:"en"}})}async function g(m){const T=m.target,M=u.value.find(j=>j.deviceId===T.value);if(!M){f.value=void 0;return}f.value=M}return Be(p,async m=>{m==="false"&&(h(),C())}),Be(i,async m=>{m&&await c()}),Wt(()=>{I()}),x(async()=>{e.value=""}),(m,T)=>(J(),oe("div",uy,[D("fieldset",cy,[D("label",{class:lt([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":""},[Et(D("input",{"onUpdate:modelValue":T[0]||(T[0]=M=>r.value=M),type:"radio",name:"tab",value:"chat",hidden:""},null,512),[[ir,r.value]]),T[5]||(T[5]=D("div",{"i-solar:dialog-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),D("div",dy,[D("span",py,be(H(S)("stage.chat.tabs.chat")),1)])],10,fy),D("label",{class:lt([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":""},[Et(D("input",{"onUpdate:modelValue":T[1]||(T[1]=M=>r.value=M),type:"radio",name:"tab",value:"custom",hidden:""},null,512),[[ir,r.value]]),T[6]||(T[6]=D("div",{"i-solar:star-fall-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),D("div",my,[D("span",null,be(H(S)("stage.chat.tabs.custom")),1)])],10,hy),D("label",{class:lt([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":""},[Et(D("input",{"onUpdate:modelValue":T[2]||(T[2]=M=>r.value=M),type:"radio",name:"tab",value:"clothes",hidden:""},null,512),[[ir,r.value]]),T[7]||(T[7]=D("div",{"i-solar:magic-stick-3-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),D("div",yy,[D("span",null,be(H(S)("stage.chat.tabs.clothes")),1)])],10,gy)]),D("div",xy,[D("div",vy,[_e(ly,{"h-full":"","flex-1":"","p-4":"",w:"full","max-h":"e.value=M),placeholder:H(S)("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:lt({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:P},null,8,["modelValue","placeholder","class"])])])]),D("div",wy,[D("div",ky,[_e(H(ui),null,{default:Ye(()=>[i.value?(J(),oe("fieldset",Ty,[(J(!0),oe(ai,null,si(H(u),(M,j)=>(J(),oe("label",{key:j,class:"[&_div_span]:dark:hover:bg-cyan-300 [&_div_span]:dark:hover:bg-cyan-900"},[D("input",{type:"radio",name:"audioInput",value:M.deviceId,hidden:"",onChange:g},null,40,_y),D("div",Ey,[D("div",My,[M.deviceId===H(d)?(J(),oe("div",Ay)):at("",!0)]),D("span",{"inline-block":"",class:lt([M.deviceId===H(d)?"cyan-400 dark:text-white":"cyan-400/50 dark:text-white/50"]),transition:"all duration-250 ease-in-out"},be(M.label),3)])]))),128))])):at("",!0)]),_:1}),D("label",{bg:"complementary-100 hover:complementary-200 dark:complementary-800 dark:hover:complementary-700",transition:"all duration-250 ease-in-out",class:lt({"transition-colors-none":H(l)}),text:"complementary-400","h-fit":"",flex:"","cursor-pointer":"","items-center":"","justify-center":"","gap-2":"","rounded-full":"","px-4":"","py-2":""},[Et(D("input",{"onUpdate:modelValue":T[4]||(T[4]=M=>i.value=M),type:"checkbox",hidden:""},null,512),[[Qr,i.value]]),T[8]||(T[8]=D("div",{"i-solar:microphone-2-bold-duotone":""},null,-1)),D("div",null,[n.value?(J(),oe("span",Iy,"Listening...")):(J(),oe("span",Sy,be(H(S)("settings.microphone")),1))])],2)])])]))}}),Cy=qn(Ry,[["__scopeId","data-v-df569696"]]),Ny={py:"1",flex:"~ col",rounded:"lg","overflow-hidden":""},Ly={key:0,flex:"",mr:"12"},Py={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=ca("auto-animate");return J(),oe("div",Ny,[c[1]||(c[1]=D("div",{"flex-1":""},null,-1)),Et((J(),oe("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"","max-h":"30vh",flex:"~ col","overflow-scroll":""},[c[0]||(c[0]=D("div",{"flex-1":""},null,-1)),(J(!0),oe(ai,null,si(H(r),(p,d)=>(J(),oe("div",{key:d,"mb-2":""},[p.role==="assistant"?(J(),oe("div",Ly,[D("div",Py,[D("div",null,[D("span",Dy,be(H(n)("stage.chat.message.character-name.airi")),1)]),p.content?(J(),oe("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 Be(a,async v=>{v==="false"&&d()}),c(async()=>{e.value=""}),Wt(()=>{y()}),(v,k)=>(J(),oe("div",null,[D("div",$y,[_e(Hy,{absolute:"","left-0":"","top-0":"",transform:"translate-y-[-100%]","w-full":""}),D("div",Gy,[_e(H(da),{modelValue:e.value,"onUpdate:modelValue":k[0]||(k[0]=S=>e.value=S),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:lt({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:p},null,8,["modelValue","placeholder","class"])])])]))}}),Ky={class:"relative"},qy={absolute:"","left-0":"","right-0":"","top-0":"","w-full":"","overflow-hidden":""},Wy=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),a=W(e.direction),s=W(e.movementDirection);function l(f,p,d,y,x){const v=[],S=Math.ceil(f/y)*y,E=1,C=x==="up"?d:p-d;v.push(`M 0 ${C}`);const P=Math.PI*2/y;for(let I=0;I<=S;I+=E){const b=d*Math.sin(P*I),g=x==="up"?C-b:C+b;v.push(`L ${I} ${g}`)}const h=x==="up"?p:0;return v.push(`L ${S} ${h}`),v.push(`L 0 ${h} Z`),v.join(" ")}const u=Ue(()=>n.value+r.value*2),c=Ue(()=>{const f=` +`},i),o}function rg(t,e){return t&&"run"in t?async function(n,r){const i=Uo(n,{file:r,...e});await t.run(i,r)}:function(n,r){return Uo(n,{file:r,...t||e})}}function jo(t){if(t)throw t}var Tr,Vo;function ig(){if(Vo)return Tr;Vo=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)},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 Tr=function l(){var u,c,f,p,d,y,x=arguments[0],v=1,k=arguments.length,S=!1;for(typeof x=="boolean"&&(S=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 Xe 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=pn(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}}Xe.prototype.file="";Xe.prototype.name="";Xe.prototype.reason="";Xe.prototype.message="";Xe.prototype.stack="";Xe.prototype.column=void 0;Xe.prototype.line=void 0;Xe.prototype.ancestors=void 0;Xe.prototype.cause=void 0;Xe.prototype.fatal=void 0;Xe.prototype.place=void 0;Xe.prototype.ruleId=void 0;Xe.prototype.source=void 0;const st={basename:lg,dirname:ug,extname:cg,join:fg,sep:"/"};function lg(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 ug(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 cg(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 fg(...t){let e=-1,n;for(;++e0&&t.codePointAt(t.length-1)===47&&(n+="/"),e?"/"+n:n}function pg(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 hg={cwd:mg};function mg(){return"/"}function Xr(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function gg(t){if(typeof t=="string")t=new URL(t);else if(!Xr(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 yg(t)}function yg(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,...y]=c;const x=r[p][1];Wr(x)&&Wr(d)&&(d=_r(!0,x,d)),r[p]=[u,d,...y]}}}}const kg=new Ti().freeze();function Sr(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Ir(t,e){if(typeof e!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Rr(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 $o(t){if(!Wr(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Go(t,e,n){if(!n)throw new Error("`"+t+"` finished async. Use `"+e+"` instead")}function Nn(t){return Tg(t)?t:new xg(t)}function Tg(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function _g(t){return typeof t=="string"||Eg(t)}function Eg(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}function _i(){const t=kg().use(am).use(rg).use(ep);return{process:e=>t.processSync(e).toString()}}const Mg={relative:""},Ag={"h-full":"","w-full":""},Sg={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"},Ig={bg:"primary-50","rounded-xl":"","px-10":"","py-6":""},Rg=["innerHTML"],Cg=Fe({__name:"Stage",props:{paused:{type:Boolean,default:!1}},setup(t){const e=W(),n=W(),{stageView:r}=Ke(Xt()),{mouthOpenSize:i}=Ke(Wl()),{audioContext:o,calculateVolume:a}=pa(),{onBeforeMessageComposed:s,onBeforeSend:l,onTokenLiteral:u,onTokenSpecial:c,onStreamEnd:f,streamingMessage:p,onAssistantResponseEnd:d}=St(),{process:y}=_i(),x=li(),v=W(),k=W(!1),S=W(!1),E=or({handlers:[_=>new Promise(ee=>{const he=o.createBufferSource();he.buffer=_.data.audioBuffer,he.connect(o.destination),he.connect(v.value),k.value=!0,he.start(0),he.onended=()=>{k.value=!1,ee()}})]}),C=Ll(),{ssmlEnabled:P,activeSpeechProvider:h,activeSpeechModel:I,activeSpeechVoice:b,pitch:g}=Ke(C);async function m(_){try{if(!h.value){console.warn("No active speech provider configured");return}if(!b.value){console.warn("No active speech voice configured");return}const ee=x.getProviderInstance(h.value);if(!ee){console.error("Failed to initialize speech provider");return}const he=x.getProviderConfig(h.value),R=P.value?C.generateSSML(_.data,b.value,{...he,pitch:g.value}):_.data,me=await Pl({...ee.speech(I.value,he),input:R,voice:b.value.id}),ke=await o.decodeAudioData(me);await E.add({audioBuffer:ke,text:_.data})}catch(ee){console.error("Speech generation failed:",ee)}}const T=or({handlers:[m]});T.on("add",_=>{console.debug("ttsQueue added",_)});const M=Dl(T),{live2dCurrentMotion:j}=Ke(Xt()),F=or({handlers:[async _=>{if(r.value==="3d"){const ee=Rl[_.data];if(!ee)return;await n.value.setExpression(ee)}else r.value==="2d"&&(j.value={group:Cl[_.data]})}]}),z=Ol(F);z.onHandlerEvent("emotion",_=>{console.debug("emotion detected",_)});const U=Fl();U.onHandlerEvent("delay",_=>{console.debug("delay detected",_)});function Q(){requestAnimationFrame(Q),k.value&&(i.value=a(v.value,"linear"))}function ie(){S.value||(Q(),o.resume(),S.value=!0)}function Z(){v.value||(v.value=o.createAnalyser())}return s(async()=>{Z(),ie()}),l(async()=>{j.value={group:Ni}}),u(async _=>{await M.add(_)}),c(async _=>{await U.add(_),await z.add(_)}),f(async()=>{await U.add(Bl)}),d(async _=>{}),Ot(()=>{var ee,he,R;S.value=!1;const _=window;(ee=_.electron)==null||ee.ipcRenderer.removeAllListeners("before-hide"),(he=_.electron)==null||he.ipcRenderer.removeAllListeners("after-show"),(R=_.electron)==null||R.ipcRenderer.removeAllListeners("before-quit")}),Wt(()=>{var ee,he,R;const _=window;(ee=_.electron)==null||ee.ipcRenderer.on("before-hide",()=>{j.value={group:Sl}}),(he=_.electron)==null||he.ipcRenderer.on("after-show",()=>{j.value={group:Il}}),(R=_.electron)==null||R.ipcRenderer.on("before-quit",()=>{j.value={group:Ni}})}),Wt(async()=>{e.value=vs({connection:{bundles:Nl()}}),await e.value.execute("CREATE TABLE memory_test (vec FLOAT[768]);")}),(_,ee)=>(J(),oe("div",Mg,[D("div",Ag,[H(r)==="2d"?(J(),Zt(ou,{key:0,"mouth-open-size":H(i),"min-w":"50% (J(),oe("header",Fg,[D("div",Bg,[_e($l)]),_e(H(ml),{class:"m-1 block max-h-[10lh] min-h-[1lh] rounded-lg bg-neutral-100 p-2 text-lg text-neutral-500 outline-none dark:bg-neutral-800 dark:text-neutral-400",to:"/settings"},{default:Ye(()=>n[0]||(n[0]=[D("div",{"i-solar:settings-minimalistic-bold-duotone":""},null,-1)])),_:1})]))}});function xs(t,e){const n=la(e??{},{...Di.getDefaultRealTimeVADOptions("v5"),preSpeechPadFrames:30,positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,minSpeechFrames:30,auto:!0}),r=W(),i=gl("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 Di.MicVAD.new({...n,stream:s}),n.auto&&r.value.start()}return Be(i,o,{immediate:!0}),Be(yl(t),o,{immediate:!0}),xl(o),Ot(()=>{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 Ug(t,e){const n=la(e,{onLoading:()=>{},onInitiate:()=>{},onProgress:()=>{},onDone:()=>{},onReady:()=>{},onStart:()=>{},onUpdate:()=>{},onComplete:()=>{}}),{post:r,data:i,terminate:o}=vl(t,{type:"module"}),a=W(null),s=W(""),l=W([]),u=W(!1),c=W(0),f=W("");return Be(i,p=>{var d,y,x,v,k,S,E,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),(y=n.onInitiate)==null||y.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",(k=n.onReady)==null||k.call(n);break;case"start":u.value=!0,(S=n.onStart)==null||S.call(n);break;case"update":c.value=p.tps,(E=n.onUpdate)==null||E.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}}),Ot(()=>{o()}),{transcribe:p=>r(p),status:a,loadingMessage:s,loadingProgress:l,transcribing:u,tps:c,result:f,load:()=>r({type:"load"}),terminate:o}}const jg="/assets/worker-LE59aox_.js";async function Vg(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),Hg(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=ca("auto-animate");return J(),oe("div",$g,[f[2]||(f[2]=D("div",{"flex-1":""},null,-1)),Et((J(),oe("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"",flex:"~ col","overflow-scroll":""},[f[1]||(f[1]=D("div",{"flex-1":""},null,-1)),(J(!0),oe(ai,null,si(H(n),(d,y)=>(J(),oe("div",{key:y,"mb-2":""},[d.role==="error"?(J(),oe("div",Gg,[D("div",Yg,[D("div",Kg,[D("div",qg,[D("span",Wg,be(H(a)("stage.chat.message.character-name.core-system")),1)]),f[0]||(f[0]=D("div",{"i-solar:danger-triangle-bold-duotone":"","text-violet-500":""},null,-1))]),H(r)&&y===H(n).length-1?(J(),oe("div",Xg)):(J(),oe("div",{key:1,class:"markdown-content break-words text-violet-500",text:"base {if(!m||!m.trim())return;const T=o.getProviderConfig(a.value);await y(m,{chatProvider:o.getProviderInstance(a.value),model:s.value,providerConfig:T})}});async function P(){if(e.value.trim())try{const m=o.getProviderConfig(a.value);await y(e.value,{chatProvider:o.getProviderInstance(a.value),model:s.value,providerConfig:m})}catch(m){v.value.pop(),v.value.push({role:"error",content:m.message})}}const{destroy:h,start:I}=xs(d,{onSpeechStart:()=>{n.value=!0},onVADMisfire:()=>{n.value=!1},onSpeechEnd:m=>{n.value=!1,b(m)},auto:!1});async function b(m){await k.resume();const T=await Vg(m,k.sampleRate);E({type:"generate",data:{audio:T,language:"en"}})}async function g(m){const T=m.target,M=u.value.find(j=>j.deviceId===T.value);if(!M){f.value=void 0;return}f.value=M}return Be(p,async m=>{m==="false"&&(h(),C())}),Be(i,async m=>{m&&await c()}),Wt(()=>{I()}),x(async()=>{e.value=""}),(m,T)=>(J(),oe("div",uy,[D("fieldset",cy,[D("label",{class:lt([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":""},[Et(D("input",{"onUpdate:modelValue":T[0]||(T[0]=M=>r.value=M),type:"radio",name:"tab",value:"chat",hidden:""},null,512),[[ir,r.value]]),T[5]||(T[5]=D("div",{"i-solar:dialog-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),D("div",dy,[D("span",py,be(H(S)("stage.chat.tabs.chat")),1)])],10,fy),D("label",{class:lt([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":""},[Et(D("input",{"onUpdate:modelValue":T[1]||(T[1]=M=>r.value=M),type:"radio",name:"tab",value:"custom",hidden:""},null,512),[[ir,r.value]]),T[6]||(T[6]=D("div",{"i-solar:star-fall-2-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),D("div",my,[D("span",null,be(H(S)("stage.chat.tabs.custom")),1)])],10,hy),D("label",{class:lt([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":""},[Et(D("input",{"onUpdate:modelValue":T[2]||(T[2]=M=>r.value=M),type:"radio",name:"tab",value:"clothes",hidden:""},null,512),[[ir,r.value]]),T[7]||(T[7]=D("div",{"i-solar:magic-stick-3-bold-duotone":"",text:"2xl",transform:"translate-y--2"},null,-1)),D("div",yy,[D("span",null,be(H(S)("stage.chat.tabs.clothes")),1)])],10,gy)]),D("div",xy,[D("div",vy,[_e(ly,{"h-full":"","flex-1":"","p-4":"",w:"full","max-h":"e.value=M),placeholder:H(S)("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:lt({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:P},null,8,["modelValue","placeholder","class"])])])]),D("div",wy,[D("div",ky,[_e(H(ui),null,{default:Ye(()=>[i.value?(J(),oe("fieldset",Ty,[(J(!0),oe(ai,null,si(H(u),(M,j)=>(J(),oe("label",{key:j,class:"[&_div_span]:dark:hover:bg-cyan-300 [&_div_span]:dark:hover:bg-cyan-900"},[D("input",{type:"radio",name:"audioInput",value:M.deviceId,hidden:"",onChange:g},null,40,_y),D("div",Ey,[D("div",My,[M.deviceId===H(d)?(J(),oe("div",Ay)):at("",!0)]),D("span",{"inline-block":"",class:lt([M.deviceId===H(d)?"cyan-400 dark:text-white":"cyan-400/50 dark:text-white/50"]),transition:"all duration-250 ease-in-out"},be(M.label),3)])]))),128))])):at("",!0)]),_:1}),D("label",{bg:"complementary-100 hover:complementary-200 dark:complementary-800 dark:hover:complementary-700",transition:"all duration-250 ease-in-out",class:lt({"transition-colors-none":H(l)}),text:"complementary-400","h-fit":"",flex:"","cursor-pointer":"","items-center":"","justify-center":"","gap-2":"","rounded-full":"","px-4":"","py-2":""},[Et(D("input",{"onUpdate:modelValue":T[4]||(T[4]=M=>i.value=M),type:"checkbox",hidden:""},null,512),[[Qr,i.value]]),T[8]||(T[8]=D("div",{"i-solar:microphone-2-bold-duotone":""},null,-1)),D("div",null,[n.value?(J(),oe("span",Iy,"Listening...")):(J(),oe("span",Sy,be(H(S)("settings.microphone")),1))])],2)])])]))}}),Cy=qn(Ry,[["__scopeId","data-v-df569696"]]),Ny={py:"1",flex:"~ col",rounded:"lg","overflow-hidden":""},Ly={key:0,flex:"",mr:"12"},Py={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=ca("auto-animate");return J(),oe("div",Ny,[c[1]||(c[1]=D("div",{"flex-1":""},null,-1)),Et((J(),oe("div",{ref_key:"chatHistoryRef",ref:e,"h-full":"","w-full":"","max-h":"30vh",flex:"~ col","overflow-scroll":""},[c[0]||(c[0]=D("div",{"flex-1":""},null,-1)),(J(!0),oe(ai,null,si(H(r),(p,d)=>(J(),oe("div",{key:d,"mb-2":""},[p.role==="assistant"?(J(),oe("div",Ly,[D("div",Py,[D("div",null,[D("span",Dy,be(H(n)("stage.chat.message.character-name.airi")),1)]),p.content?(J(),oe("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 Be(a,async v=>{v==="false"&&d()}),c(async()=>{e.value=""}),Wt(()=>{y()}),(v,k)=>(J(),oe("div",null,[D("div",$y,[_e(Hy,{absolute:"","left-0":"","top-0":"",transform:"translate-y-[-100%]","w-full":""}),D("div",Gy,[_e(H(da),{modelValue:e.value,"onUpdate:modelValue":k[0]||(k[0]=S=>e.value=S),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:lt({"transition-colors-none placeholder:transition-colors-none":H(l)}),onSubmit:p},null,8,["modelValue","placeholder","class"])])])]))}}),Ky={class:"relative"},qy={absolute:"","left-0":"","right-0":"","top-0":"","w-full":"","overflow-hidden":""},Wy=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),a=W(e.direction),s=W(e.movementDirection);function l(f,p,d,y,x){const v=[],S=Math.ceil(f/y)*y,E=1,C=x==="up"?d:p-d;v.push(`M 0 ${C}`);const P=Math.PI*2/y;for(let I=0;I<=S;I+=E){const b=d*Math.sin(P*I),g=x==="up"?C-b:C+b;v.push(`L ${I} ${g}`)}const h=x==="up"?p:0;return v.push(`L ${S} ${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 Be(()=>[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)=>(J(),oe("div",Ky,[gn(f.$slots,"default",{},void 0,!0),D("div",qy,[D("div",{class:"wave",style:Lr({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)])]))}}),Xy=qn(Wy,[["__scopeId","data-v-d4cf94d8"]]),Zy={relative:"",flex:"~ col","z-2":"","h-100dvh":"","w-100vw":"","of-hidden":""},Qy={relative:"",flex:"~ 1 row gap-y-0 gap-x-2 (J(),Zt(Og,null,{default:Ye(()=>[_e(Xy,{"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:Ye(()=>[D("div",Zy,[D("div",null,[_e(zg,{class:"flex",p2:""})]),D("div",Qy,[_e(H(Ng),{"flex-1":"","min-w":"1/2",paused:n.value},null,8,["paused"]),_e(Cy,{class:"flex "u"?!1:e instanceof ShadowRoot||e instanceof N(e).ShadowRoot}function ve(e){const{overflow:n,overflowX:t,overflowY:o,display:r}=k(e);return/auto|scroll|overlay|hidden|clip/.test(n+o+t)&&!["inline","contents"].includes(r)}function En(e){return["table","td","th"].includes(re(e))}function $e(e){return[":popover-open",":modal"].some(n=>{try{return e.matches(n)}catch{return!1}})}function qe(e){const n=Ge(),t=I(e)?k(e):e;return["transform","translate","scale","rotate","perspective"].some(o=>t[o]?t[o]!=="none":!1)||(t.containerType?t.containerType!=="normal":!1)||!n&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!n&&(t.filter?t.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(o=>(t.willChange||"").includes(o))||["paint","layout","strict","content"].some(o=>(t.contain||"").includes(o))}function _n(e){let n=q(e);for(;V(n)&&!ce(n);){if(qe(n))return n;if($e(n))return null;n=q(n)}return null}function Ge(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function ce(e){return["html","body","#document"].includes(re(e))}function k(e){return N(e).getComputedStyle(e)}function Re(e){return I(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function q(e){if(re(e)==="html")return e;const n=e.assignedSlot||e.parentNode||it(e)&&e.host||z(e);return it(n)?n.host:n}function Bt(e){const n=q(e);return ce(n)?e.ownerDocument?e.ownerDocument.body:e.body:V(n)&&ve(n)?n:Bt(n)}function pe(e,n,t){var o;n===void 0&&(n=[]),t===void 0&&(t=!0);const r=Bt(e),i=r===((o=e.ownerDocument)==null?void 0:o.body),l=N(r);if(i){const a=He(l);return n.concat(l,l.visualViewport||[],ve(r)?r:[],a&&t?pe(a):[])}return n.concat(r,pe(r,[],t))}function He(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function At(e){const n=k(e);let t=parseFloat(n.width)||0,o=parseFloat(n.height)||0;const r=V(e),i=r?e.offsetWidth:t,l=r?e.offsetHeight:o,a=Ae(t)!==i||Ae(o)!==l;return a&&(t=i,o=l),{width:t,height:o,$:a}}function Je(e){return I(e)?e:e.contextElement}function de(e){const n=Je(e);if(!V(n))return j(1);const t=n.getBoundingClientRect(),{width:o,height:r,$:i}=At(n);let l=(i?Ae(t.width):t.width)/o,a=(i?Ae(t.height):t.height)/r;return(!l||!Number.isFinite(l))&&(l=1),(!a||!Number.isFinite(a))&&(a=1),{x:l,y:a}}const Dn=j(0);function Tt(e){const n=N(e);return!Ge()||!n.visualViewport?Dn:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function Bn(e,n,t){return n===void 0&&(n=!1),!t||n&&t!==N(e)?!1:n}function te(e,n,t,o){n===void 0&&(n=!1),t===void 0&&(t=!1);const r=e.getBoundingClientRect(),i=Je(e);let l=j(1);n&&(o?I(o)&&(l=de(o)):l=de(e));const a=Bn(i,t,o)?Tt(i):j(0);let c=(r.left+a.x)/l.x,d=(r.top+a.y)/l.y,s=r.width/l.x,u=r.height/l.y;if(i){const p=N(i),v=o&&I(o)?N(o):o;let h=p,g=He(h);for(;g&&o&&v!==h;){const m=de(g),y=g.getBoundingClientRect(),B=k(g),w=y.left+(g.clientLeft+parseFloat(B.paddingLeft))*m.x,$=y.top+(g.clientTop+parseFloat(B.paddingTop))*m.y;c*=m.x,d*=m.y,s*=m.x,u*=m.y,c+=w,d+=$,h=N(g),g=He(h)}}return Dt({width:s,height:u,x:c,y:d})}function Qe(e,n){const t=Re(e).scrollLeft;return n?n.left+t:te(z(e)).left+t}function Pt(e,n,t){t===void 0&&(t=!1);const o=e.getBoundingClientRect(),r=o.left+n.scrollLeft-(t?0:Qe(e,o)),i=o.top+n.scrollTop;return{x:r,y:i}}function An(e){let{elements:n,rect:t,offsetParent:o,strategy:r}=e;const i=r==="fixed",l=z(o),a=n?$e(n.floating):!1;if(o===l||a&&i)return t;let c={scrollLeft:0,scrollTop:0},d=j(1);const s=j(0),u=V(o);if((u||!u&&!i)&&((re(o)!=="body"||ve(l))&&(c=Re(o)),V(o))){const v=te(o);d=de(o),s.x=v.x+o.clientLeft,s.y=v.y+o.clientTop}const p=l&&!u&&!i?Pt(l,c,!0):j(0);return{width:t.width*d.x,height:t.height*d.y,x:t.x*d.x-c.scrollLeft*d.x+s.x+p.x,y:t.y*d.y-c.scrollTop*d.y+s.y+p.y}}function Tn(e){return Array.from(e.getClientRects())}function Pn(e){const n=z(e),t=Re(e),o=e.ownerDocument.body,r=ue(n.scrollWidth,n.clientWidth,o.scrollWidth,o.clientWidth),i=ue(n.scrollHeight,n.clientHeight,o.scrollHeight,o.clientHeight);let l=-t.scrollLeft+Qe(e);const a=-t.scrollTop;return k(o).direction==="rtl"&&(l+=ue(n.clientWidth,o.clientWidth)-r),{width:r,height:i,x:l,y:a}}function $n(e,n){const t=N(e),o=z(e),r=t.visualViewport;let i=o.clientWidth,l=o.clientHeight,a=0,c=0;if(r){i=r.width,l=r.height;const d=Ge();(!d||d&&n==="fixed")&&(a=r.offsetLeft,c=r.offsetTop)}return{width:i,height:l,x:a,y:c}}function Rn(e,n){const t=te(e,!0,n==="fixed"),o=t.top+e.clientTop,r=t.left+e.clientLeft,i=V(e)?de(e):j(1),l=e.clientWidth*i.x,a=e.clientHeight*i.y,c=r*i.x,d=o*i.y;return{width:l,height:a,x:c,y:d}}function at(e,n,t){let o;if(n==="viewport")o=$n(e,t);else if(n==="document")o=Pn(z(e));else if(I(n))o=Rn(n,t);else{const r=Tt(e);o={x:n.x-r.x,y:n.y-r.y,width:n.width,height:n.height}}return Dt(o)}function $t(e,n){const t=q(e);return t===n||!I(t)||ce(t)?!1:k(t).position==="fixed"||$t(t,n)}function Sn(e,n){const t=n.get(e);if(t)return t;let o=pe(e,[],!1).filter(a=>I(a)&&re(a)!=="body"),r=null;const i=k(e).position==="fixed";let l=i?q(e):e;for(;I(l)&&!ce(l);){const a=k(l),c=qe(l);!c&&a.position==="fixed"&&(r=null),(i?!c&&!r:!c&&a.position==="static"&&!!r&&["absolute","fixed"].includes(r.position)||ve(l)&&!c&&$t(e,l))?o=o.filter(s=>s!==l):r=a,l=q(l)}return n.set(e,o),o}function Nn(e){let{element:n,boundary:t,rootBoundary:o,strategy:r}=e;const l=[...t==="clippingAncestors"?$e(n)?[]:Sn(n,this._c):[].concat(t),o],a=l[0],c=l.reduce((d,s)=>{const u=at(n,s,r);return d.top=ue(u.top,d.top),d.right=We(u.right,d.right),d.bottom=We(u.bottom,d.bottom),d.left=ue(u.left,d.left),d},at(n,a,r));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function Fn(e){const{width:n,height:t}=At(e);return{width:n,height:t}}function Ln(e,n,t){const o=V(n),r=z(n),i=t==="fixed",l=te(e,!0,i,n);let a={scrollLeft:0,scrollTop:0};const c=j(0);if(o||!o&&!i)if((re(n)!=="body"||ve(r))&&(a=Re(n)),o){const p=te(n,!0,i,n);c.x=p.x+n.clientLeft,c.y=p.y+n.clientTop}else r&&(c.x=Qe(r));const d=r&&!o&&!i?Pt(r,a):j(0),s=l.left+a.scrollLeft-c.x-d.x,u=l.top+a.scrollTop-c.y-d.y;return{x:s,y:u,width:l.width,height:l.height}}function Ne(e){return k(e).position==="static"}function st(e,n){if(!V(e)||k(e).position==="fixed")return null;if(n)return n(e);let t=e.offsetParent;return z(e)===t&&(t=t.ownerDocument.body),t}function Rt(e,n){const t=N(e);if($e(e))return t;if(!V(e)){let r=q(e);for(;r&&!ce(r);){if(I(r)&&!Ne(r))return r;r=q(r)}return t}let o=st(e,n);for(;o&&En(o)&&Ne(o);)o=st(o,n);return o&&ce(o)&&Ne(o)&&!qe(o)?t:o||_n(e)||t}const Mn=async function(e){const n=this.getOffsetParent||Rt,t=this.getDimensions,o=await t(e.floating);return{reference:Ln(e.reference,await n(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function In(e){return k(e).direction==="rtl"}const kn={convertOffsetParentRelativeRectToViewportRelativeRect:An,getDocumentElement:z,getClippingRect:Nn,getOffsetParent:Rt,getElementRects:Mn,getClientRects:Tn,getDimensions:Fn,getScale:de,isElement:I,isRTL:In};function St(e,n){return e.x===n.x&&e.y===n.y&&e.width===n.width&&e.height===n.height}function Wn(e,n){let t=null,o;const r=z(e);function i(){var a;clearTimeout(o),(a=t)==null||a.disconnect(),t=null}function l(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),i();const d=e.getBoundingClientRect(),{left:s,top:u,width:p,height:v}=d;if(a||n(),!p||!v)return;const h=Oe(u),g=Oe(r.clientWidth-(s+p)),m=Oe(r.clientHeight-(u+v)),y=Oe(s),w={rootMargin:-h+"px "+-g+"px "+-m+"px "+-y+"px",threshold:ue(0,We(1,c))||1};let $=!0;function R(L){const T=L[0].intersectionRatio;if(T!==c){if(!$)return l();T?l(!1,T):o=setTimeout(()=>{l(!1,1e-7)},1e3)}T===1&&!St(d,e.getBoundingClientRect())&&l(),$=!1}try{t=new IntersectionObserver(R,{...w,root:r.ownerDocument})}catch{t=new IntersectionObserver(R,w)}t.observe(e)}return l(!0),i}function Hn(e,n,t,o){o===void 0&&(o={});const{ancestorScroll:r=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=o,d=Je(e),s=r||i?[...d?pe(d):[],...pe(n)]:[];s.forEach(y=>{r&&y.addEventListener("scroll",t,{passive:!0}),i&&y.addEventListener("resize",t)});const u=d&&a?Wn(d,t):null;let p=-1,v=null;l&&(v=new ResizeObserver(y=>{let[B]=y;B&&B.target===d&&v&&(v.unobserve(n),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var w;(w=v)==null||w.observe(n)})),t()}),d&&!c&&v.observe(d),v.observe(n));let h,g=c?te(e):null;c&&m();function m(){const y=te(e);g&&!St(g,y)&&t(),g=y,h=requestAnimationFrame(m)}return t(),()=>{var y;s.forEach(B=>{r&&B.removeEventListener("scroll",t),i&&B.removeEventListener("resize",t)}),u==null||u(),(y=v)==null||y.disconnect(),v=null,c&&cancelAnimationFrame(h)}}const jn=mn,Vn=gn,ut=yn,zn=bn,Kn=wn,Un=On,Yn=xn,Xn=(e,n,t)=>{const o=new Map,r={platform:kn,...t},i={...r.platform,_c:o};return Cn(e,n,{...r,platform:i})};function qn(e){return e!=null&&typeof e=="object"&&"$el"in e}function je(e){if(qn(e)){const n=e.$el;return Xe(n)&&re(n)==="#comment"?null:n}return e}function se(e){return typeof e=="function"?e():f(e)}function Gn(e){return{name:"arrow",options:e,fn(n){const t=je(se(e.element));return t==null?{}:Un({element:t,padding:e.padding}).fn(n)}}}function Nt(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function dt(e,n){const t=Nt(e);return Math.round(n*t)/t}function Jn(e,n,t){t===void 0&&(t={});const o=t.whileElementsMounted,r=b(()=>{var T;return(T=se(t.open))!=null?T:!0}),i=b(()=>se(t.middleware)),l=b(()=>{var T;return(T=se(t.placement))!=null?T:"bottom"}),a=b(()=>{var T;return(T=se(t.strategy))!=null?T:"absolute"}),c=b(()=>{var T;return(T=se(t.transform))!=null?T:!0}),d=b(()=>je(e.value)),s=b(()=>je(n.value)),u=C(0),p=C(0),v=C(a.value),h=C(l.value),g=ht({}),m=C(!1),y=b(()=>{const T={position:v.value,left:"0",top:"0"};if(!s.value)return T;const H=dt(s.value,u.value),ge=dt(s.value,p.value);return c.value?{...T,transform:"translate("+H+"px, "+ge+"px)",...Nt(s.value)>=1.5&&{willChange:"transform"}}:{position:v.value,left:H+"px",top:ge+"px"}});let B;function w(){if(d.value==null||s.value==null)return;const T=r.value;Xn(d.value,s.value,{middleware:i.value,placement:l.value,strategy:a.value}).then(H=>{u.value=H.x,p.value=H.y,v.value=H.strategy,h.value=H.placement,g.value=H.middlewareData,m.value=T!==!1})}function $(){typeof B=="function"&&(B(),B=void 0)}function R(){if($(),o===void 0){w();return}if(d.value!=null&&s.value!=null){B=o(d.value,s.value,w);return}}function L(){r.value||(m.value=!1)}return F([i,l,a,r],w,{flush:"sync"}),F([d,s],R,{flush:"sync"}),F(r,L,{flush:"sync"}),mt()&&yt($),{x:ie(u),y:ie(p),strategy:ie(v),placement:ie(h),middlewareData:ie(g),isPositioned:ie(m),floatingStyles:y,update:w}}function le(e,n){const t=typeof e=="string"&&!n?`${e}Context`:n,o=Symbol(t);return[r=>{const i=en(o,r);if(i||i===null)return i;throw new Error(`Injection \`${o.toString()}\` not found. Component must be used within ${Array.isArray(e)?`one of the following components: ${e.join(", ")}`:`\`${e}\``}`)},r=>(hn(o,r),r)]}function Ft(e,n,t){const o=t.originalEvent.target,r=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:t});n&&o.addEventListener(e,n,{once:!0}),o.dispatchEvent(r)}function Qn(e,n){var t;const o=ht();return M(()=>{o.value=e()},{...n,flush:(t=void 0)!=null?t:"sync"}),Ct(o)}function he(e){return mt()?(yt(e),!0):!1}function Zn(){const e=new Set,n=t=>{e.delete(t)};return{on:t=>{e.add(t);const o=()=>n(t);return he(o),{off:o}},off:n,trigger:(...t)=>Promise.all(Array.from(e).map(o=>o(...t)))}}function eo(e){let n=!1,t;const o=Et(!0);return(...r)=>(n||(t=o.run(()=>e(...r)),n=!0),t)}function to(e){let n=0,t,o;const r=()=>{n-=1,o&&n<=0&&(o.stop(),t=void 0,o=void 0)};return(...i)=>(n+=1,t||(o=Et(!0),t=o.run(()=>e(...i))),he(r),t)}function Z(e){return typeof e=="function"?e():f(e)}const Q=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const no=e=>typeof e<"u",oo=Object.prototype.toString,ro=e=>oo.call(e)==="[object Object]",lo=()=>{},ct=io();function io(){var e,n;return Q&&((e=window==null?void 0:window.navigator)==null?void 0:e.userAgent)&&(/iP(?:ad|hone|od)/.test(window.navigator.userAgent)||((n=window==null?void 0:window.navigator)==null?void 0:n.maxTouchPoints)>2&&/iPad|Macintosh/.test(window==null?void 0:window.navigator.userAgent))}function ao(e){return oe()}function so(e,n=1e4){return vn((t,o)=>{let r=Z(e),i;const l=()=>setTimeout(()=>{r=Z(e),o()},Z(n));return he(()=>{clearTimeout(i)}),{get(){return t(),r},set(a){r=a,o(),clearTimeout(i),i=l()}}})}function uo(e,n){ao()&&dn(e,n)}function Lt(e,n,t={}){const{immediate:o=!0}=t,r=C(!1);let i=null;function l(){i&&(clearTimeout(i),i=null)}function a(){r.value=!1,l()}function c(...d){l(),r.value=!0,i=setTimeout(()=>{r.value=!1,i=null,e(...d)},Z(n))}return o&&(r.value=!0,Q&&c()),he(a),{isPending:Ct(r),start:c,stop:a}}function me(e){var n;const t=Z(e);return(n=t==null?void 0:t.$el)!=null?n:t}const Ze=Q?window:void 0;function Te(...e){let n,t,o,r;if(typeof e[0]=="string"||Array.isArray(e[0])?([t,o,r]=e,n=Ze):[n,t,o,r]=e,!n)return lo;Array.isArray(t)||(t=[t]),Array.isArray(o)||(o=[o]);const i=[],l=()=>{i.forEach(s=>s()),i.length=0},a=(s,u,p,v)=>(s.addEventListener(u,p,v),()=>s.removeEventListener(u,p,v)),c=F(()=>[me(n),Z(r)],([s,u])=>{if(l(),!s)return;const p=ro(u)?{...u}:u;i.push(...t.flatMap(v=>o.map(h=>a(s,v,h,p))))},{immediate:!0,flush:"post"}),d=()=>{c(),l()};return he(d),d}function co(e){return typeof e=="function"?e:typeof e=="string"?n=>n.key===e:Array.isArray(e)?n=>e.includes(n.key):()=>!0}function fo(...e){let n,t,o={};e.length===3?(n=e[0],t=e[1],o=e[2]):e.length===2?typeof e[1]=="object"?(n=!0,t=e[0],o=e[1]):(n=e[0],t=e[1]):(n=!0,t=e[0]);const{target:r=Ze,eventName:i="keydown",passive:l=!1,dedupe:a=!1}=o,c=co(n);return Te(r,i,d=>{d.repeat&&Z(a)||c(d)&&t(d)},l)}function po(){const e=C(!1),n=oe();return n&&fe(()=>{e.value=!0},n),e}function vo(e){return JSON.parse(JSON.stringify(e))}function Mt(e,n,t,o={}){var r,i,l;const{clone:a=!1,passive:c=!1,eventName:d,deep:s=!1,defaultValue:u,shouldEmit:p}=o,v=oe(),h=t||(v==null?void 0:v.emit)||((r=v==null?void 0:v.$emit)==null?void 0:r.bind(v))||((l=(i=v==null?void 0:v.proxy)==null?void 0:i.$emit)==null?void 0:l.bind(v==null?void 0:v.proxy));let g=d;g=g||`update:${n.toString()}`;const m=w=>a?typeof a=="function"?a(w):vo(w):w,y=()=>no(e[n])?m(e[n]):u,B=w=>{p?p(w)&&h(g,w):h(g,w)};if(c){const w=y(),$=C(w);let R=!1;return F(()=>e[n],L=>{R||(R=!0,$.value=m(L),ne(()=>R=!1))}),F($,L=>{!R&&(L!==e[n]||s)&&B(L)},{deep:s}),$}else return b({get(){return y()},set(w){B(w)}})}function et(e){return e?e.flatMap(n=>n.type===rn?et(n.children):[n]):[]}function X(){let e=document.activeElement;if(e==null)return null;for(;e!=null&&e.shadowRoot!=null&&e.shadowRoot.activeElement!=null;)e=e.shadowRoot.activeElement;return e}function Fe(e){if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n!==null&&n!==Object.prototype&&Object.getPrototypeOf(n)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)==="[object Module]":!0}function Ve(e,n,t=".",o){if(!Fe(n))return Ve(e,{},t);const r=Object.assign({},n);for(const i in e){if(i==="__proto__"||i==="constructor")continue;const l=e[i];l!=null&&(Array.isArray(l)&&Array.isArray(r[i])?r[i]=[...l,...r[i]]:Fe(l)&&Fe(r[i])?r[i]=Ve(l,r[i],(t?`${t}.`:"")+i.toString()):r[i]=l)}return r}function ho(e){return(...n)=>n.reduce((t,o)=>Ve(t,o,""),{})}const mo=ho(),[It,Tr]=le("ConfigProvider");let yo="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",go=(e=21)=>{let n="",t=e;for(;t--;)n+=yo[Math.random()*64|0];return n};const bo=to(()=>{const e=C(new Map),n=C(),t=b(()=>{for(const l of e.value.values())if(l)return!0;return!1}),o=It({scrollBody:C(!0)});let r=null;const i=()=>{document.body.style.paddingRight="",document.body.style.marginRight="",document.body.style.pointerEvents="",document.body.style.removeProperty("--scrollbar-width"),document.body.style.overflow=n.value??"",ct&&(r==null||r()),n.value=void 0};return F(t,(l,a)=>{var c;if(!Q)return;if(!l){a&&i();return}n.value===void 0&&(n.value=document.body.style.overflow);const d=window.innerWidth-document.documentElement.clientWidth,s={padding:d,margin:0},u=(c=o.scrollBody)!=null&&c.value?typeof o.scrollBody.value=="object"?mo({padding:o.scrollBody.value.padding===!0?d:o.scrollBody.value.padding,margin:o.scrollBody.value.margin===!0?d:o.scrollBody.value.margin},s):s:{padding:0,margin:0};d>0&&(document.body.style.paddingRight=typeof u.padding=="number"?`${u.padding}px`:String(u.padding),document.body.style.marginRight=typeof u.margin=="number"?`${u.margin}px`:String(u.margin),document.body.style.setProperty("--scrollbar-width",`${d}px`),document.body.style.overflow="hidden"),ct&&(r=Te(document,"touchmove",p=>xo(p),{passive:!1})),ne(()=>{document.body.style.pointerEvents="none",document.body.style.overflow="hidden"})},{immediate:!0,flush:"sync"}),e});function wo(e){const n=go(6),t=bo();t.value.set(n,e);const o=b({get:()=>t.value.get(n)??!1,set:r=>t.value.set(n,r)});return uo(()=>{t.value.delete(n)}),o}function kt(e){const n=window.getComputedStyle(e);if(n.overflowX==="scroll"||n.overflowY==="scroll"||n.overflowX==="auto"&&e.clientWidth1?!0:(n.preventDefault&&n.cancelable&&n.preventDefault(),!1)}function ye(e){const n=oe(),t=n==null?void 0:n.type.emits,o={};return t!=null&&t.length||console.warn(`No emitted event found. Please check component: ${n==null?void 0:n.type.__name}`),t==null||t.forEach(r=>{o[Zt(bt(r))]=(...i)=>e(r,...i)}),o}function Wt(e){const n=oe(),t=Object.keys((n==null?void 0:n.type.props)??{}).reduce((r,i)=>{const l=(n==null?void 0:n.type.props[i]).default;return l!==void 0&&(r[i]=l),r},{}),o=on(e);return b(()=>{const r={},i=(n==null?void 0:n.vnode.props)??{};return Object.keys(i).forEach(l=>{r[bt(l)]=i[l]}),Object.keys({...t,...r}).reduce((l,a)=>(o.value[a]!==void 0&&(l[a]=o.value[a]),l),{})})}function Ht(e,n){const t=Wt(e),o=n?ye(n):{};return b(()=>({...t.value,...o}))}function A(){const e=oe(),n=C(),t=b(()=>{var l,a;return["#text","#comment"].includes((l=n.value)==null?void 0:l.$el.nodeName)?(a=n.value)==null?void 0:a.$el.nextElementSibling:me(n)}),o=Object.assign({},e.exposed),r={};for(const l in e.props)Object.defineProperty(r,l,{enumerable:!0,configurable:!0,get:()=>e.props[l]});if(Object.keys(o).length>0)for(const l in o)Object.defineProperty(r,l,{enumerable:!0,configurable:!0,get:()=>o[l]});Object.defineProperty(r,"$el",{enumerable:!0,configurable:!0,get:()=>e.vnode.el}),e.exposed=r;function i(l){n.value=l,l&&(Object.defineProperty(r,"$el",{enumerable:!0,configurable:!0,get:()=>l instanceof Element?l:l.$el}),e.exposed=r)}return{forwardRef:i,currentRef:n,currentElement:t}}function Co(e,n){const t=so(!1,300),o=C(null),r=Zn();function i(){o.value=null,t.value=!1}function l(a,c){const d=a.currentTarget,s={x:a.clientX,y:a.clientY},u=Oo(s,d.getBoundingClientRect()),p=Eo(s,u),v=_o(c.getBoundingClientRect()),h=Bo([...p,...v]);o.value=h,t.value=!0}return M(a=>{if(e.value&&n.value){const c=s=>l(s,n.value),d=s=>l(s,e.value);e.value.addEventListener("pointerleave",c),n.value.addEventListener("pointerleave",d),a(()=>{var s,u;(s=e.value)==null||s.removeEventListener("pointerleave",c),(u=n.value)==null||u.removeEventListener("pointerleave",d)})}}),M(a=>{var c;if(o.value){const d=s=>{var u,p;if(!o.value)return;const v=s.target,h={x:s.clientX,y:s.clientY},g=((u=e.value)==null?void 0:u.contains(v))||((p=n.value)==null?void 0:p.contains(v)),m=!Do(h,o.value),y=!!v.closest("[data-grace-area-trigger]");g?i():(m||y)&&(i(),r.trigger())};(c=e.value)==null||c.ownerDocument.addEventListener("pointermove",d),a(()=>{var s;return(s=e.value)==null?void 0:s.ownerDocument.removeEventListener("pointermove",d)})}}),{isPointerInTransit:t,onPointerExit:r.on}}function Oo(e,n){const t=Math.abs(n.top-e.y),o=Math.abs(n.bottom-e.y),r=Math.abs(n.right-e.x),i=Math.abs(n.left-e.x);switch(Math.min(t,o,r,i)){case i:return"left";case r:return"right";case t:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function Eo(e,n,t=5){const o=[];switch(n){case"top":o.push({x:e.x-t,y:e.y+t},{x:e.x+t,y:e.y+t});break;case"bottom":o.push({x:e.x-t,y:e.y-t},{x:e.x+t,y:e.y-t});break;case"left":o.push({x:e.x+t,y:e.y-t},{x:e.x+t,y:e.y+t});break;case"right":o.push({x:e.x-t,y:e.y-t},{x:e.x-t,y:e.y+t});break}return o}function _o(e){const{top:n,right:t,bottom:o,left:r}=e;return[{x:r,y:n},{x:t,y:n},{x:t,y:o},{x:r,y:o}]}function Do(e,n){const{x:t,y:o}=e;let r=!1;for(let i=0,l=n.length-1;io!=s>o&&t<(d-a)*(o-c)/(s-c)+a&&(r=!r)}return r}function Bo(e){const n=e.slice();return n.sort((t,o)=>t.xo.x?1:t.yo.y?1:0),Ao(n)}function Ao(e){if(e.length<=1)return e.slice();const n=[];for(let o=0;o=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(r.y-l.y)>=(i.y-l.y)*(r.x-l.x))n.pop();else break}n.push(r)}n.pop();const t=[];for(let o=e.length-1;o>=0;o--){const r=e[o];for(;t.length>=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(r.y-l.y)>=(i.y-l.y)*(r.x-l.x))t.pop();else break}t.push(r)}return t.pop(),n.length===1&&t.length===1&&n[0].x===t[0].x&&n[0].y===t[0].y?n:n.concat(t)}var To=function(e){if(typeof document>"u")return null;var n=Array.isArray(e)?e[0]:e;return n.ownerDocument.body},ae=new WeakMap,Ee=new WeakMap,_e={},Le=0,jt=function(e){return e&&(e.host||jt(e.parentNode))},Po=function(e,n){return n.map(function(t){if(e.contains(t))return t;var o=jt(t);return o&&e.contains(o)?o:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(t){return!!t})},$o=function(e,n,t,o){var r=Po(n,Array.isArray(e)?e:[e]);_e[t]||(_e[t]=new WeakMap);var i=_e[t],l=[],a=new Set,c=new Set(r),d=function(u){!u||a.has(u)||(a.add(u),d(u.parentNode))};r.forEach(d);var s=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(p){if(a.has(p))s(p);else try{var v=p.getAttribute(o),h=v!==null&&v!=="false",g=(ae.get(p)||0)+1,m=(i.get(p)||0)+1;ae.set(p,g),i.set(p,m),l.push(p),g===1&&h&&Ee.set(p,!0),m===1&&p.setAttribute(t,"true"),h||p.setAttribute(o,"true")}catch(y){console.error("aria-hidden: cannot operate on ",p,y)}})};return s(n),a.clear(),Le++,function(){l.forEach(function(u){var p=ae.get(u)-1,v=i.get(u)-1;ae.set(u,p),i.set(u,v),p||(Ee.has(u)||u.removeAttribute(o),Ee.delete(u)),v||u.removeAttribute(t)}),Le--,Le||(ae=new WeakMap,ae=new WeakMap,Ee=new WeakMap,_e={})}},Ro=function(e,n,t){t===void 0&&(t="data-aria-hidden");var o=Array.from(Array.isArray(e)?e:[e]),r=To(e);return r?(o.push.apply(o,Array.from(r.querySelectorAll("[aria-live]"))),$o(o,r,t,"aria-hidden")):function(){return null}};function So(e){let n;F(()=>me(e),t=>{t?n=Ro(t):n&&n()}),wt(()=>{n&&n()})}let No=0;function ze(e,n="radix"){const t=It({useId:void 0});return lt?`${n}-${lt()}`:t.useId?`${n}-${t.useId()}`:`${n}-${++No}`}function Fo(e){const n=C(),t=b(()=>{var r;return((r=n.value)==null?void 0:r.width)??0}),o=b(()=>{var r;return((r=n.value)==null?void 0:r.height)??0});return fe(()=>{const r=me(e);if(r){n.value={width:r.offsetWidth,height:r.offsetHeight};const i=new ResizeObserver(l=>{if(!Array.isArray(l)||!l.length)return;const a=l[0];let c,d;if("borderBoxSize"in a){const s=a.borderBoxSize,u=Array.isArray(s)?s[0]:s;c=u.inlineSize,d=u.blockSize}else c=r.offsetWidth,d=r.offsetHeight;n.value={width:c,height:d}});return i.observe(r,{box:"border-box"}),()=>i.unobserve(r)}else n.value=void 0}),{width:t,height:o}}function Lo(e,n){const t=C(e);function o(r){return n[t.value][r]??t.value}return{state:t,dispatch:r=>{t.value=o(r)}}}const Mo=O({name:"PrimitiveSlot",inheritAttrs:!1,setup(e,{attrs:n,slots:t}){return()=>{var o,r;if(!t.default)return null;const i=et(t.default()),l=i.findIndex(s=>s.type!==xt);if(l===-1)return i;const a=i[l];(o=a.props)==null||delete o.ref;const c=a.props?P(n,a.props):n;n.class&&(r=a.props)!=null&&r.class&&delete a.props.class;const d=ln(a,c);for(const s in c)s.startsWith("on")&&(d.props||(d.props={}),d.props[s]=c[s]);return i.length===1?d:(i[l]=d,i)}}}),W=O({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(e,{attrs:n,slots:t}){const o=e.asChild?"template":e.as;return typeof o=="string"&&["area","img","input"].includes(o)?()=>Be(o,n):o!=="template"?()=>Be(e.as,n,{default:t.default}):()=>Be(Mo,n,{default:t.default})}});function Io(e,n){var t;const o=C({}),r=C("none"),i=C(e),l=e.value?"mounted":"unmounted";let a;const c=((t=n.value)==null?void 0:t.ownerDocument.defaultView)??Ze,{state:d,dispatch:s}=Lo(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}}),u=m=>{var y;if(Q){const B=new CustomEvent(m,{bubbles:!1,cancelable:!1});(y=n.value)==null||y.dispatchEvent(B)}};F(e,async(m,y)=>{var B;const w=y!==m;if(await ne(),w){const $=r.value,R=De(n.value);m?(s("MOUNT"),u("enter"),R==="none"&&u("after-enter")):R==="none"||((B=o.value)==null?void 0:B.display)==="none"?(s("UNMOUNT"),u("leave"),u("after-leave")):y&&$!==R?(s("ANIMATION_OUT"),u("leave")):(s("UNMOUNT"),u("after-leave"))}},{immediate:!0});const p=m=>{const y=De(n.value),B=y.includes(m.animationName),w=d.value==="mounted"?"enter":"leave";if(m.target===n.value&&B&&(u(`after-${w}`),s("ANIMATION_END"),!i.value)){const $=n.value.style.animationFillMode;n.value.style.animationFillMode="forwards",a=c==null?void 0:c.setTimeout(()=>{var R;((R=n.value)==null?void 0:R.style.animationFillMode)==="forwards"&&(n.value.style.animationFillMode=$)})}m.target===n.value&&y==="none"&&s("ANIMATION_END")},v=m=>{m.target===n.value&&(r.value=De(n.value))},h=F(n,(m,y)=>{m?(o.value=getComputedStyle(m),m.addEventListener("animationstart",v),m.addEventListener("animationcancel",p),m.addEventListener("animationend",p)):(s("ANIMATION_END"),a!==void 0&&(c==null||c.clearTimeout(a)),y==null||y.removeEventListener("animationstart",v),y==null||y.removeEventListener("animationcancel",p),y==null||y.removeEventListener("animationend",p))},{immediate:!0}),g=F(d,()=>{const m=De(n.value);r.value=d.value==="mounted"?m:"none"});return wt(()=>{h(),g()}),{isPresent:b(()=>["mounted","unmountSuspended"].includes(d.value))}}function De(e){return e&&getComputedStyle(e).animationName||"none"}const tt=O({name:"Presence",props:{present:{type:Boolean,required:!0},forceMount:{type:Boolean}},slots:{},setup(e,{slots:n,expose:t}){var o;const{present:r,forceMount:i}=Ue(e),l=C(),{isPresent:a}=Io(r,l);t({present:a});let c=n.default({present:a});c=et(c||[]);const d=oe();if(c&&(c==null?void 0:c.length)>1){const s=(o=d==null?void 0:d.parent)!=null&&o.type.name?`<${d.parent.type.name} />`:"component";throw new Error([`Detected an invalid children for \`${s}\` 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(u=>` - ${u}`).join(` +import{h as w,r as C,ay as ht,v as F,az as mt,aA as yt,aB as ie,b as f,d as O,A as D,o as _,w as x,f as E,C as G,D as J,E as P,X as ke,ax as ne,H as fe,aC as Ue,j as gt,i as ee,aD as Qt,aE as oe,aF as Zt,aG as wt,aH as en,aI as Be,aJ as tn,aK as nn,aL as on,I as bt,F as rn,aM as xt,aN as ln,aO as Ct,aP as lt,B as M,aQ as an,k as sn,t as un,c as Ot,z as Ye,aR as Et,aS as dn,aT as _t,aU as cn,aV as fn,e as pn,aW as vn,aX as hn}from"./index-CQudhZin.js";import{o as mn,f as yn,s as gn,a as wn,h as bn,l as xn,c as Cn,b as j,r as Dt,d as On,e as Ae,m as ue,g as We,i as Oe}from"./floating-ui.core-CgBsuaUc.js";function Pe(){return typeof window<"u"}function re(e){return Xe(e)?(e.nodeName||"").toLowerCase():"#document"}function N(e){var n;return(e==null||(n=e.ownerDocument)==null?void 0:n.defaultView)||window}function z(e){var n;return(n=(Xe(e)?e.ownerDocument:e.document)||window.document)==null?void 0:n.documentElement}function Xe(e){return Pe()?e instanceof Node||e instanceof N(e).Node:!1}function I(e){return Pe()?e instanceof Element||e instanceof N(e).Element:!1}function V(e){return Pe()?e instanceof HTMLElement||e instanceof N(e).HTMLElement:!1}function it(e){return!Pe()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof N(e).ShadowRoot}function ve(e){const{overflow:n,overflowX:t,overflowY:o,display:r}=k(e);return/auto|scroll|overlay|hidden|clip/.test(n+o+t)&&!["inline","contents"].includes(r)}function En(e){return["table","td","th"].includes(re(e))}function $e(e){return[":popover-open",":modal"].some(n=>{try{return e.matches(n)}catch{return!1}})}function qe(e){const n=Ge(),t=I(e)?k(e):e;return["transform","translate","scale","rotate","perspective"].some(o=>t[o]?t[o]!=="none":!1)||(t.containerType?t.containerType!=="normal":!1)||!n&&(t.backdropFilter?t.backdropFilter!=="none":!1)||!n&&(t.filter?t.filter!=="none":!1)||["transform","translate","scale","rotate","perspective","filter"].some(o=>(t.willChange||"").includes(o))||["paint","layout","strict","content"].some(o=>(t.contain||"").includes(o))}function _n(e){let n=q(e);for(;V(n)&&!ce(n);){if(qe(n))return n;if($e(n))return null;n=q(n)}return null}function Ge(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function ce(e){return["html","body","#document"].includes(re(e))}function k(e){return N(e).getComputedStyle(e)}function Re(e){return I(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function q(e){if(re(e)==="html")return e;const n=e.assignedSlot||e.parentNode||it(e)&&e.host||z(e);return it(n)?n.host:n}function Bt(e){const n=q(e);return ce(n)?e.ownerDocument?e.ownerDocument.body:e.body:V(n)&&ve(n)?n:Bt(n)}function pe(e,n,t){var o;n===void 0&&(n=[]),t===void 0&&(t=!0);const r=Bt(e),i=r===((o=e.ownerDocument)==null?void 0:o.body),l=N(r);if(i){const a=He(l);return n.concat(l,l.visualViewport||[],ve(r)?r:[],a&&t?pe(a):[])}return n.concat(r,pe(r,[],t))}function He(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function At(e){const n=k(e);let t=parseFloat(n.width)||0,o=parseFloat(n.height)||0;const r=V(e),i=r?e.offsetWidth:t,l=r?e.offsetHeight:o,a=Ae(t)!==i||Ae(o)!==l;return a&&(t=i,o=l),{width:t,height:o,$:a}}function Je(e){return I(e)?e:e.contextElement}function de(e){const n=Je(e);if(!V(n))return j(1);const t=n.getBoundingClientRect(),{width:o,height:r,$:i}=At(n);let l=(i?Ae(t.width):t.width)/o,a=(i?Ae(t.height):t.height)/r;return(!l||!Number.isFinite(l))&&(l=1),(!a||!Number.isFinite(a))&&(a=1),{x:l,y:a}}const Dn=j(0);function Tt(e){const n=N(e);return!Ge()||!n.visualViewport?Dn:{x:n.visualViewport.offsetLeft,y:n.visualViewport.offsetTop}}function Bn(e,n,t){return n===void 0&&(n=!1),!t||n&&t!==N(e)?!1:n}function te(e,n,t,o){n===void 0&&(n=!1),t===void 0&&(t=!1);const r=e.getBoundingClientRect(),i=Je(e);let l=j(1);n&&(o?I(o)&&(l=de(o)):l=de(e));const a=Bn(i,t,o)?Tt(i):j(0);let c=(r.left+a.x)/l.x,d=(r.top+a.y)/l.y,s=r.width/l.x,u=r.height/l.y;if(i){const p=N(i),v=o&&I(o)?N(o):o;let h=p,g=He(h);for(;g&&o&&v!==h;){const m=de(g),y=g.getBoundingClientRect(),B=k(g),b=y.left+(g.clientLeft+parseFloat(B.paddingLeft))*m.x,$=y.top+(g.clientTop+parseFloat(B.paddingTop))*m.y;c*=m.x,d*=m.y,s*=m.x,u*=m.y,c+=b,d+=$,h=N(g),g=He(h)}}return Dt({width:s,height:u,x:c,y:d})}function Qe(e,n){const t=Re(e).scrollLeft;return n?n.left+t:te(z(e)).left+t}function Pt(e,n,t){t===void 0&&(t=!1);const o=e.getBoundingClientRect(),r=o.left+n.scrollLeft-(t?0:Qe(e,o)),i=o.top+n.scrollTop;return{x:r,y:i}}function An(e){let{elements:n,rect:t,offsetParent:o,strategy:r}=e;const i=r==="fixed",l=z(o),a=n?$e(n.floating):!1;if(o===l||a&&i)return t;let c={scrollLeft:0,scrollTop:0},d=j(1);const s=j(0),u=V(o);if((u||!u&&!i)&&((re(o)!=="body"||ve(l))&&(c=Re(o)),V(o))){const v=te(o);d=de(o),s.x=v.x+o.clientLeft,s.y=v.y+o.clientTop}const p=l&&!u&&!i?Pt(l,c,!0):j(0);return{width:t.width*d.x,height:t.height*d.y,x:t.x*d.x-c.scrollLeft*d.x+s.x+p.x,y:t.y*d.y-c.scrollTop*d.y+s.y+p.y}}function Tn(e){return Array.from(e.getClientRects())}function Pn(e){const n=z(e),t=Re(e),o=e.ownerDocument.body,r=ue(n.scrollWidth,n.clientWidth,o.scrollWidth,o.clientWidth),i=ue(n.scrollHeight,n.clientHeight,o.scrollHeight,o.clientHeight);let l=-t.scrollLeft+Qe(e);const a=-t.scrollTop;return k(o).direction==="rtl"&&(l+=ue(n.clientWidth,o.clientWidth)-r),{width:r,height:i,x:l,y:a}}function $n(e,n){const t=N(e),o=z(e),r=t.visualViewport;let i=o.clientWidth,l=o.clientHeight,a=0,c=0;if(r){i=r.width,l=r.height;const d=Ge();(!d||d&&n==="fixed")&&(a=r.offsetLeft,c=r.offsetTop)}return{width:i,height:l,x:a,y:c}}function Rn(e,n){const t=te(e,!0,n==="fixed"),o=t.top+e.clientTop,r=t.left+e.clientLeft,i=V(e)?de(e):j(1),l=e.clientWidth*i.x,a=e.clientHeight*i.y,c=r*i.x,d=o*i.y;return{width:l,height:a,x:c,y:d}}function at(e,n,t){let o;if(n==="viewport")o=$n(e,t);else if(n==="document")o=Pn(z(e));else if(I(n))o=Rn(n,t);else{const r=Tt(e);o={x:n.x-r.x,y:n.y-r.y,width:n.width,height:n.height}}return Dt(o)}function $t(e,n){const t=q(e);return t===n||!I(t)||ce(t)?!1:k(t).position==="fixed"||$t(t,n)}function Sn(e,n){const t=n.get(e);if(t)return t;let o=pe(e,[],!1).filter(a=>I(a)&&re(a)!=="body"),r=null;const i=k(e).position==="fixed";let l=i?q(e):e;for(;I(l)&&!ce(l);){const a=k(l),c=qe(l);!c&&a.position==="fixed"&&(r=null),(i?!c&&!r:!c&&a.position==="static"&&!!r&&["absolute","fixed"].includes(r.position)||ve(l)&&!c&&$t(e,l))?o=o.filter(s=>s!==l):r=a,l=q(l)}return n.set(e,o),o}function Nn(e){let{element:n,boundary:t,rootBoundary:o,strategy:r}=e;const l=[...t==="clippingAncestors"?$e(n)?[]:Sn(n,this._c):[].concat(t),o],a=l[0],c=l.reduce((d,s)=>{const u=at(n,s,r);return d.top=ue(u.top,d.top),d.right=We(u.right,d.right),d.bottom=We(u.bottom,d.bottom),d.left=ue(u.left,d.left),d},at(n,a,r));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function Fn(e){const{width:n,height:t}=At(e);return{width:n,height:t}}function Ln(e,n,t){const o=V(n),r=z(n),i=t==="fixed",l=te(e,!0,i,n);let a={scrollLeft:0,scrollTop:0};const c=j(0);if(o||!o&&!i)if((re(n)!=="body"||ve(r))&&(a=Re(n)),o){const p=te(n,!0,i,n);c.x=p.x+n.clientLeft,c.y=p.y+n.clientTop}else r&&(c.x=Qe(r));const d=r&&!o&&!i?Pt(r,a):j(0),s=l.left+a.scrollLeft-c.x-d.x,u=l.top+a.scrollTop-c.y-d.y;return{x:s,y:u,width:l.width,height:l.height}}function Ne(e){return k(e).position==="static"}function st(e,n){if(!V(e)||k(e).position==="fixed")return null;if(n)return n(e);let t=e.offsetParent;return z(e)===t&&(t=t.ownerDocument.body),t}function Rt(e,n){const t=N(e);if($e(e))return t;if(!V(e)){let r=q(e);for(;r&&!ce(r);){if(I(r)&&!Ne(r))return r;r=q(r)}return t}let o=st(e,n);for(;o&&En(o)&&Ne(o);)o=st(o,n);return o&&ce(o)&&Ne(o)&&!qe(o)?t:o||_n(e)||t}const Mn=async function(e){const n=this.getOffsetParent||Rt,t=this.getDimensions,o=await t(e.floating);return{reference:Ln(e.reference,await n(e.floating),e.strategy),floating:{x:0,y:0,width:o.width,height:o.height}}};function In(e){return k(e).direction==="rtl"}const kn={convertOffsetParentRelativeRectToViewportRelativeRect:An,getDocumentElement:z,getClippingRect:Nn,getOffsetParent:Rt,getElementRects:Mn,getClientRects:Tn,getDimensions:Fn,getScale:de,isElement:I,isRTL:In};function St(e,n){return e.x===n.x&&e.y===n.y&&e.width===n.width&&e.height===n.height}function Wn(e,n){let t=null,o;const r=z(e);function i(){var a;clearTimeout(o),(a=t)==null||a.disconnect(),t=null}function l(a,c){a===void 0&&(a=!1),c===void 0&&(c=1),i();const d=e.getBoundingClientRect(),{left:s,top:u,width:p,height:v}=d;if(a||n(),!p||!v)return;const h=Oe(u),g=Oe(r.clientWidth-(s+p)),m=Oe(r.clientHeight-(u+v)),y=Oe(s),b={rootMargin:-h+"px "+-g+"px "+-m+"px "+-y+"px",threshold:ue(0,We(1,c))||1};let $=!0;function R(L){const T=L[0].intersectionRatio;if(T!==c){if(!$)return l();T?l(!1,T):o=setTimeout(()=>{l(!1,1e-7)},1e3)}T===1&&!St(d,e.getBoundingClientRect())&&l(),$=!1}try{t=new IntersectionObserver(R,{...b,root:r.ownerDocument})}catch{t=new IntersectionObserver(R,b)}t.observe(e)}return l(!0),i}function Hn(e,n,t,o){o===void 0&&(o={});const{ancestorScroll:r=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:c=!1}=o,d=Je(e),s=r||i?[...d?pe(d):[],...pe(n)]:[];s.forEach(y=>{r&&y.addEventListener("scroll",t,{passive:!0}),i&&y.addEventListener("resize",t)});const u=d&&a?Wn(d,t):null;let p=-1,v=null;l&&(v=new ResizeObserver(y=>{let[B]=y;B&&B.target===d&&v&&(v.unobserve(n),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var b;(b=v)==null||b.observe(n)})),t()}),d&&!c&&v.observe(d),v.observe(n));let h,g=c?te(e):null;c&&m();function m(){const y=te(e);g&&!St(g,y)&&t(),g=y,h=requestAnimationFrame(m)}return t(),()=>{var y;s.forEach(B=>{r&&B.removeEventListener("scroll",t),i&&B.removeEventListener("resize",t)}),u==null||u(),(y=v)==null||y.disconnect(),v=null,c&&cancelAnimationFrame(h)}}const jn=mn,Vn=gn,ut=yn,zn=wn,Kn=bn,Un=On,Yn=xn,Xn=(e,n,t)=>{const o=new Map,r={platform:kn,...t},i={...r.platform,_c:o};return Cn(e,n,{...r,platform:i})};function qn(e){return e!=null&&typeof e=="object"&&"$el"in e}function je(e){if(qn(e)){const n=e.$el;return Xe(n)&&re(n)==="#comment"?null:n}return e}function se(e){return typeof e=="function"?e():f(e)}function Gn(e){return{name:"arrow",options:e,fn(n){const t=je(se(e.element));return t==null?{}:Un({element:t,padding:e.padding}).fn(n)}}}function Nt(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function dt(e,n){const t=Nt(e);return Math.round(n*t)/t}function Jn(e,n,t){t===void 0&&(t={});const o=t.whileElementsMounted,r=w(()=>{var T;return(T=se(t.open))!=null?T:!0}),i=w(()=>se(t.middleware)),l=w(()=>{var T;return(T=se(t.placement))!=null?T:"bottom"}),a=w(()=>{var T;return(T=se(t.strategy))!=null?T:"absolute"}),c=w(()=>{var T;return(T=se(t.transform))!=null?T:!0}),d=w(()=>je(e.value)),s=w(()=>je(n.value)),u=C(0),p=C(0),v=C(a.value),h=C(l.value),g=ht({}),m=C(!1),y=w(()=>{const T={position:v.value,left:"0",top:"0"};if(!s.value)return T;const H=dt(s.value,u.value),ge=dt(s.value,p.value);return c.value?{...T,transform:"translate("+H+"px, "+ge+"px)",...Nt(s.value)>=1.5&&{willChange:"transform"}}:{position:v.value,left:H+"px",top:ge+"px"}});let B;function b(){if(d.value==null||s.value==null)return;const T=r.value;Xn(d.value,s.value,{middleware:i.value,placement:l.value,strategy:a.value}).then(H=>{u.value=H.x,p.value=H.y,v.value=H.strategy,h.value=H.placement,g.value=H.middlewareData,m.value=T!==!1})}function $(){typeof B=="function"&&(B(),B=void 0)}function R(){if($(),o===void 0){b();return}if(d.value!=null&&s.value!=null){B=o(d.value,s.value,b);return}}function L(){r.value||(m.value=!1)}return F([i,l,a,r],b,{flush:"sync"}),F([d,s],R,{flush:"sync"}),F(r,L,{flush:"sync"}),mt()&&yt($),{x:ie(u),y:ie(p),strategy:ie(v),placement:ie(h),middlewareData:ie(g),isPositioned:ie(m),floatingStyles:y,update:b}}function le(e,n){const t=typeof e=="string"&&!n?`${e}Context`:n,o=Symbol(t);return[r=>{const i=en(o,r);if(i||i===null)return i;throw new Error(`Injection \`${o.toString()}\` not found. Component must be used within ${Array.isArray(e)?`one of the following components: ${e.join(", ")}`:`\`${e}\``}`)},r=>(hn(o,r),r)]}function Ft(e,n,t){const o=t.originalEvent.target,r=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:t});n&&o.addEventListener(e,n,{once:!0}),o.dispatchEvent(r)}function Qn(e,n){var t;const o=ht();return M(()=>{o.value=e()},{...n,flush:(t=void 0)!=null?t:"sync"}),Ct(o)}function he(e){return mt()?(yt(e),!0):!1}function Zn(){const e=new Set,n=t=>{e.delete(t)};return{on:t=>{e.add(t);const o=()=>n(t);return he(o),{off:o}},off:n,trigger:(...t)=>Promise.all(Array.from(e).map(o=>o(...t)))}}function eo(e){let n=!1,t;const o=Et(!0);return(...r)=>(n||(t=o.run(()=>e(...r)),n=!0),t)}function to(e){let n=0,t,o;const r=()=>{n-=1,o&&n<=0&&(o.stop(),t=void 0,o=void 0)};return(...i)=>(n+=1,t||(o=Et(!0),t=o.run(()=>e(...i))),he(r),t)}function Z(e){return typeof e=="function"?e():f(e)}const Q=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const no=e=>typeof e<"u",oo=Object.prototype.toString,ro=e=>oo.call(e)==="[object Object]",lo=()=>{},ct=io();function io(){var e,n;return Q&&((e=window==null?void 0:window.navigator)==null?void 0:e.userAgent)&&(/iP(?:ad|hone|od)/.test(window.navigator.userAgent)||((n=window==null?void 0:window.navigator)==null?void 0:n.maxTouchPoints)>2&&/iPad|Macintosh/.test(window==null?void 0:window.navigator.userAgent))}function ao(e){return oe()}function so(e,n=1e4){return vn((t,o)=>{let r=Z(e),i;const l=()=>setTimeout(()=>{r=Z(e),o()},Z(n));return he(()=>{clearTimeout(i)}),{get(){return t(),r},set(a){r=a,o(),clearTimeout(i),i=l()}}})}function uo(e,n){ao()&&dn(e,n)}function Lt(e,n,t={}){const{immediate:o=!0}=t,r=C(!1);let i=null;function l(){i&&(clearTimeout(i),i=null)}function a(){r.value=!1,l()}function c(...d){l(),r.value=!0,i=setTimeout(()=>{r.value=!1,i=null,e(...d)},Z(n))}return o&&(r.value=!0,Q&&c()),he(a),{isPending:Ct(r),start:c,stop:a}}function me(e){var n;const t=Z(e);return(n=t==null?void 0:t.$el)!=null?n:t}const Ze=Q?window:void 0;function Te(...e){let n,t,o,r;if(typeof e[0]=="string"||Array.isArray(e[0])?([t,o,r]=e,n=Ze):[n,t,o,r]=e,!n)return lo;Array.isArray(t)||(t=[t]),Array.isArray(o)||(o=[o]);const i=[],l=()=>{i.forEach(s=>s()),i.length=0},a=(s,u,p,v)=>(s.addEventListener(u,p,v),()=>s.removeEventListener(u,p,v)),c=F(()=>[me(n),Z(r)],([s,u])=>{if(l(),!s)return;const p=ro(u)?{...u}:u;i.push(...t.flatMap(v=>o.map(h=>a(s,v,h,p))))},{immediate:!0,flush:"post"}),d=()=>{c(),l()};return he(d),d}function co(e){return typeof e=="function"?e:typeof e=="string"?n=>n.key===e:Array.isArray(e)?n=>e.includes(n.key):()=>!0}function fo(...e){let n,t,o={};e.length===3?(n=e[0],t=e[1],o=e[2]):e.length===2?typeof e[1]=="object"?(n=!0,t=e[0],o=e[1]):(n=e[0],t=e[1]):(n=!0,t=e[0]);const{target:r=Ze,eventName:i="keydown",passive:l=!1,dedupe:a=!1}=o,c=co(n);return Te(r,i,d=>{d.repeat&&Z(a)||c(d)&&t(d)},l)}function po(){const e=C(!1),n=oe();return n&&fe(()=>{e.value=!0},n),e}function vo(e){return JSON.parse(JSON.stringify(e))}function Mt(e,n,t,o={}){var r,i,l;const{clone:a=!1,passive:c=!1,eventName:d,deep:s=!1,defaultValue:u,shouldEmit:p}=o,v=oe(),h=t||(v==null?void 0:v.emit)||((r=v==null?void 0:v.$emit)==null?void 0:r.bind(v))||((l=(i=v==null?void 0:v.proxy)==null?void 0:i.$emit)==null?void 0:l.bind(v==null?void 0:v.proxy));let g=d;g=g||`update:${n.toString()}`;const m=b=>a?typeof a=="function"?a(b):vo(b):b,y=()=>no(e[n])?m(e[n]):u,B=b=>{p?p(b)&&h(g,b):h(g,b)};if(c){const b=y(),$=C(b);let R=!1;return F(()=>e[n],L=>{R||(R=!0,$.value=m(L),ne(()=>R=!1))}),F($,L=>{!R&&(L!==e[n]||s)&&B(L)},{deep:s}),$}else return w({get(){return y()},set(b){B(b)}})}function et(e){return e?e.flatMap(n=>n.type===rn?et(n.children):[n]):[]}function X(){let e=document.activeElement;if(e==null)return null;for(;e!=null&&e.shadowRoot!=null&&e.shadowRoot.activeElement!=null;)e=e.shadowRoot.activeElement;return e}function Fe(e){if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n!==null&&n!==Object.prototype&&Object.getPrototypeOf(n)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)==="[object Module]":!0}function Ve(e,n,t=".",o){if(!Fe(n))return Ve(e,{},t);const r=Object.assign({},n);for(const i in e){if(i==="__proto__"||i==="constructor")continue;const l=e[i];l!=null&&(Array.isArray(l)&&Array.isArray(r[i])?r[i]=[...l,...r[i]]:Fe(l)&&Fe(r[i])?r[i]=Ve(l,r[i],(t?`${t}.`:"")+i.toString()):r[i]=l)}return r}function ho(e){return(...n)=>n.reduce((t,o)=>Ve(t,o,""),{})}const mo=ho(),[It,Tr]=le("ConfigProvider");let yo="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",go=(e=21)=>{let n="",t=e;for(;t--;)n+=yo[Math.random()*64|0];return n};const wo=to(()=>{const e=C(new Map),n=C(),t=w(()=>{for(const l of e.value.values())if(l)return!0;return!1}),o=It({scrollBody:C(!0)});let r=null;const i=()=>{document.body.style.paddingRight="",document.body.style.marginRight="",document.body.style.pointerEvents="",document.body.style.removeProperty("--scrollbar-width"),document.body.style.overflow=n.value??"",ct&&(r==null||r()),n.value=void 0};return F(t,(l,a)=>{var c;if(!Q)return;if(!l){a&&i();return}n.value===void 0&&(n.value=document.body.style.overflow);const d=window.innerWidth-document.documentElement.clientWidth,s={padding:d,margin:0},u=(c=o.scrollBody)!=null&&c.value?typeof o.scrollBody.value=="object"?mo({padding:o.scrollBody.value.padding===!0?d:o.scrollBody.value.padding,margin:o.scrollBody.value.margin===!0?d:o.scrollBody.value.margin},s):s:{padding:0,margin:0};d>0&&(document.body.style.paddingRight=typeof u.padding=="number"?`${u.padding}px`:String(u.padding),document.body.style.marginRight=typeof u.margin=="number"?`${u.margin}px`:String(u.margin),document.body.style.setProperty("--scrollbar-width",`${d}px`),document.body.style.overflow="hidden"),ct&&(r=Te(document,"touchmove",p=>xo(p),{passive:!1})),ne(()=>{document.body.style.pointerEvents="none",document.body.style.overflow="hidden"})},{immediate:!0,flush:"sync"}),e});function bo(e){const n=go(6),t=wo();t.value.set(n,e);const o=w({get:()=>t.value.get(n)??!1,set:r=>t.value.set(n,r)});return uo(()=>{t.value.delete(n)}),o}function kt(e){const n=window.getComputedStyle(e);if(n.overflowX==="scroll"||n.overflowY==="scroll"||n.overflowX==="auto"&&e.clientWidth1?!0:(n.preventDefault&&n.cancelable&&n.preventDefault(),!1)}function ye(e){const n=oe(),t=n==null?void 0:n.type.emits,o={};return t!=null&&t.length||console.warn(`No emitted event found. Please check component: ${n==null?void 0:n.type.__name}`),t==null||t.forEach(r=>{o[Zt(wt(r))]=(...i)=>e(r,...i)}),o}function Wt(e){const n=oe(),t=Object.keys((n==null?void 0:n.type.props)??{}).reduce((r,i)=>{const l=(n==null?void 0:n.type.props[i]).default;return l!==void 0&&(r[i]=l),r},{}),o=on(e);return w(()=>{const r={},i=(n==null?void 0:n.vnode.props)??{};return Object.keys(i).forEach(l=>{r[wt(l)]=i[l]}),Object.keys({...t,...r}).reduce((l,a)=>(o.value[a]!==void 0&&(l[a]=o.value[a]),l),{})})}function Ht(e,n){const t=Wt(e),o=n?ye(n):{};return w(()=>({...t.value,...o}))}function A(){const e=oe(),n=C(),t=w(()=>{var l,a;return["#text","#comment"].includes((l=n.value)==null?void 0:l.$el.nodeName)?(a=n.value)==null?void 0:a.$el.nextElementSibling:me(n)}),o=Object.assign({},e.exposed),r={};for(const l in e.props)Object.defineProperty(r,l,{enumerable:!0,configurable:!0,get:()=>e.props[l]});if(Object.keys(o).length>0)for(const l in o)Object.defineProperty(r,l,{enumerable:!0,configurable:!0,get:()=>o[l]});Object.defineProperty(r,"$el",{enumerable:!0,configurable:!0,get:()=>e.vnode.el}),e.exposed=r;function i(l){n.value=l,l&&(Object.defineProperty(r,"$el",{enumerable:!0,configurable:!0,get:()=>l instanceof Element?l:l.$el}),e.exposed=r)}return{forwardRef:i,currentRef:n,currentElement:t}}function Co(e,n){const t=so(!1,300),o=C(null),r=Zn();function i(){o.value=null,t.value=!1}function l(a,c){const d=a.currentTarget,s={x:a.clientX,y:a.clientY},u=Oo(s,d.getBoundingClientRect()),p=Eo(s,u),v=_o(c.getBoundingClientRect()),h=Bo([...p,...v]);o.value=h,t.value=!0}return M(a=>{if(e.value&&n.value){const c=s=>l(s,n.value),d=s=>l(s,e.value);e.value.addEventListener("pointerleave",c),n.value.addEventListener("pointerleave",d),a(()=>{var s,u;(s=e.value)==null||s.removeEventListener("pointerleave",c),(u=n.value)==null||u.removeEventListener("pointerleave",d)})}}),M(a=>{var c;if(o.value){const d=s=>{var u,p;if(!o.value)return;const v=s.target,h={x:s.clientX,y:s.clientY},g=((u=e.value)==null?void 0:u.contains(v))||((p=n.value)==null?void 0:p.contains(v)),m=!Do(h,o.value),y=!!v.closest("[data-grace-area-trigger]");g?i():(m||y)&&(i(),r.trigger())};(c=e.value)==null||c.ownerDocument.addEventListener("pointermove",d),a(()=>{var s;return(s=e.value)==null?void 0:s.ownerDocument.removeEventListener("pointermove",d)})}}),{isPointerInTransit:t,onPointerExit:r.on}}function Oo(e,n){const t=Math.abs(n.top-e.y),o=Math.abs(n.bottom-e.y),r=Math.abs(n.right-e.x),i=Math.abs(n.left-e.x);switch(Math.min(t,o,r,i)){case i:return"left";case r:return"right";case t:return"top";case o:return"bottom";default:throw new Error("unreachable")}}function Eo(e,n,t=5){const o=[];switch(n){case"top":o.push({x:e.x-t,y:e.y+t},{x:e.x+t,y:e.y+t});break;case"bottom":o.push({x:e.x-t,y:e.y-t},{x:e.x+t,y:e.y-t});break;case"left":o.push({x:e.x+t,y:e.y-t},{x:e.x+t,y:e.y+t});break;case"right":o.push({x:e.x-t,y:e.y-t},{x:e.x-t,y:e.y+t});break}return o}function _o(e){const{top:n,right:t,bottom:o,left:r}=e;return[{x:r,y:n},{x:t,y:n},{x:t,y:o},{x:r,y:o}]}function Do(e,n){const{x:t,y:o}=e;let r=!1;for(let i=0,l=n.length-1;io!=s>o&&t<(d-a)*(o-c)/(s-c)+a&&(r=!r)}return r}function Bo(e){const n=e.slice();return n.sort((t,o)=>t.xo.x?1:t.yo.y?1:0),Ao(n)}function Ao(e){if(e.length<=1)return e.slice();const n=[];for(let o=0;o=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(r.y-l.y)>=(i.y-l.y)*(r.x-l.x))n.pop();else break}n.push(r)}n.pop();const t=[];for(let o=e.length-1;o>=0;o--){const r=e[o];for(;t.length>=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(r.y-l.y)>=(i.y-l.y)*(r.x-l.x))t.pop();else break}t.push(r)}return t.pop(),n.length===1&&t.length===1&&n[0].x===t[0].x&&n[0].y===t[0].y?n:n.concat(t)}var To=function(e){if(typeof document>"u")return null;var n=Array.isArray(e)?e[0]:e;return n.ownerDocument.body},ae=new WeakMap,Ee=new WeakMap,_e={},Le=0,jt=function(e){return e&&(e.host||jt(e.parentNode))},Po=function(e,n){return n.map(function(t){if(e.contains(t))return t;var o=jt(t);return o&&e.contains(o)?o:(console.error("aria-hidden",t,"in not contained inside",e,". Doing nothing"),null)}).filter(function(t){return!!t})},$o=function(e,n,t,o){var r=Po(n,Array.isArray(e)?e:[e]);_e[t]||(_e[t]=new WeakMap);var i=_e[t],l=[],a=new Set,c=new Set(r),d=function(u){!u||a.has(u)||(a.add(u),d(u.parentNode))};r.forEach(d);var s=function(u){!u||c.has(u)||Array.prototype.forEach.call(u.children,function(p){if(a.has(p))s(p);else try{var v=p.getAttribute(o),h=v!==null&&v!=="false",g=(ae.get(p)||0)+1,m=(i.get(p)||0)+1;ae.set(p,g),i.set(p,m),l.push(p),g===1&&h&&Ee.set(p,!0),m===1&&p.setAttribute(t,"true"),h||p.setAttribute(o,"true")}catch(y){console.error("aria-hidden: cannot operate on ",p,y)}})};return s(n),a.clear(),Le++,function(){l.forEach(function(u){var p=ae.get(u)-1,v=i.get(u)-1;ae.set(u,p),i.set(u,v),p||(Ee.has(u)||u.removeAttribute(o),Ee.delete(u)),v||u.removeAttribute(t)}),Le--,Le||(ae=new WeakMap,ae=new WeakMap,Ee=new WeakMap,_e={})}},Ro=function(e,n,t){t===void 0&&(t="data-aria-hidden");var o=Array.from(Array.isArray(e)?e:[e]),r=To(e);return r?(o.push.apply(o,Array.from(r.querySelectorAll("[aria-live]"))),$o(o,r,t,"aria-hidden")):function(){return null}};function So(e){let n;F(()=>me(e),t=>{t?n=Ro(t):n&&n()}),bt(()=>{n&&n()})}let No=0;function ze(e,n="radix"){const t=It({useId:void 0});return lt?`${n}-${lt()}`:t.useId?`${n}-${t.useId()}`:`${n}-${++No}`}function Fo(e){const n=C(),t=w(()=>{var r;return((r=n.value)==null?void 0:r.width)??0}),o=w(()=>{var r;return((r=n.value)==null?void 0:r.height)??0});return fe(()=>{const r=me(e);if(r){n.value={width:r.offsetWidth,height:r.offsetHeight};const i=new ResizeObserver(l=>{if(!Array.isArray(l)||!l.length)return;const a=l[0];let c,d;if("borderBoxSize"in a){const s=a.borderBoxSize,u=Array.isArray(s)?s[0]:s;c=u.inlineSize,d=u.blockSize}else c=r.offsetWidth,d=r.offsetHeight;n.value={width:c,height:d}});return i.observe(r,{box:"border-box"}),()=>i.unobserve(r)}else n.value=void 0}),{width:t,height:o}}function Lo(e,n){const t=C(e);function o(r){return n[t.value][r]??t.value}return{state:t,dispatch:r=>{t.value=o(r)}}}const Mo=O({name:"PrimitiveSlot",inheritAttrs:!1,setup(e,{attrs:n,slots:t}){return()=>{var o,r;if(!t.default)return null;const i=et(t.default()),l=i.findIndex(s=>s.type!==xt);if(l===-1)return i;const a=i[l];(o=a.props)==null||delete o.ref;const c=a.props?P(n,a.props):n;n.class&&(r=a.props)!=null&&r.class&&delete a.props.class;const d=ln(a,c);for(const s in c)s.startsWith("on")&&(d.props||(d.props={}),d.props[s]=c[s]);return i.length===1?d:(i[l]=d,i)}}}),W=O({name:"Primitive",inheritAttrs:!1,props:{asChild:{type:Boolean,default:!1},as:{type:[String,Object],default:"div"}},setup(e,{attrs:n,slots:t}){const o=e.asChild?"template":e.as;return typeof o=="string"&&["area","img","input"].includes(o)?()=>Be(o,n):o!=="template"?()=>Be(e.as,n,{default:t.default}):()=>Be(Mo,n,{default:t.default})}});function Io(e,n){var t;const o=C({}),r=C("none"),i=C(e),l=e.value?"mounted":"unmounted";let a;const c=((t=n.value)==null?void 0:t.ownerDocument.defaultView)??Ze,{state:d,dispatch:s}=Lo(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}}),u=m=>{var y;if(Q){const B=new CustomEvent(m,{bubbles:!1,cancelable:!1});(y=n.value)==null||y.dispatchEvent(B)}};F(e,async(m,y)=>{var B;const b=y!==m;if(await ne(),b){const $=r.value,R=De(n.value);m?(s("MOUNT"),u("enter"),R==="none"&&u("after-enter")):R==="none"||((B=o.value)==null?void 0:B.display)==="none"?(s("UNMOUNT"),u("leave"),u("after-leave")):y&&$!==R?(s("ANIMATION_OUT"),u("leave")):(s("UNMOUNT"),u("after-leave"))}},{immediate:!0});const p=m=>{const y=De(n.value),B=y.includes(m.animationName),b=d.value==="mounted"?"enter":"leave";if(m.target===n.value&&B&&(u(`after-${b}`),s("ANIMATION_END"),!i.value)){const $=n.value.style.animationFillMode;n.value.style.animationFillMode="forwards",a=c==null?void 0:c.setTimeout(()=>{var R;((R=n.value)==null?void 0:R.style.animationFillMode)==="forwards"&&(n.value.style.animationFillMode=$)})}m.target===n.value&&y==="none"&&s("ANIMATION_END")},v=m=>{m.target===n.value&&(r.value=De(n.value))},h=F(n,(m,y)=>{m?(o.value=getComputedStyle(m),m.addEventListener("animationstart",v),m.addEventListener("animationcancel",p),m.addEventListener("animationend",p)):(s("ANIMATION_END"),a!==void 0&&(c==null||c.clearTimeout(a)),y==null||y.removeEventListener("animationstart",v),y==null||y.removeEventListener("animationcancel",p),y==null||y.removeEventListener("animationend",p))},{immediate:!0}),g=F(d,()=>{const m=De(n.value);r.value=d.value==="mounted"?m:"none"});return bt(()=>{h(),g()}),{isPresent:w(()=>["mounted","unmountSuspended"].includes(d.value))}}function De(e){return e&&getComputedStyle(e).animationName||"none"}const tt=O({name:"Presence",props:{present:{type:Boolean,required:!0},forceMount:{type:Boolean}},slots:{},setup(e,{slots:n,expose:t}){var o;const{present:r,forceMount:i}=Ue(e),l=C(),{isPresent:a}=Io(r,l);t({present:a});let c=n.default({present:a});c=et(c||[]);const d=oe();if(c&&(c==null?void 0:c.length)>1){const s=(o=d==null?void 0:d.parent)!=null&&o.type.name?`<${d.parent.type.name} />`:"component";throw new Error([`Detected an invalid children for \`${s}\` 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(u=>` - ${u}`).join(` `)].join(` -`))}return()=>i.value||r.value||a.value?Be(n.default({present:a})[0],{ref:s=>{const u=me(s);return typeof(u==null?void 0:u.hasAttribute)>"u"||(u!=null&&u.hasAttribute("data-radix-popper-content-wrapper")?l.value=u.firstElementChild:l.value=u),u}}):null}}),[U,ko]=le("DialogRoot"),Wo=O({inheritAttrs:!1,__name:"DialogRoot",props:{open:{type:Boolean,default:void 0},defaultOpen:{type:Boolean,default:!1},modal:{type:Boolean,default:!0}},emits:["update:open"],setup(e,{emit:n}){const t=e,o=Mt(t,"open",n,{defaultValue:t.defaultOpen,passive:t.open===void 0}),r=C(),i=C(),{modal:l}=Ue(t);return ko({open:o,modal:l,openModal:()=>{o.value=!0},onOpenChange:a=>{o.value=a},onOpenToggle:()=>{o.value=!o.value},contentId:"",titleId:"",descriptionId:"",triggerElement:r,contentElement:i}),(a,c)=>E(a.$slots,"default",{open:f(o)})}}),nt=O({__name:"Teleport",props:{to:{default:"body"},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=po();return(t,o)=>f(n)||t.forceMount?(_(),D(Qt,{key:0,to:t.to,disabled:t.disabled},[E(t.$slots,"default")],8,["to","disabled"])):gt("",!0)}}),Pr=O({__name:"DialogPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=e;return(t,o)=>(_(),D(f(nt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Ho="dismissableLayer.pointerDownOutside",jo="dismissableLayer.focusOutside";function Vt(e,n){const t=n.closest("[data-dismissable-layer]"),o=e.dataset.dismissableLayer===""?e:e.querySelector("[data-dismissable-layer]"),r=Array.from(e.ownerDocument.querySelectorAll("[data-dismissable-layer]"));return!!(t&&o===t||r.indexOf(o){});return M(l=>{if(!Q)return;const a=async d=>{const s=d.target;if(n!=null&&n.value){if(Vt(n.value,s)){r.value=!1;return}if(d.target&&!r.value){let u=function(){Ft(Ho,e,p)};const p={originalEvent:d};d.pointerType==="touch"?(o.removeEventListener("click",i.value),i.value=u,o.addEventListener("click",i.value,{once:!0})):u()}else o.removeEventListener("click",i.value);r.value=!1}},c=window.setTimeout(()=>{o.addEventListener("pointerdown",a)},0);l(()=>{window.clearTimeout(c),o.removeEventListener("pointerdown",a),o.removeEventListener("click",i.value)})}),{onPointerDownCapture:()=>r.value=!0}}function zo(e,n){var t;const o=((t=n==null?void 0:n.value)==null?void 0:t.ownerDocument)??(globalThis==null?void 0:globalThis.document),r=C(!1);return M(i=>{if(!Q)return;const l=async a=>{n!=null&&n.value&&(await ne(),!(!n.value||Vt(n.value,a.target))&&a.target&&!r.value&&Ft(jo,e,{originalEvent:a}))};o.addEventListener("focusin",l),i(()=>o.removeEventListener("focusin",l))}),{onFocusCapture:()=>r.value=!0,onBlurCapture:()=>r.value=!1}}const K=_t({layersRoot:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),zt=O({__name:"DismissableLayer",props:{disableOutsidePointerEvents:{type:Boolean,default:!1},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","dismiss"],setup(e,{emit:n}){const t=e,o=n,{forwardRef:r,currentElement:i}=A(),l=b(()=>{var h;return((h=i.value)==null?void 0:h.ownerDocument)??globalThis.document}),a=b(()=>K.layersRoot),c=b(()=>i.value?Array.from(a.value).indexOf(i.value):-1),d=b(()=>K.layersWithOutsidePointerEventsDisabled.size>0),s=b(()=>{const h=Array.from(a.value),[g]=[...K.layersWithOutsidePointerEventsDisabled].slice(-1),m=h.indexOf(g);return c.value>=m}),u=Vo(async h=>{const g=[...K.branches].some(m=>m==null?void 0:m.contains(h.target));!s.value||g||(o("pointerDownOutside",h),o("interactOutside",h),await ne(),h.defaultPrevented||o("dismiss"))},i),p=zo(h=>{[...K.branches].some(g=>g==null?void 0:g.contains(h.target))||(o("focusOutside",h),o("interactOutside",h),h.defaultPrevented||o("dismiss"))},i);fo("Escape",h=>{c.value===a.value.size-1&&(o("escapeKeyDown",h),h.defaultPrevented||o("dismiss"))});let v;return M(h=>{i.value&&(t.disableOutsidePointerEvents&&(K.layersWithOutsidePointerEventsDisabled.size===0&&(v=l.value.body.style.pointerEvents,l.value.body.style.pointerEvents="none"),K.layersWithOutsidePointerEventsDisabled.add(i.value)),a.value.add(i.value),h(()=>{t.disableOutsidePointerEvents&&K.layersWithOutsidePointerEventsDisabled.size===1&&(l.value.body.style.pointerEvents=v)}))}),M(h=>{h(()=>{i.value&&(a.value.delete(i.value),K.layersWithOutsidePointerEventsDisabled.delete(i.value))})}),(h,g)=>(_(),D(f(W),{ref:f(r),"as-child":h.asChild,as:h.as,"data-dismissable-layer":"",style:Ye({pointerEvents:d.value?s.value?"auto":"none":void 0}),onFocusCapture:f(p).onFocusCapture,onBlurCapture:f(p).onBlurCapture,onPointerdownCapture:f(u).onPointerDownCapture},{default:x(()=>[E(h.$slots,"default")]),_:3},8,["as-child","as","style","onFocusCapture","onBlurCapture","onPointerdownCapture"]))}}),Me="focusScope.autoFocusOnMount",Ie="focusScope.autoFocusOnUnmount",ft={bubbles:!1,cancelable:!0};function Ko(e,{select:n=!1}={}){const t=X();for(const o of e)if(Y(o,{select:n}),X()!==t)return!0}function Uo(e){const n=Kt(e),t=pt(n,e),o=pt(n.reverse(),e);return[t,o]}function Kt(e){const n=[],t=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>{const r=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||r?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)n.push(t.currentNode);return n}function pt(e,n){for(const t of e)if(!Yo(t,{upTo:n}))return t}function Yo(e,{upTo:n}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(n!==void 0&&e===n)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Xo(e){return e instanceof HTMLInputElement&&"select"in e}function Y(e,{select:n=!1}={}){if(e&&e.focus){const t=X();e.focus({preventScroll:!0}),e!==t&&Xo(e)&&n&&e.select()}}const qo=eo(()=>C([]));function Go(){const e=qo();return{add(n){const t=e.value[0];n!==t&&(t==null||t.pause()),e.value=vt(e.value,n),e.value.unshift(n)},remove(n){var t;e.value=vt(e.value,n),(t=e.value[0])==null||t.resume()}}}function vt(e,n){const t=[...e],o=t.indexOf(n);return o!==-1&&t.splice(o,1),t}function Jo(e){return e.filter(n=>n.tagName!=="A")}const Qo=O({__name:"FocusScope",props:{loop:{type:Boolean,default:!1},trapped:{type:Boolean,default:!1},asChild:{type:Boolean},as:{}},emits:["mountAutoFocus","unmountAutoFocus"],setup(e,{emit:n}){const t=e,o=n,{currentRef:r,currentElement:i}=A(),l=C(null),a=Go(),c=_t({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}});M(s=>{if(!Q)return;const u=i.value;if(!t.trapped)return;function p(m){if(c.paused||!u)return;const y=m.target;u.contains(y)?l.value=y:Y(l.value,{select:!0})}function v(m){if(c.paused||!u)return;const y=m.relatedTarget;y!==null&&(u.contains(y)||Y(l.value,{select:!0}))}function h(m){u.contains(l.value)||Y(u)}document.addEventListener("focusin",p),document.addEventListener("focusout",v);const g=new MutationObserver(h);u&&g.observe(u,{childList:!0,subtree:!0}),s(()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",v),g.disconnect()})}),M(async s=>{const u=i.value;if(await ne(),!u)return;a.add(c);const p=X();if(!u.contains(p)){const v=new CustomEvent(Me,ft);u.addEventListener(Me,h=>o("mountAutoFocus",h)),u.dispatchEvent(v),v.defaultPrevented||(Ko(Jo(Kt(u)),{select:!0}),X()===p&&Y(u))}s(()=>{u.removeEventListener(Me,g=>o("mountAutoFocus",g));const v=new CustomEvent(Ie,ft),h=g=>{o("unmountAutoFocus",g)};u.addEventListener(Ie,h),u.dispatchEvent(v),setTimeout(()=>{v.defaultPrevented||Y(p??document.body,{select:!0}),u.removeEventListener(Ie,h),a.remove(c)},0)})});function d(s){if(!t.loop&&!t.trapped||c.paused)return;const u=s.key==="Tab"&&!s.altKey&&!s.ctrlKey&&!s.metaKey,p=X();if(u&&p){const v=s.currentTarget,[h,g]=Uo(v);h&&g?!s.shiftKey&&p===g?(s.preventDefault(),t.loop&&Y(h,{select:!0})):s.shiftKey&&p===h&&(s.preventDefault(),t.loop&&Y(g,{select:!0})):p===v&&s.preventDefault()}}return(s,u)=>(_(),D(f(W),{ref_key:"currentRef",ref:r,tabindex:"-1","as-child":s.asChild,as:s.as,onKeydown:d},{default:x(()=>[E(s.$slots,"default")]),_:3},8,["as-child","as"]))}});function Zo(e){return e?"open":"closed"}const Ut=O({__name:"DialogContentImpl",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=n,r=U(),{forwardRef:i,currentElement:l}=A();return r.titleId||(r.titleId=ze(void 0,"radix-vue-dialog-title")),r.descriptionId||(r.descriptionId=ze(void 0,"radix-vue-dialog-description")),fe(()=>{r.contentElement=l,X()!==document.body&&(r.triggerElement.value=X())}),(a,c)=>(_(),D(f(Qo),{"as-child":"",loop:"",trapped:t.trapFocus,onMountAutoFocus:c[5]||(c[5]=d=>o("openAutoFocus",d)),onUnmountAutoFocus:c[6]||(c[6]=d=>o("closeAutoFocus",d))},{default:x(()=>[ee(f(zt),P({id:f(r).contentId,ref:f(i),as:a.as,"as-child":a.asChild,"disable-outside-pointer-events":a.disableOutsidePointerEvents,role:"dialog","aria-describedby":f(r).descriptionId,"aria-labelledby":f(r).titleId,"data-state":f(Zo)(f(r).open.value)},a.$attrs,{onDismiss:c[0]||(c[0]=d=>f(r).onOpenChange(!1)),onEscapeKeyDown:c[1]||(c[1]=d=>o("escapeKeyDown",d)),onFocusOutside:c[2]||(c[2]=d=>o("focusOutside",d)),onInteractOutside:c[3]||(c[3]=d=>o("interactOutside",d)),onPointerDownOutside:c[4]||(c[4]=d=>o("pointerDownOutside",d))}),{default:x(()=>[E(a.$slots,"default")]),_:3},16,["id","as","as-child","disable-outside-pointer-events","aria-describedby","aria-labelledby","data-state"])]),_:3},8,["trapped"]))}}),er=O({__name:"DialogContentModal",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=n,r=U(),i=ye(o),{forwardRef:l,currentElement:a}=A();return So(a),(c,d)=>(_(),D(Ut,P({...t,...f(i)},{ref:f(l),"trap-focus":f(r).open.value,"disable-outside-pointer-events":!0,onCloseAutoFocus:d[0]||(d[0]=s=>{var u;s.defaultPrevented||(s.preventDefault(),(u=f(r).triggerElement.value)==null||u.focus())}),onPointerDownOutside:d[1]||(d[1]=s=>{const u=s.detail.originalEvent,p=u.button===0&&u.ctrlKey===!0;(u.button===2||p)&&s.preventDefault()}),onFocusOutside:d[2]||(d[2]=s=>{s.preventDefault()})}),{default:x(()=>[E(c.$slots,"default")]),_:3},16,["trap-focus"]))}}),tr=O({__name:"DialogContentNonModal",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=ye(n);A();const r=U(),i=C(!1),l=C(!1);return(a,c)=>(_(),D(Ut,P({...t,...f(o)},{"trap-focus":!1,"disable-outside-pointer-events":!1,onCloseAutoFocus:c[0]||(c[0]=d=>{var s;d.defaultPrevented||(i.value||(s=f(r).triggerElement.value)==null||s.focus(),d.preventDefault()),i.value=!1,l.value=!1}),onInteractOutside:c[1]||(c[1]=d=>{var s;d.defaultPrevented||(i.value=!0,d.detail.originalEvent.type==="pointerdown"&&(l.value=!0));const u=d.target;(s=f(r).triggerElement.value)!=null&&s.contains(u)&&d.preventDefault(),d.detail.originalEvent.type==="focusin"&&l.value&&d.preventDefault()})}),{default:x(()=>[E(a.$slots,"default")]),_:3},16))}}),nr=O({__name:"DialogContent",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=n,r=U(),i=ye(o),{forwardRef:l}=A();return(a,c)=>(_(),D(f(tt),{present:a.forceMount||f(r).open.value},{default:x(()=>[f(r).modal.value?(_(),D(er,P({key:0,ref:f(l)},{...t,...f(i),...a.$attrs}),{default:x(()=>[E(a.$slots,"default")]),_:3},16)):(_(),D(tr,P({key:1,ref:f(l)},{...t,...f(i),...a.$attrs}),{default:x(()=>[E(a.$slots,"default")]),_:3},16))]),_:3},8,["present"]))}}),or=O({__name:"DialogOverlayImpl",props:{asChild:{type:Boolean},as:{}},setup(e){const n=U();return wo(!0),A(),(t,o)=>(_(),D(f(W),{as:t.as,"as-child":t.asChild,"data-state":f(n).open.value?"open":"closed",style:{"pointer-events":"auto"}},{default:x(()=>[E(t.$slots,"default")]),_:3},8,["as","as-child","data-state"]))}}),rr=O({__name:"DialogOverlay",props:{forceMount:{type:Boolean},asChild:{type:Boolean},as:{}},setup(e){const n=U(),{forwardRef:t}=A();return(o,r)=>{var i;return(i=f(n))!=null&&i.modal.value?(_(),D(f(tt),{key:0,present:o.forceMount||f(n).open.value},{default:x(()=>[ee(or,P(o.$attrs,{ref:f(t),as:o.as,"as-child":o.asChild}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["as","as-child"])]),_:3},8,["present"])):gt("",!0)}}}),Yt=O({__name:"DialogClose",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e;A();const t=U();return(o,r)=>(_(),D(f(W),P(n,{type:o.as==="button"?"button":void 0,onClick:r[0]||(r[0]=i=>f(t).onOpenChange(!1))}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["type"]))}}),lr=O({__name:"DialogTitle",props:{asChild:{type:Boolean},as:{default:"h2"}},setup(e){const n=e,t=U();return A(),(o,r)=>(_(),D(f(W),P(n,{id:f(t).titleId}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["id"]))}}),ir=O({__name:"DialogDescription",props:{asChild:{type:Boolean},as:{default:"p"}},setup(e){const n=e;A();const t=U();return(o,r)=>(_(),D(f(W),P(n,{id:f(t).descriptionId}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["id"]))}}),$r=O({__name:"AlertDialogRoot",props:{open:{type:Boolean},defaultOpen:{type:Boolean}},emits:["update:open"],setup(e,{emit:n}){const t=Ht(e,n);return A(),(o,r)=>(_(),D(f(Wo),P(f(t),{modal:!0}),{default:x(()=>[E(o.$slots,"default")]),_:3},16))}}),Rr=O({__name:"AlertDialogPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=e;return(t,o)=>(_(),D(f(nt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),[ar,sr]=le("AlertDialogContent"),Sr=O({__name:"AlertDialogContent",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=ye(n);A();const r=C();return sr({onCancelElementChange:i=>{r.value=i}}),(i,l)=>(_(),D(f(nr),P({...t,...f(o)},{role:"alertdialog",onPointerDownOutside:l[0]||(l[0]=ke(()=>{},["prevent"])),onInteractOutside:l[1]||(l[1]=ke(()=>{},["prevent"])),onOpenAutoFocus:l[2]||(l[2]=()=>{ne(()=>{var a;(a=r.value)==null||a.focus({preventScroll:!0})})})}),{default:x(()=>[E(i.$slots,"default")]),_:3},16))}}),Nr=O({__name:"AlertDialogOverlay",props:{forceMount:{type:Boolean},asChild:{type:Boolean},as:{}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(rr),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Fr=O({__name:"AlertDialogCancel",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e,t=ar(),{forwardRef:o,currentElement:r}=A();return fe(()=>{t.onCancelElementChange(r.value)}),(i,l)=>(_(),D(f(Yt),P(n,{ref:f(o)}),{default:x(()=>[E(i.$slots,"default")]),_:3},16))}}),Lr=O({__name:"AlertDialogTitle",props:{asChild:{type:Boolean},as:{default:"h2"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(lr),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Mr=O({__name:"AlertDialogDescription",props:{asChild:{type:Boolean},as:{default:"p"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(ir),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Ir=O({__name:"AlertDialogAction",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(Yt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),[Xt,ur]=le("PopperRoot"),dr=O({inheritAttrs:!1,__name:"PopperRoot",setup(e){const n=C();return ur({anchor:n,onAnchorChange:t=>n.value=t}),(t,o)=>E(t.$slots,"default")}}),cr=O({__name:"PopperAnchor",props:{element:{},asChild:{type:Boolean},as:{}},setup(e){const n=e,{forwardRef:t,currentElement:o}=A(),r=Xt();return M(()=>{r.onAnchorChange(n.element??o.value)}),(i,l)=>(_(),D(f(W),{ref:f(t),as:i.as,"as-child":i.asChild},{default:x(()=>[E(i.$slots,"default")]),_:3},8,["as","as-child"]))}});function fr(e){return e!==null}function pr(e){return{name:"transformOrigin",options:e,fn(n){var t,o,r;const{placement:i,rects:l,middlewareData:a}=n,c=((t=a.arrow)==null?void 0:t.centerOffset)!==0,d=c?0:e.arrowWidth,s=c?0:e.arrowHeight,[u,p]=Ke(i),v={start:"0%",center:"50%",end:"100%"}[p],h=(((o=a.arrow)==null?void 0:o.x)??0)+d/2,g=(((r=a.arrow)==null?void 0:r.y)??0)+s/2;let m="",y="";return u==="bottom"?(m=c?v:`${h}px`,y=`${-s}px`):u==="top"?(m=c?v:`${h}px`,y=`${l.floating.height+s}px`):u==="right"?(m=`${-s}px`,y=c?v:`${g}px`):u==="left"&&(m=`${l.floating.width+s}px`,y=c?v:`${g}px`),{data:{x:m,y}}}}}function Ke(e){const[n,t="center"]=e.split("-");return[n,t]}const vr={side:"bottom",sideOffset:0,align:"center",alignOffset:0,arrowPadding:0,avoidCollisions:!0,collisionBoundary:()=>[],collisionPadding:0,sticky:"partial",hideWhenDetached:!1,updatePositionStrategy:"optimized",prioritizePosition:!1},[hr,mr]=le("PopperContent"),yr=O({inheritAttrs:!1,__name:"PopperContent",props:cn({side:{},sideOffset:{},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean},updatePositionStrategy:{},prioritizePosition:{type:Boolean},asChild:{type:Boolean},as:{}},{...vr}),emits:["placed"],setup(e,{emit:n}){const t=e,o=n,r=Xt(),{forwardRef:i,currentElement:l}=A(),a=C(),c=C(),{width:d,height:s}=Fo(c),u=b(()=>t.side+(t.align!=="center"?`-${t.align}`:"")),p=b(()=>typeof t.collisionPadding=="number"?t.collisionPadding:{top:0,right:0,bottom:0,left:0,...t.collisionPadding}),v=b(()=>Array.isArray(t.collisionBoundary)?t.collisionBoundary:[t.collisionBoundary]),h=b(()=>({padding:p.value,boundary:v.value.filter(fr),altBoundary:v.value.length>0})),g=Qn(()=>[jn({mainAxis:t.sideOffset+s.value,alignmentAxis:t.alignOffset}),t.prioritizePosition&&t.avoidCollisions&&ut({...h.value}),t.avoidCollisions&&Vn({mainAxis:!0,crossAxis:!!t.prioritizePosition,limiter:t.sticky==="partial"?Yn():void 0,...h.value}),!t.prioritizePosition&&t.avoidCollisions&&ut({...h.value}),zn({...h.value,apply:({elements:S,rects:rt,availableWidth:be,availableHeight:we})=>{const{width:xe,height:Jt}=rt.reference,Ce=S.floating.style;Ce.setProperty("--radix-popper-available-width",`${be}px`),Ce.setProperty("--radix-popper-available-height",`${we}px`),Ce.setProperty("--radix-popper-anchor-width",`${xe}px`),Ce.setProperty("--radix-popper-anchor-height",`${Jt}px`)}}),c.value&&Gn({element:c.value,padding:t.arrowPadding}),pr({arrowWidth:d.value,arrowHeight:s.value}),t.hideWhenDetached&&Kn({strategy:"referenceHidden",...h.value})]),{floatingStyles:m,placement:y,isPositioned:B,middlewareData:w}=Jn(r.anchor,a,{strategy:"fixed",placement:u,whileElementsMounted:(...S)=>Hn(...S,{animationFrame:t.updatePositionStrategy==="always"}),middleware:g}),$=b(()=>Ke(y.value)[0]),R=b(()=>Ke(y.value)[1]);fn(()=>{B.value&&o("placed")});const L=b(()=>{var S;return((S=w.value.arrow)==null?void 0:S.centerOffset)!==0}),T=C("");M(()=>{l.value&&(T.value=window.getComputedStyle(l.value).zIndex)});const H=b(()=>{var S;return((S=w.value.arrow)==null?void 0:S.x)??0}),ge=b(()=>{var S;return((S=w.value.arrow)==null?void 0:S.y)??0});return mr({placedSide:$,onArrowChange:S=>c.value=S,arrowX:H,arrowY:ge,shouldHideArrow:L}),(S,rt)=>{var be,we,xe;return _(),Ot("div",{ref_key:"floatingRef",ref:a,"data-radix-popper-content-wrapper":"",style:Ye({...f(m),transform:f(B)?f(m).transform:"translate(0, -200%)",minWidth:"max-content",zIndex:T.value,"--radix-popper-transform-origin":[(be=f(w).transformOrigin)==null?void 0:be.x,(we=f(w).transformOrigin)==null?void 0:we.y].join(" "),...((xe=f(w).hide)==null?void 0:xe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}})},[ee(f(W),P({ref:f(i)},S.$attrs,{"as-child":t.asChild,as:S.as,"data-side":$.value,"data-align":R.value,style:{animation:f(B)?void 0:"none"}}),{default:x(()=>[E(S.$slots,"default")]),_:3},16,["as-child","as","data-side","data-align","style"])],4)}}}),gr=pn("polygon",{points:"0,0 30,0 15,10"},null,-1),br=O({__name:"Arrow",props:{width:{default:10},height:{default:5},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(W),P(n,{width:t.width,height:t.height,viewBox:t.asChild?void 0:"0 0 30 10",preserveAspectRatio:t.asChild?void 0:"none"}),{default:x(()=>[E(t.$slots,"default",{},()=>[gr])]),_:3},16,["width","height","viewBox","preserveAspectRatio"]))}}),wr={top:"bottom",right:"left",bottom:"top",left:"right"},xr=O({inheritAttrs:!1,__name:"PopperArrow",props:{width:{},height:{},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const{forwardRef:n}=A(),t=hr(),o=b(()=>wr[t.placedSide.value]);return(r,i)=>{var l,a,c,d;return _(),Ot("span",{ref:s=>{f(t).onArrowChange(s)},style:Ye({position:"absolute",left:(l=f(t).arrowX)!=null&&l.value?`${(a=f(t).arrowX)==null?void 0:a.value}px`:void 0,top:(c=f(t).arrowY)!=null&&c.value?`${(d=f(t).arrowY)==null?void 0:d.value}px`:void 0,[o.value]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[f(t).placedSide.value],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[f(t).placedSide.value],visibility:f(t).shouldHideArrow.value?"hidden":void 0})},[ee(br,P(r.$attrs,{ref:f(n),style:{display:"block"},as:r.as,"as-child":r.asChild,width:r.width,height:r.height}),{default:x(()=>[E(r.$slots,"default")]),_:3},16,["as","as-child","width","height"])],4)}}}),Cr=O({__name:"VisuallyHidden",props:{asChild:{type:Boolean},as:{default:"span"}},setup(e){return A(),(n,t)=>(_(),D(f(W),{as:n.as,"as-child":n.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:x(()=>[E(n.$slots,"default")]),_:3},8,["as","as-child"]))}});function Or(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}Or();const qt="tooltip.open",[ot,Er]=le("TooltipProvider"),kr=O({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 n=e,{delayDuration:t,skipDelayDuration:o,disableHoverableContent:r,disableClosingTrigger:i,ignoreNonKeyboardFocus:l,disabled:a}=Ue(n);A();const c=C(!0),d=C(!1),{start:s,stop:u}=Lt(()=>{c.value=!0},o,{immediate:!1});return Er({isOpenDelayed:c,delayDuration:t,onOpen(){u(),c.value=!1},onClose(){s()},isPointerInTransitRef:d,disableHoverableContent:r,disableClosingTrigger:i,disabled:a,ignoreNonKeyboardFocus:l}),(p,v)=>E(p.$slots,"default")}}),[Se,_r]=le("TooltipRoot"),Wr=O({__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:n}){const t=e,o=n;A();const r=ot(),i=b(()=>t.disableHoverableContent??r.disableHoverableContent.value),l=b(()=>t.disableClosingTrigger??r.disableClosingTrigger.value),a=b(()=>t.disabled??r.disabled.value),c=b(()=>t.delayDuration??r.delayDuration.value),d=b(()=>t.ignoreNonKeyboardFocus??r.ignoreNonKeyboardFocus.value),s=Mt(t,"open",o,{defaultValue:t.defaultOpen,passive:t.open===void 0});F(s,w=>{r.onClose&&(w?(r.onOpen(),document.dispatchEvent(new CustomEvent(qt))):r.onClose())});const u=C(!1),p=C(),v=b(()=>s.value?u.value?"delayed-open":"instant-open":"closed"),{start:h,stop:g}=Lt(()=>{u.value=!0,s.value=!0},c,{immediate:!1});function m(){g(),u.value=!1,s.value=!0}function y(){g(),s.value=!1}function B(){h()}return _r({contentId:"",open:s,stateAttribute:v,trigger:p,onTriggerChange(w){p.value=w},onTriggerEnter(){r.isOpenDelayed.value?B():m()},onTriggerLeave(){i.value?y():g()},onOpen:m,onClose:y,disableHoverableContent:i,disableClosingTrigger:l,disabled:a,ignoreNonKeyboardFocus:d}),(w,$)=>(_(),D(f(dr),null,{default:x(()=>[E(w.$slots,"default",{open:f(s)})]),_:3}))}}),Hr=O({__name:"TooltipTrigger",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e,t=Se(),o=ot();t.contentId||(t.contentId=ze(void 0,"radix-vue-tooltip-content"));const{forwardRef:r,currentElement:i}=A(),l=C(!1),a=C(!1),c=b(()=>t.disabled.value?{}:{click:g,focus:v,pointermove:u,pointerleave:p,pointerdown:s,blur:h});fe(()=>{t.onTriggerChange(i.value)});function d(){setTimeout(()=>{l.value=!1},1)}function s(){l.value=!0,document.addEventListener("pointerup",d,{once:!0})}function u(m){m.pointerType!=="touch"&&!a.value&&!o.isPointerInTransitRef.value&&(t.onTriggerEnter(),a.value=!0)}function p(){t.onTriggerLeave(),a.value=!1}function v(m){var y,B;l.value||t.ignoreNonKeyboardFocus.value&&!((B=(y=m.target).matches)!=null&&B.call(y,":focus-visible"))||t.onOpen()}function h(){t.onClose()}function g(){t.disableClosingTrigger.value||t.onClose()}return(m,y)=>(_(),D(f(cr),{"as-child":""},{default:x(()=>[ee(f(W),P({ref:f(r),"aria-describedby":f(t).open.value?f(t).contentId:void 0,"data-state":f(t).stateAttribute.value,as:m.as,"as-child":n.asChild,"data-grace-area-trigger":""},tn(c.value)),{default:x(()=>[E(m.$slots,"default")]),_:3},16,["aria-describedby","data-state","as","as-child"])]),_:3}))}}),Gt=O({__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:n}){const t=e,o=n,r=Se(),{forwardRef:i}=A(),l=an(),a=b(()=>{var s;return(s=l.default)==null?void 0:s.call(l)}),c=b(()=>{var s;if(t.ariaLabel)return t.ariaLabel;let u="";function p(v){typeof v.children=="string"&&v.type!==xt?u+=v.children:Array.isArray(v.children)&&v.children.forEach(h=>p(h))}return(s=a.value)==null||s.forEach(v=>p(v)),u}),d=b(()=>{const{ariaLabel:s,...u}=t;return u});return fe(()=>{Te(window,"scroll",s=>{const u=s.target;u!=null&&u.contains(r.trigger.value)&&r.onClose()}),Te(window,qt,r.onClose)}),(s,u)=>(_(),D(f(zt),{"as-child":"","disable-outside-pointer-events":!1,onEscapeKeyDown:u[0]||(u[0]=p=>o("escapeKeyDown",p)),onPointerDownOutside:u[1]||(u[1]=p=>{var v;f(r).disableClosingTrigger.value&&(v=f(r).trigger.value)!=null&&v.contains(p.target)&&p.preventDefault(),o("pointerDownOutside",p)}),onFocusOutside:u[2]||(u[2]=ke(()=>{},["prevent"])),onDismiss:u[3]||(u[3]=p=>f(r).onClose())},{default:x(()=>[ee(f(yr),P({ref:f(i),"data-state":f(r).stateAttribute.value},{...s.$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:x(()=>[E(s.$slots,"default"),ee(f(Cr),{id:f(r).contentId,role:"tooltip"},{default:x(()=>[sn(un(c.value),1)]),_:1},8,["id"])]),_:3},16,["data-state"])]),_:3}))}}),Dr=O({__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 n=Wt(e),{forwardRef:t,currentElement:o}=A(),{trigger:r,onClose:i}=Se(),l=ot(),{isPointerInTransit:a,onPointerExit:c}=Co(r,o);return l.isPointerInTransitRef=a,c(()=>{i()}),(d,s)=>(_(),D(Gt,P({ref:f(t)},f(n)),{default:x(()=>[E(d.$slots,"default")]),_:3},16))}}),jr=O({__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:n}){const t=e,o=n,r=Se(),i=Ht(t,o),{forwardRef:l}=A();return(a,c)=>(_(),D(f(tt),{present:a.forceMount||f(r).open.value},{default:x(()=>[(_(),D(nn(f(r).disableHoverableContent.value?Gt:Dr),P({ref:f(l)},f(i)),{default:x(()=>[E(a.$slots,"default")]),_:3},16))]),_:3},8,["present"]))}}),Vr=O({__name:"TooltipArrow",props:{width:{default:10},height:{default:5},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(xr),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),zr=O({__name:"TooltipPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=e;return(t,o)=>(_(),D(f(nt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}});export{rr as $,Rr as A,lr as B,Mr as F,Vr as G,kr as H,Pr as I,Fr as M,Ir as N,Sr as O,nr as P,$r as T,jr as U,Lr as V,Wr as W,Hr as j,Nr as k,Wo as n,zr as q}; +`))}return()=>i.value||r.value||a.value?Be(n.default({present:a})[0],{ref:s=>{const u=me(s);return typeof(u==null?void 0:u.hasAttribute)>"u"||(u!=null&&u.hasAttribute("data-radix-popper-content-wrapper")?l.value=u.firstElementChild:l.value=u),u}}):null}}),[U,ko]=le("DialogRoot"),Wo=O({inheritAttrs:!1,__name:"DialogRoot",props:{open:{type:Boolean,default:void 0},defaultOpen:{type:Boolean,default:!1},modal:{type:Boolean,default:!0}},emits:["update:open"],setup(e,{emit:n}){const t=e,o=Mt(t,"open",n,{defaultValue:t.defaultOpen,passive:t.open===void 0}),r=C(),i=C(),{modal:l}=Ue(t);return ko({open:o,modal:l,openModal:()=>{o.value=!0},onOpenChange:a=>{o.value=a},onOpenToggle:()=>{o.value=!o.value},contentId:"",titleId:"",descriptionId:"",triggerElement:r,contentElement:i}),(a,c)=>E(a.$slots,"default",{open:f(o)})}}),nt=O({__name:"Teleport",props:{to:{default:"body"},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=po();return(t,o)=>f(n)||t.forceMount?(_(),D(Qt,{key:0,to:t.to,disabled:t.disabled},[E(t.$slots,"default")],8,["to","disabled"])):gt("",!0)}}),Pr=O({__name:"DialogPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=e;return(t,o)=>(_(),D(f(nt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Ho="dismissableLayer.pointerDownOutside",jo="dismissableLayer.focusOutside";function Vt(e,n){const t=n.closest("[data-dismissable-layer]"),o=e.dataset.dismissableLayer===""?e:e.querySelector("[data-dismissable-layer]"),r=Array.from(e.ownerDocument.querySelectorAll("[data-dismissable-layer]"));return!!(t&&o===t||r.indexOf(o){});return M(l=>{if(!Q)return;const a=async d=>{const s=d.target;if(n!=null&&n.value){if(Vt(n.value,s)){r.value=!1;return}if(d.target&&!r.value){let u=function(){Ft(Ho,e,p)};const p={originalEvent:d};d.pointerType==="touch"?(o.removeEventListener("click",i.value),i.value=u,o.addEventListener("click",i.value,{once:!0})):u()}else o.removeEventListener("click",i.value);r.value=!1}},c=window.setTimeout(()=>{o.addEventListener("pointerdown",a)},0);l(()=>{window.clearTimeout(c),o.removeEventListener("pointerdown",a),o.removeEventListener("click",i.value)})}),{onPointerDownCapture:()=>r.value=!0}}function zo(e,n){var t;const o=((t=n==null?void 0:n.value)==null?void 0:t.ownerDocument)??(globalThis==null?void 0:globalThis.document),r=C(!1);return M(i=>{if(!Q)return;const l=async a=>{n!=null&&n.value&&(await ne(),!(!n.value||Vt(n.value,a.target))&&a.target&&!r.value&&Ft(jo,e,{originalEvent:a}))};o.addEventListener("focusin",l),i(()=>o.removeEventListener("focusin",l))}),{onFocusCapture:()=>r.value=!0,onBlurCapture:()=>r.value=!1}}const K=_t({layersRoot:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),zt=O({__name:"DismissableLayer",props:{disableOutsidePointerEvents:{type:Boolean,default:!1},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","dismiss"],setup(e,{emit:n}){const t=e,o=n,{forwardRef:r,currentElement:i}=A(),l=w(()=>{var h;return((h=i.value)==null?void 0:h.ownerDocument)??globalThis.document}),a=w(()=>K.layersRoot),c=w(()=>i.value?Array.from(a.value).indexOf(i.value):-1),d=w(()=>K.layersWithOutsidePointerEventsDisabled.size>0),s=w(()=>{const h=Array.from(a.value),[g]=[...K.layersWithOutsidePointerEventsDisabled].slice(-1),m=h.indexOf(g);return c.value>=m}),u=Vo(async h=>{const g=[...K.branches].some(m=>m==null?void 0:m.contains(h.target));!s.value||g||(o("pointerDownOutside",h),o("interactOutside",h),await ne(),h.defaultPrevented||o("dismiss"))},i),p=zo(h=>{[...K.branches].some(g=>g==null?void 0:g.contains(h.target))||(o("focusOutside",h),o("interactOutside",h),h.defaultPrevented||o("dismiss"))},i);fo("Escape",h=>{c.value===a.value.size-1&&(o("escapeKeyDown",h),h.defaultPrevented||o("dismiss"))});let v;return M(h=>{i.value&&(t.disableOutsidePointerEvents&&(K.layersWithOutsidePointerEventsDisabled.size===0&&(v=l.value.body.style.pointerEvents,l.value.body.style.pointerEvents="none"),K.layersWithOutsidePointerEventsDisabled.add(i.value)),a.value.add(i.value),h(()=>{t.disableOutsidePointerEvents&&K.layersWithOutsidePointerEventsDisabled.size===1&&(l.value.body.style.pointerEvents=v)}))}),M(h=>{h(()=>{i.value&&(a.value.delete(i.value),K.layersWithOutsidePointerEventsDisabled.delete(i.value))})}),(h,g)=>(_(),D(f(W),{ref:f(r),"as-child":h.asChild,as:h.as,"data-dismissable-layer":"",style:Ye({pointerEvents:d.value?s.value?"auto":"none":void 0}),onFocusCapture:f(p).onFocusCapture,onBlurCapture:f(p).onBlurCapture,onPointerdownCapture:f(u).onPointerDownCapture},{default:x(()=>[E(h.$slots,"default")]),_:3},8,["as-child","as","style","onFocusCapture","onBlurCapture","onPointerdownCapture"]))}}),Me="focusScope.autoFocusOnMount",Ie="focusScope.autoFocusOnUnmount",ft={bubbles:!1,cancelable:!0};function Ko(e,{select:n=!1}={}){const t=X();for(const o of e)if(Y(o,{select:n}),X()!==t)return!0}function Uo(e){const n=Kt(e),t=pt(n,e),o=pt(n.reverse(),e);return[t,o]}function Kt(e){const n=[],t=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>{const r=o.tagName==="INPUT"&&o.type==="hidden";return o.disabled||o.hidden||r?NodeFilter.FILTER_SKIP:o.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;t.nextNode();)n.push(t.currentNode);return n}function pt(e,n){for(const t of e)if(!Yo(t,{upTo:n}))return t}function Yo(e,{upTo:n}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(n!==void 0&&e===n)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Xo(e){return e instanceof HTMLInputElement&&"select"in e}function Y(e,{select:n=!1}={}){if(e&&e.focus){const t=X();e.focus({preventScroll:!0}),e!==t&&Xo(e)&&n&&e.select()}}const qo=eo(()=>C([]));function Go(){const e=qo();return{add(n){const t=e.value[0];n!==t&&(t==null||t.pause()),e.value=vt(e.value,n),e.value.unshift(n)},remove(n){var t;e.value=vt(e.value,n),(t=e.value[0])==null||t.resume()}}}function vt(e,n){const t=[...e],o=t.indexOf(n);return o!==-1&&t.splice(o,1),t}function Jo(e){return e.filter(n=>n.tagName!=="A")}const Qo=O({__name:"FocusScope",props:{loop:{type:Boolean,default:!1},trapped:{type:Boolean,default:!1},asChild:{type:Boolean},as:{}},emits:["mountAutoFocus","unmountAutoFocus"],setup(e,{emit:n}){const t=e,o=n,{currentRef:r,currentElement:i}=A(),l=C(null),a=Go(),c=_t({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}});M(s=>{if(!Q)return;const u=i.value;if(!t.trapped)return;function p(m){if(c.paused||!u)return;const y=m.target;u.contains(y)?l.value=y:Y(l.value,{select:!0})}function v(m){if(c.paused||!u)return;const y=m.relatedTarget;y!==null&&(u.contains(y)||Y(l.value,{select:!0}))}function h(m){u.contains(l.value)||Y(u)}document.addEventListener("focusin",p),document.addEventListener("focusout",v);const g=new MutationObserver(h);u&&g.observe(u,{childList:!0,subtree:!0}),s(()=>{document.removeEventListener("focusin",p),document.removeEventListener("focusout",v),g.disconnect()})}),M(async s=>{const u=i.value;if(await ne(),!u)return;a.add(c);const p=X();if(!u.contains(p)){const v=new CustomEvent(Me,ft);u.addEventListener(Me,h=>o("mountAutoFocus",h)),u.dispatchEvent(v),v.defaultPrevented||(Ko(Jo(Kt(u)),{select:!0}),X()===p&&Y(u))}s(()=>{u.removeEventListener(Me,g=>o("mountAutoFocus",g));const v=new CustomEvent(Ie,ft),h=g=>{o("unmountAutoFocus",g)};u.addEventListener(Ie,h),u.dispatchEvent(v),setTimeout(()=>{v.defaultPrevented||Y(p??document.body,{select:!0}),u.removeEventListener(Ie,h),a.remove(c)},0)})});function d(s){if(!t.loop&&!t.trapped||c.paused)return;const u=s.key==="Tab"&&!s.altKey&&!s.ctrlKey&&!s.metaKey,p=X();if(u&&p){const v=s.currentTarget,[h,g]=Uo(v);h&&g?!s.shiftKey&&p===g?(s.preventDefault(),t.loop&&Y(h,{select:!0})):s.shiftKey&&p===h&&(s.preventDefault(),t.loop&&Y(g,{select:!0})):p===v&&s.preventDefault()}}return(s,u)=>(_(),D(f(W),{ref_key:"currentRef",ref:r,tabindex:"-1","as-child":s.asChild,as:s.as,onKeydown:d},{default:x(()=>[E(s.$slots,"default")]),_:3},8,["as-child","as"]))}});function Zo(e){return e?"open":"closed"}const Ut=O({__name:"DialogContentImpl",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=n,r=U(),{forwardRef:i,currentElement:l}=A();return r.titleId||(r.titleId=ze(void 0,"radix-vue-dialog-title")),r.descriptionId||(r.descriptionId=ze(void 0,"radix-vue-dialog-description")),fe(()=>{r.contentElement=l,X()!==document.body&&(r.triggerElement.value=X())}),(a,c)=>(_(),D(f(Qo),{"as-child":"",loop:"",trapped:t.trapFocus,onMountAutoFocus:c[5]||(c[5]=d=>o("openAutoFocus",d)),onUnmountAutoFocus:c[6]||(c[6]=d=>o("closeAutoFocus",d))},{default:x(()=>[ee(f(zt),P({id:f(r).contentId,ref:f(i),as:a.as,"as-child":a.asChild,"disable-outside-pointer-events":a.disableOutsidePointerEvents,role:"dialog","aria-describedby":f(r).descriptionId,"aria-labelledby":f(r).titleId,"data-state":f(Zo)(f(r).open.value)},a.$attrs,{onDismiss:c[0]||(c[0]=d=>f(r).onOpenChange(!1)),onEscapeKeyDown:c[1]||(c[1]=d=>o("escapeKeyDown",d)),onFocusOutside:c[2]||(c[2]=d=>o("focusOutside",d)),onInteractOutside:c[3]||(c[3]=d=>o("interactOutside",d)),onPointerDownOutside:c[4]||(c[4]=d=>o("pointerDownOutside",d))}),{default:x(()=>[E(a.$slots,"default")]),_:3},16,["id","as","as-child","disable-outside-pointer-events","aria-describedby","aria-labelledby","data-state"])]),_:3},8,["trapped"]))}}),er=O({__name:"DialogContentModal",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=n,r=U(),i=ye(o),{forwardRef:l,currentElement:a}=A();return So(a),(c,d)=>(_(),D(Ut,P({...t,...f(i)},{ref:f(l),"trap-focus":f(r).open.value,"disable-outside-pointer-events":!0,onCloseAutoFocus:d[0]||(d[0]=s=>{var u;s.defaultPrevented||(s.preventDefault(),(u=f(r).triggerElement.value)==null||u.focus())}),onPointerDownOutside:d[1]||(d[1]=s=>{const u=s.detail.originalEvent,p=u.button===0&&u.ctrlKey===!0;(u.button===2||p)&&s.preventDefault()}),onFocusOutside:d[2]||(d[2]=s=>{s.preventDefault()})}),{default:x(()=>[E(c.$slots,"default")]),_:3},16,["trap-focus"]))}}),tr=O({__name:"DialogContentNonModal",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=ye(n);A();const r=U(),i=C(!1),l=C(!1);return(a,c)=>(_(),D(Ut,P({...t,...f(o)},{"trap-focus":!1,"disable-outside-pointer-events":!1,onCloseAutoFocus:c[0]||(c[0]=d=>{var s;d.defaultPrevented||(i.value||(s=f(r).triggerElement.value)==null||s.focus(),d.preventDefault()),i.value=!1,l.value=!1}),onInteractOutside:c[1]||(c[1]=d=>{var s;d.defaultPrevented||(i.value=!0,d.detail.originalEvent.type==="pointerdown"&&(l.value=!0));const u=d.target;(s=f(r).triggerElement.value)!=null&&s.contains(u)&&d.preventDefault(),d.detail.originalEvent.type==="focusin"&&l.value&&d.preventDefault()})}),{default:x(()=>[E(a.$slots,"default")]),_:3},16))}}),nr=O({__name:"DialogContent",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=n,r=U(),i=ye(o),{forwardRef:l}=A();return(a,c)=>(_(),D(f(tt),{present:a.forceMount||f(r).open.value},{default:x(()=>[f(r).modal.value?(_(),D(er,P({key:0,ref:f(l)},{...t,...f(i),...a.$attrs}),{default:x(()=>[E(a.$slots,"default")]),_:3},16)):(_(),D(tr,P({key:1,ref:f(l)},{...t,...f(i),...a.$attrs}),{default:x(()=>[E(a.$slots,"default")]),_:3},16))]),_:3},8,["present"]))}}),or=O({__name:"DialogOverlayImpl",props:{asChild:{type:Boolean},as:{}},setup(e){const n=U();return bo(!0),A(),(t,o)=>(_(),D(f(W),{as:t.as,"as-child":t.asChild,"data-state":f(n).open.value?"open":"closed",style:{"pointer-events":"auto"}},{default:x(()=>[E(t.$slots,"default")]),_:3},8,["as","as-child","data-state"]))}}),rr=O({__name:"DialogOverlay",props:{forceMount:{type:Boolean},asChild:{type:Boolean},as:{}},setup(e){const n=U(),{forwardRef:t}=A();return(o,r)=>{var i;return(i=f(n))!=null&&i.modal.value?(_(),D(f(tt),{key:0,present:o.forceMount||f(n).open.value},{default:x(()=>[ee(or,P(o.$attrs,{ref:f(t),as:o.as,"as-child":o.asChild}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["as","as-child"])]),_:3},8,["present"])):gt("",!0)}}}),Yt=O({__name:"DialogClose",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e;A();const t=U();return(o,r)=>(_(),D(f(W),P(n,{type:o.as==="button"?"button":void 0,onClick:r[0]||(r[0]=i=>f(t).onOpenChange(!1))}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["type"]))}}),lr=O({__name:"DialogTitle",props:{asChild:{type:Boolean},as:{default:"h2"}},setup(e){const n=e,t=U();return A(),(o,r)=>(_(),D(f(W),P(n,{id:f(t).titleId}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["id"]))}}),ir=O({__name:"DialogDescription",props:{asChild:{type:Boolean},as:{default:"p"}},setup(e){const n=e;A();const t=U();return(o,r)=>(_(),D(f(W),P(n,{id:f(t).descriptionId}),{default:x(()=>[E(o.$slots,"default")]),_:3},16,["id"]))}}),$r=O({__name:"AlertDialogRoot",props:{open:{type:Boolean},defaultOpen:{type:Boolean}},emits:["update:open"],setup(e,{emit:n}){const t=Ht(e,n);return A(),(o,r)=>(_(),D(f(Wo),P(f(t),{modal:!0}),{default:x(()=>[E(o.$slots,"default")]),_:3},16))}}),Rr=O({__name:"AlertDialogPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=e;return(t,o)=>(_(),D(f(nt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),[ar,sr]=le("AlertDialogContent"),Sr=O({__name:"AlertDialogContent",props:{forceMount:{type:Boolean},trapFocus:{type:Boolean},disableOutsidePointerEvents:{type:Boolean},asChild:{type:Boolean},as:{}},emits:["escapeKeyDown","pointerDownOutside","focusOutside","interactOutside","openAutoFocus","closeAutoFocus"],setup(e,{emit:n}){const t=e,o=ye(n);A();const r=C();return sr({onCancelElementChange:i=>{r.value=i}}),(i,l)=>(_(),D(f(nr),P({...t,...f(o)},{role:"alertdialog",onPointerDownOutside:l[0]||(l[0]=ke(()=>{},["prevent"])),onInteractOutside:l[1]||(l[1]=ke(()=>{},["prevent"])),onOpenAutoFocus:l[2]||(l[2]=()=>{ne(()=>{var a;(a=r.value)==null||a.focus({preventScroll:!0})})})}),{default:x(()=>[E(i.$slots,"default")]),_:3},16))}}),Nr=O({__name:"AlertDialogOverlay",props:{forceMount:{type:Boolean},asChild:{type:Boolean},as:{}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(rr),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Fr=O({__name:"AlertDialogCancel",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e,t=ar(),{forwardRef:o,currentElement:r}=A();return fe(()=>{t.onCancelElementChange(r.value)}),(i,l)=>(_(),D(f(Yt),P(n,{ref:f(o)}),{default:x(()=>[E(i.$slots,"default")]),_:3},16))}}),Lr=O({__name:"AlertDialogTitle",props:{asChild:{type:Boolean},as:{default:"h2"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(lr),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Mr=O({__name:"AlertDialogDescription",props:{asChild:{type:Boolean},as:{default:"p"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(ir),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),Ir=O({__name:"AlertDialogAction",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(Yt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),[Xt,ur]=le("PopperRoot"),dr=O({inheritAttrs:!1,__name:"PopperRoot",setup(e){const n=C();return ur({anchor:n,onAnchorChange:t=>n.value=t}),(t,o)=>E(t.$slots,"default")}}),cr=O({__name:"PopperAnchor",props:{element:{},asChild:{type:Boolean},as:{}},setup(e){const n=e,{forwardRef:t,currentElement:o}=A(),r=Xt();return M(()=>{r.onAnchorChange(n.element??o.value)}),(i,l)=>(_(),D(f(W),{ref:f(t),as:i.as,"as-child":i.asChild},{default:x(()=>[E(i.$slots,"default")]),_:3},8,["as","as-child"]))}});function fr(e){return e!==null}function pr(e){return{name:"transformOrigin",options:e,fn(n){var t,o,r;const{placement:i,rects:l,middlewareData:a}=n,c=((t=a.arrow)==null?void 0:t.centerOffset)!==0,d=c?0:e.arrowWidth,s=c?0:e.arrowHeight,[u,p]=Ke(i),v={start:"0%",center:"50%",end:"100%"}[p],h=(((o=a.arrow)==null?void 0:o.x)??0)+d/2,g=(((r=a.arrow)==null?void 0:r.y)??0)+s/2;let m="",y="";return u==="bottom"?(m=c?v:`${h}px`,y=`${-s}px`):u==="top"?(m=c?v:`${h}px`,y=`${l.floating.height+s}px`):u==="right"?(m=`${-s}px`,y=c?v:`${g}px`):u==="left"&&(m=`${l.floating.width+s}px`,y=c?v:`${g}px`),{data:{x:m,y}}}}}function Ke(e){const[n,t="center"]=e.split("-");return[n,t]}const vr={side:"bottom",sideOffset:0,align:"center",alignOffset:0,arrowPadding:0,avoidCollisions:!0,collisionBoundary:()=>[],collisionPadding:0,sticky:"partial",hideWhenDetached:!1,updatePositionStrategy:"optimized",prioritizePosition:!1},[hr,mr]=le("PopperContent"),yr=O({inheritAttrs:!1,__name:"PopperContent",props:cn({side:{},sideOffset:{},align:{},alignOffset:{},avoidCollisions:{type:Boolean},collisionBoundary:{},collisionPadding:{},arrowPadding:{},sticky:{},hideWhenDetached:{type:Boolean},updatePositionStrategy:{},prioritizePosition:{type:Boolean},asChild:{type:Boolean},as:{}},{...vr}),emits:["placed"],setup(e,{emit:n}){const t=e,o=n,r=Xt(),{forwardRef:i,currentElement:l}=A(),a=C(),c=C(),{width:d,height:s}=Fo(c),u=w(()=>t.side+(t.align!=="center"?`-${t.align}`:"")),p=w(()=>typeof t.collisionPadding=="number"?t.collisionPadding:{top:0,right:0,bottom:0,left:0,...t.collisionPadding}),v=w(()=>Array.isArray(t.collisionBoundary)?t.collisionBoundary:[t.collisionBoundary]),h=w(()=>({padding:p.value,boundary:v.value.filter(fr),altBoundary:v.value.length>0})),g=Qn(()=>[jn({mainAxis:t.sideOffset+s.value,alignmentAxis:t.alignOffset}),t.prioritizePosition&&t.avoidCollisions&&ut({...h.value}),t.avoidCollisions&&Vn({mainAxis:!0,crossAxis:!!t.prioritizePosition,limiter:t.sticky==="partial"?Yn():void 0,...h.value}),!t.prioritizePosition&&t.avoidCollisions&&ut({...h.value}),zn({...h.value,apply:({elements:S,rects:rt,availableWidth:we,availableHeight:be})=>{const{width:xe,height:Jt}=rt.reference,Ce=S.floating.style;Ce.setProperty("--radix-popper-available-width",`${we}px`),Ce.setProperty("--radix-popper-available-height",`${be}px`),Ce.setProperty("--radix-popper-anchor-width",`${xe}px`),Ce.setProperty("--radix-popper-anchor-height",`${Jt}px`)}}),c.value&&Gn({element:c.value,padding:t.arrowPadding}),pr({arrowWidth:d.value,arrowHeight:s.value}),t.hideWhenDetached&&Kn({strategy:"referenceHidden",...h.value})]),{floatingStyles:m,placement:y,isPositioned:B,middlewareData:b}=Jn(r.anchor,a,{strategy:"fixed",placement:u,whileElementsMounted:(...S)=>Hn(...S,{animationFrame:t.updatePositionStrategy==="always"}),middleware:g}),$=w(()=>Ke(y.value)[0]),R=w(()=>Ke(y.value)[1]);fn(()=>{B.value&&o("placed")});const L=w(()=>{var S;return((S=b.value.arrow)==null?void 0:S.centerOffset)!==0}),T=C("");M(()=>{l.value&&(T.value=window.getComputedStyle(l.value).zIndex)});const H=w(()=>{var S;return((S=b.value.arrow)==null?void 0:S.x)??0}),ge=w(()=>{var S;return((S=b.value.arrow)==null?void 0:S.y)??0});return mr({placedSide:$,onArrowChange:S=>c.value=S,arrowX:H,arrowY:ge,shouldHideArrow:L}),(S,rt)=>{var we,be,xe;return _(),Ot("div",{ref_key:"floatingRef",ref:a,"data-radix-popper-content-wrapper":"",style:Ye({...f(m),transform:f(B)?f(m).transform:"translate(0, -200%)",minWidth:"max-content",zIndex:T.value,"--radix-popper-transform-origin":[(we=f(b).transformOrigin)==null?void 0:we.x,(be=f(b).transformOrigin)==null?void 0:be.y].join(" "),...((xe=f(b).hide)==null?void 0:xe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}})},[ee(f(W),P({ref:f(i)},S.$attrs,{"as-child":t.asChild,as:S.as,"data-side":$.value,"data-align":R.value,style:{animation:f(B)?void 0:"none"}}),{default:x(()=>[E(S.$slots,"default")]),_:3},16,["as-child","as","data-side","data-align","style"])],4)}}}),gr=pn("polygon",{points:"0,0 30,0 15,10"},null,-1),wr=O({__name:"Arrow",props:{width:{default:10},height:{default:5},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(W),P(n,{width:t.width,height:t.height,viewBox:t.asChild?void 0:"0 0 30 10",preserveAspectRatio:t.asChild?void 0:"none"}),{default:x(()=>[E(t.$slots,"default",{},()=>[gr])]),_:3},16,["width","height","viewBox","preserveAspectRatio"]))}}),br={top:"bottom",right:"left",bottom:"top",left:"right"},xr=O({inheritAttrs:!1,__name:"PopperArrow",props:{width:{},height:{},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const{forwardRef:n}=A(),t=hr(),o=w(()=>br[t.placedSide.value]);return(r,i)=>{var l,a,c,d;return _(),Ot("span",{ref:s=>{f(t).onArrowChange(s)},style:Ye({position:"absolute",left:(l=f(t).arrowX)!=null&&l.value?`${(a=f(t).arrowX)==null?void 0:a.value}px`:void 0,top:(c=f(t).arrowY)!=null&&c.value?`${(d=f(t).arrowY)==null?void 0:d.value}px`:void 0,[o.value]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[f(t).placedSide.value],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[f(t).placedSide.value],visibility:f(t).shouldHideArrow.value?"hidden":void 0})},[ee(wr,P(r.$attrs,{ref:f(n),style:{display:"block"},as:r.as,"as-child":r.asChild,width:r.width,height:r.height}),{default:x(()=>[E(r.$slots,"default")]),_:3},16,["as","as-child","width","height"])],4)}}}),Cr=O({__name:"VisuallyHidden",props:{asChild:{type:Boolean},as:{default:"span"}},setup(e){return A(),(n,t)=>(_(),D(f(W),{as:n.as,"as-child":n.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:x(()=>[E(n.$slots,"default")]),_:3},8,["as","as-child"]))}});function Or(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}Or();const qt="tooltip.open",[ot,Er]=le("TooltipProvider"),kr=O({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 n=e,{delayDuration:t,skipDelayDuration:o,disableHoverableContent:r,disableClosingTrigger:i,ignoreNonKeyboardFocus:l,disabled:a}=Ue(n);A();const c=C(!0),d=C(!1),{start:s,stop:u}=Lt(()=>{c.value=!0},o,{immediate:!1});return Er({isOpenDelayed:c,delayDuration:t,onOpen(){u(),c.value=!1},onClose(){s()},isPointerInTransitRef:d,disableHoverableContent:r,disableClosingTrigger:i,disabled:a,ignoreNonKeyboardFocus:l}),(p,v)=>E(p.$slots,"default")}}),[Se,_r]=le("TooltipRoot"),Wr=O({__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:n}){const t=e,o=n;A();const r=ot(),i=w(()=>t.disableHoverableContent??r.disableHoverableContent.value),l=w(()=>t.disableClosingTrigger??r.disableClosingTrigger.value),a=w(()=>t.disabled??r.disabled.value),c=w(()=>t.delayDuration??r.delayDuration.value),d=w(()=>t.ignoreNonKeyboardFocus??r.ignoreNonKeyboardFocus.value),s=Mt(t,"open",o,{defaultValue:t.defaultOpen,passive:t.open===void 0});F(s,b=>{r.onClose&&(b?(r.onOpen(),document.dispatchEvent(new CustomEvent(qt))):r.onClose())});const u=C(!1),p=C(),v=w(()=>s.value?u.value?"delayed-open":"instant-open":"closed"),{start:h,stop:g}=Lt(()=>{u.value=!0,s.value=!0},c,{immediate:!1});function m(){g(),u.value=!1,s.value=!0}function y(){g(),s.value=!1}function B(){h()}return _r({contentId:"",open:s,stateAttribute:v,trigger:p,onTriggerChange(b){p.value=b},onTriggerEnter(){r.isOpenDelayed.value?B():m()},onTriggerLeave(){i.value?y():g()},onOpen:m,onClose:y,disableHoverableContent:i,disableClosingTrigger:l,disabled:a,ignoreNonKeyboardFocus:d}),(b,$)=>(_(),D(f(dr),null,{default:x(()=>[E(b.$slots,"default",{open:f(s)})]),_:3}))}}),Hr=O({__name:"TooltipTrigger",props:{asChild:{type:Boolean},as:{default:"button"}},setup(e){const n=e,t=Se(),o=ot();t.contentId||(t.contentId=ze(void 0,"radix-vue-tooltip-content"));const{forwardRef:r,currentElement:i}=A(),l=C(!1),a=C(!1),c=w(()=>t.disabled.value?{}:{click:g,focus:v,pointermove:u,pointerleave:p,pointerdown:s,blur:h});fe(()=>{t.onTriggerChange(i.value)});function d(){setTimeout(()=>{l.value=!1},1)}function s(){l.value=!0,document.addEventListener("pointerup",d,{once:!0})}function u(m){m.pointerType!=="touch"&&!a.value&&!o.isPointerInTransitRef.value&&(t.onTriggerEnter(),a.value=!0)}function p(){t.onTriggerLeave(),a.value=!1}function v(m){var y,B;l.value||t.ignoreNonKeyboardFocus.value&&!((B=(y=m.target).matches)!=null&&B.call(y,":focus-visible"))||t.onOpen()}function h(){t.onClose()}function g(){t.disableClosingTrigger.value||t.onClose()}return(m,y)=>(_(),D(f(cr),{"as-child":""},{default:x(()=>[ee(f(W),P({ref:f(r),"aria-describedby":f(t).open.value?f(t).contentId:void 0,"data-state":f(t).stateAttribute.value,as:m.as,"as-child":n.asChild,"data-grace-area-trigger":""},tn(c.value)),{default:x(()=>[E(m.$slots,"default")]),_:3},16,["aria-describedby","data-state","as","as-child"])]),_:3}))}}),Gt=O({__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:n}){const t=e,o=n,r=Se(),{forwardRef:i}=A(),l=an(),a=w(()=>{var s;return(s=l.default)==null?void 0:s.call(l)}),c=w(()=>{var s;if(t.ariaLabel)return t.ariaLabel;let u="";function p(v){typeof v.children=="string"&&v.type!==xt?u+=v.children:Array.isArray(v.children)&&v.children.forEach(h=>p(h))}return(s=a.value)==null||s.forEach(v=>p(v)),u}),d=w(()=>{const{ariaLabel:s,...u}=t;return u});return fe(()=>{Te(window,"scroll",s=>{const u=s.target;u!=null&&u.contains(r.trigger.value)&&r.onClose()}),Te(window,qt,r.onClose)}),(s,u)=>(_(),D(f(zt),{"as-child":"","disable-outside-pointer-events":!1,onEscapeKeyDown:u[0]||(u[0]=p=>o("escapeKeyDown",p)),onPointerDownOutside:u[1]||(u[1]=p=>{var v;f(r).disableClosingTrigger.value&&(v=f(r).trigger.value)!=null&&v.contains(p.target)&&p.preventDefault(),o("pointerDownOutside",p)}),onFocusOutside:u[2]||(u[2]=ke(()=>{},["prevent"])),onDismiss:u[3]||(u[3]=p=>f(r).onClose())},{default:x(()=>[ee(f(yr),P({ref:f(i),"data-state":f(r).stateAttribute.value},{...s.$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:x(()=>[E(s.$slots,"default"),ee(f(Cr),{id:f(r).contentId,role:"tooltip"},{default:x(()=>[sn(un(c.value),1)]),_:1},8,["id"])]),_:3},16,["data-state"])]),_:3}))}}),Dr=O({__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 n=Wt(e),{forwardRef:t,currentElement:o}=A(),{trigger:r,onClose:i}=Se(),l=ot(),{isPointerInTransit:a,onPointerExit:c}=Co(r,o);return l.isPointerInTransitRef=a,c(()=>{i()}),(d,s)=>(_(),D(Gt,P({ref:f(t)},f(n)),{default:x(()=>[E(d.$slots,"default")]),_:3},16))}}),jr=O({__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:n}){const t=e,o=n,r=Se(),i=Ht(t,o),{forwardRef:l}=A();return(a,c)=>(_(),D(f(tt),{present:a.forceMount||f(r).open.value},{default:x(()=>[(_(),D(nn(f(r).disableHoverableContent.value?Gt:Dr),P({ref:f(l)},f(i)),{default:x(()=>[E(a.$slots,"default")]),_:3},16))]),_:3},8,["present"]))}}),Vr=O({__name:"TooltipArrow",props:{width:{default:10},height:{default:5},asChild:{type:Boolean},as:{default:"svg"}},setup(e){const n=e;return A(),(t,o)=>(_(),D(f(xr),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}}),zr=O({__name:"TooltipPortal",props:{to:{},disabled:{type:Boolean},forceMount:{type:Boolean}},setup(e){const n=e;return(t,o)=>(_(),D(f(nt),G(J(n)),{default:x(()=>[E(t.$slots,"default")]),_:3},16))}});export{rr as $,Rr as A,lr as B,Mr as F,Vr as G,kr as H,Pr as I,Fr as M,Ir as N,Sr as O,nr as P,$r as T,jr as U,Lr as V,Wr as W,Hr as j,Nr as k,Wo as n,zr as q}; diff --git a/assets/index-BQKiy4UR.js b/assets/index-CQudhZin.js similarity index 99% rename from assets/index-BQKiy4UR.js rename to assets/index-CQudhZin.js index 18171f2486dd5f3a7ae508c8f3e4ffe97fd988e4..01020149d02be07174fd833160a69410a6cf233e 100644 --- a/assets/index-BQKiy4UR.js +++ b/assets/index-CQudhZin.js @@ -1,4 +1,4 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-BhVC5vRq.js","assets/HeaderLink-CnrAQmsl.js","assets/HeaderLink-DsxHr3rn.css","assets/settings-DmZvPNPX.js","assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js","assets/Stage-DU_oFq0t.css","assets/three-vrm-animation.module-DtlqIxay.js","assets/mcp-DQCTu0C2.js","assets/mini_xsschema-P_8cZcRg.js","assets/providers-kjOpfeNb.js","assets/index-LHmcipjy.js","assets/Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js","assets/floating-ui.core-CgBsuaUc.js","assets/Select-X4vGC3oO.css","assets/index-DychlYah.js","assets/import-url-browser-CPN8ipMD.js","assets/duckdb-mvp-CaaD-olE.js","assets/speech-Db_L6FBm.js","assets/queue-DNS07_tB.js","assets/queues-C9_pVSeq.js","assets/index-C4mUnpiM.js","assets/airi-card-BqSQR9SZ.js","assets/consciousness-DS3QILRV.js","assets/TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js","assets/Model.vue_vue_type_script_setup_true_lang-Dx1Lxvvu.js","assets/Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js","assets/index-DSso2JwG.js","assets/Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js","assets/route-block-B_A1xBdJ.js","assets/index-m8JJPQt3.css","assets/background-remove-C4yhDB9Z.js","assets/InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js","assets/chat-7V8Q9Hlp.js","assets/image-BHbvwqTc.js","assets/image-BhuwcwI9.css","assets/vibrant-BaXmXZtH.js","assets/browser-CkchkNbv.js","assets/queue-DC7HdGzc.js","assets/index-BrQ5XatC.js","assets/IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js","assets/index-C0MBzJvw.js","assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-CmdVZPFO.js","assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-BwwhGept.js","assets/index-D1N6XcGk.js","assets/CardListItem.vue_vue_type_script_setup_true_lang-BYBvY3lt.js","assets/CardDetailDialog-HhbPTSqa.js","assets/CardListItem-DLmu0uN_.js","assets/DeleteCardDialog-CGam42wc.js","assets/index-CYwgNiYZ.js","assets/ColorPalette.vue_vue_type_script_setup_true_lang-CuLfdqu0.js","assets/index-BVitw2V7.css","assets/index-BJf3Tezf.js","assets/index-MYV-cYy6.js","assets/useIconAnimation-ITs7Jlod.js","assets/index-rlpEp8ML.css","assets/index-BVUPfFDK.js","assets/IconStatusItem-DqA2VeX5.js","assets/consciousness-zgXn05x5.js","assets/RadioCardSimple-DdnP6Fc5.js","assets/Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js","assets/memory-long-term-CRoA5-PX.js","assets/memory-short-term-ivGgMFGG.js","assets/speech-BJorZHUt.js","assets/FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js","assets/FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js","assets/Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js","assets/index-DANZbU0h.js","assets/alibaba-cloud-model-studio-8BnjUB5R.js","assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js","assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js","assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js","assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js","assets/anthropic-DcMJ-RH8.js","assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js","assets/cloudflare-workers-ai-CJorqeuz.js","assets/deepseek-J636LQ27.js","assets/elevenlabs-CHUs61J3.js","assets/featherless-ai-iViKpBby.js","assets/fireworks-ai-oUount_Y.js","assets/google-generative-ai-w-KmjfIn.js","assets/microsoft-speech-Bg9KcYTS.js","assets/mistral-ai-BaBOYsbt.js","assets/moonshot-ai-CpWLI90H.js","assets/novita-ai-pNiSEK4a.js","assets/ollama-lxq_i-rm.js","assets/openai-DQmuApR5.js","assets/openrouter-ai-DJMkew1w.js","assets/together-ai-DTk_B5ly.js","assets/volcengine-gKPE4jbw.js","assets/xai-_FNFPrWi.js","assets/index-C6zTw43n.js","assets/filter-message-CXNI-DZl.js","assets/delays-CflciaKu.js","assets/emotions-T9t8Z2VX.js","assets/messages-CUrOjMW7.js"])))=>i.map(i=>d[i]); +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/default-Uk3R33Mo.js","assets/HeaderLink-DVu0ldr4.js","assets/HeaderLink-DsxHr3rn.css","assets/settings-IVO3Yq5k.js","assets/Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js","assets/Stage-DU_oFq0t.css","assets/three-vrm-animation.module-Dklr5eVx.js","assets/mcp-C9U4MroK.js","assets/mini_xsschema-P_8cZcRg.js","assets/providers-Y3Mr8_DF.js","assets/index-LHmcipjy.js","assets/Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js","assets/floating-ui.core-CgBsuaUc.js","assets/Select-X4vGC3oO.css","assets/index-BvSR0QFl.js","assets/import-url-browser-CPN8ipMD.js","assets/duckdb-mvp-CaaD-olE.js","assets/speech-nVAae-rt.js","assets/queue-3c99Yq5f.js","assets/queues-B-17ADgG.js","assets/index-C4mUnpiM.js","assets/airi-card-Bpd1towy.js","assets/consciousness-BmgC4h1A.js","assets/TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js","assets/Model.vue_vue_type_script_setup_true_lang-PK96Pm-_.js","assets/Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js","assets/index-DC4guwRc.js","assets/Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js","assets/route-block-B_A1xBdJ.js","assets/index-m8JJPQt3.css","assets/background-remove-BBGqlHWm.js","assets/InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js","assets/chat-C6ApJPfV.js","assets/image-DmDCtZow.js","assets/image-BhuwcwI9.css","assets/vibrant-DQTTh5Yn.js","assets/browser-CkchkNbv.js","assets/queue-C9PyLN3M.js","assets/index-BWM8H6v1.js","assets/IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js","assets/index-BsTlOxC-.js","assets/CardDetailDialog.vue_vue_type_script_setup_true_lang-BN5mx1Hz.js","assets/DeleteCardDialog.vue_vue_type_script_setup_true_lang-ChKftqb0.js","assets/index-CAP_srMr.js","assets/CardListItem.vue_vue_type_script_setup_true_lang-B94Ybzjh.js","assets/CardDetailDialog-DUkJNKcl.js","assets/CardListItem-Bcpy7sq6.js","assets/DeleteCardDialog-BgA6bpCe.js","assets/index-fbmB4MjP.js","assets/ColorPalette.vue_vue_type_script_setup_true_lang-1nqX-kcz.js","assets/index-BVitw2V7.css","assets/index-Ep8bbMjW.js","assets/index-DCkir7nL.js","assets/useIconAnimation-BCxWQrf7.js","assets/index-rlpEp8ML.css","assets/index-RQ48LviH.js","assets/IconStatusItem-CzuT67Cw.js","assets/consciousness-CS4IBC4q.js","assets/RadioCardSimple-B-Oog_Qf.js","assets/Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js","assets/memory-long-term-B-ZAjue9.js","assets/memory-short-term-BPGQesh6.js","assets/speech-Cqx5-wPK.js","assets/FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js","assets/FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js","assets/Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js","assets/index-DhNz88Xj.js","assets/alibaba-cloud-model-studio-BjeIv5w8.js","assets/SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js","assets/ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js","assets/ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js","assets/ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js","assets/anthropic-2GUn5SX-.js","assets/ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js","assets/cloudflare-workers-ai-CmLRkAJ-.js","assets/deepseek-Dhr9828c.js","assets/elevenlabs-CtF3mm-w.js","assets/featherless-ai-8Fh6lUDA.js","assets/fireworks-ai-Dd6lQOw3.js","assets/google-generative-ai-Cst0rdKi.js","assets/microsoft-speech-B1rDo1CL.js","assets/mistral-ai-CCjWqN_I.js","assets/moonshot-ai-Og7KMbxi.js","assets/novita-ai-BiraQuur.js","assets/ollama-Bin1uANJ.js","assets/openai-BPj3vm_3.js","assets/openrouter-ai-WP7_lFby.js","assets/together-ai-CxZKBPZ7.js","assets/volcengine-C-Sx5RRX.js","assets/xai-CEcx0MIE.js","assets/index-DnVVffQQ.js","assets/filter-message-DJVIgF-Z.js","assets/delays-DJLByMTi.js","assets/emotions-COZF15gE.js","assets/messages-CNwMKqXh.js"])))=>i.map(i=>d[i]); var tC=Object.defineProperty;var nC=(n,e,t)=>e in n?tC(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var fi=(n,e,t)=>nC(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();const iC="modulepreload",sC=function(n){return"/"+n},hv={},je=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let o=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));s=o(t.map(c=>{if(c=sC(c),c in hv)return;hv[c]=!0;const u=c.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${f}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":iC,u||(d.as="script"),d.crossOrigin="",d.href=c,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((h,p)=>{d.addEventListener("load",h),d.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};/** * @vue/shared v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors @@ -3846,11 +3846,11 @@ void main() { * pinia v3.0.2 * (c) 2025 Eduardo San Martin Morote * @license MIT - */let Pw;const $h=n=>Pw=n,Iw=Symbol();function $g(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var zl;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(zl||(zl={}));function Oz(){const n=b0(!0),e=n.run(()=>et({}));let t=[],i=[];const s=w0({install(r){$h(s),s._a=r,r.provide(Iw,s),r.config.globalProperties.$pinia=s,i.forEach(o=>t.push(o)),i=[]},use(r){return this._a?t.push(r):i.push(r),this},_p:t,_a:null,_e:n,_s:new Map,state:e});return s}const Lw=()=>{};function _x(n,e,t,i=Lw){n.push(e);const s=()=>{const r=n.indexOf(e);r>-1&&(n.splice(r,1),i())};return!t&&qd()&&x0(s),s}function na(n,...e){n.slice().forEach(t=>{t(...e)})}const Nz=n=>n(),vx=Symbol(),xm=Symbol();function qg(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],s=n[t];$g(s)&&$g(i)&&n.hasOwnProperty(t)&&!Pt(i)&&!Is(i)?n[t]=qg(s,i):n[t]=i}return n}const Uz=Symbol();function Fz(n){return!$g(n)||!Object.prototype.hasOwnProperty.call(n,Uz)}const{assign:ir}=Object;function kz(n){return!!(Pt(n)&&n.effect)}function Bz(n,e,t,i){const{state:s,actions:r,getters:o}=e,a=t.state.value[n];let l;function c(){a||(t.state.value[n]=s?s():{});const u=dS(t.state.value[n]);return ir(u,r,Object.keys(o||{}).reduce((f,d)=>(f[d]=w0(Me(()=>{$h(t);const h=t._s.get(n);return o[d].call(h,h)})),f),{}))}return l=Dw(n,c,e,t,i,!0),l}function Dw(n,e,t={},i,s,r){let o;const a=ir({actions:{}},t),l={deep:!0};let c,u,f=[],d=[],h;const p=i.state.value[n];!r&&!p&&(i.state.value[n]={}),et({});let _;function g(P){let x;c=u=!1,typeof P=="function"?(P(i.state.value[n]),x={type:zl.patchFunction,storeId:n,events:h}):(qg(i.state.value[n],P),x={type:zl.patchObject,payload:P,storeId:n,events:h});const M=_=Symbol();wr().then(()=>{_===M&&(c=!0)}),u=!0,na(f,x,i.state.value[n])}const m=r?function(){const{state:x}=t,M=x?x():{};this.$patch(I=>{ir(I,M)})}:Lw;function y(){o.stop(),f=[],d=[],i._s.delete(n)}const b=(P,x="")=>{if(vx in P)return P[xm]=x,P;const M=function(){$h(i);const I=Array.from(arguments),N=[],V=[];function j(ee){N.push(ee)}function te(ee){V.push(ee)}na(d,{args:I,name:M[xm],store:E,after:j,onError:te});let Z;try{Z=P.apply(this&&this.$id===n?this:E,I)}catch(ee){throw na(V,ee),ee}return Z instanceof Promise?Z.then(ee=>(na(N,ee),ee)).catch(ee=>(na(V,ee),Promise.reject(ee))):(na(N,Z),Z)};return M[vx]=!0,M[xm]=x,M},v={_p:i,$id:n,$onAction:_x.bind(null,d),$patch:g,$reset:m,$subscribe(P,x={}){const M=_x(f,P,x.detached,()=>I()),I=o.run(()=>Xe(()=>i.state.value[n],N=>{(x.flush==="sync"?u:c)&&P({storeId:n,type:zl.direct,events:h},N)},ir({},l,x)));return M},$dispose:y},E=xi(v);i._s.set(n,E);const S=(i._a&&i._a.runWithContext||Nz)(()=>i._e.run(()=>(o=b0()).run(()=>e({action:b}))));for(const P in S){const x=S[P];if(Pt(x)&&!kz(x)||Is(x))r||(p&&Fz(x)&&(Pt(x)?x.value=p[P]:qg(x,p[P])),i.state.value[n][P]=x);else if(typeof x=="function"){const M=b(x,P);S[P]=M,a.actions[P]=x}}return ir(E,S),ir(ut(E),S),Object.defineProperty(E,"$state",{get:()=>i.state.value[n],set:P=>{g(x=>{ir(x,P)})}}),i._p.forEach(P=>{ir(E,o.run(()=>P({store:E,app:i._a,pinia:i,options:a})))}),p&&r&&t.hydrate&&t.hydrate(E.$state,p),c=!0,u=!0,E}/*! #__NO_SIDE_EFFECTS__ */function zz(n,e,t){let i;const s=typeof e=="function";i=s?t:e;function r(o,a){const l=Rc();return o=o||(l?mn(Iw,null):null),o&&$h(o),o=Pw,o._s.has(n)||(s?Dw(n,e,i,o):Bz(n,i,o)),o._s.get(n)}return r.$id=n,r}function Vz(n){const e=ut(n),t={};for(const i in e){const s=e[i];s.effect?t[i]=Me({get:()=>n[i],set(r){n[i]=r}}):(Pt(s)||Is(s))&&(t[i]=hS(n,i))}return t}const Hz=n=>{const e={};Object.entries(Object.assign({"/src/layouts/default.vue":()=>je(()=>import("./default-BhVC5vRq.js"),__vite__mapDeps([0,1,2])),"/src/layouts/settings.vue":()=>je(()=>import("./settings-DmZvPNPX.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2])),"/src/layouts/stage.vue":()=>je(()=>import("./stage-BD_fFd6P.js"),[])})).forEach(([s,r])=>{let o=s.replace("/src/layouts/","").replace(".vue","");e[o]=r});function i(s,r=!0){return s.map(o=>{var a,l,c,u,f,d;if(((a=o.children)==null?void 0:a.length)>0&&(o.children=i(o.children,!1)),r){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[(d=o.meta)==null?void 0:d.layout],children:[{...o,path:""}],meta:{isLayout:!0}}:o})}return i(n)};/*! + */let Pw;const $h=n=>Pw=n,Iw=Symbol();function $g(n){return n&&typeof n=="object"&&Object.prototype.toString.call(n)==="[object Object]"&&typeof n.toJSON!="function"}var zl;(function(n){n.direct="direct",n.patchObject="patch object",n.patchFunction="patch function"})(zl||(zl={}));function Oz(){const n=b0(!0),e=n.run(()=>et({}));let t=[],i=[];const s=w0({install(r){$h(s),s._a=r,r.provide(Iw,s),r.config.globalProperties.$pinia=s,i.forEach(o=>t.push(o)),i=[]},use(r){return this._a?t.push(r):i.push(r),this},_p:t,_a:null,_e:n,_s:new Map,state:e});return s}const Lw=()=>{};function _x(n,e,t,i=Lw){n.push(e);const s=()=>{const r=n.indexOf(e);r>-1&&(n.splice(r,1),i())};return!t&&qd()&&x0(s),s}function na(n,...e){n.slice().forEach(t=>{t(...e)})}const Nz=n=>n(),vx=Symbol(),xm=Symbol();function qg(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],s=n[t];$g(s)&&$g(i)&&n.hasOwnProperty(t)&&!Pt(i)&&!Is(i)?n[t]=qg(s,i):n[t]=i}return n}const Uz=Symbol();function Fz(n){return!$g(n)||!Object.prototype.hasOwnProperty.call(n,Uz)}const{assign:ir}=Object;function kz(n){return!!(Pt(n)&&n.effect)}function Bz(n,e,t,i){const{state:s,actions:r,getters:o}=e,a=t.state.value[n];let l;function c(){a||(t.state.value[n]=s?s():{});const u=dS(t.state.value[n]);return ir(u,r,Object.keys(o||{}).reduce((f,d)=>(f[d]=w0(Me(()=>{$h(t);const h=t._s.get(n);return o[d].call(h,h)})),f),{}))}return l=Dw(n,c,e,t,i,!0),l}function Dw(n,e,t={},i,s,r){let o;const a=ir({actions:{}},t),l={deep:!0};let c,u,f=[],d=[],h;const p=i.state.value[n];!r&&!p&&(i.state.value[n]={}),et({});let _;function g(P){let x;c=u=!1,typeof P=="function"?(P(i.state.value[n]),x={type:zl.patchFunction,storeId:n,events:h}):(qg(i.state.value[n],P),x={type:zl.patchObject,payload:P,storeId:n,events:h});const M=_=Symbol();wr().then(()=>{_===M&&(c=!0)}),u=!0,na(f,x,i.state.value[n])}const m=r?function(){const{state:x}=t,M=x?x():{};this.$patch(I=>{ir(I,M)})}:Lw;function y(){o.stop(),f=[],d=[],i._s.delete(n)}const b=(P,x="")=>{if(vx in P)return P[xm]=x,P;const M=function(){$h(i);const I=Array.from(arguments),N=[],V=[];function j(ee){N.push(ee)}function te(ee){V.push(ee)}na(d,{args:I,name:M[xm],store:E,after:j,onError:te});let Z;try{Z=P.apply(this&&this.$id===n?this:E,I)}catch(ee){throw na(V,ee),ee}return Z instanceof Promise?Z.then(ee=>(na(N,ee),ee)).catch(ee=>(na(V,ee),Promise.reject(ee))):(na(N,Z),Z)};return M[vx]=!0,M[xm]=x,M},v={_p:i,$id:n,$onAction:_x.bind(null,d),$patch:g,$reset:m,$subscribe(P,x={}){const M=_x(f,P,x.detached,()=>I()),I=o.run(()=>Xe(()=>i.state.value[n],N=>{(x.flush==="sync"?u:c)&&P({storeId:n,type:zl.direct,events:h},N)},ir({},l,x)));return M},$dispose:y},E=xi(v);i._s.set(n,E);const S=(i._a&&i._a.runWithContext||Nz)(()=>i._e.run(()=>(o=b0()).run(()=>e({action:b}))));for(const P in S){const x=S[P];if(Pt(x)&&!kz(x)||Is(x))r||(p&&Fz(x)&&(Pt(x)?x.value=p[P]:qg(x,p[P])),i.state.value[n][P]=x);else if(typeof x=="function"){const M=b(x,P);S[P]=M,a.actions[P]=x}}return ir(E,S),ir(ut(E),S),Object.defineProperty(E,"$state",{get:()=>i.state.value[n],set:P=>{g(x=>{ir(x,P)})}}),i._p.forEach(P=>{ir(E,o.run(()=>P({store:E,app:i._a,pinia:i,options:a})))}),p&&r&&t.hydrate&&t.hydrate(E.$state,p),c=!0,u=!0,E}/*! #__NO_SIDE_EFFECTS__ */function zz(n,e,t){let i;const s=typeof e=="function";i=s?t:e;function r(o,a){const l=Rc();return o=o||(l?mn(Iw,null):null),o&&$h(o),o=Pw,o._s.has(n)||(s?Dw(n,e,i,o):Bz(n,i,o)),o._s.get(n)}return r.$id=n,r}function Vz(n){const e=ut(n),t={};for(const i in e){const s=e[i];s.effect?t[i]=Me({get:()=>n[i],set(r){n[i]=r}}):(Pt(s)||Is(s))&&(t[i]=hS(n,i))}return t}const Hz=n=>{const e={};Object.entries(Object.assign({"/src/layouts/default.vue":()=>je(()=>import("./default-Uk3R33Mo.js"),__vite__mapDeps([0,1,2])),"/src/layouts/settings.vue":()=>je(()=>import("./settings-IVO3Yq5k.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2])),"/src/layouts/stage.vue":()=>je(()=>import("./stage-Q-xHGzY4.js"),[])})).forEach(([s,r])=>{let o=s.replace("/src/layouts/","").replace(".vue","");e[o]=r});function i(s,r=!0){return s.map(o=>{var a,l,c,u,f,d;if(((a=o.children)==null?void 0:a.length)>0&&(o.children=i(o.children,!1)),r){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[(d=o.meta)==null?void 0:d.layout],children:[{...o,path:""}],meta:{isLayout:!0}}:o})}return i(n)};/*! * vue-router v4.5.1 * (c) 2025 Eduardo San Martin Morote * @license MIT - */const sa=typeof document<"u";function Ow(n){return typeof n=="object"||"displayName"in n||"props"in n||"__vccOpts"in n}function Gz(n){return n.__esModule||n[Symbol.toStringTag]==="Module"||n.default&&Ow(n.default)}const Mt=Object.assign;function Mm(n,e){const t={};for(const i in e){const s=e[i];t[i]=Vi(s)?s.map(n):n(s)}return t}const Vl=()=>{},Vi=Array.isArray,Nw=/#/g,Wz=/&/g,Xz=/\//g,$z=/=/g,qz=/\?/g,Uw=/\+/g,Yz=/%5B/g,jz=/%5D/g,Fw=/%5E/g,Kz=/%60/g,kw=/%7B/g,Zz=/%7C/g,Bw=/%7D/g,Jz=/%20/g;function H_(n){return encodeURI(""+n).replace(Zz,"|").replace(Yz,"[").replace(jz,"]")}function Qz(n){return H_(n).replace(kw,"{").replace(Bw,"}").replace(Fw,"^")}function Yg(n){return H_(n).replace(Uw,"%2B").replace(Jz,"+").replace(Nw,"%23").replace(Wz,"%26").replace(Kz,"`").replace(kw,"{").replace(Bw,"}").replace(Fw,"^")}function eV(n){return Yg(n).replace($z,"%3D")}function tV(n){return H_(n).replace(Nw,"%23").replace(qz,"%3F")}function nV(n){return n==null?"":tV(n).replace(Xz,"%2F")}function xc(n){try{return decodeURIComponent(""+n)}catch{}return""+n}const iV=/\/$/,sV=n=>n.replace(iV,"");function Sm(n,e,t="/"){let i,s={},r="",o="";const a=e.indexOf("#");let l=e.indexOf("?");return a=0&&(l=-1),l>-1&&(i=e.slice(0,l),r=e.slice(l+1,a>-1?a:e.length),s=n(r)),a>-1&&(i=i||e.slice(0,a),o=e.slice(a,e.length)),i=lV(i??e,t),{fullPath:i+(r&&"?")+r+o,path:i,query:s,hash:xc(o)}}function rV(n,e){const t=e.query?n(e.query):"";return e.path+(t&&"?")+t+(e.hash||"")}function yx(n,e){return!e||!n.toLowerCase().startsWith(e.toLowerCase())?n:n.slice(e.length)||"/"}function oV(n,e,t){const i=e.matched.length-1,s=t.matched.length-1;return i>-1&&i===s&&Ia(e.matched[i],t.matched[s])&&zw(e.params,t.params)&&n(e.query)===n(t.query)&&e.hash===t.hash}function Ia(n,e){return(n.aliasOf||n)===(e.aliasOf||e)}function zw(n,e){if(Object.keys(n).length!==Object.keys(e).length)return!1;for(const t in n)if(!aV(n[t],e[t]))return!1;return!0}function aV(n,e){return Vi(n)?bx(n,e):Vi(e)?bx(e,n):n===e}function bx(n,e){return Vi(e)?n.length===e.length&&n.every((t,i)=>t===e[i]):n.length===1&&n[0]===e}function lV(n,e){if(n.startsWith("/"))return n;if(!n)return e;const t=e.split("/"),i=n.split("/"),s=i[i.length-1];(s===".."||s===".")&&i.push("");let r=t.length-1,o,a;for(o=0;o1&&r--;else break;return t.slice(0,r).join("/")+"/"+i.slice(o).join("/")}const tr={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0};var Mc;(function(n){n.pop="pop",n.push="push"})(Mc||(Mc={}));var Hl;(function(n){n.back="back",n.forward="forward",n.unknown=""})(Hl||(Hl={}));function cV(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),sV(n)}const uV=/^[^#]+#/;function fV(n,e){return n.replace(uV,"#")+e}function dV(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 qh=()=>({left:window.scrollX,top:window.scrollY});function hV(n){let e;if("el"in n){const t=n.el,i=typeof t=="string"&&t.startsWith("#"),s=typeof t=="string"?i?document.getElementById(t.slice(1)):document.querySelector(t):t;if(!s)return;e=dV(s,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 xx(n,e){return(history.state?history.state.position-e:-1)+n}const jg=new Map;function pV(n,e){jg.set(n,e)}function mV(n){const e=jg.get(n);return jg.delete(n),e}let gV=()=>location.protocol+"//"+location.host;function Vw(n,e){const{pathname:t,search:i,hash:s}=e,r=n.indexOf("#");if(r>-1){let a=s.includes(n.slice(r))?n.slice(r).length:1,l=s.slice(a);return l[0]!=="/"&&(l="/"+l),yx(l,"")}return yx(t,n)+i+s}function _V(n,e,t,i){let s=[],r=[],o=null;const a=({state:d})=>{const h=Vw(n,location),p=t.value,_=e.value;let g=0;if(d){if(t.value=h,e.value=d,o&&o===p){o=null;return}g=_?d.position-_.position:0}else i(h);s.forEach(m=>{m(t.value,p,{delta:g,type:Mc.pop,direction:g?g>0?Hl.forward:Hl.back:Hl.unknown})})};function l(){o=t.value}function c(d){s.push(d);const h=()=>{const p=s.indexOf(d);p>-1&&s.splice(p,1)};return r.push(h),h}function u(){const{history:d}=window;d.state&&d.replaceState(Mt({},d.state,{scroll:qh()}),"")}function f(){for(const d of r)d();r=[],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 Mx(n,e,t,i=!1,s=!1){return{back:n,current:e,forward:t,replaced:i,position:window.history.length,scroll:s?qh():null}}function vV(n){const{history:e,location:t}=window,i={value:Vw(n,t)},s={value:e.state};s.value||r(i.value,{back:null,current:i.value,forward:null,position:e.length-1,replaced:!0,scroll:null},!0);function r(l,c,u){const f=n.indexOf("#"),d=f>-1?(t.host&&document.querySelector("base")?n:n.slice(f))+l:gV()+n+l;try{e[u?"replaceState":"pushState"](c,"",d),s.value=c}catch(h){console.error(h),t[u?"replace":"assign"](d)}}function o(l,c){const u=Mt({},e.state,Mx(s.value.back,l,s.value.forward,!0),c,{position:s.value.position});r(l,u,!0),i.value=l}function a(l,c){const u=Mt({},s.value,e.state,{forward:l,scroll:qh()});r(u.current,u,!0);const f=Mt({},Mx(i.value,l,null),{position:u.position+1},c);r(l,f,!1),i.value=l}return{location:i,state:s,push:a,replace:o}}function yV(n){n=cV(n);const e=vV(n),t=_V(n,e.state,e.location,e.replace);function i(r,o=!0){o||t.pauseListeners(),history.go(r)}const s=Mt({location:"",base:n,go:i,createHref:fV.bind(null,n)},e,t);return Object.defineProperty(s,"location",{enumerable:!0,get:()=>e.location.value}),Object.defineProperty(s,"state",{enumerable:!0,get:()=>e.state.value}),s}function bV(n){return n=location.host?n||location.pathname+location.search:"",n.includes("#")||(n+="#"),yV(n)}function xV(n){return typeof n=="string"||n&&typeof n=="object"}function Hw(n){return typeof n=="string"||typeof n=="symbol"}const Gw=Symbol("");var Sx;(function(n){n[n.aborted=4]="aborted",n[n.cancelled=8]="cancelled",n[n.duplicated=16]="duplicated"})(Sx||(Sx={}));function La(n,e){return Mt(new Error,{type:n,[Gw]:!0},e)}function ys(n,e){return n instanceof Error&&Gw in n&&(e==null||!!(n.type&e))}const Ex="[^/]+?",MV={sensitive:!1,strict:!1,start:!0,end:!0},SV=/[.+*?^${}()[\]/\\]/g;function EV(n,e){const t=Mt({},MV,e),i=[];let s=t.start?"^":"";const r=[];for(const c of n){const u=c.length?[]:[90];t.strict&&!c.length&&(s+="/");for(let f=0;fe.length?e.length===1&&e[0]===80?1:-1:0}function Ww(n,e){let t=0;const i=n.score,s=e.score;for(;t0&&e[e.length-1]<0}const wV={type:0,value:""},AV=/[a-zA-Z0-9_]/;function CV(n){if(!n)return[[]];if(n==="/")return[[wV]];if(!n.startsWith("/"))throw new Error(`Invalid path "${n}"`);function e(h){throw new Error(`ERR (${t})/"${c}": ${h}`)}let t=0,i=t;const s=[];let r;function o(){r&&s.push(r),r=[]}let a=0,l,c="",u="";function f(){c&&(t===0?r.push({type:0,value:c}):t===1||t===2||t===3?(r.length>1&&(l==="*"||l==="+")&&e(`A repeatable param (${c}) must be alone in its segment. eg: '/:ids+.`),r.push({type:1,value:c,regexp:u,repeatable:l==="*"||l==="+",optional:l==="*"||l==="?"})):e("Invalid state to consume buffer"),c="")}function d(){c+=l}for(;a{o(b)}:Vl}function o(f){if(Hw(f)){const d=i.get(f);d&&(i.delete(f),t.splice(t.indexOf(d),1),d.children.forEach(o),d.alias.forEach(o))}else{const d=t.indexOf(f);d>-1&&(t.splice(d,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 d=DV(f,t);t.splice(d,0,f),f.record.name&&!Cx(f)&&i.set(f.record.name,f)}function c(f,d){let h,p={},_,g;if("name"in f&&f.name){if(h=i.get(f.name),!h)throw La(1,{location:f});g=h.record.name,p=Mt(wx(d.params,h.keys.filter(b=>!b.optional).concat(h.parent?h.parent.keys.filter(b=>b.optional):[]).map(b=>b.name)),f.params&&wx(f.params,h.keys.map(b=>b.name))),_=h.stringify(p)}else if(f.path!=null)_=f.path,h=t.find(b=>b.re.test(_)),h&&(p=h.parse(_),g=h.record.name);else{if(h=d.name?i.get(d.name):t.find(b=>b.re.test(d.path)),!h)throw La(1,{location:f,currentLocation:d});g=h.record.name,p=Mt({},d.params,f.params),_=h.stringify(p)}const m=[];let y=h;for(;y;)m.unshift(y.record),y=y.parent;return{name:g,path:_,params:p,matched:m,meta:LV(m)}}n.forEach(f=>r(f));function u(){t.length=0,i.clear()}return{addRoute:r,resolve:c,removeRoute:o,clearRoutes:u,getRoutes:a,getRecordMatcher:s}}function wx(n,e){const t={};for(const i of e)i in n&&(t[i]=n[i]);return t}function Ax(n){const e={path:n.path,redirect:n.redirect,name:n.name,meta:n.meta||{},aliasOf:n.aliasOf,beforeEnter:n.beforeEnter,props:IV(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 IV(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 Cx(n){for(;n;){if(n.record.aliasOf)return!0;n=n.parent}return!1}function LV(n){return n.reduce((e,t)=>Mt(e,t.meta),{})}function Rx(n,e){const t={};for(const i in n)t[i]=i in e?e[i]:n[i];return t}function DV(n,e){let t=0,i=e.length;for(;t!==i;){const r=t+i>>1;Ww(n,e[r])<0?i=r:t=r+1}const s=OV(n);return s&&(i=e.lastIndexOf(s,i-1)),i}function OV(n){let e=n;for(;e=e.parent;)if(Xw(e)&&Ww(n,e)===0)return e}function Xw({record:n}){return!!(n.name||n.components&&Object.keys(n.components).length||n.redirect)}function NV(n){const e={};if(n===""||n==="?")return e;const i=(n[0]==="?"?n.slice(1):n).split("&");for(let s=0;sr&&Yg(r)):[i&&Yg(i)]).forEach(r=>{r!==void 0&&(e+=(e.length?"&":"")+t,r!=null&&(e+="="+r))})}return e}function UV(n){const e={};for(const t in n){const i=n[t];i!==void 0&&(e[t]=Vi(i)?i.map(s=>s==null?null:""+s):i==null?i:""+i)}return e}const FV=Symbol(""),Ix=Symbol(""),Yh=Symbol(""),G_=Symbol(""),Kg=Symbol("");function ul(){let n=[];function e(i){return n.push(i),()=>{const s=n.indexOf(i);s>-1&&n.splice(s,1)}}function t(){n=[]}return{add:e,list:()=>n.slice(),reset:t}}function cr(n,e,t,i,s,r=o=>o()){const o=i&&(i.enterCallbacks[s]=i.enterCallbacks[s]||[]);return()=>new Promise((a,l)=>{const c=d=>{d===!1?l(La(4,{from:t,to:e})):d instanceof Error?l(d):xV(d)?l(La(2,{from:e,to:d})):(o&&i.enterCallbacks[s]===o&&typeof d=="function"&&o.push(d),a())},u=r(()=>n.call(i&&i.instances[s],e,t,c));let f=Promise.resolve(u);n.length<3&&(f=f.then(c)),f.catch(d=>l(d))})}function Em(n,e,t,i,s=r=>r()){const r=[];for(const o of n)for(const a in o.components){let l=o.components[a];if(!(e!=="beforeRouteEnter"&&!o.instances[a]))if(Ow(l)){const u=(l.__vccOpts||l)[e];u&&r.push(cr(u,t,i,o,a,s))}else{let c=l();r.push(()=>c.then(u=>{if(!u)throw new Error(`Couldn't resolve component "${a}" at "${o.path}"`);const f=Gz(u)?u.default:u;o.mods[a]=u,o.components[a]=f;const h=(f.__vccOpts||f)[e];return h&&cr(h,t,i,o,a,s)()}))}}return r}function Lx(n){const e=mn(Yh),t=mn(G_),i=Me(()=>{const l=Ot(n.to);return e.resolve(l)}),s=Me(()=>{const{matched:l}=i.value,{length:c}=l,u=l[c-1],f=t.matched;if(!u||!f.length)return-1;const d=f.findIndex(Ia.bind(null,u));if(d>-1)return d;const h=Dx(l[c-2]);return c>1&&Dx(u)===h&&f[f.length-1].path!==h?f.findIndex(Ia.bind(null,l[c-2])):d}),r=Me(()=>s.value>-1&&HV(t.params,i.value.params)),o=Me(()=>s.value>-1&&s.value===t.matched.length-1&&zw(t.params,i.value.params));function a(l={}){if(VV(l)){const c=e[Ot(n.replace)?"replace":"push"](Ot(n.to)).catch(Vl);return n.viewTransition&&typeof document<"u"&&"startViewTransition"in document&&document.startViewTransition(()=>c),c}return Promise.resolve()}return{route:i,href:Me(()=>i.value.href),isActive:r,isExactActive:o,navigate:a}}function kV(n){return n.length===1?n[0]:n}const BV=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"},viewTransition:Boolean},useLink:Lx,setup(n,{slots:e}){const t=xi(Lx(n)),{options:i}=mn(Yh),s=Me(()=>({[Ox(n.activeClass,i.linkActiveClass,"router-link-active")]:t.isActive,[Ox(n.exactActiveClass,i.linkExactActiveClass,"router-link-exact-active")]:t.isExactActive}));return()=>{const r=e.default&&kV(e.default(t));return n.custom?r:Ns("a",{"aria-current":t.isExactActive?n.ariaCurrentValue:null,href:t.href,onClick:t.navigate,class:s.value},r)}}}),zV=BV;function VV(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 HV(n,e){for(const t in e){const i=e[t],s=n[t];if(typeof i=="string"){if(i!==s)return!1}else if(!Vi(s)||s.length!==i.length||i.some((r,o)=>r!==s[o]))return!1}return!0}function Dx(n){return n?n.aliasOf?n.aliasOf.path:n.path:""}const Ox=(n,e,t)=>n??e??t,GV=fn({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(n,{attrs:e,slots:t}){const i=mn(Kg),s=Me(()=>n.route||i.value),r=mn(Ix,0),o=Me(()=>{let c=Ot(r);const{matched:u}=s.value;let f;for(;(f=u[c])&&!f.components;)c++;return c}),a=Me(()=>s.value.matched[o.value]);pr(Ix,Me(()=>o.value+1)),pr(FV,a),pr(Kg,s);const l=et();return Xe(()=>[l.value,a.value,n.name],([c,u,f],[d,h,p])=>{u&&(u.instances[f]=c,h&&h!==u&&c&&c===d&&(u.leaveGuards.size||(u.leaveGuards=h.leaveGuards),u.updateGuards.size||(u.updateGuards=h.updateGuards))),c&&u&&(!h||!Ia(u,h)||!d)&&(u.enterCallbacks[f]||[]).forEach(_=>_(c))},{flush:"post"}),()=>{const c=s.value,u=n.name,f=a.value,d=f&&f.components[u];if(!d)return Nx(t.default,{Component:d,route:c});const h=f.props[u],p=h?h===!0?c.params:typeof h=="function"?h(c):h:null,g=Ns(d,Mt({},p,e,{onVnodeUnmounted:m=>{m.component.isUnmounted&&(f.instances[u]=null)},ref:l}));return Nx(t.default,{Component:g,route:c})||g}}});function Nx(n,e){if(!n)return null;const t=n(e);return t.length===1?t[0]:t}const $w=GV;function WV(n){const e=PV(n.routes,n),t=n.parseQuery||NV,i=n.stringifyQuery||Px,s=n.history,r=ul(),o=ul(),a=ul(),l=Oe(tr);let c=tr;sa&&n.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const u=Mm.bind(null,$=>""+$),f=Mm.bind(null,nV),d=Mm.bind(null,xc);function h($,ae){let le,ce;return Hw($)?(le=e.getRecordMatcher($),ce=ae):ce=$,e.addRoute(ce,le)}function p($){const ae=e.getRecordMatcher($);ae&&e.removeRoute(ae)}function _(){return e.getRoutes().map($=>$.record)}function g($){return!!e.getRecordMatcher($)}function m($,ae){if(ae=Mt({},ae||l.value),typeof $=="string"){const w=Sm(t,$,ae.path),X=e.resolve({path:w.path},ae),G=s.createHref(w.fullPath);return Mt(w,X,{params:d(X.params),hash:xc(w.hash),redirectedFrom:void 0,href:G})}let le;if($.path!=null)le=Mt({},$,{path:Sm(t,$.path,ae.path).path});else{const w=Mt({},$.params);for(const X in w)w[X]==null&&delete w[X];le=Mt({},$,{params:f(w)}),ae.params=f(ae.params)}const ce=e.resolve(le,ae),He=$.hash||"";ce.params=u(d(ce.params));const F=rV(i,Mt({},$,{hash:Qz(He),path:ce.path})),k=s.createHref(F);return Mt({fullPath:F,hash:He,query:i===Px?UV($.query):$.query||{}},ce,{redirectedFrom:void 0,href:k})}function y($){return typeof $=="string"?Sm(t,$,l.value.path):Mt({},$)}function b($,ae){if(c!==$)return La(8,{from:ae,to:$})}function v($){return S($)}function E($){return v(Mt(y($),{replace:!0}))}function T($){const ae=$.matched[$.matched.length-1];if(ae&&ae.redirect){const{redirect:le}=ae;let ce=typeof le=="function"?le($):le;return typeof ce=="string"&&(ce=ce.includes("?")||ce.includes("#")?ce=y(ce):{path:ce},ce.params={}),Mt({query:$.query,hash:$.hash,params:ce.path!=null?{}:$.params},ce)}}function S($,ae){const le=c=m($),ce=l.value,He=$.state,F=$.force,k=$.replace===!0,w=T(le);if(w)return S(Mt(y(w),{state:typeof w=="object"?Mt({},He,w.state):He,force:F,replace:k}),ae||le);const X=le;X.redirectedFrom=ae;let G;return!F&&oV(i,ce,le)&&(G=La(16,{to:X,from:ce}),se(ce,ce,!0,!1)),(G?Promise.resolve(G):M(X,ce)).catch(W=>ys(W)?ys(W,2)?W:be(W):J(W,X,ce)).then(W=>{if(W){if(ys(W,2))return S(Mt({replace:k},y(W.to),{state:typeof W.to=="object"?Mt({},He,W.to.state):He,force:F}),ae||X)}else W=N(X,ce,!0,k,He);return I(X,ce,W),W})}function P($,ae){const le=b($,ae);return le?Promise.reject(le):Promise.resolve()}function x($){const ae=re.values().next().value;return ae&&typeof ae.runWithContext=="function"?ae.runWithContext($):$()}function M($,ae){let le;const[ce,He,F]=XV($,ae);le=Em(ce.reverse(),"beforeRouteLeave",$,ae);for(const w of ce)w.leaveGuards.forEach(X=>{le.push(cr(X,$,ae))});const k=P.bind(null,$,ae);return le.push(k),xe(le).then(()=>{le=[];for(const w of r.list())le.push(cr(w,$,ae));return le.push(k),xe(le)}).then(()=>{le=Em(He,"beforeRouteUpdate",$,ae);for(const w of He)w.updateGuards.forEach(X=>{le.push(cr(X,$,ae))});return le.push(k),xe(le)}).then(()=>{le=[];for(const w of F)if(w.beforeEnter)if(Vi(w.beforeEnter))for(const X of w.beforeEnter)le.push(cr(X,$,ae));else le.push(cr(w.beforeEnter,$,ae));return le.push(k),xe(le)}).then(()=>($.matched.forEach(w=>w.enterCallbacks={}),le=Em(F,"beforeRouteEnter",$,ae,x),le.push(k),xe(le))).then(()=>{le=[];for(const w of o.list())le.push(cr(w,$,ae));return le.push(k),xe(le)}).catch(w=>ys(w,8)?w:Promise.reject(w))}function I($,ae,le){a.list().forEach(ce=>x(()=>ce($,ae,le)))}function N($,ae,le,ce,He){const F=b($,ae);if(F)return F;const k=ae===tr,w=sa?history.state:{};le&&(ce||k?s.replace($.fullPath,Mt({scroll:k&&w&&w.scroll},He)):s.push($.fullPath,He)),l.value=$,se($,ae,le,k),be()}let V;function j(){V||(V=s.listen(($,ae,le)=>{if(!ge.listening)return;const ce=m($),He=T(ce);if(He){S(Mt(He,{replace:!0,force:!0}),ce).catch(Vl);return}c=ce;const F=l.value;sa&&pV(xx(F.fullPath,le.delta),qh()),M(ce,F).catch(k=>ys(k,12)?k:ys(k,2)?(S(Mt(y(k.to),{force:!0}),ce).then(w=>{ys(w,20)&&!le.delta&&le.type===Mc.pop&&s.go(-1,!1)}).catch(Vl),Promise.reject()):(le.delta&&s.go(-le.delta,!1),J(k,ce,F))).then(k=>{k=k||N(ce,F,!1),k&&(le.delta&&!ys(k,8)?s.go(-le.delta,!1):le.type===Mc.pop&&ys(k,20)&&s.go(-1,!1)),I(ce,F,k)}).catch(Vl)}))}let te=ul(),Z=ul(),ee;function J($,ae,le){be($);const ce=Z.list();return ce.length?ce.forEach(He=>He($,ae,le)):console.error($),Promise.reject($)}function he(){return ee&&l.value!==tr?Promise.resolve():new Promise(($,ae)=>{te.add([$,ae])})}function be($){return ee||(ee=!$,j(),te.list().forEach(([ae,le])=>$?le($):ae()),te.reset()),$}function se($,ae,le,ce){const{scrollBehavior:He}=n;if(!sa||!He)return Promise.resolve();const F=!le&&mV(xx($.fullPath,0))||(ce||!le)&&history.state&&history.state.scroll||null;return wr().then(()=>He($,ae,F)).then(k=>k&&hV(k)).catch(k=>J(k,$,ae))}const ye=$=>s.go($);let Be;const re=new Set,ge={currentRoute:l,listening:!0,addRoute:h,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:r.add,beforeResolve:o.add,afterEach:a.add,onError:Z.add,isReady:he,install($){const ae=this;$.component("RouterLink",zV),$.component("RouterView",$w),$.config.globalProperties.$router=ae,Object.defineProperty($.config.globalProperties,"$route",{enumerable:!0,get:()=>Ot(l)}),sa&&!Be&&l.value===tr&&(Be=!0,v(s.location).catch(He=>{}));const le={};for(const He in tr)Object.defineProperty(le,He,{get:()=>l.value[He],enumerable:!0});$.provide(Yh,ae),$.provide(G_,lS(le)),$.provide(Kg,l);const ce=$.unmount;re.add($),$.unmount=function(){re.delete($),re.size<1&&(c=tr,V&&V(),V=null,l.value=tr,Be=!1,ee=!1),ce()}}};function xe($){return $.reduce((ae,le)=>ae.then(()=>x(le)),Promise.resolve())}return ge}function XV(n,e){const t=[],i=[],s=[],r=Math.max(e.matched.length,n.matched.length);for(let o=0;oIa(c,a))?i.push(a):t.push(a));const l=n.matched[o];l&&(e.matched.find(c=>Ia(c,l))||s.push(l))}return[t,i,s]}function $V(){return mn(Yh)}function FG(n){return mn(G_)}const qV=[{path:"/",name:"/",component:()=>je(()=>import("./index-DychlYah.js"),__vite__mapDeps([14,4,5,6,7,8,11,12,13,15,16,17,10,9,18,19,20,21,22,23,24,25,1,2,26,27,28,29])),meta:{layout:"stage",stageTransition:{name:"bubble-wave-out"}}},{path:"/:all(.*)",name:"/[...all]",component:()=>je(()=>import("./_...all_-CkQbMceU.js"),[])},{path:"/audio",name:"/audio",component:()=>je(()=>import("./audio-NB4UDUvk.js"),[])},{path:"/devtools",children:[{path:"background-remove",name:"/devtools/background-remove",component:()=>je(()=>import("./background-remove-C4yhDB9Z.js"),__vite__mapDeps([30,11,12,13,31]))},{path:"chat",name:"/devtools/chat",component:()=>je(()=>import("./chat-7V8Q9Hlp.js"),__vite__mapDeps([32,20,10]))},{path:"image",name:"/devtools/image",component:()=>je(()=>import("./image-BHbvwqTc.js"),__vite__mapDeps([33,34]))},{path:"vibrant",name:"/devtools/vibrant",component:()=>je(()=>import("./vibrant-BaXmXZtH.js"),__vite__mapDeps([35,11,12,13,31,36]))}]},{path:"/queue",name:"/queue",component:()=>je(()=>import("./queue-DC7HdGzc.js"),__vite__mapDeps([37,18]))},{path:"/settings",children:[{path:"",name:"/settings/",component:()=>je(()=>import("./index-BrQ5XatC.js"),__vite__mapDeps([38,4,5,6,7,8,11,12,13,39,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"airi-card",children:[{path:"",name:"/settings/airi-card/",component:()=>je(()=>import("./index-C0MBzJvw.js"),__vite__mapDeps([40,7,21,8,22,9,10,17,11,12,13,31,41,42,43,4,5,6,44,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"components",children:[{path:"CardDetailDialog",name:"/settings/airi-card/components/CardDetailDialog",component:()=>je(()=>import("./CardDetailDialog-HhbPTSqa.js"),__vite__mapDeps([45,41,42,43,12,4,5,6,7,21,8,22,9,10,17,11,13]))},{path:"CardListItem",name:"/settings/airi-card/components/CardListItem",component:()=>je(()=>import("./CardListItem-DLmu0uN_.js"),__vite__mapDeps([46,44,4,5,6,7,8,11,12,13]))},{path:"DeleteCardDialog",name:"/settings/airi-card/components/DeleteCardDialog",component:()=>je(()=>import("./DeleteCardDialog-CGam42wc.js"),__vite__mapDeps([47,42,43,12]))}]}]},{path:"appearance",children:[{path:"",name:"/settings/appearance/",component:()=>je(()=>import("./index-CYwgNiYZ.js"),__vite__mapDeps([48,4,5,6,7,8,11,12,13,49,25,23,43,28,50])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"memory",children:[{path:"",name:"/settings/memory/",component:()=>je(()=>import("./index-BJf3Tezf.js"),__vite__mapDeps([51,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}}]},{path:"models",children:[{path:"",name:"/settings/models/",component:()=>je(()=>import("./index-MYV-cYy6.js"),__vite__mapDeps([52,39,4,5,24,6,7,8,11,12,13,36,49,25,23,43,53,28,54])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"modules",children:[{path:"",name:"/settings/modules/",component:()=>je(()=>import("./index-BVUPfFDK.js"),__vite__mapDeps([55,4,5,6,7,8,56,11,12,13,39,53,28])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"consciousness",name:"/settings/modules/consciousness",component:()=>je(()=>import("./consciousness-zgXn05x5.js"),__vite__mapDeps([57,4,5,6,7,8,22,9,10,11,12,13,58,23,59,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"memory-long-term",name:"/settings/modules/memory-long-term",component:()=>je(()=>import("./memory-long-term-CRoA5-PX.js"),__vite__mapDeps([60,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"memory-short-term",name:"/settings/modules/memory-short-term",component:()=>je(()=>import("./memory-short-term-ivGgMFGG.js"),__vite__mapDeps([61,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"speech",name:"/settings/modules/speech",component:()=>je(()=>import("./speech-BJorZHUt.js"),__vite__mapDeps([62,63,4,5,11,12,13,6,7,8,9,10,17,64,59,65,27,58,23,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}}]},{path:"providers",children:[{path:"",name:"/settings/providers/",component:()=>je(()=>import("./index-DANZbU0h.js"),__vite__mapDeps([66,39,4,5,6,7,8,9,10,56,11,12,13,53,28])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"alibaba-cloud-model-studio",name:"/settings/providers/alibaba-cloud-model-studio",component:()=>je(()=>import("./alibaba-cloud-model-studio-8BnjUB5R.js"),__vite__mapDeps([67,4,5,6,7,8,9,10,17,63,11,12,13,68,69,25,23,64,59,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"anthropic",name:"/settings/providers/anthropic",component:()=>je(()=>import("./anthropic-DcMJ-RH8.js"),__vite__mapDeps([72,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"cloudflare-workers-ai",name:"/settings/providers/cloudflare-workers-ai",component:()=>je(()=>import("./cloudflare-workers-ai-CJorqeuz.js"),__vite__mapDeps([74,4,5,6,7,8,9,10,11,12,13,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"deepseek",name:"/settings/providers/deepseek",component:()=>je(()=>import("./deepseek-J636LQ27.js"),__vite__mapDeps([75,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"elevenlabs",name:"/settings/providers/elevenlabs",component:()=>je(()=>import("./elevenlabs-CHUs61J3.js"),__vite__mapDeps([76,4,5,6,7,8,9,10,17,63,11,12,13,68,69,25,23,64,59,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"featherless-ai",name:"/settings/providers/featherless-ai",component:()=>je(()=>import("./featherless-ai-iViKpBby.js"),__vite__mapDeps([77,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"fireworks-ai",name:"/settings/providers/fireworks-ai",component:()=>je(()=>import("./fireworks-ai-oUount_Y.js"),__vite__mapDeps([78,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"google-generative-ai",name:"/settings/providers/google-generative-ai",component:()=>je(()=>import("./google-generative-ai-w-KmjfIn.js"),__vite__mapDeps([79,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"microsoft-speech",name:"/settings/providers/microsoft-speech",component:()=>je(()=>import("./microsoft-speech-Bg9KcYTS.js"),__vite__mapDeps([80,4,5,6,7,8,9,10,17,64,59,63,11,12,13,68,69,25,23,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"mistral-ai",name:"/settings/providers/mistral-ai",component:()=>je(()=>import("./mistral-ai-BaBOYsbt.js"),__vite__mapDeps([81,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"moonshot-ai",name:"/settings/providers/moonshot-ai",component:()=>je(()=>import("./moonshot-ai-CpWLI90H.js"),__vite__mapDeps([82,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"novita-ai",name:"/settings/providers/novita-ai",component:()=>je(()=>import("./novita-ai-pNiSEK4a.js"),__vite__mapDeps([83,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"ollama",name:"/settings/providers/ollama",component:()=>je(()=>import("./ollama-lxq_i-rm.js"),__vite__mapDeps([84,4,5,6,7,8,9,10,59,11,12,13,69,25,23,64,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"openai",name:"/settings/providers/openai",component:()=>je(()=>import("./openai-DQmuApR5.js"),__vite__mapDeps([85,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"openrouter-ai",name:"/settings/providers/openrouter-ai",component:()=>je(()=>import("./openrouter-ai-DJMkew1w.js"),__vite__mapDeps([86,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"together-ai",name:"/settings/providers/together-ai",component:()=>je(()=>import("./together-ai-DTk_B5ly.js"),__vite__mapDeps([87,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"volcengine",name:"/settings/providers/volcengine",component:()=>je(()=>import("./volcengine-gKPE4jbw.js"),__vite__mapDeps([88,4,5,6,7,8,9,10,17,64,59,63,11,12,13,68,69,25,23,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"xai",name:"/settings/providers/xai",component:()=>je(()=>import("./xai-_FNFPrWi.js"),__vite__mapDeps([89,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}}]},{path:"scene",children:[{path:"",name:"/settings/scene/",component:()=>je(()=>import("./index-C6zTw43n.js"),__vite__mapDeps([90,39,53,7,8,28])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]}]},{path:"/test",children:[{path:"filter-message",name:"/test/filter-message",component:()=>je(()=>import("./filter-message-CXNI-DZl.js"),__vite__mapDeps([91,11,12,13,65,27]))},{path:"queues",children:[{path:"delays",name:"/test/queues/delays",component:()=>je(()=>import("./delays-CflciaKu.js"),__vite__mapDeps([92,26,19,8,18,6,11,12,13,65,27]))},{path:"emotions",name:"/test/queues/emotions",component:()=>je(()=>import("./emotions-T9t8Z2VX.js"),__vite__mapDeps([93,18,19,8,11,12,13,65,27]))},{path:"messages",name:"/test/queues/messages",component:()=>je(()=>import("./messages-CUrOjMW7.js"),__vite__mapDeps([94,18,19,8,11,12,13,65,27]))}]}]}],qw=(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}}},YV={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},jV=n=>qw(YV[n.toLowerCase()],6),KV=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,ZV=n=>{let e;return(e=n.match(KV))?qw(parseInt(e[1],16),e[1].length):void 0},mr="([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)",Gl=`${mr}%`,W_=`(?:${mr}%|${mr})`,JV=`(?:${mr}(deg|grad|rad|turn)|${mr})`,Da="\\s*,\\s*",QV=new RegExp(`^rgba?\\(\\s*${mr}${Da}${mr}${Da}${mr}\\s*(?:,\\s*${W_}\\s*)?\\)$`),e6=new RegExp(`^rgba?\\(\\s*${Gl}${Da}${Gl}${Da}${Gl}\\s*(?:,\\s*${W_}\\s*)?\\)$`),t6=n=>{let e={mode:"rgb"},t;if(t=n.match(QV))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(e6))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},n6=(n,e)=>n===void 0?void 0:typeof n!="object"?d6(n):n.mode!==void 0?n:e?{...n,mode:e}:void 0,Yw=(n="rgb")=>e=>(e=n6(e,n))!==void 0?e.mode===n?e:Ji[e.mode][n]?Ji[e.mode][n](e):n==="rgb"?Ji[e.mode].rgb(e):Ji.rgb[n](Ji[e.mode].rgb(e)):void 0,Ji={},jw={},Od=[],Kw={},i6=n=>n,Et=n=>(Ji[n.mode]={...Ji[n.mode],...n.toMode},Object.keys(n.fromMode||{}).forEach(e=>{Ji[e]||(Ji[e]={}),Ji[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=i6)}),jw[n.mode]=n,(n.parse||[]).forEach(e=>{r6(e,n.mode)}),Yw(n.mode)),s6=n=>jw[n],r6=(n,e)=>{if(typeof n=="string"){if(!e)throw new Error("'mode' required when 'parser' is a string");Kw[n]=e}else typeof n=="function"&&Od.indexOf(n)<0&&Od.push(n)},Zg=/[^\x00-\x7F]|[a-zA-Z_]/,o6=/[^\x00-\x7F]|[-\w]/,_e={Function:"function",Ident:"ident",Number:"number",Percentage:"percentage",ParenClose:")",None:"none",Hue:"hue",Alpha:"alpha"};let $e=0;function uf(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 Jg(n){if($e>=n.length)return!1;let e=n[$e];if(Zg.test(e))return!0;if(e==="-"){if(n.length-$e<2)return!1;let t=n[$e+1];return!!(t==="-"||Zg.test(t))}return!1}const a6={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function fl(n){let e="";if((n[$e]==="-"||n[$e]==="+")&&(e+=n[$e++]),e+=ff(n),n[$e]==="."&&/\d/.test(n[$e+1])&&(e+=n[$e++]+ff(n)),(n[$e]==="e"||n[$e]==="E")&&((n[$e+1]==="-"||n[$e+1]==="+")&&/\d/.test(n[$e+2])?e+=n[$e++]+n[$e++]+ff(n):/\d/.test(n[$e+1])&&(e+=n[$e++]+ff(n))),Jg(n)){let t=Nd(n);return t==="deg"||t==="rad"||t==="turn"||t==="grad"?{type:_e.Hue,value:e*a6[t]}:void 0}return n[$e]==="%"?($e++,{type:_e.Percentage,value:+e}):{type:_e.Number,value:+e}}function ff(n){let e="";for(;/\d/.test(n[$e]);)e+=n[$e++];return e}function Nd(n){let e="";for(;$e{},Vi=Array.isArray,Nw=/#/g,Wz=/&/g,Xz=/\//g,$z=/=/g,qz=/\?/g,Uw=/\+/g,Yz=/%5B/g,jz=/%5D/g,Fw=/%5E/g,Kz=/%60/g,kw=/%7B/g,Zz=/%7C/g,Bw=/%7D/g,Jz=/%20/g;function H_(n){return encodeURI(""+n).replace(Zz,"|").replace(Yz,"[").replace(jz,"]")}function Qz(n){return H_(n).replace(kw,"{").replace(Bw,"}").replace(Fw,"^")}function Yg(n){return H_(n).replace(Uw,"%2B").replace(Jz,"+").replace(Nw,"%23").replace(Wz,"%26").replace(Kz,"`").replace(kw,"{").replace(Bw,"}").replace(Fw,"^")}function eV(n){return Yg(n).replace($z,"%3D")}function tV(n){return H_(n).replace(Nw,"%23").replace(qz,"%3F")}function nV(n){return n==null?"":tV(n).replace(Xz,"%2F")}function xc(n){try{return decodeURIComponent(""+n)}catch{}return""+n}const iV=/\/$/,sV=n=>n.replace(iV,"");function Sm(n,e,t="/"){let i,s={},r="",o="";const a=e.indexOf("#");let l=e.indexOf("?");return a=0&&(l=-1),l>-1&&(i=e.slice(0,l),r=e.slice(l+1,a>-1?a:e.length),s=n(r)),a>-1&&(i=i||e.slice(0,a),o=e.slice(a,e.length)),i=lV(i??e,t),{fullPath:i+(r&&"?")+r+o,path:i,query:s,hash:xc(o)}}function rV(n,e){const t=e.query?n(e.query):"";return e.path+(t&&"?")+t+(e.hash||"")}function yx(n,e){return!e||!n.toLowerCase().startsWith(e.toLowerCase())?n:n.slice(e.length)||"/"}function oV(n,e,t){const i=e.matched.length-1,s=t.matched.length-1;return i>-1&&i===s&&Ia(e.matched[i],t.matched[s])&&zw(e.params,t.params)&&n(e.query)===n(t.query)&&e.hash===t.hash}function Ia(n,e){return(n.aliasOf||n)===(e.aliasOf||e)}function zw(n,e){if(Object.keys(n).length!==Object.keys(e).length)return!1;for(const t in n)if(!aV(n[t],e[t]))return!1;return!0}function aV(n,e){return Vi(n)?bx(n,e):Vi(e)?bx(e,n):n===e}function bx(n,e){return Vi(e)?n.length===e.length&&n.every((t,i)=>t===e[i]):n.length===1&&n[0]===e}function lV(n,e){if(n.startsWith("/"))return n;if(!n)return e;const t=e.split("/"),i=n.split("/"),s=i[i.length-1];(s===".."||s===".")&&i.push("");let r=t.length-1,o,a;for(o=0;o1&&r--;else break;return t.slice(0,r).join("/")+"/"+i.slice(o).join("/")}const tr={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0};var Mc;(function(n){n.pop="pop",n.push="push"})(Mc||(Mc={}));var Hl;(function(n){n.back="back",n.forward="forward",n.unknown=""})(Hl||(Hl={}));function cV(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),sV(n)}const uV=/^[^#]+#/;function fV(n,e){return n.replace(uV,"#")+e}function dV(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 qh=()=>({left:window.scrollX,top:window.scrollY});function hV(n){let e;if("el"in n){const t=n.el,i=typeof t=="string"&&t.startsWith("#"),s=typeof t=="string"?i?document.getElementById(t.slice(1)):document.querySelector(t):t;if(!s)return;e=dV(s,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 xx(n,e){return(history.state?history.state.position-e:-1)+n}const jg=new Map;function pV(n,e){jg.set(n,e)}function mV(n){const e=jg.get(n);return jg.delete(n),e}let gV=()=>location.protocol+"//"+location.host;function Vw(n,e){const{pathname:t,search:i,hash:s}=e,r=n.indexOf("#");if(r>-1){let a=s.includes(n.slice(r))?n.slice(r).length:1,l=s.slice(a);return l[0]!=="/"&&(l="/"+l),yx(l,"")}return yx(t,n)+i+s}function _V(n,e,t,i){let s=[],r=[],o=null;const a=({state:d})=>{const h=Vw(n,location),p=t.value,_=e.value;let g=0;if(d){if(t.value=h,e.value=d,o&&o===p){o=null;return}g=_?d.position-_.position:0}else i(h);s.forEach(m=>{m(t.value,p,{delta:g,type:Mc.pop,direction:g?g>0?Hl.forward:Hl.back:Hl.unknown})})};function l(){o=t.value}function c(d){s.push(d);const h=()=>{const p=s.indexOf(d);p>-1&&s.splice(p,1)};return r.push(h),h}function u(){const{history:d}=window;d.state&&d.replaceState(Mt({},d.state,{scroll:qh()}),"")}function f(){for(const d of r)d();r=[],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 Mx(n,e,t,i=!1,s=!1){return{back:n,current:e,forward:t,replaced:i,position:window.history.length,scroll:s?qh():null}}function vV(n){const{history:e,location:t}=window,i={value:Vw(n,t)},s={value:e.state};s.value||r(i.value,{back:null,current:i.value,forward:null,position:e.length-1,replaced:!0,scroll:null},!0);function r(l,c,u){const f=n.indexOf("#"),d=f>-1?(t.host&&document.querySelector("base")?n:n.slice(f))+l:gV()+n+l;try{e[u?"replaceState":"pushState"](c,"",d),s.value=c}catch(h){console.error(h),t[u?"replace":"assign"](d)}}function o(l,c){const u=Mt({},e.state,Mx(s.value.back,l,s.value.forward,!0),c,{position:s.value.position});r(l,u,!0),i.value=l}function a(l,c){const u=Mt({},s.value,e.state,{forward:l,scroll:qh()});r(u.current,u,!0);const f=Mt({},Mx(i.value,l,null),{position:u.position+1},c);r(l,f,!1),i.value=l}return{location:i,state:s,push:a,replace:o}}function yV(n){n=cV(n);const e=vV(n),t=_V(n,e.state,e.location,e.replace);function i(r,o=!0){o||t.pauseListeners(),history.go(r)}const s=Mt({location:"",base:n,go:i,createHref:fV.bind(null,n)},e,t);return Object.defineProperty(s,"location",{enumerable:!0,get:()=>e.location.value}),Object.defineProperty(s,"state",{enumerable:!0,get:()=>e.state.value}),s}function bV(n){return n=location.host?n||location.pathname+location.search:"",n.includes("#")||(n+="#"),yV(n)}function xV(n){return typeof n=="string"||n&&typeof n=="object"}function Hw(n){return typeof n=="string"||typeof n=="symbol"}const Gw=Symbol("");var Sx;(function(n){n[n.aborted=4]="aborted",n[n.cancelled=8]="cancelled",n[n.duplicated=16]="duplicated"})(Sx||(Sx={}));function La(n,e){return Mt(new Error,{type:n,[Gw]:!0},e)}function ys(n,e){return n instanceof Error&&Gw in n&&(e==null||!!(n.type&e))}const Ex="[^/]+?",MV={sensitive:!1,strict:!1,start:!0,end:!0},SV=/[.+*?^${}()[\]/\\]/g;function EV(n,e){const t=Mt({},MV,e),i=[];let s=t.start?"^":"";const r=[];for(const c of n){const u=c.length?[]:[90];t.strict&&!c.length&&(s+="/");for(let f=0;fe.length?e.length===1&&e[0]===80?1:-1:0}function Ww(n,e){let t=0;const i=n.score,s=e.score;for(;t0&&e[e.length-1]<0}const wV={type:0,value:""},AV=/[a-zA-Z0-9_]/;function CV(n){if(!n)return[[]];if(n==="/")return[[wV]];if(!n.startsWith("/"))throw new Error(`Invalid path "${n}"`);function e(h){throw new Error(`ERR (${t})/"${c}": ${h}`)}let t=0,i=t;const s=[];let r;function o(){r&&s.push(r),r=[]}let a=0,l,c="",u="";function f(){c&&(t===0?r.push({type:0,value:c}):t===1||t===2||t===3?(r.length>1&&(l==="*"||l==="+")&&e(`A repeatable param (${c}) must be alone in its segment. eg: '/:ids+.`),r.push({type:1,value:c,regexp:u,repeatable:l==="*"||l==="+",optional:l==="*"||l==="?"})):e("Invalid state to consume buffer"),c="")}function d(){c+=l}for(;a{o(b)}:Vl}function o(f){if(Hw(f)){const d=i.get(f);d&&(i.delete(f),t.splice(t.indexOf(d),1),d.children.forEach(o),d.alias.forEach(o))}else{const d=t.indexOf(f);d>-1&&(t.splice(d,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 d=DV(f,t);t.splice(d,0,f),f.record.name&&!Cx(f)&&i.set(f.record.name,f)}function c(f,d){let h,p={},_,g;if("name"in f&&f.name){if(h=i.get(f.name),!h)throw La(1,{location:f});g=h.record.name,p=Mt(wx(d.params,h.keys.filter(b=>!b.optional).concat(h.parent?h.parent.keys.filter(b=>b.optional):[]).map(b=>b.name)),f.params&&wx(f.params,h.keys.map(b=>b.name))),_=h.stringify(p)}else if(f.path!=null)_=f.path,h=t.find(b=>b.re.test(_)),h&&(p=h.parse(_),g=h.record.name);else{if(h=d.name?i.get(d.name):t.find(b=>b.re.test(d.path)),!h)throw La(1,{location:f,currentLocation:d});g=h.record.name,p=Mt({},d.params,f.params),_=h.stringify(p)}const m=[];let y=h;for(;y;)m.unshift(y.record),y=y.parent;return{name:g,path:_,params:p,matched:m,meta:LV(m)}}n.forEach(f=>r(f));function u(){t.length=0,i.clear()}return{addRoute:r,resolve:c,removeRoute:o,clearRoutes:u,getRoutes:a,getRecordMatcher:s}}function wx(n,e){const t={};for(const i of e)i in n&&(t[i]=n[i]);return t}function Ax(n){const e={path:n.path,redirect:n.redirect,name:n.name,meta:n.meta||{},aliasOf:n.aliasOf,beforeEnter:n.beforeEnter,props:IV(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 IV(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 Cx(n){for(;n;){if(n.record.aliasOf)return!0;n=n.parent}return!1}function LV(n){return n.reduce((e,t)=>Mt(e,t.meta),{})}function Rx(n,e){const t={};for(const i in n)t[i]=i in e?e[i]:n[i];return t}function DV(n,e){let t=0,i=e.length;for(;t!==i;){const r=t+i>>1;Ww(n,e[r])<0?i=r:t=r+1}const s=OV(n);return s&&(i=e.lastIndexOf(s,i-1)),i}function OV(n){let e=n;for(;e=e.parent;)if(Xw(e)&&Ww(n,e)===0)return e}function Xw({record:n}){return!!(n.name||n.components&&Object.keys(n.components).length||n.redirect)}function NV(n){const e={};if(n===""||n==="?")return e;const i=(n[0]==="?"?n.slice(1):n).split("&");for(let s=0;sr&&Yg(r)):[i&&Yg(i)]).forEach(r=>{r!==void 0&&(e+=(e.length?"&":"")+t,r!=null&&(e+="="+r))})}return e}function UV(n){const e={};for(const t in n){const i=n[t];i!==void 0&&(e[t]=Vi(i)?i.map(s=>s==null?null:""+s):i==null?i:""+i)}return e}const FV=Symbol(""),Ix=Symbol(""),Yh=Symbol(""),G_=Symbol(""),Kg=Symbol("");function ul(){let n=[];function e(i){return n.push(i),()=>{const s=n.indexOf(i);s>-1&&n.splice(s,1)}}function t(){n=[]}return{add:e,list:()=>n.slice(),reset:t}}function cr(n,e,t,i,s,r=o=>o()){const o=i&&(i.enterCallbacks[s]=i.enterCallbacks[s]||[]);return()=>new Promise((a,l)=>{const c=d=>{d===!1?l(La(4,{from:t,to:e})):d instanceof Error?l(d):xV(d)?l(La(2,{from:e,to:d})):(o&&i.enterCallbacks[s]===o&&typeof d=="function"&&o.push(d),a())},u=r(()=>n.call(i&&i.instances[s],e,t,c));let f=Promise.resolve(u);n.length<3&&(f=f.then(c)),f.catch(d=>l(d))})}function Em(n,e,t,i,s=r=>r()){const r=[];for(const o of n)for(const a in o.components){let l=o.components[a];if(!(e!=="beforeRouteEnter"&&!o.instances[a]))if(Ow(l)){const u=(l.__vccOpts||l)[e];u&&r.push(cr(u,t,i,o,a,s))}else{let c=l();r.push(()=>c.then(u=>{if(!u)throw new Error(`Couldn't resolve component "${a}" at "${o.path}"`);const f=Gz(u)?u.default:u;o.mods[a]=u,o.components[a]=f;const h=(f.__vccOpts||f)[e];return h&&cr(h,t,i,o,a,s)()}))}}return r}function Lx(n){const e=mn(Yh),t=mn(G_),i=Me(()=>{const l=Ot(n.to);return e.resolve(l)}),s=Me(()=>{const{matched:l}=i.value,{length:c}=l,u=l[c-1],f=t.matched;if(!u||!f.length)return-1;const d=f.findIndex(Ia.bind(null,u));if(d>-1)return d;const h=Dx(l[c-2]);return c>1&&Dx(u)===h&&f[f.length-1].path!==h?f.findIndex(Ia.bind(null,l[c-2])):d}),r=Me(()=>s.value>-1&&HV(t.params,i.value.params)),o=Me(()=>s.value>-1&&s.value===t.matched.length-1&&zw(t.params,i.value.params));function a(l={}){if(VV(l)){const c=e[Ot(n.replace)?"replace":"push"](Ot(n.to)).catch(Vl);return n.viewTransition&&typeof document<"u"&&"startViewTransition"in document&&document.startViewTransition(()=>c),c}return Promise.resolve()}return{route:i,href:Me(()=>i.value.href),isActive:r,isExactActive:o,navigate:a}}function kV(n){return n.length===1?n[0]:n}const BV=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"},viewTransition:Boolean},useLink:Lx,setup(n,{slots:e}){const t=xi(Lx(n)),{options:i}=mn(Yh),s=Me(()=>({[Ox(n.activeClass,i.linkActiveClass,"router-link-active")]:t.isActive,[Ox(n.exactActiveClass,i.linkExactActiveClass,"router-link-exact-active")]:t.isExactActive}));return()=>{const r=e.default&&kV(e.default(t));return n.custom?r:Ns("a",{"aria-current":t.isExactActive?n.ariaCurrentValue:null,href:t.href,onClick:t.navigate,class:s.value},r)}}}),zV=BV;function VV(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 HV(n,e){for(const t in e){const i=e[t],s=n[t];if(typeof i=="string"){if(i!==s)return!1}else if(!Vi(s)||s.length!==i.length||i.some((r,o)=>r!==s[o]))return!1}return!0}function Dx(n){return n?n.aliasOf?n.aliasOf.path:n.path:""}const Ox=(n,e,t)=>n??e??t,GV=fn({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(n,{attrs:e,slots:t}){const i=mn(Kg),s=Me(()=>n.route||i.value),r=mn(Ix,0),o=Me(()=>{let c=Ot(r);const{matched:u}=s.value;let f;for(;(f=u[c])&&!f.components;)c++;return c}),a=Me(()=>s.value.matched[o.value]);pr(Ix,Me(()=>o.value+1)),pr(FV,a),pr(Kg,s);const l=et();return Xe(()=>[l.value,a.value,n.name],([c,u,f],[d,h,p])=>{u&&(u.instances[f]=c,h&&h!==u&&c&&c===d&&(u.leaveGuards.size||(u.leaveGuards=h.leaveGuards),u.updateGuards.size||(u.updateGuards=h.updateGuards))),c&&u&&(!h||!Ia(u,h)||!d)&&(u.enterCallbacks[f]||[]).forEach(_=>_(c))},{flush:"post"}),()=>{const c=s.value,u=n.name,f=a.value,d=f&&f.components[u];if(!d)return Nx(t.default,{Component:d,route:c});const h=f.props[u],p=h?h===!0?c.params:typeof h=="function"?h(c):h:null,g=Ns(d,Mt({},p,e,{onVnodeUnmounted:m=>{m.component.isUnmounted&&(f.instances[u]=null)},ref:l}));return Nx(t.default,{Component:g,route:c})||g}}});function Nx(n,e){if(!n)return null;const t=n(e);return t.length===1?t[0]:t}const $w=GV;function WV(n){const e=PV(n.routes,n),t=n.parseQuery||NV,i=n.stringifyQuery||Px,s=n.history,r=ul(),o=ul(),a=ul(),l=Oe(tr);let c=tr;sa&&n.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const u=Mm.bind(null,$=>""+$),f=Mm.bind(null,nV),d=Mm.bind(null,xc);function h($,ae){let le,ce;return Hw($)?(le=e.getRecordMatcher($),ce=ae):ce=$,e.addRoute(ce,le)}function p($){const ae=e.getRecordMatcher($);ae&&e.removeRoute(ae)}function _(){return e.getRoutes().map($=>$.record)}function g($){return!!e.getRecordMatcher($)}function m($,ae){if(ae=Mt({},ae||l.value),typeof $=="string"){const w=Sm(t,$,ae.path),X=e.resolve({path:w.path},ae),G=s.createHref(w.fullPath);return Mt(w,X,{params:d(X.params),hash:xc(w.hash),redirectedFrom:void 0,href:G})}let le;if($.path!=null)le=Mt({},$,{path:Sm(t,$.path,ae.path).path});else{const w=Mt({},$.params);for(const X in w)w[X]==null&&delete w[X];le=Mt({},$,{params:f(w)}),ae.params=f(ae.params)}const ce=e.resolve(le,ae),He=$.hash||"";ce.params=u(d(ce.params));const F=rV(i,Mt({},$,{hash:Qz(He),path:ce.path})),k=s.createHref(F);return Mt({fullPath:F,hash:He,query:i===Px?UV($.query):$.query||{}},ce,{redirectedFrom:void 0,href:k})}function y($){return typeof $=="string"?Sm(t,$,l.value.path):Mt({},$)}function b($,ae){if(c!==$)return La(8,{from:ae,to:$})}function v($){return S($)}function E($){return v(Mt(y($),{replace:!0}))}function T($){const ae=$.matched[$.matched.length-1];if(ae&&ae.redirect){const{redirect:le}=ae;let ce=typeof le=="function"?le($):le;return typeof ce=="string"&&(ce=ce.includes("?")||ce.includes("#")?ce=y(ce):{path:ce},ce.params={}),Mt({query:$.query,hash:$.hash,params:ce.path!=null?{}:$.params},ce)}}function S($,ae){const le=c=m($),ce=l.value,He=$.state,F=$.force,k=$.replace===!0,w=T(le);if(w)return S(Mt(y(w),{state:typeof w=="object"?Mt({},He,w.state):He,force:F,replace:k}),ae||le);const X=le;X.redirectedFrom=ae;let G;return!F&&oV(i,ce,le)&&(G=La(16,{to:X,from:ce}),se(ce,ce,!0,!1)),(G?Promise.resolve(G):M(X,ce)).catch(W=>ys(W)?ys(W,2)?W:be(W):J(W,X,ce)).then(W=>{if(W){if(ys(W,2))return S(Mt({replace:k},y(W.to),{state:typeof W.to=="object"?Mt({},He,W.to.state):He,force:F}),ae||X)}else W=N(X,ce,!0,k,He);return I(X,ce,W),W})}function P($,ae){const le=b($,ae);return le?Promise.reject(le):Promise.resolve()}function x($){const ae=re.values().next().value;return ae&&typeof ae.runWithContext=="function"?ae.runWithContext($):$()}function M($,ae){let le;const[ce,He,F]=XV($,ae);le=Em(ce.reverse(),"beforeRouteLeave",$,ae);for(const w of ce)w.leaveGuards.forEach(X=>{le.push(cr(X,$,ae))});const k=P.bind(null,$,ae);return le.push(k),xe(le).then(()=>{le=[];for(const w of r.list())le.push(cr(w,$,ae));return le.push(k),xe(le)}).then(()=>{le=Em(He,"beforeRouteUpdate",$,ae);for(const w of He)w.updateGuards.forEach(X=>{le.push(cr(X,$,ae))});return le.push(k),xe(le)}).then(()=>{le=[];for(const w of F)if(w.beforeEnter)if(Vi(w.beforeEnter))for(const X of w.beforeEnter)le.push(cr(X,$,ae));else le.push(cr(w.beforeEnter,$,ae));return le.push(k),xe(le)}).then(()=>($.matched.forEach(w=>w.enterCallbacks={}),le=Em(F,"beforeRouteEnter",$,ae,x),le.push(k),xe(le))).then(()=>{le=[];for(const w of o.list())le.push(cr(w,$,ae));return le.push(k),xe(le)}).catch(w=>ys(w,8)?w:Promise.reject(w))}function I($,ae,le){a.list().forEach(ce=>x(()=>ce($,ae,le)))}function N($,ae,le,ce,He){const F=b($,ae);if(F)return F;const k=ae===tr,w=sa?history.state:{};le&&(ce||k?s.replace($.fullPath,Mt({scroll:k&&w&&w.scroll},He)):s.push($.fullPath,He)),l.value=$,se($,ae,le,k),be()}let V;function j(){V||(V=s.listen(($,ae,le)=>{if(!ge.listening)return;const ce=m($),He=T(ce);if(He){S(Mt(He,{replace:!0,force:!0}),ce).catch(Vl);return}c=ce;const F=l.value;sa&&pV(xx(F.fullPath,le.delta),qh()),M(ce,F).catch(k=>ys(k,12)?k:ys(k,2)?(S(Mt(y(k.to),{force:!0}),ce).then(w=>{ys(w,20)&&!le.delta&&le.type===Mc.pop&&s.go(-1,!1)}).catch(Vl),Promise.reject()):(le.delta&&s.go(-le.delta,!1),J(k,ce,F))).then(k=>{k=k||N(ce,F,!1),k&&(le.delta&&!ys(k,8)?s.go(-le.delta,!1):le.type===Mc.pop&&ys(k,20)&&s.go(-1,!1)),I(ce,F,k)}).catch(Vl)}))}let te=ul(),Z=ul(),ee;function J($,ae,le){be($);const ce=Z.list();return ce.length?ce.forEach(He=>He($,ae,le)):console.error($),Promise.reject($)}function he(){return ee&&l.value!==tr?Promise.resolve():new Promise(($,ae)=>{te.add([$,ae])})}function be($){return ee||(ee=!$,j(),te.list().forEach(([ae,le])=>$?le($):ae()),te.reset()),$}function se($,ae,le,ce){const{scrollBehavior:He}=n;if(!sa||!He)return Promise.resolve();const F=!le&&mV(xx($.fullPath,0))||(ce||!le)&&history.state&&history.state.scroll||null;return wr().then(()=>He($,ae,F)).then(k=>k&&hV(k)).catch(k=>J(k,$,ae))}const ye=$=>s.go($);let Be;const re=new Set,ge={currentRoute:l,listening:!0,addRoute:h,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:r.add,beforeResolve:o.add,afterEach:a.add,onError:Z.add,isReady:he,install($){const ae=this;$.component("RouterLink",zV),$.component("RouterView",$w),$.config.globalProperties.$router=ae,Object.defineProperty($.config.globalProperties,"$route",{enumerable:!0,get:()=>Ot(l)}),sa&&!Be&&l.value===tr&&(Be=!0,v(s.location).catch(He=>{}));const le={};for(const He in tr)Object.defineProperty(le,He,{get:()=>l.value[He],enumerable:!0});$.provide(Yh,ae),$.provide(G_,lS(le)),$.provide(Kg,l);const ce=$.unmount;re.add($),$.unmount=function(){re.delete($),re.size<1&&(c=tr,V&&V(),V=null,l.value=tr,Be=!1,ee=!1),ce()}}};function xe($){return $.reduce((ae,le)=>ae.then(()=>x(le)),Promise.resolve())}return ge}function XV(n,e){const t=[],i=[],s=[],r=Math.max(e.matched.length,n.matched.length);for(let o=0;oIa(c,a))?i.push(a):t.push(a));const l=n.matched[o];l&&(e.matched.find(c=>Ia(c,l))||s.push(l))}return[t,i,s]}function $V(){return mn(Yh)}function FG(n){return mn(G_)}const qV=[{path:"/",name:"/",component:()=>je(()=>import("./index-BvSR0QFl.js"),__vite__mapDeps([14,4,5,6,7,8,11,12,13,15,16,17,10,9,18,19,20,21,22,23,24,25,1,2,26,27,28,29])),meta:{layout:"stage",stageTransition:{name:"bubble-wave-out"}}},{path:"/:all(.*)",name:"/[...all]",component:()=>je(()=>import("./_...all_-P27fyW0_.js"),[])},{path:"/audio",name:"/audio",component:()=>je(()=>import("./audio-xRnZtF8v.js"),[])},{path:"/devtools",children:[{path:"background-remove",name:"/devtools/background-remove",component:()=>je(()=>import("./background-remove-BBGqlHWm.js"),__vite__mapDeps([30,11,12,13,31]))},{path:"chat",name:"/devtools/chat",component:()=>je(()=>import("./chat-C6ApJPfV.js"),__vite__mapDeps([32,20,10]))},{path:"image",name:"/devtools/image",component:()=>je(()=>import("./image-DmDCtZow.js"),__vite__mapDeps([33,34]))},{path:"vibrant",name:"/devtools/vibrant",component:()=>je(()=>import("./vibrant-DQTTh5Yn.js"),__vite__mapDeps([35,11,12,13,31,36]))}]},{path:"/queue",name:"/queue",component:()=>je(()=>import("./queue-C9PyLN3M.js"),__vite__mapDeps([37,18]))},{path:"/settings",children:[{path:"",name:"/settings/",component:()=>je(()=>import("./index-BWM8H6v1.js"),__vite__mapDeps([38,4,5,6,7,8,11,12,13,39,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"airi-card",children:[{path:"",name:"/settings/airi-card/",component:()=>je(()=>import("./index-BsTlOxC-.js"),__vite__mapDeps([40,7,21,8,22,9,10,17,11,12,13,31,41,42,43,4,5,6,44,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"components",children:[{path:"CardDetailDialog",name:"/settings/airi-card/components/CardDetailDialog",component:()=>je(()=>import("./CardDetailDialog-DUkJNKcl.js"),__vite__mapDeps([45,41,42,43,12,4,5,6,7,21,8,22,9,10,17,11,13]))},{path:"CardListItem",name:"/settings/airi-card/components/CardListItem",component:()=>je(()=>import("./CardListItem-Bcpy7sq6.js"),__vite__mapDeps([46,44,4,5,6,7,8,11,12,13]))},{path:"DeleteCardDialog",name:"/settings/airi-card/components/DeleteCardDialog",component:()=>je(()=>import("./DeleteCardDialog-BgA6bpCe.js"),__vite__mapDeps([47,42,43,12]))}]}]},{path:"appearance",children:[{path:"",name:"/settings/appearance/",component:()=>je(()=>import("./index-fbmB4MjP.js"),__vite__mapDeps([48,4,5,6,7,8,11,12,13,49,25,23,43,28,50])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"memory",children:[{path:"",name:"/settings/memory/",component:()=>je(()=>import("./index-Ep8bbMjW.js"),__vite__mapDeps([51,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}}]},{path:"models",children:[{path:"",name:"/settings/models/",component:()=>je(()=>import("./index-DCkir7nL.js"),__vite__mapDeps([52,39,4,5,24,6,7,8,11,12,13,36,49,25,23,43,53,28,54])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]},{path:"modules",children:[{path:"",name:"/settings/modules/",component:()=>je(()=>import("./index-RQ48LviH.js"),__vite__mapDeps([55,4,5,6,7,8,56,11,12,13,39,53,28])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"consciousness",name:"/settings/modules/consciousness",component:()=>je(()=>import("./consciousness-CS4IBC4q.js"),__vite__mapDeps([57,4,5,6,7,8,22,9,10,11,12,13,58,23,59,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"memory-long-term",name:"/settings/modules/memory-long-term",component:()=>je(()=>import("./memory-long-term-B-ZAjue9.js"),__vite__mapDeps([60,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"memory-short-term",name:"/settings/modules/memory-short-term",component:()=>je(()=>import("./memory-short-term-BPGQesh6.js"),__vite__mapDeps([61,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"speech",name:"/settings/modules/speech",component:()=>je(()=>import("./speech-Cqx5-wPK.js"),__vite__mapDeps([62,63,4,5,11,12,13,6,7,8,9,10,17,64,59,65,27,58,23,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}}]},{path:"providers",children:[{path:"",name:"/settings/providers/",component:()=>je(()=>import("./index-DhNz88Xj.js"),__vite__mapDeps([66,39,4,5,6,7,8,9,10,56,11,12,13,53,28])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}},{path:"alibaba-cloud-model-studio",name:"/settings/providers/alibaba-cloud-model-studio",component:()=>je(()=>import("./alibaba-cloud-model-studio-BjeIv5w8.js"),__vite__mapDeps([67,4,5,6,7,8,9,10,17,63,11,12,13,68,69,25,23,64,59,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"anthropic",name:"/settings/providers/anthropic",component:()=>je(()=>import("./anthropic-2GUn5SX-.js"),__vite__mapDeps([72,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"cloudflare-workers-ai",name:"/settings/providers/cloudflare-workers-ai",component:()=>je(()=>import("./cloudflare-workers-ai-CmLRkAJ-.js"),__vite__mapDeps([74,4,5,6,7,8,9,10,11,12,13,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"deepseek",name:"/settings/providers/deepseek",component:()=>je(()=>import("./deepseek-Dhr9828c.js"),__vite__mapDeps([75,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"elevenlabs",name:"/settings/providers/elevenlabs",component:()=>je(()=>import("./elevenlabs-CtF3mm-w.js"),__vite__mapDeps([76,4,5,6,7,8,9,10,17,63,11,12,13,68,69,25,23,64,59,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"featherless-ai",name:"/settings/providers/featherless-ai",component:()=>je(()=>import("./featherless-ai-8Fh6lUDA.js"),__vite__mapDeps([77,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"fireworks-ai",name:"/settings/providers/fireworks-ai",component:()=>je(()=>import("./fireworks-ai-Dd6lQOw3.js"),__vite__mapDeps([78,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"google-generative-ai",name:"/settings/providers/google-generative-ai",component:()=>je(()=>import("./google-generative-ai-Cst0rdKi.js"),__vite__mapDeps([79,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"microsoft-speech",name:"/settings/providers/microsoft-speech",component:()=>je(()=>import("./microsoft-speech-B1rDo1CL.js"),__vite__mapDeps([80,4,5,6,7,8,9,10,17,64,59,63,11,12,13,68,69,25,23,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"mistral-ai",name:"/settings/providers/mistral-ai",component:()=>je(()=>import("./mistral-ai-CCjWqN_I.js"),__vite__mapDeps([81,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"moonshot-ai",name:"/settings/providers/moonshot-ai",component:()=>je(()=>import("./moonshot-ai-Og7KMbxi.js"),__vite__mapDeps([82,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"novita-ai",name:"/settings/providers/novita-ai",component:()=>je(()=>import("./novita-ai-BiraQuur.js"),__vite__mapDeps([83,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"ollama",name:"/settings/providers/ollama",component:()=>je(()=>import("./ollama-Bin1uANJ.js"),__vite__mapDeps([84,4,5,6,7,8,9,10,59,11,12,13,69,25,23,64,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"openai",name:"/settings/providers/openai",component:()=>je(()=>import("./openai-BPj3vm_3.js"),__vite__mapDeps([85,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"openrouter-ai",name:"/settings/providers/openrouter-ai",component:()=>je(()=>import("./openrouter-ai-WP7_lFby.js"),__vite__mapDeps([86,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"together-ai",name:"/settings/providers/together-ai",component:()=>je(()=>import("./together-ai-CxZKBPZ7.js"),__vite__mapDeps([87,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"volcengine",name:"/settings/providers/volcengine",component:()=>je(()=>import("./volcengine-C-Sx5RRX.js"),__vite__mapDeps([88,4,5,6,7,8,9,10,17,64,59,63,11,12,13,68,69,25,23,70,71,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}},{path:"xai",name:"/settings/providers/xai",component:()=>je(()=>import("./xai-CEcx0MIE.js"),__vite__mapDeps([89,4,5,6,7,8,9,10,11,12,13,69,25,23,64,59,70,71,73,28])),meta:{layout:"settings",stageTransition:{name:"slide"}}}]},{path:"scene",children:[{path:"",name:"/settings/scene/",component:()=>je(()=>import("./index-DnVVffQQ.js"),__vite__mapDeps([90,39,53,7,8,28])),meta:{layout:"settings",stageTransition:{name:"slide",pageSpecificAvailable:!0}}}]}]},{path:"/test",children:[{path:"filter-message",name:"/test/filter-message",component:()=>je(()=>import("./filter-message-DJVIgF-Z.js"),__vite__mapDeps([91,11,12,13,65,27]))},{path:"queues",children:[{path:"delays",name:"/test/queues/delays",component:()=>je(()=>import("./delays-DJLByMTi.js"),__vite__mapDeps([92,26,19,8,18,6,11,12,13,65,27]))},{path:"emotions",name:"/test/queues/emotions",component:()=>je(()=>import("./emotions-COZF15gE.js"),__vite__mapDeps([93,18,19,8,11,12,13,65,27]))},{path:"messages",name:"/test/queues/messages",component:()=>je(()=>import("./messages-CNwMKqXh.js"),__vite__mapDeps([94,18,19,8,11,12,13,65,27]))}]}]}],qw=(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}}},YV={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},jV=n=>qw(YV[n.toLowerCase()],6),KV=/^#?([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})$/i,ZV=n=>{let e;return(e=n.match(KV))?qw(parseInt(e[1],16),e[1].length):void 0},mr="([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)",Gl=`${mr}%`,W_=`(?:${mr}%|${mr})`,JV=`(?:${mr}(deg|grad|rad|turn)|${mr})`,Da="\\s*,\\s*",QV=new RegExp(`^rgba?\\(\\s*${mr}${Da}${mr}${Da}${mr}\\s*(?:,\\s*${W_}\\s*)?\\)$`),e6=new RegExp(`^rgba?\\(\\s*${Gl}${Da}${Gl}${Da}${Gl}\\s*(?:,\\s*${W_}\\s*)?\\)$`),t6=n=>{let e={mode:"rgb"},t;if(t=n.match(QV))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(e6))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},n6=(n,e)=>n===void 0?void 0:typeof n!="object"?d6(n):n.mode!==void 0?n:e?{...n,mode:e}:void 0,Yw=(n="rgb")=>e=>(e=n6(e,n))!==void 0?e.mode===n?e:Ji[e.mode][n]?Ji[e.mode][n](e):n==="rgb"?Ji[e.mode].rgb(e):Ji.rgb[n](Ji[e.mode].rgb(e)):void 0,Ji={},jw={},Od=[],Kw={},i6=n=>n,Et=n=>(Ji[n.mode]={...Ji[n.mode],...n.toMode},Object.keys(n.fromMode||{}).forEach(e=>{Ji[e]||(Ji[e]={}),Ji[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=i6)}),jw[n.mode]=n,(n.parse||[]).forEach(e=>{r6(e,n.mode)}),Yw(n.mode)),s6=n=>jw[n],r6=(n,e)=>{if(typeof n=="string"){if(!e)throw new Error("'mode' required when 'parser' is a string");Kw[n]=e}else typeof n=="function"&&Od.indexOf(n)<0&&Od.push(n)},Zg=/[^\x00-\x7F]|[a-zA-Z_]/,o6=/[^\x00-\x7F]|[-\w]/,_e={Function:"function",Ident:"ident",Number:"number",Percentage:"percentage",ParenClose:")",None:"none",Hue:"hue",Alpha:"alpha"};let $e=0;function uf(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 Jg(n){if($e>=n.length)return!1;let e=n[$e];if(Zg.test(e))return!0;if(e==="-"){if(n.length-$e<2)return!1;let t=n[$e+1];return!!(t==="-"||Zg.test(t))}return!1}const a6={deg:1,rad:180/Math.PI,grad:9/10,turn:360};function fl(n){let e="";if((n[$e]==="-"||n[$e]==="+")&&(e+=n[$e++]),e+=ff(n),n[$e]==="."&&/\d/.test(n[$e+1])&&(e+=n[$e++]+ff(n)),(n[$e]==="e"||n[$e]==="E")&&((n[$e+1]==="-"||n[$e+1]==="+")&&/\d/.test(n[$e+2])?e+=n[$e++]+n[$e++]+ff(n):/\d/.test(n[$e+1])&&(e+=n[$e++]+ff(n))),Jg(n)){let t=Nd(n);return t==="deg"||t==="rad"||t==="turn"||t==="grad"?{type:_e.Hue,value:e*a6[t]}:void 0}return n[$e]==="%"?($e++,{type:_e.Percentage,value:+e}):{type:_e.Number,value:+e}}function ff(n){let e="";for(;/\d/.test(n[$e]);)e+=n[$e++];return e}function Nd(n){let e="";for(;$e4)){if(t.length===4){if(t[3].type!==_e.Alpha)return;t[3]=t[3].value}return t.length===3&&t.push({type:_e.None,value:void 0}),t.every(s=>s.type!==_e.Alpha)?t:void 0}}function f6(n,e){n._i=0;let t=n[n._i++];if(!t||t.type!==_e.Function)return;let i=Zw(n,e);if(i)return i.unshift(t.value),i}const d6=n=>{if(typeof n!="string")return;const e=c6(n),t=e?f6(e,!0):void 0;let i,s=0,r=Od.length;for(;sn==="transparent"?{mode:"rgb",r:0,g:0,b:0,alpha:0}:void 0,m6=(n,e,t)=>n+t*(e-n),g6=n=>{let e=[];for(let t=0;te=>{let t=g6(e);return i=>{let s=i*t.length,r=i>=1?t.length-1:Math.max(Math.floor(s),0),o=t[r];return o===void 0?void 0:n(o[0],o[1],s-r)}},we=_6(m6),on=n=>{let e=!1,t=n.map(i=>i!==void 0?(e=!0,i):1);return e?t:n},Wa={mode:"rgb",channels:["r","g","b","alpha"],parse:[h6,ZV,t6,jV,p6,"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}},Tm=(n=0)=>Math.pow(Math.abs(n),563/256)*Math.sign(n),Ux=n=>{let e=Tm(n.r),t=Tm(n.g),i=Tm(n.b),s={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&&(s.alpha=n.alpha),s},wm=n=>Math.pow(Math.abs(n),256/563)*Math.sign(n),Fx=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s={mode:"a98",r:wm(n*2.0415879038107465-e*.5650069742788597-.3447313507783297*t),g:wm(n*-.9692436362808798+e*1.8759675015077206+.0415550574071756*t),b:wm(n*.0134442806320312-e*.1183623922310184+1.0151749943912058*t)};return i!==void 0&&(s.alpha=i),s},Am=(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)},Xa=({r:n,g:e,b:t,alpha:i})=>{let s={mode:"lrgb",r:Am(n),g:Am(e),b:Am(t)};return i!==void 0&&(s.alpha=i),s},Do=n=>{let{r:e,g:t,b:i,alpha:s}=Xa(n),r={mode:"xyz65",x:.4123907992659593*e+.357584339383878*t+.1804807884018343*i,y:.2126390058715102*e+.715168678767756*t+.0721923153607337*i,z:.0193308187155918*e+.119194779794626*t+.9505321522496607*i};return s!==void 0&&(r.alpha=s),r},Cm=(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},$a=({r:n,g:e,b:t,alpha:i},s="rgb")=>{let r={mode:s,r:Cm(n),g:Cm(e),b:Cm(t)};return i!==void 0&&(r.alpha=i),r},Oo=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=$a({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&&(s.alpha=i),s},v6={...Wa,mode:"a98",parse:["a98-rgb"],serialize:"a98-rgb",fromMode:{rgb:n=>Fx(Do(n)),xyz65:Fx},toMode:{rgb:n=>Oo(Ux(n)),xyz65:Ux}},yn=n=>(n=n%360)<0?n+360:n,y6=(n,e)=>n.map((t,i,s)=>{if(t===void 0)return t;let r=yn(t);return i===0||n[i-1]===void 0?r:e(r-yn(s[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),[]),Xs=n=>y6(n,e=>Math.abs(e)<=180?e:e-360*Math.sign(e)),ln=[-.14861,1.78277,-.29227,-.90649,1.97294,0],b6=Math.PI/180,x6=180/Math.PI;let kx=ln[3]*ln[4],Bx=ln[1]*ln[4],zx=ln[1]*ln[2]-ln[0]*ln[3];const M6=({r:n,g:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=(zx*t+n*kx-e*Bx)/(zx+kx-Bx),r=t-s,o=(ln[4]*(e-s)-ln[2]*r)/ln[3],a={mode:"cubehelix",l:s,s:s===0||s===1?void 0:Math.sqrt(r*r+o*o)/(ln[4]*s*(1-s))};return a.s&&(a.h=Math.atan2(o,r)*x6-120),i!==void 0&&(a.alpha=i),a},S6=({h:n,s:e,l:t,alpha:i})=>{let s={mode:"rgb"};n=(n===void 0?0:n+120)*b6,t===void 0&&(t=0);let r=e===void 0?0:e*t*(1-t),o=Math.cos(n),a=Math.sin(n);return s.r=t+r*(ln[0]*o+ln[1]*a),s.g=t+r*(ln[2]*o+ln[3]*a),s.b=t+r*(ln[4]*o+ln[5]*a),i!==void 0&&(s.alpha=i),s},jh=(n,e)=>{if(n.h===void 0||e.h===void 0||!n.s||!e.s)return 0;let t=yn(n.h),i=yn(e.h),s=Math.sin((i-t+360)/2*Math.PI/180);return 2*Math.sqrt(n.s*e.s)*s},E6=(n,e)=>{if(n.h===void 0||e.h===void 0)return 0;let t=yn(n.h),i=yn(e.h);return Math.abs(i-t)>180?t-(i-360*Math.sign(i-t)):i-t},Kh=(n,e)=>{if(n.h===void 0||e.h===void 0||!n.c||!e.c)return 0;let t=yn(n.h),i=yn(e.h),s=Math.sin((i-t+360)/2*Math.PI/180);return 2*Math.sqrt(n.c*e.c)*s},$s=n=>{let e=n.reduce((i,s)=>{if(s!==void 0){let r=s*Math.PI/180;i.sin+=Math.sin(r),i.cos+=Math.cos(r)}return i},{sin:0,cos:0}),t=Math.atan2(e.sin,e.cos)*180/Math.PI;return t<0?360+t:t},T6={mode:"cubehelix",channels:["h","s","l","alpha"],parse:["--cubehelix"],serialize:"--cubehelix",ranges:{h:[0,360],s:[0,4.614],l:[0,1]},fromMode:{rgb:M6},toMode:{rgb:S6},interpolate:{h:{use:we,fixup:Xs},s:we,l:we,alpha:{use:we,fixup:on}},difference:{h:jh},average:{h:$s}},Mr=({l:n,a:e,b:t,alpha:i},s="lch")=>{e===void 0&&(e=0),t===void 0&&(t=0);let r=Math.sqrt(e*e+t*t),o={mode:s,l:n,c:r};return r&&(o.h=yn(Math.atan2(t,e)*180/Math.PI)),i!==void 0&&(o.alpha=i),o},Sr=({l:n,c:e,h:t,alpha:i},s="lab")=>{t===void 0&&(t=0);let r={mode:s,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&&(r.alpha=i),r},Jw=Math.pow(29,3)/Math.pow(3,3),Qw=Math.pow(6,3)/Math.pow(29,3),Jt={X:.3457/.3585,Y:1,Z:(1-.3457-.3585)/.3585},_a={X:.3127/.329,Y:1,Z:(1-.3127-.329)/.329};let Rm=n=>Math.pow(n,3)>Qw?Math.pow(n,3):(116*n-16)/Jw;const eA=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=(n+16)/116,r=e/500+s,o=s-t/200,a={mode:"xyz65",x:Rm(r)*_a.X,y:Rm(s)*_a.Y,z:Rm(o)*_a.Z};return i!==void 0&&(a.alpha=i),a},Zh=n=>Oo(eA(n)),Pm=n=>n>Qw?Math.cbrt(n):(Jw*n+16)/116,tA=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Pm(n/_a.X),r=Pm(e/_a.Y),o=Pm(t/_a.Z),a={mode:"lab65",l:116*r-16,a:500*(s-r),b:200*(r-o)};return i!==void 0&&(a.alpha=i),a},Jh=n=>{let e=tA(Do(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e},Ud=1,nA=1,Sc=26/180*Math.PI,Fd=Math.cos(Sc),kd=Math.sin(Sc),iA=100/Math.log(139/100),Qg=({l:n,c:e,h:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s={mode:"lab65",l:(Math.exp(n*Ud/iA)-1)/.0039},r=(Math.exp(.0435*e*nA*Ud)-1)/.075,o=r*Math.cos(t/180*Math.PI-Sc),a=r*Math.sin(t/180*Math.PI-Sc);return s.a=o*Fd-a/.83*kd,s.b=o*kd+a/.83*Fd,i!==void 0&&(s.alpha=i),s},e0=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=e*Fd+t*kd,r=.83*(t*Fd-e*kd),o=Math.sqrt(s*s+r*r),a={mode:"dlch",l:iA/Ud*Math.log(1+.0039*n),c:Math.log(1+.075*o)/(.0435*nA*Ud)};return a.c&&(a.h=yn((Math.atan2(r,s)+Sc)/Math.PI*180)),i!==void 0&&(a.alpha=i),a},Vx=n=>Qg(Mr(n,"dlch")),Hx=n=>Sr(e0(n),"dlab"),w6={mode:"dlab",parse:["--din99o-lab"],serialize:"--din99o-lab",toMode:{lab65:Vx,rgb:n=>Zh(Vx(n))},fromMode:{lab65:Hx,rgb:n=>Hx(Jh(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}}},A6={mode:"dlch",parse:["--din99o-lch"],serialize:"--din99o-lch",toMode:{lab65:Qg,dlab:n=>Sr(n,"dlab"),rgb:n=>Zh(Qg(n))},fromMode:{lab65:e0,dlab:n=>Mr(n,"dlch"),rgb:n=>e0(Jh(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:Xs},alpha:{use:we,fixup:on}},difference:{h:Kh},average:{h:$s}};function C6({h:n,s:e,i:t,alpha:i}){n=yn(n!==void 0?n:0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.abs(n/60%2-1),r;switch(Math.floor(n/60)){case 0:r={r:t*(1+e*(3/(2-s)-1)),g:t*(1+e*(3*(1-s)/(2-s)-1)),b:t*(1-e)};break;case 1:r={r:t*(1+e*(3*(1-s)/(2-s)-1)),g:t*(1+e*(3/(2-s)-1)),b:t*(1-e)};break;case 2:r={r:t*(1-e),g:t*(1+e*(3/(2-s)-1)),b:t*(1+e*(3*(1-s)/(2-s)-1))};break;case 3:r={r:t*(1-e),g:t*(1+e*(3*(1-s)/(2-s)-1)),b:t*(1+e*(3/(2-s)-1))};break;case 4:r={r:t*(1+e*(3*(1-s)/(2-s)-1)),g:t*(1-e),b:t*(1+e*(3/(2-s)-1))};break;case 5:r={r:t*(1+e*(3/(2-s)-1)),g:t*(1-e),b:t*(1+e*(3*(1-s)/(2-s)-1))};break;default:r={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return r.mode="rgb",i!==void 0&&(r.alpha=i),r}function R6({r:n,g:e,b:t,alpha:i}){n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.max(n,e,t),r=Math.min(n,e,t),o={mode:"hsi",s:n+e+t===0?0:1-3*r/(n+e+t),i:(n+e+t)/3};return s-r!==0&&(o.h=(s===n?(e-t)/(s-r)+(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}},O6=new RegExp(`^hsla?\\(\\s*${JV}${Da}${Gl}${Da}${Gl}\\s*(?:,\\s*${W_}\\s*)?\\)$`),N6=n=>{let e=n.match(O6);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=D6(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 U6(n,e){if(!e||e[0]!=="hsl"&&e[0]!=="hsla")return;const t={mode:"hsl"},[,i,s,r,o]=e;if(i.type!==_e.None){if(i.type===_e.Percentage)return;t.h=i.value}if(s.type!==_e.None){if(s.type===_e.Hue)return;t.s=s.value/100}if(r.type!==_e.None){if(r.type===_e.Hue)return;t.l=r.value/100}return o.type!==_e.None&&(t.alpha=Math.min(1,Math.max(0,o.type===_e.Number?o.value:o.value/100))),t}const sA={mode:"hsl",toMode:{rgb:I6},fromMode:{rgb:L6},channels:["h","s","l","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[U6,N6],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:Xs},s:we,l:we,alpha:{use:we,fixup:on}},difference:{h:jh},average:{h:$s}};function rA({h:n,s:e,v:t,alpha:i}){n=yn(n!==void 0?n:0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.abs(n/60%2-1),r;switch(Math.floor(n/60)){case 0:r={r:t,g:t*(1-e*s),b:t*(1-e)};break;case 1:r={r:t*(1-e*s),g:t,b:t*(1-e)};break;case 2:r={r:t*(1-e),g:t,b:t*(1-e*s)};break;case 3:r={r:t*(1-e),g:t*(1-e*s),b:t};break;case 4:r={r:t*(1-e*s),g:t*(1-e),b:t};break;case 5:r={r:t,g:t*(1-e),b:t*(1-e*s)};break;default:r={r:t*(1-e),g:t*(1-e),b:t*(1-e)}}return r.mode="rgb",i!==void 0&&(r.alpha=i),r}function oA({r:n,g:e,b:t,alpha:i}){n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.max(n,e,t),r=Math.min(n,e,t),o={mode:"hsv",s:s===0?0:1-r/s,v:s};return s-r!==0&&(o.h=(s===n?(e-t)/(s-r)+(e1){let s=e+t;e/=s,t/=s}return rA({h:n,s:t===1?1:1-e/(1-t),v:1-t,alpha:i})}function k6(n){let e=oA(n);if(e===void 0)return;let t=e.s!==void 0?e.s:0,i=e.v!==void 0?e.v:0,s={mode:"hwb",w:(1-t)*i,b:1-i};return e.h!==void 0&&(s.h=e.h),e.alpha!==void 0&&(s.alpha=e.alpha),s}function B6(n,e){if(!e||e[0]!=="hwb")return;const t={mode:"hwb"},[,i,s,r,o]=e;if(i.type!==_e.None){if(i.type===_e.Percentage)return;t.h=i.value}if(s.type!==_e.None){if(s.type===_e.Hue)return;t.w=s.value/100}if(r.type!==_e.None){if(r.type===_e.Hue)return;t.b=r.value/100}return o.type!==_e.None&&(t.alpha=Math.min(1,Math.max(0,o.type===_e.Number?o.value:o.value/100))),t}const z6={mode:"hwb",toMode:{rgb:F6},fromMode:{rgb:k6},channels:["h","w","b","alpha"],ranges:{h:[0,360]},gamut:"rgb",parse:[B6],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:Xs},w:we,b:we,alpha:{use:we,fixup:on}},difference:{h:E6},average:{h:$s}},lA=203,Qh=.1593017578125,cA=78.84375,ep=.8359375,tp=18.8515625,np=18.6875;function Im(n){if(n<0)return 0;const e=Math.pow(n,1/cA);return 1e4*Math.pow(Math.max(0,e-ep)/(tp-np*e),1/Qh)}function Lm(n){if(n<0)return 0;const e=Math.pow(n/1e4,Qh);return Math.pow((ep+tp*e)/(1+np*e),cA)}const Dm=n=>Math.max(n/lA,0),Gx=({i:n,t:e,p:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const s=Im(n+.008609037037932761*e+.11102962500302593*t),r=Im(n-.00860903703793275*e-.11102962500302599*t),o=Im(n+.5600313357106791*e-.32062717498731885*t),a={mode:"xyz65",x:Dm(2.070152218389422*s-1.3263473389671556*r+.2066510476294051*o),y:Dm(.3647385209748074*s+.680566024947227*r-.0453045459220346*o),z:Dm(-.049747207535812*s-.0492609666966138*r+1.1880659249923042*o)};return i!==void 0&&(a.alpha=i),a},Om=(n=0)=>Math.max(n*lA,0),Wx=({x:n,y:e,z:t,alpha:i})=>{const s=Om(n),r=Om(e),o=Om(t),a=Lm(.3592832590121217*s+.6976051147779502*r-.0358915932320289*o),l=Lm(-.1920808463704995*s+1.1004767970374323*r+.0753748658519118*o),c=Lm(.0070797844607477*s+.0748396662186366*r+.8433265453898765*o),u=.5*a+.5*l,f=1.61376953125*a-3.323486328125*l+1.709716796875*c,d=4.378173828125*a-4.24560546875*l-.132568359375*c,h={mode:"itp",i:u,t:f,p:d};return i!==void 0&&(h.alpha=i),h},V6={mode:"itp",channels:["i","t","p","alpha"],parse:["--ictcp"],serialize:"--ictcp",toMode:{xyz65:Gx,rgb:n=>Oo(Gx(n))},fromMode:{xyz65:Wx,rgb:n=>Wx(Do(n))},ranges:{i:[0,.581],t:[-.369,.272],p:[-.164,.331]},interpolate:{i:we,t:we,p:we,alpha:{use:we,fixup:on}}},H6=134.03437499999998,G6=16295499532821565e-27,Nm=n=>{if(n<0)return 0;let e=Math.pow(n/1e4,Qh);return Math.pow((ep+tp*e)/(1+np*e),H6)},Um=(n=0)=>Math.max(n*203,0),uA=({x:n,y:e,z:t,alpha:i})=>{n=Um(n),e=Um(e),t=Um(t);let s=1.15*n-.15*t,r=.66*e+.34*n,o=Nm(.41478972*s+.579999*r+.014648*t),a=Nm(-.20151*s+1.120649*r+.0531008*t),l=Nm(-.0166008*s+.2648*r+.6684799*t),c=(o+a)/2,u={mode:"jab",j:.44*c/(1-.56*c)-G6,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},W6=134.03437499999998,Xx=16295499532821565e-27,Fm=n=>{if(n<0)return 0;let e=Math.pow(n,1/W6);return 1e4*Math.pow((ep-e)/(np*e-tp),1/Qh)},km=n=>n/203,fA=({j:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=(n+Xx)/(.44+.56*(n+Xx)),r=Fm(s+.13860504*e+.058047316*t),o=Fm(s-.13860504*e-.058047316*t),a=Fm(s-.096019242*e-.8118919*t),l={mode:"xyz65",x:km(1.661373024652174*r-.914523081304348*o+.23136208173913045*a),y:km(-.3250758611844533*r+1.571847026732543*o-.21825383453227928*a),z:km(-.090982811*r-.31272829*o+1.5227666*a)};return i!==void 0&&(l.alpha=i),l},dA=n=>{let e=uA(Do(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e},hA=n=>Oo(fA(n)),X6={mode:"jab",channels:["j","a","b","alpha"],parse:["--jzazbz"],serialize:"--jzazbz",fromMode:{rgb:dA,xyz65:uA},toMode:{rgb:hA,xyz65:fA},ranges:{j:[0,.222],a:[-.109,.129],b:[-.185,.134]},interpolate:{j:we,a:we,b:we,alpha:{use:we,fixup:on}}},$x=({j:n,a:e,b:t,alpha:i})=>{e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.sqrt(e*e+t*t),r={mode:"jch",j:n,c:s};return s&&(r.h=yn(Math.atan2(t,e)*180/Math.PI)),i!==void 0&&(r.alpha=i),r},qx=({j:n,c:e,h:t,alpha:i})=>{t===void 0&&(t=0);let s={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&&(s.alpha=i),s},$6={mode:"jch",parse:["--jzczhz"],serialize:"--jzczhz",toMode:{jab:qx,rgb:n=>hA(qx(n))},fromMode:{rgb:n=>$x(dA(n)),jab:$x},channels:["j","c","h","alpha"],ranges:{j:[0,.221],c:[0,.19],h:[0,360]},interpolate:{h:{use:we,fixup:Xs},c:we,j:we,alpha:{use:we,fixup:on}},difference:{h:Kh},average:{h:$s}},ip=Math.pow(29,3)/Math.pow(3,3),X_=Math.pow(6,3)/Math.pow(29,3);let Bm=n=>Math.pow(n,3)>X_?Math.pow(n,3):(116*n-16)/ip;const $_=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=(n+16)/116,r=e/500+s,o=s-t/200,a={mode:"xyz50",x:Bm(r)*Jt.X,y:Bm(s)*Jt.Y,z:Bm(o)*Jt.Z};return i!==void 0&&(a.alpha=i),a},Zc=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=$a({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&&(s.alpha=i),s},pA=n=>Zc($_(n)),Jc=n=>{let{r:e,g:t,b:i,alpha:s}=Xa(n),r={mode:"xyz50",x:.436065742824811*e+.3851514688337912*t+.14307845442264197*i,y:.22249319175623702*e+.7168870538238823*t+.06061979053616537*i,z:.013923904500943465*e+.09708128566574634*t+.7140993584005155*i};return s!==void 0&&(r.alpha=s),r},zm=n=>n>X_?Math.cbrt(n):(ip*n+16)/116,q_=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=zm(n/Jt.X),r=zm(e/Jt.Y),o=zm(t/Jt.Z),a={mode:"lab",l:116*r-16,a:500*(s-r),b:200*(r-o)};return i!==void 0&&(a.alpha=i),a},mA=n=>{let e=q_(Jc(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e};function q6(n,e){if(!e||e[0]!=="lab")return;const t={mode:"lab"},[,i,s,r,o]=e;if(!(i.type===_e.Hue||s.type===_e.Hue||r.type===_e.Hue))return i.type!==_e.None&&(t.l=Math.min(Math.max(0,i.value),100)),s.type!==_e.None&&(t.a=s.type===_e.Number?s.value:s.value*125/100),r.type!==_e.None&&(t.b=r.type===_e.Number?r.value:r.value*125/100),o.type!==_e.None&&(t.alpha=Math.min(1,Math.max(0,o.type===_e.Number?o.value:o.value/100))),t}const Y_={mode:"lab",toMode:{xyz50:$_,rgb:pA},fromMode:{xyz50:q_,rgb:mA},channels:["l","a","b","alpha"],ranges:{l:[0,100],a:[-100,100],b:[-100,100]},parse:[q6],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}}},Y6={...Y_,mode:"lab65",parse:["--lab-d65"],serialize:"--lab-d65",toMode:{xyz65:eA,rgb:Zh},fromMode:{xyz65:tA,rgb:Jh},ranges:{l:[0,100],a:[-86.182,98.234],b:[-107.86,94.477]}};function j6(n,e){if(!e||e[0]!=="lch")return;const t={mode:"lch"},[,i,s,r,o]=e;if(i.type!==_e.None){if(i.type===_e.Hue)return;t.l=Math.min(Math.max(0,i.value),100)}if(s.type!==_e.None&&(t.c=Math.max(0,s.type===_e.Number?s.value:s.value*150/100)),r.type!==_e.None){if(r.type===_e.Percentage)return;t.h=r.value}return o.type!==_e.None&&(t.alpha=Math.min(1,Math.max(0,o.type===_e.Number?o.value:o.value/100))),t}const j_={mode:"lch",toMode:{lab:Sr,rgb:n=>pA(Sr(n))},fromMode:{rgb:n=>Mr(mA(n)),lab:Mr},channels:["l","c","h","alpha"],ranges:{l:[0,100],c:[0,150],h:[0,360]},parse:[j6],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:Xs},c:we,l:we,alpha:{use:we,fixup:on}},difference:{h:Kh},average:{h:$s}},K6={...j_,mode:"lch65",parse:["--lch-d65"],serialize:"--lch-d65",toMode:{lab65:n=>Sr(n,"lab65"),rgb:n=>Zh(Sr(n,"lab65"))},fromMode:{rgb:n=>Mr(Jh(n),"lch65"),lab65:n=>Mr(n,"lch65")},ranges:{l:[0,100],c:[0,133.807],h:[0,360]}},gA=({l:n,u:e,v:t,alpha:i})=>{e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.sqrt(e*e+t*t),r={mode:"lchuv",l:n,c:s};return s&&(r.h=yn(Math.atan2(t,e)*180/Math.PI)),i!==void 0&&(r.alpha=i),r},_A=({l:n,c:e,h:t,alpha:i})=>{t===void 0&&(t=0);let s={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&&(s.alpha=i),s},vA=(n,e,t)=>4*n/(n+15*e+3*t),yA=(n,e,t)=>9*e/(n+15*e+3*t),Z6=vA(Jt.X,Jt.Y,Jt.Z),J6=yA(Jt.X,Jt.Y,Jt.Z),Q6=n=>n<=X_?ip*n:116*Math.cbrt(n)-16,t0=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Q6(e/Jt.Y),r=vA(n,e,t),o=yA(n,e,t);!isFinite(r)||!isFinite(o)?s=r=o=0:(r=13*s*(r-Z6),o=13*s*(o-J6));let a={mode:"luv",l:s,u:r,v:o};return i!==void 0&&(a.alpha=i),a},eH=(n,e,t)=>4*n/(n+15*e+3*t),tH=(n,e,t)=>9*e/(n+15*e+3*t),nH=eH(Jt.X,Jt.Y,Jt.Z),iH=tH(Jt.X,Jt.Y,Jt.Z),n0=({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 s=e/(13*n)+nH,r=t/(13*n)+iH,o=Jt.Y*(n<=8?n/ip:Math.pow((n+16)/116,3)),a=o*(9*s)/(4*r),l=o*(12-3*s-20*r)/(4*r),c={mode:"xyz50",x:a,y:o,z:l};return i!==void 0&&(c.alpha=i),c},sH=n=>gA(t0(Jc(n))),rH=n=>Zc(n0(_A(n))),oH={mode:"lchuv",toMode:{luv:_A,rgb:rH},fromMode:{rgb:sH,luv:gA},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:Xs},c:we,l:we,alpha:{use:we,fixup:on}},difference:{h:Kh},average:{h:$s}},aH={...Wa,mode:"lrgb",toMode:{rgb:$a},fromMode:{rgb:Xa},parse:["srgb-linear"],serialize:"srgb-linear"},lH={mode:"luv",toMode:{xyz50:n0,rgb:n=>Zc(n0(n))},fromMode:{xyz50:t0,rgb:n=>t0(Jc(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}}},bA=({r:n,g:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.cbrt(.41222147079999993*n+.5363325363*e+.0514459929*t),r=Math.cbrt(.2119034981999999*n+.6806995450999999*e+.1073969566*t),o=Math.cbrt(.08830246189999998*n+.2817188376*e+.6299787005000002*t),a={mode:"oklab",l:.2104542553*s+.793617785*r-.0040720468*o,a:1.9779984951*s-2.428592205*r+.4505937099*o,b:.0259040371*s+.7827717662*r-.808675766*o};return i!==void 0&&(a.alpha=i),a},sp=n=>{let e=bA(Xa(n));return n.r===n.b&&n.b===n.g&&(e.a=e.b=0),e},Qc=({l:n,a:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=Math.pow(n*.9999999984505198+.39633779217376786*e+.2158037580607588*t,3),r=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*s-3.307711590408193*r+.230969928729428*o,g:-1.2684380040921763*s+2.6097574006633715*r-.3413193963102197*o,b:-.004196086541837188*s-.7034186144594493*r+1.7076147009309444*o};return i!==void 0&&(a.alpha=i),a},rp=n=>$a(Qc(n));function i0(n){const i=1.170873786407767;return .5*(i*n-.206+Math.sqrt((i*n-.206)*(i*n-.206)+4*.03*i*n))}function Bd(n){return(n*n+.206*n)/(1.170873786407767*(n+.03))}function cH(n,e){let t,i,s,r,o,a,l,c;-1.88170328*n-.80936493*e>1?(t=1.19086277,i=1.76576728,s=.59662641,r=.75515197,o=.56771245,a=4.0767416621,l=-3.3077115913,c=.2309699292):1.81444104*n-1.19445276*e>1?(t=.73956515,i=-.45954404,s=.08285427,r=.1254107,o=.14503204,a=-1.2684380046,l=2.6097574011,c=-.3413193965):(t=1.35733652,i=-.00915799,s=-1.1513021,r=-.50559606,o=.00692167,a=-.0041960863,l=-.7034186147,c=1.707614701);let u=t+i*n+s*e+r*n*n+o*n*e,f=.3963377774*n+.2158037573*e,d=-.1055613458*n-.0638541728*e,h=-.0894841775*n-1.291485548*e;{let p=1+u*f,_=1+u*d,g=1+u*h,m=p*p*p,y=_*_*_,b=g*g*g,v=3*f*p*p,E=3*d*_*_,T=3*h*g*g,S=6*f*f*p,P=6*d*d*_,x=6*h*h*g,M=a*m+l*y+c*b,I=a*v+l*E+c*T,N=a*S+l*P+c*x;u=u-M*I/(I*I-.5*M*N)}return u}function K_(n,e){let t=cH(n,e),i=Qc({l:1,a:t*n,b:t*e}),s=Math.cbrt(1/Math.max(i.r,i.g,i.b)),r=s*t;return[s,r]}function uH(n,e,t,i,s,r=null){r||(r=K_(n,e));let o;if((t-s)*r[1]-(r[0]-s)*i<=0)o=r[1]*s/(i*r[0]+r[1]*(s-t));else{o=r[1]*(s-1)/(i*(r[0]-1)+r[1]*(s-t));{let a=t-s,l=i,c=.3963377774*n+.2158037573*e,u=-.1055613458*n-.0638541728*e,f=-.0894841775*n-1.291485548*e,d=a+l*c,h=a+l*u,p=a+l*f;{let _=s*(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*d*m*m,P=3*h*y*y,x=3*p*b*b,M=6*d*d*m,I=6*h*h*y,N=6*p*p*b,V=4.0767416621*v-3.3077115913*E+.2309699292*T-1,j=4.0767416621*S-3.3077115913*P+.2309699292*x,te=4.0767416621*M-3.3077115913*I+.2309699292*N,Z=j/(j*j-.5*V*te),ee=-V*Z,J=-1.2684380046*v+2.6097574011*E-.3413193965*T-1,he=-1.2684380046*S+2.6097574011*P-.3413193965*x,be=-1.2684380046*M+2.6097574011*I-.3413193965*N,se=he/(he*he-.5*J*be),ye=-J*se,Be=-.0041960863*v-.7034186147*E+1.707614701*T-1,re=-.0041960863*S-.7034186147*P+1.707614701*x,ge=-.0041960863*M-.7034186147*I+1.707614701*N,xe=re/(re*re-.5*Be*ge),$=-Be*xe;ee=Z>=0?ee:1e6,ye=se>=0?ye:1e6,$=xe>=0?$:1e6,o+=Math.min(ee,Math.min(ye,$))}}}return o}function Z_(n,e,t=null){t||(t=K_(n,e));let i=t[0],s=t[1];return[s/i,s/(1-i)]}function xA(n,e,t){let i=K_(e,t),s=uH(e,t,n,1,n,i),r=Z_(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=s/Math.min(n*r[0],(1-n)*r[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,s]}function Yx(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,s={mode:"okhsl",l:i0(e)};n.alpha!==void 0&&(s.alpha=n.alpha);let r=Math.sqrt(t*t+i*i);if(!r)return s.s=0,s;let[o,a,l]=xA(e,t/r,i/r),c;if(rYx(sp(n))},toMode:{oklab:jx,rgb:n=>rp(jx(n))}};function Kx(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,s=Math.sqrt(t*t+i*i),r=s?t/s:1,o=s?i/s:1,[a,l]=Z_(r,o),c=.5,u=1-c/a,f=l/(s+e*l),d=f*e,h=f*s,p=Bd(d),_=h*p/d,g=Qc({l:p,a:r*_,b:o*_}),m=Math.cbrt(1/Math.max(g.r,g.g,g.b,0));e=e/m,s=s/m*i0(e)/e,e=i0(e);const y={mode:"okhsv",s:s?(c+l)*h/(l*c+l*u*h):0,v:e?e/d:0};return y.s&&(y.h=yn(Math.atan2(i,t)*180/Math.PI)),n.alpha!==void 0&&(y.alpha=n.alpha),y}function Zx(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,s=n.v!==void 0?n.v:0,r=Math.cos(t/180*Math.PI),o=Math.sin(t/180*Math.PI),[a,l]=Z_(r,o),c=.5,u=1-c/a,f=1-i*c/(c+l-l*u*i),d=i*l*c/(c+l-l*u*i),h=Bd(f),p=d*h/f,_=Qc({l:h,a:r*p,b:o*p}),g=Math.cbrt(1/Math.max(_.r,_.g,_.b,0)),m=Bd(s*f),y=d*m/f;return e.l=m*g,e.a=y*r*g,e.b=y*o*g,e}const dH={...aA,mode:"okhsv",channels:["h","s","v","alpha"],parse:["--okhsv"],serialize:"--okhsv",fromMode:{oklab:Kx,rgb:n=>Kx(sp(n))},toMode:{oklab:Zx,rgb:n=>rp(Zx(n))}};function hH(n,e){if(!e||e[0]!=="oklab")return;const t={mode:"oklab"},[,i,s,r,o]=e;if(!(i.type===_e.Hue||s.type===_e.Hue||r.type===_e.Hue))return i.type!==_e.None&&(t.l=Math.min(Math.max(0,i.type===_e.Number?i.value:i.value/100),1)),s.type!==_e.None&&(t.a=s.type===_e.Number?s.value:s.value*.4/100),r.type!==_e.None&&(t.b=r.type===_e.Number?r.value:r.value*.4/100),o.type!==_e.None&&(t.alpha=Math.min(1,Math.max(0,o.type===_e.Number?o.value:o.value/100))),t}const pH={...Y_,mode:"oklab",toMode:{lrgb:Qc,rgb:rp},fromMode:{lrgb:bA,rgb:sp},ranges:{l:[0,1],a:[-.4,.4],b:[-.4,.4]},parse:[hH],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 mH(n,e){if(!e||e[0]!=="oklch")return;const t={mode:"oklch"},[,i,s,r,o]=e;if(i.type!==_e.None){if(i.type===_e.Hue)return;t.l=Math.min(Math.max(0,i.type===_e.Number?i.value:i.value/100),1)}if(s.type!==_e.None&&(t.c=Math.max(0,s.type===_e.Number?s.value:s.value*.4/100)),r.type!==_e.None){if(r.type===_e.Percentage)return;t.h=r.value}return o.type!==_e.None&&(t.alpha=Math.min(1,Math.max(0,o.type===_e.Number?o.value:o.value/100))),t}const gH={...j_,mode:"oklch",toMode:{oklab:n=>Sr(n,"oklab"),rgb:n=>rp(Sr(n,"oklab"))},fromMode:{rgb:n=>Mr(sp(n),"oklch"),oklab:n=>Mr(n,"oklch")},parse:[mH],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]}},Jx=n=>{let{r:e,g:t,b:i,alpha:s}=Xa(n),r={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 s!==void 0&&(r.alpha=s),r},Qx=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s=$a({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&&(s.alpha=i),s},_H={...Wa,mode:"p3",parse:["display-p3"],serialize:"display-p3",fromMode:{rgb:n=>Qx(Do(n)),xyz65:Qx},toMode:{rgb:n=>Oo(Jx(n)),xyz65:Jx}},Vm=n=>{let e=Math.abs(n);return e>=1/512?Math.sign(n)*Math.pow(e,1/1.8):16*n},eM=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s={mode:"prophoto",r:Vm(n*1.3457868816471585-e*.2555720873797946-.0511018649755453*t),g:Vm(n*-.5446307051249019+e*1.5082477428451466+.0205274474364214*t),b:Vm(n*0+e*0+1.2119675456389452*t)};return i!==void 0&&(s.alpha=i),s},Hm=(n=0)=>{let e=Math.abs(n);return e>=16/512?Math.sign(n)*Math.pow(e,1.8):n/16},tM=n=>{let e=Hm(n.r),t=Hm(n.g),i=Hm(n.b),s={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&&(s.alpha=n.alpha),s},vH={...Wa,mode:"prophoto",parse:["prophoto-rgb"],serialize:"prophoto-rgb",fromMode:{xyz50:eM,rgb:n=>eM(Jc(n))},toMode:{xyz50:tM,rgb:n=>Zc(tM(n))}},nM=1.09929682680944,yH=.018053968510807,Gm=n=>{const e=Math.abs(n);return e>yH?(Math.sign(n)||1)*(nM*Math.pow(e,.45)-(nM-1)):4.5*n},iM=({x:n,y:e,z:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);let s={mode:"rec2020",r:Gm(n*1.7166511879712683-e*.3556707837763925-.2533662813736599*t),g:Gm(n*-.6666843518324893+e*1.6164812366349395+.0157685458139111*t),b:Gm(n*.0176398574453108-e*.0427706132578085+.9421031212354739*t)};return i!==void 0&&(s.alpha=i),s},sM=1.09929682680944,bH=.018053968510807,Wm=(n=0)=>{let e=Math.abs(n);return e{let e=Wm(n.r),t=Wm(n.g),i=Wm(n.b),s={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&&(s.alpha=n.alpha),s},xH={...Wa,mode:"rec2020",fromMode:{xyz65:iM,rgb:n=>iM(Do(n))},toMode:{xyz65:rM,rgb:n=>Oo(rM(n))},parse:["rec2020"],serialize:"rec2020"},yo=.0037930732552754493,MA=Math.cbrt(yo),Xm=n=>Math.cbrt(n)-MA,MH=n=>{const{r:e,g:t,b:i,alpha:s}=Xa(n),r=Xm(.3*e+.622*t+.078*i+yo),o=Xm(.23*e+.692*t+.078*i+yo),a=Xm(.2434226892454782*e+.2047674442449682*t+.5518098665095535*i+yo),l={mode:"xyb",x:(r-o)/2,y:(r+o)/2,b:a-(r+o)/2};return s!==void 0&&(l.alpha=s),l},$m=n=>Math.pow(n+MA,3),SH=({x:n,y:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const s=$m(n+e)-yo,r=$m(e-n)-yo,o=$m(t+e)-yo,a=$a({r:11.031566904639861*s-9.866943908131562*r-.16462299650829934*o,g:-3.2541473810744237*s+4.418770377582723*r-.16462299650829934*o,b:-3.6588512867136815*s+2.7129230459360922*r+1.9459282407775895*o});return i!==void 0&&(a.alpha=i),a},EH={mode:"xyb",channels:["x","y","b","alpha"],parse:["--xyb"],serialize:"--xyb",toMode:{rgb:SH},fromMode:{rgb:MH},ranges:{x:[-.0154,.0281],y:[0,.8453],b:[-.2778,.388]},interpolate:{x:we,y:we,b:we,alpha:{use:we,fixup:on}}},TH={mode:"xyz50",parse:["xyz-d50"],serialize:"xyz-d50",toMode:{rgb:Zc,lab:q_},fromMode:{rgb:Jc,lab:$_},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}}},wH=n=>{let{x:e,y:t,z:i,alpha:s}=n;e===void 0&&(e=0),t===void 0&&(t=0),i===void 0&&(i=0);let r={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 s!==void 0&&(r.alpha=s),r},AH=n=>{let{x:e,y:t,z:i,alpha:s}=n;e===void 0&&(e=0),t===void 0&&(t=0),i===void 0&&(i=0);let r={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 s!==void 0&&(r.alpha=s),r},CH={mode:"xyz65",toMode:{rgb:Oo,xyz50:wH},fromMode:{rgb:Do,xyz50:AH},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}}},RH=({r:n,g:e,b:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const s={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&&(s.alpha=i),s},PH=({y:n,i:e,q:t,alpha:i})=>{n===void 0&&(n=0),e===void 0&&(e=0),t===void 0&&(t=0);const s={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&&(s.alpha=i),s},IH={mode:"yiq",toMode:{rgb:PH},fromMode:{rgb:RH},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(v6);Et(T6);Et(w6);Et(A6);Et(P6);Et(sA);Et(aA);Et(z6);Et(V6);Et(X6);Et($6);Et(Y_);Et(Y6);Et(j_);Et(K6);Et(oH);Et(aH);Et(lH);Et(fH);Et(dH);Et(pH);Et(gH);Et(_H);Et(vH);Et(xH);Et(Wa);Et(EH);Et(TH);Et(CH);Et(IH);const s0=220.44,LH=Yw("oklch"),oM=n=>{var e;return n?(e=LH(n))==null?void 0:e.h:s0},DH=zz("settings",()=>{const n=et(),e=vs("settings/language","en-US"),t=vs("settings/stage/view/model-renderer","2d"),i=vs("settings/audio/input","false"),s=Me(()=>{var T;return(T=n.value)==null?void 0:T.deviceId}),{audioInputs:r,ensurePermissions:o}=WB({constraints:{audio:!0}}),a=et(),l=et("/assets/live2d/models/hiyori_pro_zh.zip"),c=et("url"),u=et(!1),f=vs("settings/live2d/position",{x:0,y:0}),d=et({group:"Idle",index:0}),h=et([]),p=vs("settings/live2d/motion-map",{}),_=vs("settings/disable-transitions",!0),g=vs("settings/use-page-specific-transitions",!0),m=vs("settings/theme/colors/hue",s0),y=vs("settings/theme/colors/hue-dynamic",!1);function b(T=s0){m.value=T,y.value=!1}function v(T){b(oM(T))}function E(T){if(y.value)return!1;const S=oM(T);if(!S)return!1;const P=Math.abs(S-m.value);return P<.01||P>359.99}return Xe(i,T=>{T==="false"&&(n.value=void 0),T==="true"&&o().then(()=>{n.value=r.value[0]})}),Xe(r,()=>{i.value==="true"&&!n.value&&(n.value=r.value[0])},{immediate:!0}),{live2dModelFile:a,live2dModelUrl:l,live2dLoadSource:c,live2dCurrentMotion:d,live2dPosition:f,availableLive2dMotions:h,live2dMotionMap:p,loadingLive2dModel:u,disableTransitions:_,usePageSpecificTransitions:g,language:e,stageView:t,themeColorsHue:m,themeColorsHueDynamic:y,isAudioInputOn:i,selectedAudioDevice:n,selectedAudioDeviceId:s,setThemeColorsHue:b,applyPrimaryColorFrom:v,isColorSelectedForPrimary:E}}),OH=fn({__name:"ArrowTransition",props:{stageTransition:{default:()=>({primaryColor:"#666",secondaryColor:"#ccc"})}},setup(n){const e=n,t=Me(()=>e.stageTransition),i=Me(()=>t.value.primaryColor||"#666"),s=Me(()=>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",s.value)}),(r,o)=>(gn(),yi("div",{class:"stage-transition-3",style:Si({zIndex:t.value.zIndex||100})},null,4))}}),No=(n,e)=>{const t=n.__vccOpts||n;for(const[i,s]of e)t[i]=s;return t},NH=No(OH,[["__scopeId","data-v-df576df0"]]),UH=fn({__name:"BubbleWaveOutTransition",props:{stageTransition:null},setup(n){const e=n,t=Me(()=>{var i;return((i=e.stageTransition)==null?void 0:i.colors)||["#eee","#ebcb8b","#c56370","#3f3b52"]});return Hn(()=>{var i,s;document.documentElement.style.setProperty("--circle-expansion-delay",`${((i=e.stageTransition)==null?void 0:i.delay)||0}s`),document.documentElement.style.setProperty("--circle-expansion-duration",`${((s=e.stageTransition)==null?void 0:s.duration)||.4}s`),t.value.forEach((r,o)=>{document.documentElement.style.setProperty(`--circle-expansion-color-${o+1}`,r)})}),(i,s)=>{var r;return gn(),yi("div",{class:"circle-expansion-transition",style:Si({zIndex:((r=n.stageTransition)==null?void 0:r.zIndex)||100})},[(gn(!0),yi(jt,null,d2(t.value,(o,a)=>(gn(),yi("div",{key:a}))),128))],4)}}}),FH=No(UH,[["__scopeId","data-v-0c29056c"]]),kH=fn({__name:"FantasyFallTransition",props:{stageTransition:null},setup(n){const e=n,t=Me(()=>{var s;return((s=e.stageTransition)==null?void 0:s.direction)||"up"}),i=Me(()=>`fantasy-fall-${t.value}`);return Hn(()=>{var s,r,o,a,l,c,u,f,d;document.documentElement.style.setProperty("--fantasy-fall-color",((s=e.stageTransition)==null?void 0:s.primaryColor)||"#eee"),document.documentElement.style.setProperty("--fantasy-fall-duration",`${((r=e.stageTransition)==null?void 0:r.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",`${((d=(f=e.stageTransition)==null?void 0:f.borderRadius)==null?void 0:d.lg)||"50%"}`)}),(s,r)=>{var o;return gn(),yi("div",{class:Ua(["fantasy-fall-transition",i.value]),style:Si({zIndex:((o=n.stageTransition)==null?void 0:o.zIndex)??100})},null,6)}}}),BH=No(kH,[["__scopeId","data-v-e62bf496"]]),zH=fn({__name:"MultipleBlocksRevealTransition",props:{stageTransition:null},setup(n){const e=n,t=Me(()=>e.stageTransition),i=Me(()=>{var r;return((r=t.value)==null?void 0:r.primaryColor)||"#666"}),s=Me(()=>{var r;return((r=t.value)==null?void 0:r.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",s.value)}),(r,o)=>{var a;return gn(),yi("div",{class:"stage-transition-4",style:Si({zIndex:((a=t.value)==null?void 0:a.zIndex)??100})},o[0]||(o[0]=[X2('
',5)]),4)}}}),VH=No(zH,[["__scopeId","data-v-6d1179fc"]]),HH=fn({__name:"SlideTransition",props:{stageTransition:null},setup(n){const e=n,t=Me(()=>e.stageTransition),i=Me(()=>{var r;return((r=t.value)==null?void 0:r.primaryColor)||"#666"}),s=Me(()=>{var r;return((r=t.value)==null?void 0:r.secondaryColor)||"#ccc"});return Xe([t,i,s],()=>{document.documentElement.style.setProperty("--stage-transition-1-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-1-overlay-color-2",s.value)}),Hn(()=>{document.documentElement.style.setProperty("--stage-transition-1-overlay-color-1",i.value),document.documentElement.style.setProperty("--stage-transition-1-overlay-color-2",s.value)}),(r,o)=>{var a;return gn(),yi("div",{class:"stage-transition-1",style:Si({zIndex:((a=t.value)==null?void 0:a.zIndex)??100})},null,4)}}}),GH=No(HH,[["__scopeId","data-v-bf1d1566"]]),WH=fn({__name:"SlopeSlideTransition",props:{stageTransition:null},setup(n){const e=n,t=Me(()=>e.stageTransition),i=Me(()=>{var r;return((r=t.value)==null?void 0:r.primaryColor)??"#666"}),s=Me(()=>{var r;return((r=t.value)==null?void 0:r.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",s.value)}),(r,o)=>{var a;return gn(),yi("div",{class:"stage-transition-2",style:Si({zIndex:((a=t.value)==null?void 0:a.zIndex)??100})},null,4)}}}),XH=No(WH,[["__scopeId","data-v-8ff7120f"]]),$H=fn({__name:"RectanglesRotateTransition",props:{stageTransition:null},setup(n){const e=n;return Hn(()=>{var t,i,s,r,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",((s=e.stageTransition)==null?void 0:s.tertiaryColor)||"#43445b"),document.documentElement.style.setProperty("--rectangle-rotate-duration",`${((r=e.stageTransition)==null?void 0:r.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 s;return gn(),yi("div",{class:"rectangle-rotate-transition",style:Si({zIndex:((s=n.stageTransition)==null?void 0:s.zIndex)??100})},i[0]||(i[0]=[or("div",{class:"rectangle rectangle-rotate-1"},[or("div")],-1),or("div",{class:"rectangle rectangle-rotate-2"},[or("div")],-1),or("div",{class:"rectangle rectangle-rotate-3"},[or("div")],-1)]),4)}}}),qH=No($H,[["__scopeId","data-v-f4b1dc64"]]),YH=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=$V(),i=et(!1),s=et(),r=et(""),o=et(),a=Oe({slide:{component:GH,duration:2700},"slope-slide":{component:XH,duration:2700},arrow:{component:NH,duration:2700},"multiple-blocks-reveal":{component:VH,duration:2800},"fantasy-fall":{component:BH,duration:2700},"rectangles-rotate":{component:qH,duration:2700},"bubble-wave-out":{component:FH,duration:1e3}}),l=et([]);function c(h){return l.value.push(h),()=>{const p=l.value.indexOf(h);p>=0&&l.value.splice(p,1)}}async function u(h,p={}){s.value=h;for(const _ of l.value)try{await Promise.resolve(_(h,p))}catch(g){console.error(`Error in transition hook at stage "${h}":`,g)}}async function f(h,p,_){if(h.name==="none"||!h.name){p(),_();return}const g=a.value[h.name];if(!g){console.error(`Transition ${h.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:h.name}),i.value&&(await u("before-leave",{transitionName:r.value}),r.value="",o.value=void 0,i.value=!1,await u("after-leave",{transitionName:r.value}),await new Promise(T=>setTimeout(T,50))),r.value=h.name,o.value=h,i.value=!0,await u("enter-active",{transitionName:name}),setTimeout(async()=>{await u("navigation",{transitionName:h.name,config:g}),y||(y=!0,p())},m),setTimeout(async()=>{await u("after-enter",{transitionName:h.name})},g.duration),setTimeout(async()=>{await u("before-leave",{transitionName:h.name})},g.duration+10),setTimeout(async()=>{await u("leave-active",{transitionName:h.name})},g.duration+20);const E=g.exitDuration??0;setTimeout(async()=>{i.value=!1,r.value="",o.value=void 0,await u("after-leave",{transitionName:h.name}),_()},g.duration+E)}catch(E){console.error(E)}finally{v(),setTimeout(()=>{y||(y=!0,p())},g.duration*2)}}function d(h,p){return new Promise(_=>{f(h,p,_)})}return t.beforeEach((h,p,_)=>{if(e.disableTransitions){_();return}if(typeof h.meta.stageTransition!="object"){_();return}const g=h.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),d(g,_)}),(h,p)=>(gn(),yi(jt,null,[h2(h.$slots,"default"),i.value?(gn(),yi(jt,{key:0},[a.value[r.value]?(gn(),Kl(f2(a.value[r.value].component),{key:0,"stage-transition":o.value},null,8,["stage-transition"])):Lv("",!0)],64)):Lv("",!0)],64))}});/*! @@ -3903,4 +3903,4 @@ And the last, do what ever you want! - <|DELAY:3|> (延迟 3 秒) 最后,做任何你想做的事! -`}}},settings:{animations:{"stage-transitions":{title:{t:0,b:{t:2,i:[{t:3}],s:"是否开启舞台动画"}}},"use-page-specific-transitions":{description:{t:0,b:{t:2,i:[{t:3}],s:"某些页面会有自己的过场动画,这将覆盖舞台过场动画"}},title:{t:0,b:{t:2,i:[{t:3}],s:"是否使用页面特定过场动画"}}}},language:{chinese:{t:0,b:{t:2,i:[{t:3}],s:"简体中文"}},english:{t:0,b:{t:2,i:[{t:3}],s:"English"}},title:{t:0,b:{t:2,i:[{t:3}],s:"语言"}}},live2d:{"change-model":{"from-file":{t:0,b:{t:2,i:[{t:3}],s:"从文件加载"}},"from-file-select":{t:0,b:{t:2,i:[{t:3}],s:"选择"}},"from-url":{t:0,b:{t:2,i:[{t:3}],s:"从 URL 加载"}},"from-url-confirm":{t:0,b:{t:2,i:[{t:3}],s:"加载"}},"from-url-placeholder":{t:0,b:{t:2,i:[{t:3}],s:"输入 Live2D 模型 URL"}},title:{t:0,b:{t:2,i:[{t:3}],s:"更换模型"}}},"edit-motion-map":{title:{t:0,b:{t:2,i:[{t:3}],s:"编辑动作映射"}}},"map-motions":{play:{t:0,b:{t:2,i:[{t:3}],s:"播放动作"}},title:{t:0,b:{t:2,i:[{t:3}],s:"映射动作"}}},title:{t:0,b:{t:2,i:[{t:3}],s:"Live2D 设置"}}},microphone:{t:0,b:{t:2,i:[{t:3}],s:"麦克风"}},models:{t:0,b:{t:2,i:[{t:3}],s:"模型"}},pages:{card:{activate:{t:0,b:{t:2,i:[{t:3}],s:"激活"}},active:{t:0,b:{t:2,i:[{t:3}],s:"已激活"}},active_badge:{t:0,b:{t:2,i:[{t:3}],s:"当前使用中"}},cancel:{t:0,b:{t:2,i:[{t:3}],s:"取消"}},card_not_found:{t:0,b:{t:2,i:[{t:3}],s:"未找到角色卡"}},character:{t:0,b:{t:2,i:[{t:3}],s:"角色设定"}},close:{t:0,b:{t:2,i:[{t:3}],s:"关闭"}},consciousness:{model:{t:0,b:{t:2,i:[{t:3}],s:"意识 / 模型"}}},created_by:{t:0,b:{t:2,i:[{t:3}],s:"创建者"}},creator_notes:{t:0,b:{t:2,i:[{t:3}],s:"创建者笔记"}},delete:{t:0,b:{t:2,i:[{t:3}],s:"删除"}},delete_card:{t:0,b:{t:2,i:[{t:3}],s:"删除角色卡"}},delete_confirmation:{t:0,b:{t:2,i:[{t:3}],s:"确定要删除这张角色卡吗?"}},description:{t:0,b:{t:2,i:[{t:3}],s:"使用 Airi 角色卡预设"}},description_label:{t:0,b:{t:2,i:[{t:3}],s:"描述"}},drop_here:{t:0,b:{t:2,i:[{t:3}],s:"放开以上传文件"}},modules:{t:0,b:{t:2,i:[{t:3}],s:"模块"}},name_asc:{t:0,b:{t:2,i:[{t:3}],s:"名称 (A-Z)"}},name_desc:{t:0,b:{t:2,i:[{t:3}],s:"名称 (Z-A)"}},no_cards:{t:0,b:{t:2,i:[{t:3}],s:"还没有任何角色卡,点击上方按钮上传一个吧!"}},no_results:{t:0,b:{t:2,i:[{t:3}],s:"没有找到匹配的角色卡"}},personality:{t:0,b:{t:2,i:[{t:3}],s:"性格"}},posthistoryinstructions:{t:0,b:{t:2,i:[{t:3}],s:"历史提示指令"}},recent:{t:0,b:{t:2,i:[{t:3}],s:"最近添加"}},scenario:{t:0,b:{t:2,i:[{t:3}],s:"场景"}},search:{t:0,b:{t:2,i:[{t:3}],s:"搜索角色卡..."}},sort_by:{t:0,b:{t:2,i:[{t:3}],s:"排序方式"}},speech:{model:{t:0,b:{t:2,i:[{t:3}],s:"声音 / 模型"}},voice:{t:0,b:{t:2,i:[{t:3}],s:"声音 / 声线"}}},systemprompt:{t:0,b:{t:2,i:[{t:3}],s:"系统提示词"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Airi 角色卡"}},try_different_search:{t:0,b:{t:2,i:[{t:3}],s:"尝试使用其他关键词搜索"}},upload:{t:0,b:{t:2,i:[{t:3}],s:"上传"}},upload_desc:{t:0,b:{t:2,i:[{t:3}],s:"点击或拖拽文件到此处上传"}}},memory:{description:{t:0,b:{t:2,i:[{t:3}],s:"存放记忆的地方,以及策略"}},title:{t:0,b:{t:2,i:[{t:3}],s:"记忆体"}}},models:{description:{t:0,b:{t:2,i:[{t:3}],s:"切换角色的 Live2D,VRM 模型"}},title:{t:0,b:{t:2,i:[{t:3}],s:"角色模型"}}},modules:{consciousness:{description:{t:0,b:{t:2,i:[{t:3}],s:"人格设定、使用的模型等配置"}},sections:{section:{"provider-model-selection":{collapse:{t:0,b:{t:2,i:[{t:3}],s:"折叠"}},custom_model_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入自订模型名字"}},description:{t:0,b:{t:2,i:[{t:3}],s:"为意识选择合适的 LLM 提供商"}},error:{t:0,b:{t:2,i:[{t:3}],s:"获取出错啦"}},expand:{t:0,b:{t:2,i:[{t:3}],s:"展开"}},loading:{t:0,b:{t:2,i:[{t:3}],s:"获取模型中..."}},manual_model_name:{t:0,b:{t:2,i:[{t:3}],s:"模型名字"}},manual_model_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入与该提供商一起使用的模型名字"}},no_models:{t:0,b:{t:2,i:[{t:3}],s:"没有任何可用的模型"}},no_models_description:{t:0,b:{t:2,i:[{t:3}],s:"该提供商的模型列表没有返回任何的数据"}},no_search_results:{t:0,b:{t:2,i:[{t:3}],s:"没有匹配的模型"}},no_search_results_description:{t:0,b:{t:2,i:[{t:3,v:"没有模型匹配 '"},{t:4,k:"query"},{t:3,v:"' 关键字,请尝试一下别的关键词呢"}]}},not_supported:{t:0,b:{t:2,i:[{t:3}],s:"无法列出模型"}},not_supported_description:{t:0,b:{t:2,i:[{t:3}],s:"此提供商不支持列出模型的功能"}},search_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"搜索模型..."}},search_results:{t:0,b:{t:2,i:[{t:3,v:"找到 "},{t:4,k:"count"},{t:3,v:" / "},{t:4,k:"total"},{t:3,v:" 个模型"}]}},show_less:{t:0,b:{t:2,i:[{t:3}],s:"显示更多"}},show_more:{t:0,b:{t:2,i:[{t:3}],s:"收起"}},subtitle:{t:0,b:{t:2,i:[{t:3}],s:"选择一个模型"}},title:{t:0,b:{t:2,i:[{t:3}],s:"模型"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"意识"}}},description:{t:0,b:{t:2,i:[{t:3}],s:"思维,视觉,言语综合,游戏等"}},"gaming-factorio":{description:{t:0,b:{t:2,i:[{t:3}],s:"一起玩 Factorio!"}},title:{t:0,b:{t:2,i:[{t:3}],s:"异星工厂 Factorio"}}},"gaming-minecraft":{description:{t:0,b:{t:2,i:[{t:3}],s:"一起 Minecraft!"}},title:{t:0,b:{t:2,i:[{t:3}],s:"我的世界 Minecraft"}}},hearing:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音识别"}},title:{t:0,b:{t:2,i:[{t:3}],s:"听觉"}}},"memory-long-term":{description:{t:0,b:{t:2,i:[{t:3}],s:"长期记忆"}},title:{t:0,b:{t:2,i:[{t:3}],s:"长期记忆"}}},"memory-short-term":{description:{t:0,b:{t:2,i:[{t:3}],s:"短期记忆"}},title:{t:0,b:{t:2,i:[{t:3}],s:"短期记忆"}}},"messaging-discord":{description:{t:0,b:{t:2,i:[{t:3}],s:"Discord 发消息和语音聊天"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Discord"}}},speech:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音合成"}},sections:{section:{playground:{buttons:{stop:{label:{t:0,b:{t:2,i:[{t:3}],s:"停止"}}}},"select-voice":{required:{t:0,b:{t:2,i:[{t:3}],s:"请选择声线"}}}},"provider-voice-selection":{custom_model_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入指定模型名字..."}},custom_voice_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入指定声线 ID..."}},description:{t:0,b:{t:2,i:[{t:3}],s:"选择合适的语音提供商"}},no_models:{t:0,b:{t:2,i:[{t:3}],s:"没有任何可用的模型"}},no_models_description:{t:0,b:{t:2,i:[{t:3}],s:"该提供商的模型列表没有返回任何的数据"}},no_voices:{t:0,b:{t:2,i:[{t:3}],s:"没有任何可用的声线"}},no_voices_description:{t:0,b:{t:2,i:[{t:3}],s:"该提供商的声线列表没有返回任何的数据"}},pause:{t:0,b:{t:2,i:[{t:3}],s:"Pause"}},play_sample:{t:0,b:{t:2,i:[{t:3}],s:"Play"}},search_models_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"搜索模型..."}},search_models_results:{t:0,b:{t:2,i:[{t:3,v:"找到 "},{t:4,k:"count"},{t:3,v:" / "},{t:4,k:"total"},{t:3,v:" 个模型"}]}},search_voices_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"搜索声线..."}},search_voices_results:{t:0,b:{t:2,i:[{t:3,v:"找到 "},{t:4,k:"count"},{t:3,v:" / "},{t:4,k:"total"},{t:3,v:" 个声线"}]}},show_less:{t:0,b:{t:2,i:[{t:3}],s:"显示更少"}},show_more:{t:0,b:{t:2,i:[{t:3}],s:"显示更多"}},title:{t:0,b:{t:2,i:[{t:3}],s:"选择语音合成提供商"}}},"voice-settings":{"input-ssml":{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请输入 SSML 文本"}}},"use-ssml":{description:{t:0,b:{t:2,i:[{t:3}],s:"启用后可以输入原始 SSML 而不是纯文本"}},label:{t:0,b:{t:2,i:[{t:3}],s:"选用自定义 SSML"}}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"发声"}}},title:{t:0,b:{t:2,i:[{t:3}],s:"机体模块"}},vision:{description:{t:0,b:{t:2,i:[{t:3}],s:"视觉"}},title:{t:0,b:{t:2,i:[{t:3}],s:"视觉"}}},x:{description:{t:0,b:{t:2,i:[{t:3}],s:"X / Twitter 的浏览和使用"}},title:{t:0,b:{t:2,i:[{t:3}],s:"X / Twitter"}}}},providers:{common:{fields:{field:{"api-key":{label:{t:0,b:{t:2,i:[{t:3}],s:"API 密钥"}}}}},section:{advanced:{fields:{field:{headers:{description:{t:0,b:{t:2,i:[{t:3}],s:"添加自定义 HTTP 标头"}},key:{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请求头名字"}}},label:{t:0,b:{t:2,i:[{t:3}],s:"HTTP 请求头"}},value:{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请求头数值"}}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"高级配置"}}},basic:{description:{t:0,b:{t:2,i:[{t:3}],s:"基本设置"}},title:{t:0,b:{t:2,i:[{t:3}],s:"基础配置"}}},voice:{title:{t:0,b:{t:2,i:[{t:3}],s:"声音配置"}}}}},description:{t:0,b:{t:2,i:[{t:3}],s:"LLM,语音合成,语音识别提供商等"}},provider:{"alibaba-cloud-model-studio":{description:{t:0,b:{t:2,i:[{t:3}],s:"bailian.console.aliyun.com"}},title:{t:0,b:{t:2,i:[{t:3}],s:"阿里百炼"}}},anthropic:{description:{t:0,b:{t:2,i:[{t:3}],s:"anthropic.com"}},title:{t:0,b:{t:1,c:[{t:2,i:[{t:3}],s:"Anthropic"},{t:2,i:[{t:3}],s:"Claude"}]}}},"cloudflare-workers-ai":{description:{t:0,b:{t:2,i:[{t:3}],s:"Cloudflare.com"}},fields:{field:{"account-id":{description:{t:0,b:{t:2,i:[{t:3}],s:"Cloudflare 帐户 ID"}},label:{t:0,b:{t:2,i:[{t:3}],s:"Cloudflare Account ID"}},placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请输入 Cloudflare Account ID"}}},"api-key":{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请输入 Cloudflare Workers AI 的 API Key"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"Workers AI"}}},common:{fields:{field:{pitch:{description:{t:0,b:{t:2,i:[{t:3}],s:"调节合成语音的音高(比如更尖锐或更粗旷)"}},label:{t:0,b:{t:2,i:[{t:3}],s:"音高"}}},speed:{description:{t:0,b:{t:2,i:[{t:3}],s:"调节说话的语速"}},label:{t:0,b:{t:2,i:[{t:3}],s:"语速"}}},volume:{description:{t:0,b:{t:2,i:[{t:3}],s:"调节语音的响度"}},label:{t:0,b:{t:2,i:[{t:3}],s:"响度"}}}}}},deepseek:{description:{t:0,b:{t:2,i:[{t:3}],s:"DeepSeek.com"}},title:{t:0,b:{t:2,i:[{t:3}],s:"深度求索 DeepSeek"}}},elevenlabs:{description:{t:0,b:{t:2,i:[{t:3}],s:"Elevenlabs.io"}},fields:{field:{"simularity-boost":{description:{t:0,b:{t:2,i:[{t:3}],s:"声音相似性依从性"}},label:{t:0,b:{t:2,i:[{t:3}],s:"相似度修正"}}},"speaker-boost":{description:{t:0,b:{t:2,i:[{t:3}],s:"增强说话者的相似性"}},label:{t:0,b:{t:2,i:[{t:3}],s:"扬声器增强"}}},speed:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音生成速度"}},label:{t:0,b:{t:2,i:[{t:3}],s:"语速"}}},stability:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音稳定性和随机性"}},label:{t:0,b:{t:2,i:[{t:3}],s:"稳定性"}}},style:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音风格夸张"}},label:{t:0,b:{t:2,i:[{t:3}],s:"风格"}}}}},playground:{buttons:{button:{"test-voice":{generating:{t:0,b:{t:2,i:[{t:3}],s:"生成中..."}},label:{t:0,b:{t:2,i:[{t:3}],s:"测试声音"}}}}},fields:{field:{input:{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入用于测试发音的文本"}}},language:{description:{t:0,b:{t:2,i:[{t:3}],s:"选择语音语言"}},label:{t:0,b:{t:2,i:[{t:3}],s:"语言"}}},voice:{description:{t:0,b:{t:2,i:[{t:3}],s:"选择首选语音"}},label:{t:0,b:{t:2,i:[{t:3}],s:"声线"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"实验平台"}},validation:{"error-missing-api-key":{t:0,b:{t:2,i:[{t:3}],s:"需要填写 API Key 才能用哦!"}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"ElevenLabs (11labs)"}}},fireworks:{description:{t:0,b:{t:2,i:[{t:3}],s:"Fireworks.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Fireworks.ai"}}},"microsoft-speech":{description:{t:0,b:{t:2,i:[{t:3}],s:"speech.microsoft.com"}},fields:{field:{region:{description:{t:0,b:{t:2,i:[{t:3}],s:"服务 Endpoint 地区(比如亚太 eastasia 区域)"}},label:{t:0,b:{t:2,i:[{t:3}],s:"Endpoint 地区"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"Microsoft / Azure 语音服务"}}},mistral:{description:{t:0,b:{t:2,i:[{t:3}],s:"mistral.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Mistral"}}},moonshot:{description:{t:0,b:{t:2,i:[{t:3}],s:"Moonshot.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"月之暗面"}}},novita:{description:{t:0,b:{t:2,i:[{t:3}],s:"novita.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Novita"}}},ollama:{description:{t:0,b:{t:2,i:[{t:3}],s:"ollama.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Ollama"}}},openai:{description:{t:0,b:{t:2,i:[{t:3}],s:"OpenAi.com"}},title:{t:0,b:{t:2,i:[{t:3}],s:"OpenAI"}}},openrouter:{description:{t:0,b:{t:2,i:[{t:3}],s:"OpenRouter.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"OpenRouter"}}},perplexity:{description:{t:0,b:{t:2,i:[{t:3}],s:"perplexity.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Perplexity"}}},together:{description:{t:0,b:{t:2,i:[{t:3}],s:"一起"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Together.ai"}}},vllm:{description:{t:0,b:{t:2,i:[{t:3}],s:"vllm.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"vLLM"}}},volcengine:{description:{t:0,b:{t:2,i:[{t:3}],s:"volcengine.com"}},fields:{field:{appId:{description:{t:0,b:{t:2,i:[{t:3}],s:"可在控制台获取的 App ID"}},label:{t:0,b:{t:2,i:[{t:3}],s:"App ID"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"火山引擎"}}},xai:{description:{t:0,b:{t:2,i:[{t:3}],s:"X.AI"}},title:{t:0,b:{t:2,i:[{t:3}],s:"xAI"}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"提供商"}}},scene:{description:{t:0,b:{t:2,i:[{t:3}],s:"配置角色所在环境"}},title:{t:0,b:{t:2,i:[{t:3}],s:"场景"}}},themes:{description:{t:0,b:{t:2,i:[{t:3}],s:"自定义你的舞台外观!"}},sections:{section:{"custom-color":{fields:{field:{"primary-color":{label:{t:0,b:{t:2,i:[{t:3}],s:"强调色"}},"rgb-on":{title:{t:0,b:{t:2,i:[{t:3}],s:"RGB ON!"}}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"配色"}}},developer:{title:{t:0,b:{t:2,i:[{t:3}],s:"开发者"}}},"theme-presets":{presets:[{colors:[{t:0,b:{t:2,i:[{t:3}],s:"Airi 绿"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"默认的绿色主题,由 Airi 为您带来!"}},title:{t:0,b:{t:2,i:[{t:3}],s:"默认颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"灰褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"米色"}},{t:0,b:{t:2,i:[{t:3}],s:"灰白色"}},{t:0,b:{t:2,i:[{t:3}],s:"浅灰褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"象牙色"}},{t:0,b:{t:2,i:[{t:3}],s:"橄榄灰"}},{t:0,b:{t:2,i:[{t:3}],s:"沙色"}},{t:0,b:{t:2,i:[{t:3}],s:"暖灰色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"受乔治·莫兰迪绘画启发的柔和、低调的色调"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Morandi 颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"天蓝色"}},{t:0,b:{t:2,i:[{t:3}],s:"薄雾色"}},{t:0,b:{t:2,i:[{t:3}],s:"沙色"}},{t:0,b:{t:2,i:[{t:3}],s:"苔藓绿"}},{t:0,b:{t:2,i:[{t:3}],s:"睡莲色"}},{t:0,b:{t:2,i:[{t:3}],s:"小麦色"}},{t:0,b:{t:2,i:[{t:3}],s:"板岩蓝"}},{t:0,b:{t:2,i:[{t:3}],s:"鼠尾草色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"受克劳德·莫奈作品启发的印象派调色板"}},title:{t:0,b:{t:2,i:[{t:3}],s:"莫奈颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"棕褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"暖灰褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"赭色"}},{t:0,b:{t:2,i:[{t:3}],s:"咖啡色"}},{t:0,b:{t:2,i:[{t:3}],s:"青铜色"}},{t:0,b:{t:2,i:[{t:3}],s:"金色"}},{t:0,b:{t:2,i:[{t:3}],s:"芥末色"}},{t:0,b:{t:2,i:[{t:3}],s:"琥珀色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"传统日本色彩调色板"}},title:{t:0,b:{t:2,i:[{t:3}],s:"日本颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"北欧蓝"}},{t:0,b:{t:2,i:[{t:3}],s:"冰色"}},{t:0,b:{t:2,i:[{t:3}],s:"峡湾色"}},{t:0,b:{t:2,i:[{t:3}],s:"钢铁色"}},{t:0,b:{t:2,i:[{t:3}],s:"冰川色"}},{t:0,b:{t:2,i:[{t:3}],s:"板岩色"}},{t:0,b:{t:2,i:[{t:3}],s:"云色"}},{t:0,b:{t:2,i:[{t:3}],s:"石头色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"北欧极简主义配色方案"}},title:{t:0,b:{t:2,i:[{t:3}],s:"北欧颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"霞光红"}},{t:0,b:{t:2,i:[{t:3}],s:"枣红"}},{t:0,b:{t:2,i:[{t:3}],s:"黄栌"}},{t:0,b:{t:2,i:[{t:3}],s:"竹青"}},{t:0,b:{t:2,i:[{t:3}],s:"乌梅紫"}},{t:0,b:{t:2,i:[{t:3}],s:"缃色"}},{t:0,b:{t:2,i:[{t:3}],s:"青冥"}},{t:0,b:{t:2,i:[{t:3}],s:"赭石"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"中国传统色彩,源自古代纺织品、瓷器和绘画"}},title:{t:0,b:{t:2,i:[{t:3}],s:"中国传统颜色"}}}],title:{t:0,b:{t:2,i:[{t:3}],s:"预设"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"外观"}}}},sections:{section:{general:{title:{t:0,b:{t:2,i:[{t:3}],s:"通用"}}}}},theme:{t:0,b:{t:2,i:[{t:3}],s:"主题"}},title:{t:0,b:{t:2,i:[{t:3}],s:"设置"}},voices:{t:0,b:{t:2,i:[{t:3}],s:"声线"}}},stage:{chat:{message:{"character-name":{airi:{t:0,b:{t:2,i:[{t:3}],s:"Airi"}},"core-system":{t:0,b:{t:2,i:[{t:3}],s:"核心系统"}},you:{t:0,b:{t:2,i:[{t:3}],s:"你"}}}},tabs:{chat:{t:0,b:{t:2,i:[{t:3}],s:"聊天"}},clothes:{t:0,b:{t:2,i:[{t:3}],s:"换装"}},custom:{t:0,b:{t:2,i:[{t:3}],s:"自定义"}}}},message:{t:0,b:{t:2,i:[{t:3}],s:"消息"}},"select-a-audio-input":{t:0,b:{t:2,i:[{t:3}],s:"选择一个音频输入设备"}},"select-a-model":{t:0,b:{t:2,i:[{t:3}],s:"选择一个模型"}},"select-a-voice":{t:0,b:{t:2,i:[{t:3}],s:"选择一个声线"}},viewers:{"debug-menu":{emotions:{t:0,b:{t:2,i:[{t:3}],s:"表情"}},"emotions-btn":{angry:{t:0,b:{t:2,i:[{t:3}],s:"生气"}},awkward:{t:0,b:{t:2,i:[{t:3}],s:"尴尬"}},happy:{t:0,b:{t:2,i:[{t:3}],s:"开心"}},neutral:{t:0,b:{t:2,i:[{t:3}],s:"日常"}},question:{t:0,b:{t:2,i:[{t:3}],s:"疑问"}},sad:{t:0,b:{t:2,i:[{t:3}],s:"难过"}},surprised:{t:0,b:{t:2,i:[{t:3}],s:"惊喜"}},think:{t:0,b:{t:2,i:[{t:3}],s:"思考"}}},vrm:{camera:{t:0,b:{t:2,i:[{t:3}],s:"摄像机"}},model:{title:{t:0,b:{t:2,i:[{t:3}],s:"模型"}}}}}},waiting:{t:0,b:{t:2,i:[{t:3}],s:"等待中"}}}}}),K9=k9({locale:Z9(),fallbackLocale:"en",messages:YA});function Z9(){const n=localStorage.getItem("settings/language"),e=Object.keys(YA);return n&&e.includes(n)?n:"en"}const J9=Oz(),Q9=Hz(qV);let eu;eu=WV({routes:Q9,history:bV()});eu.beforeEach((n,e)=>{n.path!==e.path&&Rw.start()});eu.afterEach(()=>{Rw.done()});eu.isReady().then(async()=>{}).catch(()=>{});NR(j9).use(Rz).use(t3).use(eu).use(J9).use(K9).use(yB).mount("#app");export{qe as $,Kl as A,Pc as B,tG as C,G2 as D,$2 as E,jt as F,DH as G,Hn as H,rs as I,_G as J,cG as K,je as L,LG as M,lG as N,s0 as O,zV as P,Pt as Q,$w as R,$V as S,gG as T,AG as U,vG as V,Ae as W,de as X,z as Y,st as Z,No as _,SG as a,ow as a$,Cn as a0,Vn as a1,Q0 as a2,Jn as a3,li as a4,ca as a5,Hs as a6,Ii as a7,$t as a8,Gn as a9,jc as aA,kl as aB,Gg as aC,lt as aD,ox as aE,Qr as aF,lf as aG,qn as aH,Q4 as aI,fw as aJ,HT as aK,kg as aL,dw as aM,o5 as aN,Id as aO,W4 as aP,G4 as aQ,B4 as aR,F4 as aS,k4 as aT,F_ as aU,cw as aV,U4 as aW,lw as aX,N4 as aY,aw as aZ,U_ as a_,ls as aa,vc as ab,zi as ac,Ar as ad,rE as ae,Te as af,ht as ag,Ct as ah,P3 as ai,ot as aj,br as ak,fE as al,mL as am,xh as an,DL as ao,Oc as ap,_c as aq,mc as ar,Xc as as,RR as at,R_ as au,xi as av,Pd as aw,$B as ax,Ft as ay,Kc as az,Ot as b,jn as b$,PB as b0,oi as b1,FG as b2,wr as b3,Oe as b4,qd as b5,x0 as b6,cS as b7,dS as b8,oG as b9,iG as bA,yG as bB,sG as bC,ut as bD,RG as bE,IG as bF,CG as bG,CR as bH,Di as bI,hn as bJ,xG as bK,UG as bL,OG as bM,n3 as bN,i3 as bO,ST as bP,MG as bQ,as as bR,gL as bS,kh as bT,Kt as bU,Ba as bV,lr as bW,mt as bX,Sd as bY,bh as bZ,To as b_,An as ba,mf as bb,ai as bc,mn as bd,Ns as be,uG as bf,f2 as bg,hS as bh,kn as bi,gr as bj,Fi as bk,aG as bl,L0 as bm,b0 as bn,PS as bo,dG as bp,pG as bq,A0 as br,pr as bs,GB as bt,AR as bu,Yw as bv,wG as bw,EG as bx,TG as by,nG as bz,yi as c,DG as c$,wn as c0,gt as c1,yL as c2,vn as c3,Va as c4,fG as c5,bG as c6,Ro as c7,os as c8,ka as c9,Mg as cA,Bs as cB,PE as cC,Eo as cD,Un as cE,WE as cF,XE as cG,$E as cH,dE as cI,Ca as cJ,kI as cK,WI as cL,s_ as cM,f_ as cN,pE as cO,mE as cP,i_ as cQ,gc as cR,ft as cS,Us as cT,Wc as cU,cL as cV,vB as cW,Pz as cX,CT as cY,Ng as cZ,Ga as c_,ts as ca,Sh as cb,Wt as cc,zn as cd,oc as ce,yh as cf,ns as cg,_n as ch,gi as ci,RE as cj,dg as ck,vL as cl,M_ as cm,Tf as cn,H0 as co,aa as cp,en as cq,El as cr,Qi as cs,sc as ct,rc as cu,OL as cv,f3 as cw,h3 as cx,d3 as cy,ei as cz,fn as d,PG as d0,WB as d1,NG as d2,or as e,h2 as f,cp as g,Me as h,pn as i,Lv as j,W2 as k,d2 as l,hG as m,Ua as n,gn as o,zz as p,vs as q,et as r,Vz as s,vC as t,mG as u,Xe as v,R0 as w,rG as x,Qv as y,Si as z}; +`}}},settings:{animations:{"stage-transitions":{title:{t:0,b:{t:2,i:[{t:3}],s:"是否开启舞台动画"}}},"use-page-specific-transitions":{description:{t:0,b:{t:2,i:[{t:3}],s:"某些页面会有自己的过场动画,这将覆盖舞台过场动画"}},title:{t:0,b:{t:2,i:[{t:3}],s:"是否使用页面特定过场动画"}}}},language:{chinese:{t:0,b:{t:2,i:[{t:3}],s:"简体中文"}},english:{t:0,b:{t:2,i:[{t:3}],s:"English"}},title:{t:0,b:{t:2,i:[{t:3}],s:"语言"}}},live2d:{"change-model":{"from-file":{t:0,b:{t:2,i:[{t:3}],s:"从文件加载"}},"from-file-select":{t:0,b:{t:2,i:[{t:3}],s:"选择"}},"from-url":{t:0,b:{t:2,i:[{t:3}],s:"从 URL 加载"}},"from-url-confirm":{t:0,b:{t:2,i:[{t:3}],s:"加载"}},"from-url-placeholder":{t:0,b:{t:2,i:[{t:3}],s:"输入 Live2D 模型 URL"}},title:{t:0,b:{t:2,i:[{t:3}],s:"更换模型"}}},"edit-motion-map":{title:{t:0,b:{t:2,i:[{t:3}],s:"编辑动作映射"}}},"map-motions":{play:{t:0,b:{t:2,i:[{t:3}],s:"播放动作"}},title:{t:0,b:{t:2,i:[{t:3}],s:"映射动作"}}},title:{t:0,b:{t:2,i:[{t:3}],s:"Live2D 设置"}}},microphone:{t:0,b:{t:2,i:[{t:3}],s:"麦克风"}},models:{t:0,b:{t:2,i:[{t:3}],s:"模型"}},pages:{card:{activate:{t:0,b:{t:2,i:[{t:3}],s:"激活"}},active:{t:0,b:{t:2,i:[{t:3}],s:"已激活"}},active_badge:{t:0,b:{t:2,i:[{t:3}],s:"当前使用中"}},cancel:{t:0,b:{t:2,i:[{t:3}],s:"取消"}},card_not_found:{t:0,b:{t:2,i:[{t:3}],s:"未找到角色卡"}},character:{t:0,b:{t:2,i:[{t:3}],s:"角色设定"}},close:{t:0,b:{t:2,i:[{t:3}],s:"关闭"}},consciousness:{model:{t:0,b:{t:2,i:[{t:3}],s:"意识 / 模型"}}},created_by:{t:0,b:{t:2,i:[{t:3}],s:"创建者"}},creator_notes:{t:0,b:{t:2,i:[{t:3}],s:"创建者笔记"}},delete:{t:0,b:{t:2,i:[{t:3}],s:"删除"}},delete_card:{t:0,b:{t:2,i:[{t:3}],s:"删除角色卡"}},delete_confirmation:{t:0,b:{t:2,i:[{t:3}],s:"确定要删除这张角色卡吗?"}},description:{t:0,b:{t:2,i:[{t:3}],s:"使用 Airi 角色卡预设"}},description_label:{t:0,b:{t:2,i:[{t:3}],s:"描述"}},drop_here:{t:0,b:{t:2,i:[{t:3}],s:"放开以上传文件"}},modules:{t:0,b:{t:2,i:[{t:3}],s:"模块"}},name_asc:{t:0,b:{t:2,i:[{t:3}],s:"名称 (A-Z)"}},name_desc:{t:0,b:{t:2,i:[{t:3}],s:"名称 (Z-A)"}},no_cards:{t:0,b:{t:2,i:[{t:3}],s:"还没有任何角色卡,点击上方按钮上传一个吧!"}},no_results:{t:0,b:{t:2,i:[{t:3}],s:"没有找到匹配的角色卡"}},personality:{t:0,b:{t:2,i:[{t:3}],s:"性格"}},posthistoryinstructions:{t:0,b:{t:2,i:[{t:3}],s:"历史提示指令"}},recent:{t:0,b:{t:2,i:[{t:3}],s:"最近添加"}},scenario:{t:0,b:{t:2,i:[{t:3}],s:"场景"}},search:{t:0,b:{t:2,i:[{t:3}],s:"搜索角色卡..."}},sort_by:{t:0,b:{t:2,i:[{t:3}],s:"排序方式"}},speech:{model:{t:0,b:{t:2,i:[{t:3}],s:"声音 / 模型"}},voice:{t:0,b:{t:2,i:[{t:3}],s:"声音 / 声线"}}},systemprompt:{t:0,b:{t:2,i:[{t:3}],s:"系统提示词"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Airi 角色卡"}},try_different_search:{t:0,b:{t:2,i:[{t:3}],s:"尝试使用其他关键词搜索"}},upload:{t:0,b:{t:2,i:[{t:3}],s:"上传"}},upload_desc:{t:0,b:{t:2,i:[{t:3}],s:"点击或拖拽文件到此处上传"}}},memory:{description:{t:0,b:{t:2,i:[{t:3}],s:"存放记忆的地方,以及策略"}},title:{t:0,b:{t:2,i:[{t:3}],s:"记忆体"}}},models:{description:{t:0,b:{t:2,i:[{t:3}],s:"切换角色的 Live2D,VRM 模型"}},title:{t:0,b:{t:2,i:[{t:3}],s:"角色模型"}}},modules:{consciousness:{description:{t:0,b:{t:2,i:[{t:3}],s:"人格设定、使用的模型等配置"}},sections:{section:{"provider-model-selection":{collapse:{t:0,b:{t:2,i:[{t:3}],s:"折叠"}},custom_model_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入自订模型名字"}},description:{t:0,b:{t:2,i:[{t:3}],s:"为意识选择合适的 LLM 提供商"}},error:{t:0,b:{t:2,i:[{t:3}],s:"获取出错啦"}},expand:{t:0,b:{t:2,i:[{t:3}],s:"展开"}},loading:{t:0,b:{t:2,i:[{t:3}],s:"获取模型中..."}},manual_model_name:{t:0,b:{t:2,i:[{t:3}],s:"模型名字"}},manual_model_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入与该提供商一起使用的模型名字"}},no_models:{t:0,b:{t:2,i:[{t:3}],s:"没有任何可用的模型"}},no_models_description:{t:0,b:{t:2,i:[{t:3}],s:"该提供商的模型列表没有返回任何的数据"}},no_search_results:{t:0,b:{t:2,i:[{t:3}],s:"没有匹配的模型"}},no_search_results_description:{t:0,b:{t:2,i:[{t:3,v:"没有模型匹配 '"},{t:4,k:"query"},{t:3,v:"' 关键字,请尝试一下别的关键词呢"}]}},not_supported:{t:0,b:{t:2,i:[{t:3}],s:"无法列出模型"}},not_supported_description:{t:0,b:{t:2,i:[{t:3}],s:"此提供商不支持列出模型的功能"}},search_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"搜索模型..."}},search_results:{t:0,b:{t:2,i:[{t:3,v:"找到 "},{t:4,k:"count"},{t:3,v:" / "},{t:4,k:"total"},{t:3,v:" 个模型"}]}},show_less:{t:0,b:{t:2,i:[{t:3}],s:"显示更多"}},show_more:{t:0,b:{t:2,i:[{t:3}],s:"收起"}},subtitle:{t:0,b:{t:2,i:[{t:3}],s:"选择一个模型"}},title:{t:0,b:{t:2,i:[{t:3}],s:"模型"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"意识"}}},description:{t:0,b:{t:2,i:[{t:3}],s:"思维,视觉,言语综合,游戏等"}},"gaming-factorio":{description:{t:0,b:{t:2,i:[{t:3}],s:"一起玩 Factorio!"}},title:{t:0,b:{t:2,i:[{t:3}],s:"异星工厂 Factorio"}}},"gaming-minecraft":{description:{t:0,b:{t:2,i:[{t:3}],s:"一起 Minecraft!"}},title:{t:0,b:{t:2,i:[{t:3}],s:"我的世界 Minecraft"}}},hearing:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音识别"}},title:{t:0,b:{t:2,i:[{t:3}],s:"听觉"}}},"memory-long-term":{description:{t:0,b:{t:2,i:[{t:3}],s:"长期记忆"}},title:{t:0,b:{t:2,i:[{t:3}],s:"长期记忆"}}},"memory-short-term":{description:{t:0,b:{t:2,i:[{t:3}],s:"短期记忆"}},title:{t:0,b:{t:2,i:[{t:3}],s:"短期记忆"}}},"messaging-discord":{description:{t:0,b:{t:2,i:[{t:3}],s:"Discord 发消息和语音聊天"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Discord"}}},speech:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音合成"}},sections:{section:{playground:{buttons:{stop:{label:{t:0,b:{t:2,i:[{t:3}],s:"停止"}}}},"select-voice":{required:{t:0,b:{t:2,i:[{t:3}],s:"请选择声线"}}}},"provider-voice-selection":{custom_model_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入指定模型名字..."}},custom_voice_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入指定声线 ID..."}},description:{t:0,b:{t:2,i:[{t:3}],s:"选择合适的语音提供商"}},no_models:{t:0,b:{t:2,i:[{t:3}],s:"没有任何可用的模型"}},no_models_description:{t:0,b:{t:2,i:[{t:3}],s:"该提供商的模型列表没有返回任何的数据"}},no_voices:{t:0,b:{t:2,i:[{t:3}],s:"没有任何可用的声线"}},no_voices_description:{t:0,b:{t:2,i:[{t:3}],s:"该提供商的声线列表没有返回任何的数据"}},pause:{t:0,b:{t:2,i:[{t:3}],s:"Pause"}},play_sample:{t:0,b:{t:2,i:[{t:3}],s:"Play"}},search_models_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"搜索模型..."}},search_models_results:{t:0,b:{t:2,i:[{t:3,v:"找到 "},{t:4,k:"count"},{t:3,v:" / "},{t:4,k:"total"},{t:3,v:" 个模型"}]}},search_voices_placeholder:{t:0,b:{t:2,i:[{t:3}],s:"搜索声线..."}},search_voices_results:{t:0,b:{t:2,i:[{t:3,v:"找到 "},{t:4,k:"count"},{t:3,v:" / "},{t:4,k:"total"},{t:3,v:" 个声线"}]}},show_less:{t:0,b:{t:2,i:[{t:3}],s:"显示更少"}},show_more:{t:0,b:{t:2,i:[{t:3}],s:"显示更多"}},title:{t:0,b:{t:2,i:[{t:3}],s:"选择语音合成提供商"}}},"voice-settings":{"input-ssml":{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请输入 SSML 文本"}}},"use-ssml":{description:{t:0,b:{t:2,i:[{t:3}],s:"启用后可以输入原始 SSML 而不是纯文本"}},label:{t:0,b:{t:2,i:[{t:3}],s:"选用自定义 SSML"}}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"发声"}}},title:{t:0,b:{t:2,i:[{t:3}],s:"机体模块"}},vision:{description:{t:0,b:{t:2,i:[{t:3}],s:"视觉"}},title:{t:0,b:{t:2,i:[{t:3}],s:"视觉"}}},x:{description:{t:0,b:{t:2,i:[{t:3}],s:"X / Twitter 的浏览和使用"}},title:{t:0,b:{t:2,i:[{t:3}],s:"X / Twitter"}}}},providers:{common:{fields:{field:{"api-key":{label:{t:0,b:{t:2,i:[{t:3}],s:"API 密钥"}}}}},section:{advanced:{fields:{field:{headers:{description:{t:0,b:{t:2,i:[{t:3}],s:"添加自定义 HTTP 标头"}},key:{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请求头名字"}}},label:{t:0,b:{t:2,i:[{t:3}],s:"HTTP 请求头"}},value:{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请求头数值"}}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"高级配置"}}},basic:{description:{t:0,b:{t:2,i:[{t:3}],s:"基本设置"}},title:{t:0,b:{t:2,i:[{t:3}],s:"基础配置"}}},voice:{title:{t:0,b:{t:2,i:[{t:3}],s:"声音配置"}}}}},description:{t:0,b:{t:2,i:[{t:3}],s:"LLM,语音合成,语音识别提供商等"}},provider:{"alibaba-cloud-model-studio":{description:{t:0,b:{t:2,i:[{t:3}],s:"bailian.console.aliyun.com"}},title:{t:0,b:{t:2,i:[{t:3}],s:"阿里百炼"}}},anthropic:{description:{t:0,b:{t:2,i:[{t:3}],s:"anthropic.com"}},title:{t:0,b:{t:1,c:[{t:2,i:[{t:3}],s:"Anthropic"},{t:2,i:[{t:3}],s:"Claude"}]}}},"cloudflare-workers-ai":{description:{t:0,b:{t:2,i:[{t:3}],s:"Cloudflare.com"}},fields:{field:{"account-id":{description:{t:0,b:{t:2,i:[{t:3}],s:"Cloudflare 帐户 ID"}},label:{t:0,b:{t:2,i:[{t:3}],s:"Cloudflare Account ID"}},placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请输入 Cloudflare Account ID"}}},"api-key":{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"请输入 Cloudflare Workers AI 的 API Key"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"Workers AI"}}},common:{fields:{field:{pitch:{description:{t:0,b:{t:2,i:[{t:3}],s:"调节合成语音的音高(比如更尖锐或更粗旷)"}},label:{t:0,b:{t:2,i:[{t:3}],s:"音高"}}},speed:{description:{t:0,b:{t:2,i:[{t:3}],s:"调节说话的语速"}},label:{t:0,b:{t:2,i:[{t:3}],s:"语速"}}},volume:{description:{t:0,b:{t:2,i:[{t:3}],s:"调节语音的响度"}},label:{t:0,b:{t:2,i:[{t:3}],s:"响度"}}}}}},deepseek:{description:{t:0,b:{t:2,i:[{t:3}],s:"DeepSeek.com"}},title:{t:0,b:{t:2,i:[{t:3}],s:"深度求索 DeepSeek"}}},elevenlabs:{description:{t:0,b:{t:2,i:[{t:3}],s:"Elevenlabs.io"}},fields:{field:{"simularity-boost":{description:{t:0,b:{t:2,i:[{t:3}],s:"声音相似性依从性"}},label:{t:0,b:{t:2,i:[{t:3}],s:"相似度修正"}}},"speaker-boost":{description:{t:0,b:{t:2,i:[{t:3}],s:"增强说话者的相似性"}},label:{t:0,b:{t:2,i:[{t:3}],s:"扬声器增强"}}},speed:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音生成速度"}},label:{t:0,b:{t:2,i:[{t:3}],s:"语速"}}},stability:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音稳定性和随机性"}},label:{t:0,b:{t:2,i:[{t:3}],s:"稳定性"}}},style:{description:{t:0,b:{t:2,i:[{t:3}],s:"语音风格夸张"}},label:{t:0,b:{t:2,i:[{t:3}],s:"风格"}}}}},playground:{buttons:{button:{"test-voice":{generating:{t:0,b:{t:2,i:[{t:3}],s:"生成中..."}},label:{t:0,b:{t:2,i:[{t:3}],s:"测试声音"}}}}},fields:{field:{input:{placeholder:{t:0,b:{t:2,i:[{t:3}],s:"输入用于测试发音的文本"}}},language:{description:{t:0,b:{t:2,i:[{t:3}],s:"选择语音语言"}},label:{t:0,b:{t:2,i:[{t:3}],s:"语言"}}},voice:{description:{t:0,b:{t:2,i:[{t:3}],s:"选择首选语音"}},label:{t:0,b:{t:2,i:[{t:3}],s:"声线"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"实验平台"}},validation:{"error-missing-api-key":{t:0,b:{t:2,i:[{t:3}],s:"需要填写 API Key 才能用哦!"}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"ElevenLabs (11labs)"}}},fireworks:{description:{t:0,b:{t:2,i:[{t:3}],s:"Fireworks.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Fireworks.ai"}}},"microsoft-speech":{description:{t:0,b:{t:2,i:[{t:3}],s:"speech.microsoft.com"}},fields:{field:{region:{description:{t:0,b:{t:2,i:[{t:3}],s:"服务 Endpoint 地区(比如亚太 eastasia 区域)"}},label:{t:0,b:{t:2,i:[{t:3}],s:"Endpoint 地区"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"Microsoft / Azure 语音服务"}}},mistral:{description:{t:0,b:{t:2,i:[{t:3}],s:"mistral.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Mistral"}}},moonshot:{description:{t:0,b:{t:2,i:[{t:3}],s:"Moonshot.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"月之暗面"}}},novita:{description:{t:0,b:{t:2,i:[{t:3}],s:"novita.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Novita"}}},ollama:{description:{t:0,b:{t:2,i:[{t:3}],s:"ollama.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Ollama"}}},openai:{description:{t:0,b:{t:2,i:[{t:3}],s:"OpenAi.com"}},title:{t:0,b:{t:2,i:[{t:3}],s:"OpenAI"}}},openrouter:{description:{t:0,b:{t:2,i:[{t:3}],s:"OpenRouter.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"OpenRouter"}}},perplexity:{description:{t:0,b:{t:2,i:[{t:3}],s:"perplexity.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Perplexity"}}},together:{description:{t:0,b:{t:2,i:[{t:3}],s:"一起"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Together.ai"}}},vllm:{description:{t:0,b:{t:2,i:[{t:3}],s:"vllm.ai"}},title:{t:0,b:{t:2,i:[{t:3}],s:"vLLM"}}},volcengine:{description:{t:0,b:{t:2,i:[{t:3}],s:"volcengine.com"}},fields:{field:{appId:{description:{t:0,b:{t:2,i:[{t:3}],s:"可在控制台获取的 App ID"}},label:{t:0,b:{t:2,i:[{t:3}],s:"App ID"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"火山引擎"}}},xai:{description:{t:0,b:{t:2,i:[{t:3}],s:"X.AI"}},title:{t:0,b:{t:2,i:[{t:3}],s:"xAI"}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"提供商"}}},scene:{description:{t:0,b:{t:2,i:[{t:3}],s:"配置角色所在环境"}},title:{t:0,b:{t:2,i:[{t:3}],s:"场景"}}},themes:{description:{t:0,b:{t:2,i:[{t:3}],s:"自定义你的舞台外观!"}},sections:{section:{"custom-color":{fields:{field:{"primary-color":{label:{t:0,b:{t:2,i:[{t:3}],s:"强调色"}},"rgb-on":{title:{t:0,b:{t:2,i:[{t:3}],s:"RGB ON!"}}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"配色"}}},developer:{title:{t:0,b:{t:2,i:[{t:3}],s:"开发者"}}},"theme-presets":{presets:[{colors:[{t:0,b:{t:2,i:[{t:3}],s:"Airi 绿"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"默认的绿色主题,由 Airi 为您带来!"}},title:{t:0,b:{t:2,i:[{t:3}],s:"默认颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"灰褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"米色"}},{t:0,b:{t:2,i:[{t:3}],s:"灰白色"}},{t:0,b:{t:2,i:[{t:3}],s:"浅灰褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"象牙色"}},{t:0,b:{t:2,i:[{t:3}],s:"橄榄灰"}},{t:0,b:{t:2,i:[{t:3}],s:"沙色"}},{t:0,b:{t:2,i:[{t:3}],s:"暖灰色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"受乔治·莫兰迪绘画启发的柔和、低调的色调"}},title:{t:0,b:{t:2,i:[{t:3}],s:"Morandi 颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"天蓝色"}},{t:0,b:{t:2,i:[{t:3}],s:"薄雾色"}},{t:0,b:{t:2,i:[{t:3}],s:"沙色"}},{t:0,b:{t:2,i:[{t:3}],s:"苔藓绿"}},{t:0,b:{t:2,i:[{t:3}],s:"睡莲色"}},{t:0,b:{t:2,i:[{t:3}],s:"小麦色"}},{t:0,b:{t:2,i:[{t:3}],s:"板岩蓝"}},{t:0,b:{t:2,i:[{t:3}],s:"鼠尾草色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"受克劳德·莫奈作品启发的印象派调色板"}},title:{t:0,b:{t:2,i:[{t:3}],s:"莫奈颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"棕褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"暖灰褐色"}},{t:0,b:{t:2,i:[{t:3}],s:"赭色"}},{t:0,b:{t:2,i:[{t:3}],s:"咖啡色"}},{t:0,b:{t:2,i:[{t:3}],s:"青铜色"}},{t:0,b:{t:2,i:[{t:3}],s:"金色"}},{t:0,b:{t:2,i:[{t:3}],s:"芥末色"}},{t:0,b:{t:2,i:[{t:3}],s:"琥珀色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"传统日本色彩调色板"}},title:{t:0,b:{t:2,i:[{t:3}],s:"日本颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"北欧蓝"}},{t:0,b:{t:2,i:[{t:3}],s:"冰色"}},{t:0,b:{t:2,i:[{t:3}],s:"峡湾色"}},{t:0,b:{t:2,i:[{t:3}],s:"钢铁色"}},{t:0,b:{t:2,i:[{t:3}],s:"冰川色"}},{t:0,b:{t:2,i:[{t:3}],s:"板岩色"}},{t:0,b:{t:2,i:[{t:3}],s:"云色"}},{t:0,b:{t:2,i:[{t:3}],s:"石头色"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"北欧极简主义配色方案"}},title:{t:0,b:{t:2,i:[{t:3}],s:"北欧颜色"}}},{colors:[{t:0,b:{t:2,i:[{t:3}],s:"霞光红"}},{t:0,b:{t:2,i:[{t:3}],s:"枣红"}},{t:0,b:{t:2,i:[{t:3}],s:"黄栌"}},{t:0,b:{t:2,i:[{t:3}],s:"竹青"}},{t:0,b:{t:2,i:[{t:3}],s:"乌梅紫"}},{t:0,b:{t:2,i:[{t:3}],s:"缃色"}},{t:0,b:{t:2,i:[{t:3}],s:"青冥"}},{t:0,b:{t:2,i:[{t:3}],s:"赭石"}}],description:{t:0,b:{t:2,i:[{t:3}],s:"中国传统色彩,源自古代纺织品、瓷器和绘画"}},title:{t:0,b:{t:2,i:[{t:3}],s:"中国传统颜色"}}}],title:{t:0,b:{t:2,i:[{t:3}],s:"预设"}}}}},title:{t:0,b:{t:2,i:[{t:3}],s:"外观"}}}},sections:{section:{general:{title:{t:0,b:{t:2,i:[{t:3}],s:"通用"}}}}},theme:{t:0,b:{t:2,i:[{t:3}],s:"主题"}},title:{t:0,b:{t:2,i:[{t:3}],s:"设置"}},voices:{t:0,b:{t:2,i:[{t:3}],s:"声线"}}},stage:{chat:{message:{"character-name":{airi:{t:0,b:{t:2,i:[{t:3}],s:"Airi"}},"core-system":{t:0,b:{t:2,i:[{t:3}],s:"核心系统"}},you:{t:0,b:{t:2,i:[{t:3}],s:"你"}}}},tabs:{chat:{t:0,b:{t:2,i:[{t:3}],s:"聊天"}},clothes:{t:0,b:{t:2,i:[{t:3}],s:"换装"}},custom:{t:0,b:{t:2,i:[{t:3}],s:"自定义"}}}},message:{t:0,b:{t:2,i:[{t:3}],s:"消息"}},"select-a-audio-input":{t:0,b:{t:2,i:[{t:3}],s:"选择一个音频输入设备"}},"select-a-model":{t:0,b:{t:2,i:[{t:3}],s:"选择一个模型"}},"select-a-voice":{t:0,b:{t:2,i:[{t:3}],s:"选择一个声线"}},viewers:{"debug-menu":{emotions:{t:0,b:{t:2,i:[{t:3}],s:"表情"}},"emotions-btn":{angry:{t:0,b:{t:2,i:[{t:3}],s:"生气"}},awkward:{t:0,b:{t:2,i:[{t:3}],s:"尴尬"}},happy:{t:0,b:{t:2,i:[{t:3}],s:"开心"}},neutral:{t:0,b:{t:2,i:[{t:3}],s:"日常"}},question:{t:0,b:{t:2,i:[{t:3}],s:"疑问"}},sad:{t:0,b:{t:2,i:[{t:3}],s:"难过"}},surprised:{t:0,b:{t:2,i:[{t:3}],s:"惊喜"}},think:{t:0,b:{t:2,i:[{t:3}],s:"思考"}}},vrm:{camera:{t:0,b:{t:2,i:[{t:3}],s:"摄像机"}},model:{title:{t:0,b:{t:2,i:[{t:3}],s:"模型"}}}}}},waiting:{t:0,b:{t:2,i:[{t:3}],s:"等待中"}}}}}),K9=k9({locale:Z9(),fallbackLocale:"en",messages:YA});function Z9(){const n=localStorage.getItem("settings/language"),e=Object.keys(YA);return n&&e.includes(n)?n:"en"}const J9=Oz(),Q9=Hz(qV);let eu;eu=WV({routes:Q9,history:bV()});eu.beforeEach((n,e)=>{n.path!==e.path&&Rw.start()});eu.afterEach(()=>{Rw.done()});eu.isReady().then(async()=>{}).catch(()=>{});NR(j9).use(Rz).use(t3).use(eu).use(J9).use(K9).use(yB).mount("#app");export{z as $,Kl as A,Pc as B,tG as C,G2 as D,$2 as E,jt as F,DH as G,Hn as H,rs as I,_G as J,cG as K,je as L,LG as M,lG as N,s0 as O,zV as P,Pt as Q,$w as R,$V as S,gG as T,Ew as U,FG as V,AG as W,vG as X,Ae as Y,de as Z,No as _,SG as a,wG as a$,st as a0,qe as a1,Cn as a2,Vn as a3,Q0 as a4,Jn as a5,li as a6,ca as a7,Hs as a8,Ii as a9,x0 as aA,cS as aB,dS as aC,oG as aD,An as aE,mf as aF,ai as aG,mn as aH,Ns as aI,uG as aJ,f2 as aK,hS as aL,kn as aM,gr as aN,Fi as aO,aG as aP,L0 as aQ,b0 as aR,PS as aS,xi as aT,dG as aU,pG as aV,A0 as aW,pr as aX,GB as aY,AR as aZ,Yw as a_,$t as aa,Gn as ab,ls as ac,vc as ad,zi as ae,Ar as af,rE as ag,Te as ah,ht as ai,Ct as aj,P3 as ak,ot as al,br as am,fE as an,mL as ao,xh as ap,DL as aq,Oc as ar,_c as as,mc as at,Xc as au,RR as av,R_ as aw,wr as ax,Oe as ay,qd as az,Ot as b,f3 as b$,EG as b0,TG as b1,nG as b2,iG as b3,yG as b4,sG as b5,ut as b6,RG as b7,IG as b8,CG as b9,fG as bA,bG as bB,Ro as bC,os as bD,ka as bE,ts as bF,Sh as bG,Wt as bH,zn as bI,oc as bJ,yh as bK,ns as bL,_n as bM,gi as bN,RE as bO,dg as bP,vL as bQ,M_ as bR,Tf as bS,H0 as bT,aa as bU,en as bV,El as bW,Qi as bX,sc as bY,rc as bZ,OL as b_,CR as ba,Di as bb,hn as bc,xG as bd,UG as be,OG as bf,n3 as bg,i3 as bh,ST as bi,MG as bj,as as bk,gL as bl,kh as bm,Kt as bn,Ba as bo,lr as bp,mt as bq,Sd as br,bh as bs,To as bt,jn as bu,wn as bv,gt as bw,yL as bx,vn as by,Va as bz,yi as c,h3 as c0,d3 as c1,ei as c2,Mg as c3,Bs as c4,PE as c5,Eo as c6,Un as c7,WE as c8,XE as c9,$E as ca,dE as cb,Ca as cc,kI as cd,WI as ce,s_ as cf,f_ as cg,pE as ch,mE as ci,i_ as cj,gc as ck,ft as cl,Us as cm,Wc as cn,cL as co,vB as cp,Pz as cq,CT as cr,Ng as cs,Ga as ct,DG as cu,PG as cv,WB as cw,NG as cx,fn as d,or as e,h2 as f,cp as g,Me as h,pn as i,Lv as j,W2 as k,d2 as l,hG as m,Ua as n,gn as o,zz as p,vs as q,et as r,Vz as s,vC as t,mG as u,Xe as v,R0 as w,rG as x,Qv as y,Si as z}; diff --git a/assets/index-DSso2JwG.js b/assets/index-DC4guwRc.js similarity index 84% rename from assets/index-DSso2JwG.js rename to assets/index-DC4guwRc.js index e164f0931f18816cf2dc56725023c24f382bb5c2..a535dd83bb5d8458535a4f5e612cd9e14d487d3e 100644 --- a/assets/index-DSso2JwG.js +++ b/assets/index-DC4guwRc.js @@ -1,12 +1,12 @@ -import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.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{be as getAugmentedNamespace}from"./index-CQudhZin.js";var dist={},assetPath={},hasRequiredAssetPath;function requireAssetPath(){if(hasRequiredAssetPath)return assetPath;hasRequiredAssetPath=1,Object.defineProperty(assetPath,"__esModule",{value:!0}),assetPath.baseAssetPath=void 0;const u=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let b="/";return u&&(b=u.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),assetPath.baseAssetPath=b,assetPath}var defaultModelFetcher={},hasRequiredDefaultModelFetcher;function requireDefaultModelFetcher(){if(hasRequiredDefaultModelFetcher)return defaultModelFetcher;hasRequiredDefaultModelFetcher=1,Object.defineProperty(defaultModelFetcher,"__esModule",{value:!0}),defaultModelFetcher.defaultModelFetcher=void 0;const D=u=>fetch(u).then(b=>b.arrayBuffer());return defaultModelFetcher.defaultModelFetcher=D,defaultModelFetcher}var frameProcessor={},logging={},hasRequiredLogging;function requireLogging(){return hasRequiredLogging||(hasRequiredLogging=1,function(D){Object.defineProperty(D,"__esModule",{value:!0}),D.log=D.LOG_PREFIX=void 0,D.LOG_PREFIX="[VAD]";const u=["error","debug","warn"];function b(p){return(...h)=>{console[p](D.LOG_PREFIX,...h)}}const g=u.reduce((p,h)=>(p[h]=b(h),p),{});D.log=g}(logging)),logging}var messages={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages;hasRequiredMessages=1,Object.defineProperty(messages,"__esModule",{value:!0}),messages.Message=void 0;var D;return function(u){u.AudioFrame="AUDIO_FRAME",u.SpeechStart="SPEECH_START",u.VADMisfire="VAD_MISFIRE",u.SpeechEnd="SPEECH_END",u.SpeechStop="SPEECH_STOP",u.SpeechRealStart="SPEECH_REAL_START",u.FrameProcessed="FRAME_PROCESSED"}(D||(messages.Message=D={})),messages}var hasRequiredFrameProcessor;function requireFrameProcessor(){if(hasRequiredFrameProcessor)return frameProcessor;hasRequiredFrameProcessor=1,Object.defineProperty(frameProcessor,"__esModule",{value:!0}),frameProcessor.FrameProcessor=frameProcessor.validateOptions=frameProcessor.defaultV5FrameProcessorOptions=frameProcessor.defaultLegacyFrameProcessorOptions=void 0;const D=requireLogging(),u=requireMessages(),b=[512,1024,1536];frameProcessor.defaultLegacyFrameProcessorOptions={positiveSpeechThreshold:.5,negativeSpeechThreshold:.5-.15,preSpeechPadFrames:1,redemptionFrames:8,frameSamples:1536,minSpeechFrames:3,submitUserSpeechOnPause:!1},frameProcessor.defaultV5FrameProcessorOptions={positiveSpeechThreshold:.5,negativeSpeechThreshold:.5-.15,preSpeechPadFrames:3,redemptionFrames:24,frameSamples:512,minSpeechFrames:9,submitUserSpeechOnPause:!1};function g(o){b.includes(o.frameSamples)||D.log.warn("You are using an unusual frame size"),(o.positiveSpeechThreshold<0||o.positiveSpeechThreshold>1)&&D.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(o.negativeSpeechThreshold<0||o.negativeSpeechThreshold>o.positiveSpeechThreshold)&&D.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),o.preSpeechPadFrames<0&&D.log.error("preSpeechPadFrames should be positive"),o.redemptionFrames<0&&D.log.error("redemptionFrames should be positive")}frameProcessor.validateOptions=g;const p=o=>{const c=o.reduce((s,i)=>(s.push(s.at(-1)+i.length),s),[0]),f=new Float32Array(c.at(-1));return o.forEach((s,i)=>{const t=c[i];f.set(s,t)}),f};class h{constructor(c,f,s){this.modelProcessFunc=c,this.modelResetFunc=f,this.options=s,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=i=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(i):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=i=>{const t=this.audioBuffer;this.audioBuffer=[];const e=this.speaking;if(this.reset(),e)if(t.reduce((r,a)=>a.isSpeech?r+1:r,0)>=this.options.minSpeechFrames){const r=p(t.map(a=>a.frame));i({msg:u.Message.SpeechEnd,audio:r})}else i({msg:u.Message.VADMisfire});return{}},this.process=async(i,t)=>{if(!this.active)return;const e=await this.modelProcessFunc(i),n=e.isSpeech>=this.options.positiveSpeechThreshold;if(t({probs:e,msg:u.Message.FrameProcessed,frame:i}),this.audioBuffer.push({frame:i,isSpeech:n}),n&&(this.speechFrameCount++,this.redemptionCounter=0),n&&!this.speaking&&(this.speaking=!0,t({msg:u.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.options.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,t({msg:u.Message.SpeechRealStart})),e.isSpeech=this.options.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const r=this.audioBuffer;if(this.audioBuffer=[],r.reduce((l,d)=>d.isSpeech?l+1:l,0)>=this.options.minSpeechFrames){const l=p(r.map(d=>d.frame));t({msg:u.Message.SpeechEnd,audio:l})}else t({msg:u.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.options.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.reset()}}return frameProcessor.FrameProcessor=h,frameProcessor}var nonRealTimeVad={},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,_=e*2,v=-1;s==="RGBA"?(m=0,y=e,_=e*2,v=e*3):s==="RGB"?(m=0,y=e,_=e*2):s==="RBG"&&(m=0,_=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. -*/var hasRequiredOrtWeb_min;function requireOrtWeb_min(){return hasRequiredOrtWeb_min||(hasRequiredOrtWeb_min=1,function(module,exports){(function(D,u){module.exports=u(require$$0)})(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(D,u,b)=>{var g,p=(g=(g=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(h){function o(){return Y.buffer!=ne&&Ee(Y.buffer),me}function c(){return Y.buffer!=ne&&Ee(Y.buffer),Pe}function f(){return Y.buffer!=ne&&Ee(Y.buffer),Oe}function s(){return Y.buffer!=ne&&Ee(Y.buffer),le}function i(){return Y.buffer!=ne&&Ee(Y.buffer),xe}var t,e,n;h=h||{},t||(t=h!==void 0?h:{}),t.ready=new Promise(function(x,O){e=x,n=O});var r,a,l,d,m,y,v=Object.assign({},t),_="./this.program",T=(x,O)=>{throw O},S=typeof window=="object",A=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I=t.ENVIRONMENT_IS_PTHREAD||!1,R="";function B(x){return t.locateFile?t.locateFile(x,R):R+x}if(w){let x;R=A?b(908).dirname(R)+"/":"//",y=()=>{m||(d=b(1384),m=b(908))},r=function(O,P){return y(),O=m.normalize(O),d.readFileSync(O,P?void 0:"utf8")},l=O=>((O=r(O,!0)).buffer||(O=new Uint8Array(O)),O),a=(O,P,F)=>{y(),O=m.normalize(O),d.readFile(O,function(L,z){L?F(L):P(z.buffer)})},1{if(ze())throw process.exitCode=O,P;P instanceof Ze||V("exiting due to exception: "+P),process.exit(O)},t.inspect=function(){return"[Emscripten Module object]"};try{x=b(9925)}catch(O){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),O}b.g.Worker=x.Worker}else(S||A)&&(A?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),g&&(R=g),R=R.indexOf("blob:")!==0?R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):"",w||(r=x=>{var O=new XMLHttpRequest;return O.open("GET",x,!1),O.send(null),O.responseText},A&&(l=x=>{var O=new XMLHttpRequest;return O.open("GET",x,!1),O.responseType="arraybuffer",O.send(null),new Uint8Array(O.response)}),a=(x,O,P)=>{var F=new XMLHttpRequest;F.open("GET",x,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?O(F.response):P()},F.onerror=P,F.send(null)}));w&&typeof performance>"u"&&(b.g.performance=b(6953).performance);var j=console.log.bind(console),N=console.warn.bind(console);w&&(y(),j=x=>d.writeSync(1,x+` +*/var hasRequiredOrtWeb_min;function requireOrtWeb_min(){return hasRequiredOrtWeb_min||(hasRequiredOrtWeb_min=1,function(module,exports){(function(D,u){module.exports=u(require$$0)})(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(D,u,b)=>{var g,p=(g=(g=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(h){function o(){return Y.buffer!=ne&&Ee(Y.buffer),me}function c(){return Y.buffer!=ne&&Ee(Y.buffer),Pe}function f(){return Y.buffer!=ne&&Ee(Y.buffer),Oe}function s(){return Y.buffer!=ne&&Ee(Y.buffer),le}function i(){return Y.buffer!=ne&&Ee(Y.buffer),xe}var t,e,n;h=h||{},t||(t=h!==void 0?h:{}),t.ready=new Promise(function(x,A){e=x,n=A});var r,a,l,d,m,y,_=Object.assign({},t),v="./this.program",T=(x,A)=>{throw A},S=typeof window=="object",O=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I=t.ENVIRONMENT_IS_PTHREAD||!1,R="";function B(x){return t.locateFile?t.locateFile(x,R):R+x}if(w){let x;R=O?b(908).dirname(R)+"/":"//",y=()=>{m||(d=b(1384),m=b(908))},r=function(A,P){return y(),A=m.normalize(A),d.readFileSync(A,P?void 0:"utf8")},l=A=>((A=r(A,!0)).buffer||(A=new Uint8Array(A)),A),a=(A,P,F)=>{y(),A=m.normalize(A),d.readFile(A,function(L,z){L?F(L):P(z.buffer)})},1{if(ze())throw process.exitCode=A,P;P instanceof Ze||V("exiting due to exception: "+P),process.exit(A)},t.inspect=function(){return"[Emscripten Module object]"};try{x=b(9925)}catch(A){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),A}b.g.Worker=x.Worker}else(S||O)&&(O?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),g&&(R=g),R=R.indexOf("blob:")!==0?R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1):"",w||(r=x=>{var A=new XMLHttpRequest;return A.open("GET",x,!1),A.send(null),A.responseText},O&&(l=x=>{var A=new XMLHttpRequest;return A.open("GET",x,!1),A.responseType="arraybuffer",A.send(null),new Uint8Array(A.response)}),a=(x,A,P)=>{var F=new XMLHttpRequest;F.open("GET",x,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?A(F.response):P()},F.onerror=P,F.send(null)}));w&&typeof performance>"u"&&(b.g.performance=b(6953).performance);var j=console.log.bind(console),N=console.warn.bind(console);w&&(y(),j=x=>d.writeSync(1,x+` `),N=x=>d.writeSync(2,x+` -`));var W,k=t.print||j,V=t.printErr||N;Object.assign(t,v),v=null,t.thisProgram&&(_=t.thisProgram),t.quit&&(T=t.quit),t.wasmBinary&&(W=t.wasmBinary);var J=t.noExitRuntime||!1;typeof WebAssembly!="object"&&pe("no native wasm support detected");var Y,te,ne,me,Pe,Oe,le,xe,_e=!1,Ne=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function He(x,O,P){var F=(O>>>=0)+P;for(P=O;x[P]&&!(P>=F);)++P;if(16(L=(240&L)==224?(15&L)<<12|z<<6|K:(7&L)<<18|z<<12|K<<6|63&x[O++])?F+=String.fromCharCode(L):(L-=65536,F+=String.fromCharCode(55296|L>>10,56320|1023&L))}}else F+=String.fromCharCode(L)}return F}function Ae(x,O){return(x>>>=0)?He(c(),x,O):""}function Ce(x,O,P,F){if(!(0>>=0;F=P+F-1;for(var z=0;z=K&&(K=65536+((1023&K)<<10)|1023&x.charCodeAt(++z)),127>=K){if(P>=F)break;O[P++>>>0]=K}else{if(2047>=K){if(P+1>=F)break;O[P++>>>0]=192|K>>6}else{if(65535>=K){if(P+2>=F)break;O[P++>>>0]=224|K>>12}else{if(P+3>=F)break;O[P++>>>0]=240|K>>18,O[P++>>>0]=128|K>>12&63}O[P++>>>0]=128|K>>6&63}O[P++>>>0]=128|63&K}}return O[P>>>0]=0,P-L}function Fe(x){for(var O=0,P=0;P=F?O++:2047>=F?O+=2:55296<=F&&57343>=F?(O+=4,++P):O+=3}return O}function Ee(x){ne=x,t.HEAP8=me=new Int8Array(x),t.HEAP16=new Int16Array(x),t.HEAP32=Oe=new Int32Array(x),t.HEAPU8=Pe=new Uint8Array(x),t.HEAPU16=new Uint16Array(x),t.HEAPU32=le=new Uint32Array(x),t.HEAPF32=new Float32Array(x),t.HEAPF64=xe=new Float64Array(x)}I&&(ne=t.buffer);var we=t.INITIAL_MEMORY||16777216;if(I)Y=t.wasmMemory,ne=t.buffer;else if(t.wasmMemory)Y=t.wasmMemory;else if(!((Y=new WebAssembly.Memory({initial:we/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw V("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Y&&(ne=Y.buffer),we=ne.byteLength,Ee(ne);var je,Ue=[],Be=[],We=[],Ke=[];function ze(){return J||!1}function Ve(){var x=t.preRun.shift();Ue.unshift(x)}var Se,Me=0,Ye=null;function pe(x){throw I?postMessage({cmd:"onAbort",arg:x}):t.onAbort&&t.onAbort(x),V(x="Aborted("+x+")"),_e=!0,x=new WebAssembly.RuntimeError(x+". Build with -sASSERTIONS for more info."),n(x),x}function ft(){return Se.startsWith("data:application/octet-stream;base64,")}function st(){var x=Se;try{if(x==Se&&W)return new Uint8Array(W);if(l)return l(x);throw"both async and sync fetching of the wasm failed"}catch(O){pe(O)}}Se="ort-wasm-threaded.wasm",ft()||(Se=B(Se));var At={};function Ze(x){this.name="ExitStatus",this.message="Program terminated with exit("+x+")",this.status=x}function ut(x){(x=re.Vb[x])||pe(),re.mc(x)}function ct(x){var O=re.Cc();if(!O)return 6;re.ac.push(O),re.Vb[x.Ub]=O,O.Ub=x.Ub;var P={cmd:"run",start_routine:x.Ic,arg:x.zc,pthread_ptr:x.Ub};return O.$b=()=>{P.time=performance.now(),O.postMessage(P,x.Nc)},O.loaded&&(O.$b(),delete O.$b),0}function Re(x){if(I)return Z(1,1,x);ze()||(re.oc(),t.onExit&&t.onExit(x),_e=!0),T(x,new Ze(x))}function nt(x,O){if(!O&&I)throw It(x),"unwind";ze()||I||(Gt(),tt(We),zt(0),kt[1].length&&Ct(1,10),kt[2].length&&Ct(2,10),re.oc()),Re(x)}var re={Yb:[],ac:[],qc:[],Vb:{},fc:function(){I&&re.Ec()},Pc:function(){},Ec:function(){re.receiveObjectTransfer=re.Gc,re.threadInitTLS=re.pc,re.setExitStatus=re.nc,J=!1},nc:function(){},oc:function(){for(var x of Object.values(re.Vb))re.mc(x);for(x of re.Yb)x.terminate();re.Yb=[]},mc:function(x){var O=x.Ub;delete re.Vb[O],re.Yb.push(x),re.ac.splice(re.ac.indexOf(x),1),x.Ub=0,Nt(O)},Gc:function(){},pc:function(){re.qc.forEach(x=>x())},Fc:function(x,O){x.onmessage=P=>{var F=(P=P.data).cmd;if(x.Ub&&(re.Bc=x.Ub),P.targetThread&&P.targetThread!=Dt()){var L=re.Vb[P.Qc];L?L.postMessage(P,P.transferList):V('Internal error! Worker sent a message "'+F+'" to target pthread '+P.targetThread+", but that thread no longer exists!")}else F==="processProxyingQueue"?C(P.queue):F==="spawnThread"?ct(P):F==="cleanupThread"?ut(P.thread):F==="killThread"?(P=P.thread,F=re.Vb[P],delete re.Vb[P],F.terminate(),Nt(P),re.ac.splice(re.ac.indexOf(F),1),F.Ub=0):F==="cancelThread"?re.Vb[P.thread].postMessage({cmd:"cancel"}):F==="loaded"?(x.loaded=!0,O&&O(x),x.$b&&(x.$b(),delete x.$b)):F==="print"?k("Thread "+P.threadId+": "+P.text):F==="printErr"?V("Thread "+P.threadId+": "+P.text):F==="alert"?alert("Thread "+P.threadId+": "+P.text):P.target==="setimmediate"?x.postMessage(P):F==="onAbort"?t.onAbort&&t.onAbort(P.arg):F&&V("worker sent an unknown command "+F);re.Bc=void 0},x.onerror=P=>{throw V("worker sent an error! "+P.filename+":"+P.lineno+": "+P.message),P},w&&(x.on("message",function(P){x.onmessage({data:P})}),x.on("error",function(P){x.onerror(P)}),x.on("detachedExit",function(){})),x.postMessage({cmd:"load",urlOrBlob:t.mainScriptUrlOrBlob||g,wasmMemory:Y,wasmModule:te})},yc:function(){var x=B("ort-wasm-threaded.worker.js");re.Yb.push(new Worker(x))},Cc:function(){return re.Yb.length==0&&(re.yc(),re.Fc(re.Yb[0])),re.Yb.pop()}};function tt(x){for(;0>2>>>0];x=f()[x+48>>2>>>0],Xt(O,O-x),ue(O)};var Je=[];function ye(x){var O=Je[x];return O||(x>=Je.length&&(Je.length=x+1),Je[x]=O=je.get(x)),O}t.invokeEntryPoint=function(x,O){x=ye(x)(O),ze()?re.nc(x):Yt(x)};var rt,dt,it=[],ae=0,ie=0;function oe(x){this.Zb=x,this.Sb=x-24,this.xc=function(O){s()[this.Sb+4>>2>>>0]=O},this.bc=function(){return s()[this.Sb+4>>2>>>0]},this.wc=function(O){s()[this.Sb+8>>2>>>0]=O},this.Dc=function(){return s()[this.Sb+8>>2>>>0]},this.rc=function(){f()[this.Sb>>2>>>0]=0},this.hc=function(O){O=O?1:0,o()[this.Sb+12>>0>>>0]=O},this.uc=function(){return o()[this.Sb+12>>0>>>0]!=0},this.ic=function(O){O=O?1:0,o()[this.Sb+13>>0>>>0]=O},this.kc=function(){return o()[this.Sb+13>>0>>>0]!=0},this.fc=function(O,P){this.cc(0),this.xc(O),this.wc(P),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(f(),this.Sb>>2,1)},this.Hc=function(){return Atomics.sub(f(),this.Sb>>2,1)===1},this.cc=function(O){s()[this.Sb+16>>2>>>0]=O},this.tc=function(){return s()[this.Sb+16>>2>>>0]},this.vc=function(){if(Kt(this.bc()))return s()[this.Zb>>2>>>0];var O=this.tc();return O!==0?O:this.Zb}}function pt(x){return Bt(new oe(x).Sb)}function ot(x,O,P,F){return I?Z(3,1,x,O,P,F):ht(x,O,P,F)}function ht(x,O,P,F){if(typeof SharedArrayBuffer>"u")return V("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var L=[];return I&&L.length===0?ot(x,O,P,F):(x={Ic:P,Ub:x,zc:F,Nc:L},I?(x.Oc="spawnThread",postMessage(x,L),0):ct(x))}function gt(x,O,P){return I?Z(4,1,x,O,P):0}function mt(x,O){if(I)return Z(5,1,x,O)}function bt(x,O){if(I)return Z(6,1,x,O)}function yt(x,O,P){if(I)return Z(7,1,x,O,P)}function _t(x,O,P){return I?Z(8,1,x,O,P):0}function vt(x,O){if(I)return Z(9,1,x,O)}function wt(x,O,P){if(I)return Z(10,1,x,O,P)}function xt(x,O,P,F){if(I)return Z(11,1,x,O,P,F)}function Tt(x,O,P,F){if(I)return Z(12,1,x,O,P,F)}function St(x,O,P,F){if(I)return Z(13,1,x,O,P,F)}function Ot(x){if(I)return Z(14,1,x)}function E(x,O){if(I)return Z(15,1,x,O)}function $(x,O,P){if(I)return Z(16,1,x,O,P)}function C(x){Atomics.store(f(),x>>2,1),Dt()&&Wt(x),Atomics.compareExchange(f(),x>>2,1,0)}function M(x){return s()[x>>>2]+4294967296*f()[x+4>>>2]}function U(x,O,P,F,L,z){return I?Z(17,1,x,O,P,F,L,z):-52}function H(x,O,P,F,L,z){if(I)return Z(18,1,x,O,P,F,L,z)}function X(x){var O=Fe(x)+1,P=Rt(O);return P&&Ce(x,o(),P,O),P}function Q(x,O,P){function F(he){return(he=he.toTimeString().match(/\(([A-Za-z ]+)\)$/))?he[1]:"GMT"}if(I)return Z(19,1,x,O,P);var L=new Date().getFullYear(),z=new Date(L,0,1),K=new Date(L,6,1);L=z.getTimezoneOffset();var ee=K.getTimezoneOffset(),de=Math.max(L,ee);f()[x>>2>>>0]=60*de,f()[O>>2>>>0]=+(L!=ee),x=F(z),O=F(K),x=X(x),O=X(O),ee>2>>>0]=x,s()[P+4>>2>>>0]=O):(s()[P>>2>>>0]=O,s()[P+4>>2>>>0]=x)}function Z(x,O){var P=arguments.length-2,F=arguments;return Et(()=>{for(var L=Mt(8*P),z=L>>3,K=0;K>>0]=ee}return Ht(x,P,L,O)})}t.executeNotifiedProxyingQueue=C,dt=w?()=>{var x=process.hrtime();return 1e3*x[0]+x[1]/1e6}:I?()=>performance.now()-t.__performance_now_clock_drift:()=>performance.now();var se,ve=[],ke={};function $e(){if(!se){var x,O={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(x in ke)ke[x]===void 0?delete O[x]:O[x]=ke[x];var P=[];for(x in O)P.push(x+"="+O[x]);se=P}return se}function G(x,O){if(I)return Z(20,1,x,O);var P=0;return $e().forEach(function(F,L){var z=O+P;for(L=s()[x+4*L>>2>>>0]=z,z=0;z>0>>>0]=F.charCodeAt(z);o()[L>>0>>>0]=0,P+=F.length+1}),0}function ge(x,O){if(I)return Z(21,1,x,O);var P=$e();s()[x>>2>>>0]=P.length;var F=0;return P.forEach(function(L){F+=L.length+1}),s()[O>>2>>>0]=F,0}function Te(x){return I?Z(22,1,x):52}function Ge(x,O,P,F){return I?Z(23,1,x,O,P,F):52}function Qe(x,O,P,F,L){return I?Z(24,1,x,O,P,F,L):70}var kt=[null,[],[]];function Ct(x,O){var P=kt[x];O===0||O===10?((x===1?k:V)(He(P,0)),P.length=0):P.push(O)}function Lt(x,O,P,F){if(I)return Z(25,1,x,O,P,F);for(var L=0,z=0;z>2>>>0],ee=s()[O+4>>2>>>0];O+=8;for(var de=0;de>>0]);L+=ee}return s()[F>>2>>>0]=L,0}var Le=0;function Pt(x){return x%4==0&&(x%100!=0||x%400==0)}var jt=[31,29,31,30,31,30,31,31,30,31,30,31],Vt=[31,28,31,30,31,30,31,31,30,31,30,31];function Ut(x,O,P,F){function L(q,be,Ie){for(q=typeof q=="number"?q.toString():q||"";q.lengthlt?-1:0et-q.getDate())){q.setDate(q.getDate()+be);break}be-=et-q.getDate()+1,q.setDate(1),11>Ie?q.setMonth(Ie+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1))}return Ie=new Date(q.getFullYear()+1,0,4),be=ee(new Date(q.getFullYear(),0,4)),Ie=ee(Ie),0>=K(be,q)?0>=K(Ie,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}var he=f()[F+40>>2>>>0];for(var De in F={Lc:f()[F>>2>>>0],Kc:f()[F+4>>2>>>0],dc:f()[F+8>>2>>>0],jc:f()[F+12>>2>>>0],ec:f()[F+16>>2>>>0],Xb:f()[F+20>>2>>>0],Tb:f()[F+24>>2>>>0],Wb:f()[F+28>>2>>>0],Rc:f()[F+32>>2>>>0],Jc:f()[F+36>>2>>>0],Mc:he?Ae(he):""},P=Ae(P),he={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})P=P.replace(new RegExp(De,"g"),he[De]);var Xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),qe="January February March April May June July August September October November December".split(" ");for(De in he={"%a":function(q){return Xe[q.Tb].substring(0,3)},"%A":function(q){return Xe[q.Tb]},"%b":function(q){return qe[q.ec].substring(0,3)},"%B":function(q){return qe[q.ec]},"%C":function(q){return z((q.Xb+1900)/100|0,2)},"%d":function(q){return z(q.jc,2)},"%e":function(q){return L(q.jc,2," ")},"%g":function(q){return de(q).toString().substring(2)},"%G":function(q){return de(q)},"%H":function(q){return z(q.dc,2)},"%I":function(q){return(q=q.dc)==0?q=12:12q.dc?"AM":"PM"},"%S":function(q){return z(q.Lc,2)},"%t":function(){return" "},"%u":function(q){return q.Tb||7},"%U":function(q){return z(Math.floor((q.Wb+7-q.Tb)/7),2)},"%V":function(q){var be=Math.floor((q.Wb+7-(q.Tb+6)%7)/7);if(2>=(q.Tb+371-q.Wb-2)%7&&be++,be)be==53&&((Ie=(q.Tb+371-q.Wb)%7)==4||Ie==3&&Pt(q.Xb)||(be=1));else{be=52;var Ie=(q.Tb+7-q.Wb-1)%7;(Ie==4||Ie==5&&Pt(q.Xb%400-1))&&be++}return z(be,2)},"%w":function(q){return q.Tb},"%W":function(q){return z(Math.floor((q.Wb+7-(q.Tb+6)%7)/7),2)},"%y":function(q){return(q.Xb+1900).toString().substring(2)},"%Y":function(q){return q.Xb+1900},"%z":function(q){var be=0<=(q=q.Jc);return q=Math.abs(q)/60,(be?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":function(q){return q.Mc},"%%":function(){return"%"}},P=P.replace(/%%/g,"\0\0"),he)P.includes(De)&&(P=P.replace(new RegExp(De,"g"),he[De](F)));return De=function(q){var be=Array(Fe(q)+1);return Ce(q,be,0,be.length),be}(P=P.replace(/\0\0/g,"%")),De.length>O?0:(function(q,be){o().set(q,be>>>0)}(De,x),De.length-1)}re.fc();var ln=[null,Re,It,ot,gt,mt,bt,yt,_t,vt,wt,xt,Tt,St,Ot,E,$,U,H,Q,G,ge,Te,Ge,Qe,Lt],fn={b:function(x){return Rt(x+24)+24},n:function(x){return(x=new oe(x)).uc()||(x.hc(!0),ae--),x.ic(!1),it.push(x),x.sc(),x.vc()},ma:function(x){throw V("Unexpected exception thrown, this is not properly supported - aborting"),_e=!0,x},x:function(){fe(0);var x=it.pop();if(x.Hc()&&!x.kc()){var O=x.Dc();O&&ye(O)(x.Zb),pt(x.Zb)}ie=0},e:function(){var x=ie;if(!x)return Le=0;var O=new oe(x);O.cc(x);var P=O.bc();if(!P)return Le=0,x;for(var F=Array.prototype.slice.call(arguments),L=0;LC(F));else if(I)postMessage({targetThread:x,cmd:"processProxyingQueue",queue:F});else{if(!(x=re.Vb[x]))return;x.postMessage({cmd:"processProxyingQueue",queue:F})}return 1},Ea:function(){return-1},Pa:function(x,O){x=new Date(1e3*M(x)),f()[O>>2>>>0]=x.getUTCSeconds(),f()[O+4>>2>>>0]=x.getUTCMinutes(),f()[O+8>>2>>>0]=x.getUTCHours(),f()[O+12>>2>>>0]=x.getUTCDate(),f()[O+16>>2>>>0]=x.getUTCMonth(),f()[O+20>>2>>>0]=x.getUTCFullYear()-1900,f()[O+24>>2>>>0]=x.getUTCDay(),x=(x.getTime()-Date.UTC(x.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,f()[O+28>>2>>>0]=x},Qa:function(x,O){x=new Date(1e3*M(x)),f()[O>>2>>>0]=x.getSeconds(),f()[O+4>>2>>>0]=x.getMinutes(),f()[O+8>>2>>>0]=x.getHours(),f()[O+12>>2>>>0]=x.getDate(),f()[O+16>>2>>>0]=x.getMonth(),f()[O+20>>2>>>0]=x.getFullYear()-1900,f()[O+24>>2>>>0]=x.getDay();var P=new Date(x.getFullYear(),0,1),F=(x.getTime()-P.getTime())/864e5|0;f()[O+28>>2>>>0]=F,f()[O+36>>2>>>0]=-60*x.getTimezoneOffset(),F=new Date(x.getFullYear(),6,1).getTimezoneOffset(),x=0|(F!=(P=P.getTimezoneOffset())&&x.getTimezoneOffset()==Math.min(P,F)),f()[O+32>>2>>>0]=x},Ra:function(x){var O=new Date(f()[x+20>>2>>>0]+1900,f()[x+16>>2>>>0],f()[x+12>>2>>>0],f()[x+8>>2>>>0],f()[x+4>>2>>>0],f()[x>>2>>>0],0),P=f()[x+32>>2>>>0],F=O.getTimezoneOffset(),L=new Date(O.getFullYear(),0,1),z=new Date(O.getFullYear(),6,1).getTimezoneOffset(),K=L.getTimezoneOffset(),ee=Math.min(K,z);return 0>P?f()[x+32>>2>>>0]=+(z!=K&&ee==F):0>2>>>0]=O.getDay(),P=(O.getTime()-L.getTime())/864e5|0,f()[x+28>>2>>>0]=P,f()[x>>2>>>0]=O.getSeconds(),f()[x+4>>2>>>0]=O.getMinutes(),f()[x+8>>2>>>0]=O.getHours(),f()[x+12>>2>>>0]=O.getDate(),f()[x+16>>2>>>0]=O.getMonth(),O.getTime()/1e3|0},Aa:U,Ba:H,Sa:function x(O,P,F){x.Ac||(x.Ac=!0,Q(O,P,F))},y:function(){pe("")},U:function(){if(!w&&!A){var x="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";rt||(rt={}),rt[x]||(rt[x]=1,w&&(x="warning: "+x),V(x))}},ra:function(){return 4294901760},B:dt,Ia:function(x,O,P){c().copyWithin(x>>>0,O>>>0,O+P>>>0)},F:function(){return w?b(3993).cpus().length:navigator.hardwareConcurrency},Da:function(x,O,P){ve.length=O,P>>=3;for(var F=0;F>>0];return(0>x?At[-x-1]:ln[x]).apply(null,ve)},qa:function(x){var O=c().length;if((x>>>=0)<=O||4294901760=P;P*=2){var F=O*(1+.2/P);F=Math.min(F,x+100663296);var L=Math;F=Math.max(x,F),L=L.min.call(L,4294901760,F+(65536-F%65536)%65536);e:{try{Y.grow(L-ne.byteLength+65535>>>16),Ee(Y.buffer);var z=1;break e}catch{}z=void 0}if(z)return!0}return!1},Na:function(){throw"unwind"},Ga:G,Ha:ge,J:nt,I:Te,S:Ge,ga:Qe,R:Lt,d:function(){return Le},na:function x(O,P){x.lc||(x.lc=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var L=new Uint8Array(1);return()=>(crypto.getRandomValues(L),L[0])}if(w)try{var z=b(Object(function(){var K=new Error("Cannot find module 'crypto'");throw K.code="MODULE_NOT_FOUND",K}()));return()=>z.randomBytes(1)[0]}catch{}return()=>pe("randomDevice")}());for(var F=0;F>0>>>0]=x.lc();return 0},ia:function(x,O,P){var F=ce();try{return ye(x)(O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},ja:function(x,O,P){var F=ce();try{return ye(x)(O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},K:function(x){var O=ce();try{return ye(x)()}catch(P){if(ue(O),P!==P+0)throw P;fe(1,0)}},f:function(x,O){var P=ce();try{return ye(x)(O)}catch(F){if(ue(P),F!==F+0)throw F;fe(1,0)}},P:function(x,O,P){var F=ce();try{return ye(x)(O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},Q:function(x,O,P){var F=ce();try{return ye(x)(O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},k:function(x,O,P){var F=ce();try{return ye(x)(O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},p:function(x,O,P,F){var L=ce();try{return ye(x)(O,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},q:function(x,O,P,F,L){var z=ce();try{return ye(x)(O,P,F,L)}catch(K){if(ue(z),K!==K+0)throw K;fe(1,0)}},N:function(x,O,P,F,L,z){var K=ce();try{return ye(x)(O,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},s:function(x,O,P,F,L,z){var K=ce();try{return ye(x)(O,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},w:function(x,O,P,F,L,z,K){var ee=ce();try{return ye(x)(O,P,F,L,z,K)}catch(de){if(ue(ee),de!==de+0)throw de;fe(1,0)}},L:function(x,O,P,F,L,z,K,ee){var de=ce();try{return ye(x)(O,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},E:function(x,O,P,F,L,z,K,ee,de,he,De,Xe){var qe=ce();try{return ye(x)(O,P,F,L,z,K,ee,de,he,De,Xe)}catch(q){if(ue(qe),q!==q+0)throw q;fe(1,0)}},aa:function(x,O,P,F,L,z,K,ee){var de=ce();try{return an(x,O,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},_:function(x,O,P,F,L,z,K){var ee=ce();try{return Jt(x,O,P,F,L,z,K)}catch(de){if(ue(ee),de!==de+0)throw de;fe(1,0)}},Z:function(x,O,P,F,L){var z=ce();try{return sn(x,O,P,F,L)}catch(K){if(ue(z),K!==K+0)throw K;fe(1,0)}},ca:function(x,O,P,F){var L=ce();try{return rn(x,O,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},$:function(x){var O=ce();try{return Zt(x)}catch(P){if(ue(O),P!==P+0)throw P;fe(1,0)}},ba:function(x,O){var P=ce();try{return on(x,O)}catch(F){if(ue(P),F!==F+0)throw F;fe(1,0)}},Y:function(x,O,P){var F=ce();try{return Qt(x,O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},g:function(x){var O=ce();try{ye(x)()}catch(P){if(ue(O),P!==P+0)throw P;fe(1,0)}},r:function(x,O){var P=ce();try{ye(x)(O)}catch(F){if(ue(P),F!==F+0)throw F;fe(1,0)}},i:function(x,O,P){var F=ce();try{ye(x)(O,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},ha:function(x,O,P,F){var L=ce();try{ye(x)(O,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},m:function(x,O,P,F){var L=ce();try{ye(x)(O,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},v:function(x,O,P,F,L){var z=ce();try{ye(x)(O,P,F,L)}catch(K){if(ue(z),K!==K+0)throw K;fe(1,0)}},u:function(x,O,P,F,L,z){var K=ce();try{ye(x)(O,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},O:function(x,O,P,F,L,z,K){var ee=ce();try{ye(x)(O,P,F,L,z,K)}catch(de){if(ue(ee),de!==de+0)throw de;fe(1,0)}},A:function(x,O,P,F,L,z,K,ee){var de=ce();try{ye(x)(O,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},ka:function(x,O,P,F,L,z,K,ee,de){var he=ce();try{ye(x)(O,P,F,L,z,K,ee,de)}catch(De){if(ue(he),De!==De+0)throw De;fe(1,0)}},C:function(x,O,P,F,L,z,K,ee,de,he,De){var Xe=ce();try{ye(x)(O,P,F,L,z,K,ee,de,he,De)}catch(qe){if(ue(Xe),qe!==qe+0)throw qe;fe(1,0)}},D:function(x,O,P,F,L,z,K,ee,de,he,De,Xe,qe,q,be,Ie){var et=ce();try{ye(x)(O,P,F,L,z,K,ee,de,he,De,Xe,qe,q,be,Ie)}catch(lt){if(ue(et),lt!==lt+0)throw lt;fe(1,0)}},fa:function(x,O,P,F,L,z,K,ee){var de=ce();try{en(x,O,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},da:function(x,O,P,F,L,z,K,ee,de,he,De,Xe){var qe=ce();try{nn(x,O,P,F,L,z,K,ee,de,he,De,Xe)}catch(q){if(ue(qe),q!==q+0)throw q;fe(1,0)}},ea:function(x,O,P,F,L,z){var K=ce();try{tn(x,O,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},o:function(x){return x},a:Y||t.wasmMemory,G:function(x){Le=x},la:Ut,z:function(x,O,P,F){return Ut(x,O,P,F)}};(function(){function x(L,z){t.asm=L.exports,re.qc.push(t.asm.sb),je=t.asm.ub,Be.unshift(t.asm.Va),te=z,I||(Me--,t.monitorRunDependencies&&t.monitorRunDependencies(Me),Me==0&&Ye&&(L=Ye,Ye=null,L()))}function O(L){x(L.instance,L.module)}function P(L){return function(){if(!W&&(S||A)){if(typeof fetch=="function"&&!Se.startsWith("file://"))return fetch(Se,{credentials:"same-origin"}).then(function(z){if(!z.ok)throw"failed to load wasm binary file at '"+Se+"'";return z.arrayBuffer()}).catch(function(){return st()});if(a)return new Promise(function(z,K){a(Se,function(ee){z(new Uint8Array(ee))},K)})}return Promise.resolve().then(function(){return st()})}().then(function(z){return WebAssembly.instantiate(z,F)}).then(function(z){return z}).then(L,function(z){V("failed to asynchronously prepare wasm: "+z),pe(z)})}var F={a:fn};if(I||(Me++,t.monitorRunDependencies&&t.monitorRunDependencies(Me)),t.instantiateWasm)try{return t.instantiateWasm(F,x)}catch(L){return V("Module.instantiateWasm callback failed with error: "+L),!1}(W||typeof WebAssembly.instantiateStreaming!="function"||ft()||Se.startsWith("file://")||w||typeof fetch!="function"?P(O):fetch(Se,{credentials:"same-origin"}).then(function(L){return WebAssembly.instantiateStreaming(L,F).then(O,function(z){return V("wasm streaming compile failed: "+z),V("falling back to ArrayBuffer instantiation"),P(O)})})).catch(n)})(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Va).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.Wa).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.Xa).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.Ya).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.Za).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm._a).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.$a).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.ab).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.bb).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.cb).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm.db).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.eb).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.fb).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.gb).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.hb).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.ib).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.jb).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.kb).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.lb).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.mb).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.nb).apply(null,arguments)};var Dt=t._pthread_self=function(){return(Dt=t._pthread_self=t.asm.ob).apply(null,arguments)},Rt=t._malloc=function(){return(Rt=t._malloc=t.asm.pb).apply(null,arguments)},Bt=t._free=function(){return(Bt=t._free=t.asm.qb).apply(null,arguments)},zt=t._fflush=function(){return(zt=t._fflush=t.asm.rb).apply(null,arguments)};t.__emscripten_tls_init=function(){return(t.__emscripten_tls_init=t.asm.sb).apply(null,arguments)};var Gt=t.___funcs_on_exit=function(){return(Gt=t.___funcs_on_exit=t.asm.tb).apply(null,arguments)},qt=t.__emscripten_thread_init=function(){return(qt=t.__emscripten_thread_init=t.asm.vb).apply(null,arguments)};t.__emscripten_thread_crashed=function(){return(t.__emscripten_thread_crashed=t.asm.wb).apply(null,arguments)};var $t,Ht=t._emscripten_run_in_main_runtime_thread_js=function(){return(Ht=t._emscripten_run_in_main_runtime_thread_js=t.asm.xb).apply(null,arguments)},Wt=t.__emscripten_proxy_execute_task_queue=function(){return(Wt=t.__emscripten_proxy_execute_task_queue=t.asm.yb).apply(null,arguments)},Nt=t.__emscripten_thread_free_data=function(){return(Nt=t.__emscripten_thread_free_data=t.asm.zb).apply(null,arguments)},Yt=t.__emscripten_thread_exit=function(){return(Yt=t.__emscripten_thread_exit=t.asm.Ab).apply(null,arguments)},fe=t._setThrew=function(){return(fe=t._setThrew=t.asm.Bb).apply(null,arguments)},Xt=t._emscripten_stack_set_limits=function(){return(Xt=t._emscripten_stack_set_limits=t.asm.Cb).apply(null,arguments)},ce=t.stackSave=function(){return(ce=t.stackSave=t.asm.Db).apply(null,arguments)},ue=t.stackRestore=function(){return(ue=t.stackRestore=t.asm.Eb).apply(null,arguments)},Mt=t.stackAlloc=function(){return(Mt=t.stackAlloc=t.asm.Fb).apply(null,arguments)},Ft=t.___cxa_can_catch=function(){return(Ft=t.___cxa_can_catch=t.asm.Gb).apply(null,arguments)},Kt=t.___cxa_is_pointer_type=function(){return(Kt=t.___cxa_is_pointer_type=t.asm.Hb).apply(null,arguments)},Zt=t.dynCall_j=function(){return(Zt=t.dynCall_j=t.asm.Ib).apply(null,arguments)},Jt=t.dynCall_iiiiij=function(){return(Jt=t.dynCall_iiiiij=t.asm.Jb).apply(null,arguments)},Qt=t.dynCall_jii=function(){return(Qt=t.dynCall_jii=t.asm.Kb).apply(null,arguments)},en=t.dynCall_viiiiij=function(){return(en=t.dynCall_viiiiij=t.asm.Lb).apply(null,arguments)},tn=t.dynCall_vjji=function(){return(tn=t.dynCall_vjji=t.asm.Mb).apply(null,arguments)},nn=t.dynCall_viiijjjii=function(){return(nn=t.dynCall_viiijjjii=t.asm.Nb).apply(null,arguments)},rn=t.dynCall_iij=function(){return(rn=t.dynCall_iij=t.asm.Ob).apply(null,arguments)},on=t.dynCall_ji=function(){return(on=t.dynCall_ji=t.asm.Pb).apply(null,arguments)},an=t.dynCall_iiiiiij=function(){return(an=t.dynCall_iiiiiij=t.asm.Qb).apply(null,arguments)},sn=t.dynCall_iiij=function(){return(sn=t.dynCall_iiij=t.asm.Rb).apply(null,arguments)};function un(){function x(){if(!$t&&($t=!0,t.calledRun=!0,!_e)&&(I||tt(Be),e(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),!I)){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;){var O=t.postRun.shift();Ke.unshift(O)}tt(Ke)}}if(!(0{var g,p=(g=(g=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(h){var o,c,f;h=h||{},o||(o=h!==void 0?h:{}),o.ready=new Promise(function(E,$){c=E,f=$});var s,i,t,e,n,r,a=Object.assign({},o),l="./this.program",d=(E,$)=>{throw $},m=typeof window=="object",y=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_="";v?(_=y?b(908).dirname(_)+"/":"//",r=()=>{n||(e=b(1384),n=b(908))},s=function(E,$){return r(),E=n.normalize(E),e.readFileSync(E,$?void 0:"utf8")},t=E=>((E=s(E,!0)).buffer||(E=new Uint8Array(E)),E),i=(E,$,C)=>{r(),E=n.normalize(E),e.readFile(E,function(M,U){M?C(M):$(U.buffer)})},1{if(w||0{var $=new XMLHttpRequest;return $.open("GET",E,!1),$.send(null),$.responseText},y&&(t=E=>{var $=new XMLHttpRequest;return $.open("GET",E,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),i=(E,$,C)=>{var M=new XMLHttpRequest;M.open("GET",E,!0),M.responseType="arraybuffer",M.onload=()=>{M.status==200||M.status==0&&M.response?$(M.response):C()},M.onerror=C,M.send(null)});var T,S=o.print||console.log.bind(console),A=o.printErr||console.warn.bind(console);Object.assign(o,a),a=null,o.thisProgram&&(l=o.thisProgram),o.quit&&(d=o.quit),o.wasmBinary&&(T=o.wasmBinary);var w=o.noExitRuntime||!1;typeof WebAssembly!="object"&&Ee("no native wasm support detected");var I,R,B,j,N,W,k=!1,V=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function J(E,$,C){var M=($>>>=0)+C;for(C=$;E[C]&&!(C>=M);)++C;if(16(U=(240&U)==224?(15&U)<<12|H<<6|X:(7&U)<<18|H<<12|X<<6|63&E[$++])?M+=String.fromCharCode(U):(U-=65536,M+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else M+=String.fromCharCode(U)}return M}function Y(E,$){return(E>>>=0)?J(j,E,$):""}function te(E,$,C,M){if(!(0>>=0;M=C+M-1;for(var H=0;H=X&&(X=65536+((1023&X)<<10)|1023&E.charCodeAt(++H)),127>=X){if(C>=M)break;$[C++>>>0]=X}else{if(2047>=X){if(C+1>=M)break;$[C++>>>0]=192|X>>6}else{if(65535>=X){if(C+2>=M)break;$[C++>>>0]=224|X>>12}else{if(C+3>=M)break;$[C++>>>0]=240|X>>18,$[C++>>>0]=128|X>>12&63}$[C++>>>0]=128|X>>6&63}$[C++>>>0]=128|63&X}}return $[C>>>0]=0,C-U}function ne(E){for(var $=0,C=0;C=M?$++:2047>=M?$+=2:55296<=M&&57343>=M?($+=4,++C):$+=3}return $}function me(){var E=I.buffer;R=E,o.HEAP8=B=new Int8Array(E),o.HEAP16=new Int16Array(E),o.HEAP32=N=new Int32Array(E),o.HEAPU8=j=new Uint8Array(E),o.HEAPU16=new Uint16Array(E),o.HEAPU32=W=new Uint32Array(E),o.HEAPF32=new Float32Array(E),o.HEAPF64=new Float64Array(E)}var Pe,Oe=[],le=[],xe=[],_e=[],Ne=0;function He(){var E=o.preRun.shift();Oe.unshift(E)}var Ae,Ce=0,Fe=null;function Ee(E){throw o.onAbort&&o.onAbort(E),A(E="Aborted("+E+")"),k=!0,E=new WebAssembly.RuntimeError(E+". Build with -sASSERTIONS for more info."),f(E),E}function we(){return Ae.startsWith("data:application/octet-stream;base64,")}if(Ae="ort-wasm.wasm",!we()){var je=Ae;Ae=o.locateFile?o.locateFile(je,_):_+je}function Ue(){var E=Ae;try{if(E==Ae&&T)return new Uint8Array(T);if(t)return t(E);throw"both async and sync fetching of the wasm failed"}catch($){Ee($)}}function Be(E){this.name="ExitStatus",this.message="Program terminated with exit("+E+")",this.status=E}function We(E){for(;0>2>>>0]=$},this.Eb=function(){return W[this.zb+4>>2>>>0]},this.Sb=function($){W[this.zb+8>>2>>>0]=$},this.Wb=function(){return W[this.zb+8>>2>>>0]},this.Tb=function(){N[this.zb>>2>>>0]=0},this.Ib=function($){B[this.zb+12>>0>>>0]=$?1:0},this.Pb=function(){return B[this.zb+12>>0>>>0]!=0},this.Jb=function($){B[this.zb+13>>0>>>0]=$?1:0},this.Lb=function(){return B[this.zb+13>>0>>>0]!=0},this.Rb=function($,C){this.Fb(0),this.Ub($),this.Sb(C),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){N[this.zb>>2>>>0]+=1},this.Xb=function(){var $=N[this.zb>>2>>>0];return N[this.zb>>2>>>0]=$-1,$===1},this.Fb=function($){W[this.zb+16>>2>>>0]=$},this.Ob=function(){return W[this.zb+16>>2>>>0]},this.Qb=function(){if(ht(this.Eb()))return W[this.Db>>2>>>0];var $=this.Ob();return $!==0?$:this.Db}}function Me(E){return rt(new Se(E).zb)}var Ye=[];function pe(E){var $=Ye[E];return $||(E>=Ye.length&&(Ye.length=E+1),Ye[E]=$=Pe.get(E)),$}function ft(E){var $=ne(E)+1,C=ye($);return C&&te(E,B,C,$),C}var st={};function At(){if(!Ze){var E,$={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",_:l||"./this.program"};for(E in st)st[E]===void 0?delete $[E]:$[E]=st[E];var C=[];for(E in $)C.push(E+"="+$[E]);Ze=C}return Ze}var Ze,ut=[null,[],[]];function ct(E,$){var C=ut[E];$===0||$===10?((E===1?S:A)(J(C,0)),C.length=0):C.push($)}var Re=0;function nt(E){return E%4==0&&(E%100!=0||E%400==0)}var re=[31,29,31,30,31,30,31,31,30,31,30,31],tt=[31,28,31,30,31,30,31,31,30,31,30,31];function Et(E,$,C,M){function U(G,ge,Te){for(G=typeof G=="number"?G.toString():G||"";G.lengthQe?-1:0Ge-G.getDate())){G.setDate(G.getDate()+ge);break}ge-=Ge-G.getDate()+1,G.setDate(1),11>Te?G.setMonth(Te+1):(G.setMonth(0),G.setFullYear(G.getFullYear()+1))}return Te=new Date(G.getFullYear()+1,0,4),ge=Q(new Date(G.getFullYear(),0,4)),Te=Q(Te),0>=X(ge,G)?0>=X(Te,G)?G.getFullYear()+1:G.getFullYear():G.getFullYear()-1}var se=N[M+40>>2>>>0];for(var ve in M={$b:N[M>>2>>>0],Zb:N[M+4>>2>>>0],Gb:N[M+8>>2>>>0],Kb:N[M+12>>2>>>0],Hb:N[M+16>>2>>>0],Cb:N[M+20>>2>>>0],Ab:N[M+24>>2>>>0],Bb:N[M+28>>2>>>0],bc:N[M+32>>2>>>0],Yb:N[M+36>>2>>>0],ac:se?Y(se):""},C=Y(C),se={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})C=C.replace(new RegExp(ve,"g"),se[ve]);var ke="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),$e="January February March April May June July August September October November December".split(" ");for(ve in se={"%a":function(G){return ke[G.Ab].substring(0,3)},"%A":function(G){return ke[G.Ab]},"%b":function(G){return $e[G.Hb].substring(0,3)},"%B":function(G){return $e[G.Hb]},"%C":function(G){return H((G.Cb+1900)/100|0,2)},"%d":function(G){return H(G.Kb,2)},"%e":function(G){return U(G.Kb,2," ")},"%g":function(G){return Z(G).toString().substring(2)},"%G":function(G){return Z(G)},"%H":function(G){return H(G.Gb,2)},"%I":function(G){return(G=G.Gb)==0?G=12:12G.Gb?"AM":"PM"},"%S":function(G){return H(G.$b,2)},"%t":function(){return" "},"%u":function(G){return G.Ab||7},"%U":function(G){return H(Math.floor((G.Bb+7-G.Ab)/7),2)},"%V":function(G){var ge=Math.floor((G.Bb+7-(G.Ab+6)%7)/7);if(2>=(G.Ab+371-G.Bb-2)%7&&ge++,ge)ge==53&&((Te=(G.Ab+371-G.Bb)%7)==4||Te==3&&nt(G.Cb)||(ge=1));else{ge=52;var Te=(G.Ab+7-G.Bb-1)%7;(Te==4||Te==5&&nt(G.Cb%400-1))&&ge++}return H(ge,2)},"%w":function(G){return G.Ab},"%W":function(G){return H(Math.floor((G.Bb+7-(G.Ab+6)%7)/7),2)},"%y":function(G){return(G.Cb+1900).toString().substring(2)},"%Y":function(G){return G.Cb+1900},"%z":function(G){var ge=0<=(G=G.Yb);return G=Math.abs(G)/60,(ge?"+":"-")+("0000"+(G/60*100+G%60)).slice(-4)},"%Z":function(G){return G.ac},"%%":function(){return"%"}},C=C.replace(/%%/g,"\0\0"),se)C.includes(ve)&&(C=C.replace(new RegExp(ve,"g"),se[ve](M)));return ve=function(G){var ge=Array(ne(G)+1);return te(G,ge,0,ge.length),ge}(C=C.replace(/\0\0/g,"%")),ve.length>$?0:(B.set(ve,E>>>0),ve.length-1)}var It={a:function(E){return ye(E+24)+24},m:function(E){return(E=new Se(E)).Pb()||(E.Ib(!0),ze--),E.Jb(!1),Ke.push(E),E.Nb(),E.Qb()},ia:function(E){throw A("Unexpected exception thrown, this is not properly supported - aborting"),k=!0,E},w:function(){ae(0);var E=Ke.pop();if(E.Xb()&&!E.Lb()){var $=E.Wb();$&&pe($)(E.Db),Me(E.Db)}Ve=0},d:function(){var E=Ve;if(!E)return Re=0;var $=new Se(E);$.Fb(E);var C=$.Eb();if(!C)return Re=0,E;for(var M=Array.prototype.slice.call(arguments),U=0;U>>2]+4294967296*N[E+4>>>2])),N[$>>2>>>0]=E.getUTCSeconds(),N[$+4>>2>>>0]=E.getUTCMinutes(),N[$+8>>2>>>0]=E.getUTCHours(),N[$+12>>2>>>0]=E.getUTCDate(),N[$+16>>2>>>0]=E.getUTCMonth(),N[$+20>>2>>>0]=E.getUTCFullYear()-1900,N[$+24>>2>>>0]=E.getUTCDay(),N[$+28>>2>>>0]=(E.getTime()-Date.UTC(E.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(E,$){E=new Date(1e3*(W[E>>>2]+4294967296*N[E+4>>>2])),N[$>>2>>>0]=E.getSeconds(),N[$+4>>2>>>0]=E.getMinutes(),N[$+8>>2>>>0]=E.getHours(),N[$+12>>2>>>0]=E.getDate(),N[$+16>>2>>>0]=E.getMonth(),N[$+20>>2>>>0]=E.getFullYear()-1900,N[$+24>>2>>>0]=E.getDay();var C=new Date(E.getFullYear(),0,1);N[$+28>>2>>>0]=(E.getTime()-C.getTime())/864e5|0,N[$+36>>2>>>0]=-60*E.getTimezoneOffset();var M=new Date(E.getFullYear(),6,1).getTimezoneOffset();C=C.getTimezoneOffset(),N[$+32>>2>>>0]=0|(M!=C&&E.getTimezoneOffset()==Math.min(C,M))},Fa:function(E){var $=new Date(N[E+20>>2>>>0]+1900,N[E+16>>2>>>0],N[E+12>>2>>>0],N[E+8>>2>>>0],N[E+4>>2>>>0],N[E>>2>>>0],0),C=N[E+32>>2>>>0],M=$.getTimezoneOffset(),U=new Date($.getFullYear(),0,1),H=new Date($.getFullYear(),6,1).getTimezoneOffset(),X=U.getTimezoneOffset(),Q=Math.min(X,H);return 0>C?N[E+32>>2>>>0]=+(H!=X&&Q==M):0>2>>>0]=$.getDay(),N[E+28>>2>>>0]=($.getTime()-U.getTime())/864e5|0,N[E>>2>>>0]=$.getSeconds(),N[E+4>>2>>>0]=$.getMinutes(),N[E+8>>2>>>0]=$.getHours(),N[E+12>>2>>>0]=$.getDate(),N[E+16>>2>>>0]=$.getMonth(),$.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function E($,C,M){E.Vb||(E.Vb=!0,function(U,H,X){function Q($e){return($e=$e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?$e[1]:"GMT"}var Z=new Date().getFullYear(),se=new Date(Z,0,1),ve=new Date(Z,6,1);Z=se.getTimezoneOffset();var ke=ve.getTimezoneOffset();N[U>>2>>>0]=60*Math.max(Z,ke),N[H>>2>>>0]=+(Z!=ke),U=Q(se),H=Q(ve),U=ft(U),H=ft(H),ke>2>>>0]=U,W[X+4>>2>>>0]=H):(W[X>>2>>>0]=H,W[X+4>>2>>>0]=U)}($,C,M))},B:function(){Ee("")},ma:function(){return 4294901760},I:v?()=>{var E=process.hrtime();return 1e3*E[0]+E[1]/1e6}:()=>performance.now(),xa:function(E,$,C){j.copyWithin(E>>>0,$>>>0,$+C>>>0)},G:function(E){var $=j.length;if(4294901760<(E>>>=0))return!1;for(var C=1;4>=C;C*=2){var M=$*(1+.2/C);M=Math.min(M,E+100663296);var U=Math;M=Math.max(E,M),U=U.min.call(U,4294901760,M+(65536-M%65536)%65536);e:{try{I.grow(U-R.byteLength+65535>>>16),me();var H=1;break e}catch{}H=void 0}if(H)return!0}return!1},va:function(E,$){var C=0;return At().forEach(function(M,U){var H=$+C;for(U=W[E+4*U>>2>>>0]=H,H=0;H>0>>>0]=M.charCodeAt(H);B[U>>0>>>0]=0,C+=M.length+1}),0},wa:function(E,$){var C=At();W[E>>2>>>0]=C.length;var M=0;return C.forEach(function(U){M+=U.length+1}),W[$>>2>>>0]=M,0},ba:function(E){w||0>2>>>0],Q=W[$+4>>2>>>0];$+=8;for(var Z=0;Z>>0]);U+=Q}return W[M>>2>>>0]=U,0},c:function(){return Re},ja:function E($,C){E.Mb||(E.Mb=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var U=new Uint8Array(1);return()=>(crypto.getRandomValues(U),U[0])}if(v)try{var H=b(Object(function(){var X=new Error("Cannot find module 'crypto'");throw X.code="MODULE_NOT_FOUND",X}()));return()=>H.randomBytes(1)[0]}catch{}return()=>Ee("randomDevice")}());for(var M=0;M>0>>>0]=E.Mb();return 0},ea:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},fa:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},J:function(E){var $=ie();try{return pe(E)()}catch(C){if(oe($),C!==C+0)throw C;ae(1,0)}},e:function(E,$){var C=ie();try{return pe(E)($)}catch(M){if(oe(C),M!==M+0)throw M;ae(1,0)}},N:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},O:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},j:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},o:function(E,$,C,M){var U=ie();try{return pe(E)($,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},p:function(E,$,C,M,U){var H=ie();try{return pe(E)($,C,M,U)}catch(X){if(oe(H),X!==X+0)throw X;ae(1,0)}},M:function(E,$,C,M,U,H){var X=ie();try{return pe(E)($,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},r:function(E,$,C,M,U,H){var X=ie();try{return pe(E)($,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},v:function(E,$,C,M,U,H,X){var Q=ie();try{return pe(E)($,C,M,U,H,X)}catch(Z){if(oe(Q),Z!==Z+0)throw Z;ae(1,0)}},K:function(E,$,C,M,U,H,X,Q){var Z=ie();try{return pe(E)($,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},D:function(E,$,C,M,U,H,X,Q,Z,se,ve,ke){var $e=ie();try{return pe(E)($,C,M,U,H,X,Q,Z,se,ve,ke)}catch(G){if(oe($e),G!==G+0)throw G;ae(1,0)}},X:function(E,$,C,M,U,H,X,Q){var Z=ie();try{return Tt(E,$,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},V:function(E,$,C,M,U,H,X){var Q=ie();try{return mt(E,$,C,M,U,H,X)}catch(Z){if(oe(Q),Z!==Z+0)throw Z;ae(1,0)}},U:function(E,$,C,M,U){var H=ie();try{return St(E,$,C,M,U)}catch(X){if(oe(H),X!==X+0)throw X;ae(1,0)}},Z:function(E,$,C,M){var U=ie();try{return wt(E,$,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},W:function(E){var $=ie();try{return gt(E)}catch(C){if(oe($),C!==C+0)throw C;ae(1,0)}},Y:function(E,$){var C=ie();try{return xt(E,$)}catch(M){if(oe(C),M!==M+0)throw M;ae(1,0)}},T:function(E,$,C){var M=ie();try{return bt(E,$,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},f:function(E){var $=ie();try{pe(E)()}catch(C){if(oe($),C!==C+0)throw C;ae(1,0)}},q:function(E,$){var C=ie();try{pe(E)($)}catch(M){if(oe(C),M!==M+0)throw M;ae(1,0)}},h:function(E,$,C){var M=ie();try{pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},da:function(E,$,C,M){var U=ie();try{pe(E)($,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},l:function(E,$,C,M){var U=ie();try{pe(E)($,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},t:function(E,$,C,M,U){var H=ie();try{pe(E)($,C,M,U)}catch(X){if(oe(H),X!==X+0)throw X;ae(1,0)}},u:function(E,$,C,M,U,H){var X=ie();try{pe(E)($,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},x:function(E,$,C,M,U,H,X){var Q=ie();try{pe(E)($,C,M,U,H,X)}catch(Z){if(oe(Q),Z!==Z+0)throw Z;ae(1,0)}},z:function(E,$,C,M,U,H,X,Q){var Z=ie();try{pe(E)($,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},ga:function(E,$,C,M,U,H,X,Q,Z){var se=ie();try{pe(E)($,C,M,U,H,X,Q,Z)}catch(ve){if(oe(se),ve!==ve+0)throw ve;ae(1,0)}},A:function(E,$,C,M,U,H,X,Q,Z,se,ve){var ke=ie();try{pe(E)($,C,M,U,H,X,Q,Z,se,ve)}catch($e){if(oe(ke),$e!==$e+0)throw $e;ae(1,0)}},C:function(E,$,C,M,U,H,X,Q,Z,se,ve,ke,$e,G,ge,Te){var Ge=ie();try{pe(E)($,C,M,U,H,X,Q,Z,se,ve,ke,$e,G,ge,Te)}catch(Qe){if(oe(Ge),Qe!==Qe+0)throw Qe;ae(1,0)}},aa:function(E,$,C,M,U,H,X,Q){var Z=ie();try{yt(E,$,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},_:function(E,$,C,M,U,H,X,Q,Z,se,ve,ke){var $e=ie();try{vt(E,$,C,M,U,H,X,Q,Z,se,ve,ke)}catch(G){if(oe($e),G!==G+0)throw G;ae(1,0)}},$:function(E,$,C,M,U,H){var X=ie();try{_t(E,$,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},n:function(E){return E},F:function(E){Re=E},ha:Et,y:function(E,$,C,M){return Et(E,$,C,M)}};(function(){function E(U){o.asm=U.exports,I=o.asm.Ka,me(),Pe=o.asm.ib,le.unshift(o.asm.La),Ce--,o.monitorRunDependencies&&o.monitorRunDependencies(Ce),Ce==0&&Fe&&(U=Fe,Fe=null,U())}function $(U){E(U.instance)}function C(U){return function(){if(!T&&(m||y)){if(typeof fetch=="function"&&!Ae.startsWith("file://"))return fetch(Ae,{credentials:"same-origin"}).then(function(H){if(!H.ok)throw"failed to load wasm binary file at '"+Ae+"'";return H.arrayBuffer()}).catch(function(){return Ue()});if(i)return new Promise(function(H,X){i(Ae,function(Q){H(new Uint8Array(Q))},X)})}return Promise.resolve().then(function(){return Ue()})}().then(function(H){return WebAssembly.instantiate(H,M)}).then(function(H){return H}).then(U,function(H){A("failed to asynchronously prepare wasm: "+H),Ee(H)})}var M={a:It};if(Ce++,o.monitorRunDependencies&&o.monitorRunDependencies(Ce),o.instantiateWasm)try{return o.instantiateWasm(M,E)}catch(U){return A("Module.instantiateWasm callback failed with error: "+U),!1}(T||typeof WebAssembly.instantiateStreaming!="function"||we()||Ae.startsWith("file://")||v||typeof fetch!="function"?C($):fetch(Ae,{credentials:"same-origin"}).then(function(U){return WebAssembly.instantiateStreaming(U,M).then($,function(H){return A("wasm streaming compile failed: "+H),A("falling back to ArrayBuffer instantiation"),C($)})})).catch(f)})(),o.___wasm_call_ctors=function(){return(o.___wasm_call_ctors=o.asm.La).apply(null,arguments)},o._OrtInit=function(){return(o._OrtInit=o.asm.Ma).apply(null,arguments)},o._OrtCreateSessionOptions=function(){return(o._OrtCreateSessionOptions=o.asm.Na).apply(null,arguments)},o._OrtAppendExecutionProvider=function(){return(o._OrtAppendExecutionProvider=o.asm.Oa).apply(null,arguments)},o._OrtAddSessionConfigEntry=function(){return(o._OrtAddSessionConfigEntry=o.asm.Pa).apply(null,arguments)},o._OrtReleaseSessionOptions=function(){return(o._OrtReleaseSessionOptions=o.asm.Qa).apply(null,arguments)},o._OrtCreateSession=function(){return(o._OrtCreateSession=o.asm.Ra).apply(null,arguments)},o._OrtReleaseSession=function(){return(o._OrtReleaseSession=o.asm.Sa).apply(null,arguments)},o._OrtGetInputCount=function(){return(o._OrtGetInputCount=o.asm.Ta).apply(null,arguments)},o._OrtGetOutputCount=function(){return(o._OrtGetOutputCount=o.asm.Ua).apply(null,arguments)},o._OrtGetInputName=function(){return(o._OrtGetInputName=o.asm.Va).apply(null,arguments)},o._OrtGetOutputName=function(){return(o._OrtGetOutputName=o.asm.Wa).apply(null,arguments)},o._OrtFree=function(){return(o._OrtFree=o.asm.Xa).apply(null,arguments)},o._OrtCreateTensor=function(){return(o._OrtCreateTensor=o.asm.Ya).apply(null,arguments)},o._OrtGetTensorData=function(){return(o._OrtGetTensorData=o.asm.Za).apply(null,arguments)},o._OrtReleaseTensor=function(){return(o._OrtReleaseTensor=o.asm._a).apply(null,arguments)},o._OrtCreateRunOptions=function(){return(o._OrtCreateRunOptions=o.asm.$a).apply(null,arguments)},o._OrtAddRunConfigEntry=function(){return(o._OrtAddRunConfigEntry=o.asm.ab).apply(null,arguments)},o._OrtReleaseRunOptions=function(){return(o._OrtReleaseRunOptions=o.asm.bb).apply(null,arguments)},o._OrtRun=function(){return(o._OrtRun=o.asm.cb).apply(null,arguments)},o._OrtEndProfiling=function(){return(o._OrtEndProfiling=o.asm.db).apply(null,arguments)};var Je,ye=o._malloc=function(){return(ye=o._malloc=o.asm.eb).apply(null,arguments)},rt=o._free=function(){return(rt=o._free=o.asm.fb).apply(null,arguments)},dt=o._fflush=function(){return(dt=o._fflush=o.asm.gb).apply(null,arguments)},it=o.___funcs_on_exit=function(){return(it=o.___funcs_on_exit=o.asm.hb).apply(null,arguments)},ae=o._setThrew=function(){return(ae=o._setThrew=o.asm.jb).apply(null,arguments)},ie=o.stackSave=function(){return(ie=o.stackSave=o.asm.kb).apply(null,arguments)},oe=o.stackRestore=function(){return(oe=o.stackRestore=o.asm.lb).apply(null,arguments)},pt=o.stackAlloc=function(){return(pt=o.stackAlloc=o.asm.mb).apply(null,arguments)},ot=o.___cxa_can_catch=function(){return(ot=o.___cxa_can_catch=o.asm.nb).apply(null,arguments)},ht=o.___cxa_is_pointer_type=function(){return(ht=o.___cxa_is_pointer_type=o.asm.ob).apply(null,arguments)},gt=o.dynCall_j=function(){return(gt=o.dynCall_j=o.asm.pb).apply(null,arguments)},mt=o.dynCall_iiiiij=function(){return(mt=o.dynCall_iiiiij=o.asm.qb).apply(null,arguments)},bt=o.dynCall_jii=function(){return(bt=o.dynCall_jii=o.asm.rb).apply(null,arguments)},yt=o.dynCall_viiiiij=function(){return(yt=o.dynCall_viiiiij=o.asm.sb).apply(null,arguments)},_t=o.dynCall_vjji=function(){return(_t=o.dynCall_vjji=o.asm.tb).apply(null,arguments)},vt=o.dynCall_viiijjjii=function(){return(vt=o.dynCall_viiijjjii=o.asm.ub).apply(null,arguments)},wt=o.dynCall_iij=function(){return(wt=o.dynCall_iij=o.asm.vb).apply(null,arguments)},xt=o.dynCall_ji=function(){return(xt=o.dynCall_ji=o.asm.wb).apply(null,arguments)},Tt=o.dynCall_iiiiiij=function(){return(Tt=o.dynCall_iiiiiij=o.asm.xb).apply(null,arguments)},St=o.dynCall_iiij=function(){return(St=o.dynCall_iiij=o.asm.yb).apply(null,arguments)};function Ot(){function E(){if(!Je&&(Je=!0,o.calledRun=!0,!k)){if(We(le),c(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;){var $=o.postRun.shift();_e.unshift($)}We(_e)}}if(!(0{D.exports=function(u,b){for(var g=new Array(arguments.length-1),p=0,h=2,o=!0;h{var b=u;b.length=function(c){var f=c.length;if(!f)return 0;for(var s=0;--f%4>1&&c.charAt(f)==="=";)++s;return Math.ceil(3*c.length)/4-s};for(var g=new Array(64),p=new Array(123),h=0;h<64;)p[g[h]=h<26?h+65:h<52?h+71:h<62?h-4:h-59|43]=h++;b.encode=function(c,f,s){for(var i,t=null,e=[],n=0,r=0;f>2],i=(3&a)<<4,r=1;break;case 1:e[n++]=g[i|a>>4],i=(15&a)<<2,r=2;break;case 2:e[n++]=g[i|a>>6],e[n++]=g[63&a],r=0}n>8191&&((t||(t=[])).push(String.fromCharCode.apply(String,e)),n=0)}return r&&(e[n++]=g[i],e[n++]=61,r===1&&(e[n++]=61)),t?(n&&t.push(String.fromCharCode.apply(String,e.slice(0,n))),t.join("")):String.fromCharCode.apply(String,e.slice(0,n))};var o="invalid encoding";b.decode=function(c,f,s){for(var i,t=s,e=0,n=0;n1)break;if((r=p[r])===void 0)throw Error(o);switch(e){case 0:i=r,e=1;break;case 1:f[s++]=i<<2|(48&r)>>4,i=r,e=2;break;case 2:f[s++]=(15&i)<<4|(60&r)>>2,i=r,e=3;break;case 3:f[s++]=(3&i)<<6|r,e=0}}if(e===1)throw Error(o);return s-t},b.test=function(c){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(c)}},9211:D=>{function u(){this._listeners={}}D.exports=u,u.prototype.on=function(b,g,p){return(this._listeners[b]||(this._listeners[b]=[])).push({fn:g,ctx:p||this}),this},u.prototype.off=function(b,g){if(b===void 0)this._listeners={};else if(g===void 0)this._listeners[b]=[];else for(var p=this._listeners[b],h=0;h{function u(o){return typeof Float32Array<"u"?function(){var c=new Float32Array([-0]),f=new Uint8Array(c.buffer),s=f[3]===128;function i(r,a,l){c[0]=r,a[l]=f[0],a[l+1]=f[1],a[l+2]=f[2],a[l+3]=f[3]}function t(r,a,l){c[0]=r,a[l]=f[3],a[l+1]=f[2],a[l+2]=f[1],a[l+3]=f[0]}function e(r,a){return f[0]=r[a],f[1]=r[a+1],f[2]=r[a+2],f[3]=r[a+3],c[0]}function n(r,a){return f[3]=r[a],f[2]=r[a+1],f[1]=r[a+2],f[0]=r[a+3],c[0]}o.writeFloatLE=s?i:t,o.writeFloatBE=s?t:i,o.readFloatLE=s?e:n,o.readFloatBE=s?n:e}():function(){function c(s,i,t,e){var n=i<0?1:0;if(n&&(i=-i),i===0)s(1/i>0?0:2147483648,t,e);else if(isNaN(i))s(2143289344,t,e);else if(i>34028234663852886e22)s((n<<31|2139095040)>>>0,t,e);else if(i<11754943508222875e-54)s((n<<31|Math.round(i/1401298464324817e-60))>>>0,t,e);else{var r=Math.floor(Math.log(i)/Math.LN2);s((n<<31|r+127<<23|8388607&Math.round(i*Math.pow(2,-r)*8388608))>>>0,t,e)}}function f(s,i,t){var e=s(i,t),n=2*(e>>31)+1,r=e>>>23&255,a=8388607&e;return r===255?a?NaN:n*(1/0):r===0?1401298464324817e-60*n*a:n*Math.pow(2,r-150)*(a+8388608)}o.writeFloatLE=c.bind(null,b),o.writeFloatBE=c.bind(null,g),o.readFloatLE=f.bind(null,p),o.readFloatBE=f.bind(null,h)}(),typeof Float64Array<"u"?function(){var c=new Float64Array([-0]),f=new Uint8Array(c.buffer),s=f[7]===128;function i(r,a,l){c[0]=r,a[l]=f[0],a[l+1]=f[1],a[l+2]=f[2],a[l+3]=f[3],a[l+4]=f[4],a[l+5]=f[5],a[l+6]=f[6],a[l+7]=f[7]}function t(r,a,l){c[0]=r,a[l]=f[7],a[l+1]=f[6],a[l+2]=f[5],a[l+3]=f[4],a[l+4]=f[3],a[l+5]=f[2],a[l+6]=f[1],a[l+7]=f[0]}function e(r,a){return f[0]=r[a],f[1]=r[a+1],f[2]=r[a+2],f[3]=r[a+3],f[4]=r[a+4],f[5]=r[a+5],f[6]=r[a+6],f[7]=r[a+7],c[0]}function n(r,a){return f[7]=r[a],f[6]=r[a+1],f[5]=r[a+2],f[4]=r[a+3],f[3]=r[a+4],f[2]=r[a+5],f[1]=r[a+6],f[0]=r[a+7],c[0]}o.writeDoubleLE=s?i:t,o.writeDoubleBE=s?t:i,o.readDoubleLE=s?e:n,o.readDoubleBE=s?n:e}():function(){function c(s,i,t,e,n,r){var a=e<0?1:0;if(a&&(e=-e),e===0)s(0,n,r+i),s(1/e>0?0:2147483648,n,r+t);else if(isNaN(e))s(0,n,r+i),s(2146959360,n,r+t);else if(e>17976931348623157e292)s(0,n,r+i),s((a<<31|2146435072)>>>0,n,r+t);else{var l;if(e<22250738585072014e-324)s((l=e/5e-324)>>>0,n,r+i),s((a<<31|l/4294967296)>>>0,n,r+t);else{var d=Math.floor(Math.log(e)/Math.LN2);d===1024&&(d=1023),s(4503599627370496*(l=e*Math.pow(2,-d))>>>0,n,r+i),s((a<<31|d+1023<<20|1048576*l&1048575)>>>0,n,r+t)}}}function f(s,i,t,e,n){var r=s(e,n+i),a=s(e,n+t),l=2*(a>>31)+1,d=a>>>20&2047,m=4294967296*(1048575&a)+r;return d===2047?m?NaN:l*(1/0):d===0?5e-324*l*m:l*Math.pow(2,d-1075)*(m+4503599627370496)}o.writeDoubleLE=c.bind(null,b,0,4),o.writeDoubleBE=c.bind(null,g,4,0),o.readDoubleLE=f.bind(null,p,0,4),o.readDoubleBE=f.bind(null,h,4,0)}(),o}function b(o,c,f){c[f]=255&o,c[f+1]=o>>>8&255,c[f+2]=o>>>16&255,c[f+3]=o>>>24}function g(o,c,f){c[f]=o>>>24,c[f+1]=o>>>16&255,c[f+2]=o>>>8&255,c[f+3]=255&o}function p(o,c){return(o[c]|o[c+1]<<8|o[c+2]<<16|o[c+3]<<24)>>>0}function h(o,c){return(o[c]<<24|o[c+1]<<16|o[c+2]<<8|o[c+3])>>>0}D.exports=u(u)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(D){}return null}module.exports=inquire},6662:D=>{D.exports=function(u,b,g){var p=g||8192,h=p>>>1,o=null,c=p;return function(f){if(f<1||f>h)return u(f);c+f>p&&(o=u(p),c=0);var s=b.call(o,c,c+=f);return 7&c&&(c=1+(7|c)),s}}},4997:(D,u)=>{var b=u;b.length=function(g){for(var p=0,h=0,o=0;o191&&o<224?f[s++]=(31&o)<<6|63&g[p++]:o>239&&o<365?(o=((7&o)<<18|(63&g[p++])<<12|(63&g[p++])<<6|63&g[p++])-65536,f[s++]=55296+(o>>10),f[s++]=56320+(1023&o)):f[s++]=(15&o)<<12|(63&g[p++])<<6|63&g[p++],s>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,f)),s=0);return c?(s&&c.push(String.fromCharCode.apply(String,f.slice(0,s))),c.join("")):String.fromCharCode.apply(String,f.slice(0,s))},b.write=function(g,p,h){for(var o,c,f=h,s=0;s>6|192,p[h++]=63&o|128):(64512&o)==55296&&(64512&(c=g.charCodeAt(s+1)))==56320?(o=65536+((1023&o)<<10)+(1023&c),++s,p[h++]=o>>18|240,p[h++]=o>>12&63|128,p[h++]=o>>6&63|128,p[h++]=63&o|128):(p[h++]=o>>12|224,p[h++]=o>>6&63|128,p[h++]=63&o|128);return h-f}},3442:(D,u)=>{u.__esModule=!0;var b=function(){function g(p){if(!p)throw new TypeError("Invalid argument; `value` has no value.");this.value=g.EMPTY,p&&g.isGuid(p)&&(this.value=p)}return g.isGuid=function(p){var h=p.toString();return p&&(p instanceof g||g.validator.test(h))},g.create=function(){return new g([g.gen(2),g.gen(1),g.gen(1),g.gen(1),g.gen(3)].join("-"))},g.createEmpty=function(){return new g("emptyguid")},g.parse=function(p){return new g(p)},g.raw=function(){return[g.gen(2),g.gen(1),g.gen(1),g.gen(1),g.gen(3)].join("-")},g.gen=function(p){for(var h="",o=0;o{D.exports=b;var u=null;try{u=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function b(w,I,R){this.low=0|w,this.high=0|I,this.unsigned=!!R}function g(w){return(w&&w.__isLong__)===!0}b.prototype.__isLong__,Object.defineProperty(b.prototype,"__isLong__",{value:!0}),b.isLong=g;var p={},h={};function o(w,I){var R,B,j;return I?(j=0<=(w>>>=0)&&w<256)&&(B=h[w])?B:(R=f(w,(0|w)<0?-1:0,!0),j&&(h[w]=R),R):(j=-128<=(w|=0)&&w<128)&&(B=p[w])?B:(R=f(w,w<0?-1:0,!1),j&&(p[w]=R),R)}function c(w,I){if(isNaN(w))return I?d:l;if(I){if(w<0)return d;if(w>=n)return T}else{if(w<=-9223372036854776e3)return S;if(w+1>=r)return _}return w<0?c(-w,I).neg():f(w%e|0,w/e|0,I)}function f(w,I,R){return new b(w,I,R)}b.fromInt=o,b.fromNumber=c,b.fromBits=f;var s=Math.pow;function i(w,I,R){if(w.length===0)throw Error("empty string");if(w==="NaN"||w==="Infinity"||w==="+Infinity"||w==="-Infinity")return l;if(typeof I=="number"?(R=I,I=!1):I=!!I,(R=R||10)<2||360)throw Error("interior hyphen");if(B===0)return i(w.substring(1),I,R).neg();for(var j=c(s(R,8)),N=l,W=0;W>>0:this.low},A.toNumber=function(){return this.unsigned?(this.high>>>0)*e+(this.low>>>0):this.high*e+(this.low>>>0)},A.toString=function(w){if((w=w||10)<2||36>>0).toString(w);if((N=k).isZero())return V+W;for(;V.length<6;)V="0"+V;W=""+V+W}},A.getHighBits=function(){return this.high},A.getHighBitsUnsigned=function(){return this.high>>>0},A.getLowBits=function(){return this.low},A.getLowBitsUnsigned=function(){return this.low>>>0},A.getNumBitsAbs=function(){if(this.isNegative())return this.eq(S)?64:this.neg().getNumBitsAbs();for(var w=this.high!=0?this.high:this.low,I=31;I>0&&(w&1<=0},A.isOdd=function(){return(1&this.low)==1},A.isEven=function(){return(1&this.low)==0},A.equals=function(w){return g(w)||(w=t(w)),(this.unsigned===w.unsigned||this.high>>>31!=1||w.high>>>31!=1)&&this.high===w.high&&this.low===w.low},A.eq=A.equals,A.notEquals=function(w){return!this.eq(w)},A.neq=A.notEquals,A.ne=A.notEquals,A.lessThan=function(w){return this.comp(w)<0},A.lt=A.lessThan,A.lessThanOrEqual=function(w){return this.comp(w)<=0},A.lte=A.lessThanOrEqual,A.le=A.lessThanOrEqual,A.greaterThan=function(w){return this.comp(w)>0},A.gt=A.greaterThan,A.greaterThanOrEqual=function(w){return this.comp(w)>=0},A.gte=A.greaterThanOrEqual,A.ge=A.greaterThanOrEqual,A.compare=function(w){if(g(w)||(w=t(w)),this.eq(w))return 0;var I=this.isNegative(),R=w.isNegative();return I&&!R?-1:!I&&R?1:this.unsigned?w.high>>>0>this.high>>>0||w.high===this.high&&w.low>>>0>this.low>>>0?-1:1:this.sub(w).isNegative()?-1:1},A.comp=A.compare,A.negate=function(){return!this.unsigned&&this.eq(S)?S:this.not().add(m)},A.neg=A.negate,A.add=function(w){g(w)||(w=t(w));var I=this.high>>>16,R=65535&this.high,B=this.low>>>16,j=65535&this.low,N=w.high>>>16,W=65535&w.high,k=w.low>>>16,V=0,J=0,Y=0,te=0;return Y+=(te+=j+(65535&w.low))>>>16,J+=(Y+=B+k)>>>16,V+=(J+=R+W)>>>16,V+=I+N,f((Y&=65535)<<16|(te&=65535),(V&=65535)<<16|(J&=65535),this.unsigned)},A.subtract=function(w){return g(w)||(w=t(w)),this.add(w.neg())},A.sub=A.subtract,A.multiply=function(w){if(this.isZero())return l;if(g(w)||(w=t(w)),u)return f(u.mul(this.low,this.high,w.low,w.high),u.get_high(),this.unsigned);if(w.isZero())return l;if(this.eq(S))return w.isOdd()?S:l;if(w.eq(S))return this.isOdd()?S:l;if(this.isNegative())return w.isNegative()?this.neg().mul(w.neg()):this.neg().mul(w).neg();if(w.isNegative())return this.mul(w.neg()).neg();if(this.lt(a)&&w.lt(a))return c(this.toNumber()*w.toNumber(),this.unsigned);var I=this.high>>>16,R=65535&this.high,B=this.low>>>16,j=65535&this.low,N=w.high>>>16,W=65535&w.high,k=w.low>>>16,V=65535&w.low,J=0,Y=0,te=0,ne=0;return te+=(ne+=j*V)>>>16,Y+=(te+=B*V)>>>16,te&=65535,Y+=(te+=j*k)>>>16,J+=(Y+=R*V)>>>16,Y&=65535,J+=(Y+=B*k)>>>16,Y&=65535,J+=(Y+=j*W)>>>16,J+=I*V+R*k+B*W+j*N,f((te&=65535)<<16|(ne&=65535),(J&=65535)<<16|(Y&=65535),this.unsigned)},A.mul=A.multiply,A.divide=function(w){if(g(w)||(w=t(w)),w.isZero())throw Error("division by zero");var I,R,B;if(u)return this.unsigned||this.high!==-2147483648||w.low!==-1||w.high!==-1?f((this.unsigned?u.div_u:u.div_s)(this.low,this.high,w.low,w.high),u.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?d:l;if(this.unsigned){if(w.unsigned||(w=w.toUnsigned()),w.gt(this))return d;if(w.gt(this.shru(1)))return y;B=d}else{if(this.eq(S))return w.eq(m)||w.eq(v)?S:w.eq(S)?m:(I=this.shr(1).div(w).shl(1)).eq(l)?w.isNegative()?m:v:(R=this.sub(w.mul(I)),B=I.add(R.div(w)));if(w.eq(S))return this.unsigned?d:l;if(this.isNegative())return w.isNegative()?this.neg().div(w.neg()):this.neg().div(w).neg();if(w.isNegative())return this.div(w.neg()).neg();B=l}for(R=this;R.gte(w);){I=Math.max(1,Math.floor(R.toNumber()/w.toNumber()));for(var j=Math.ceil(Math.log(I)/Math.LN2),N=j<=48?1:s(2,j-48),W=c(I),k=W.mul(w);k.isNegative()||k.gt(R);)k=(W=c(I-=N,this.unsigned)).mul(w);W.isZero()&&(W=m),B=B.add(W),R=R.sub(k)}return B},A.div=A.divide,A.modulo=function(w){return g(w)||(w=t(w)),u?f((this.unsigned?u.rem_u:u.rem_s)(this.low,this.high,w.low,w.high),u.get_high(),this.unsigned):this.sub(this.div(w).mul(w))},A.mod=A.modulo,A.rem=A.modulo,A.not=function(){return f(~this.low,~this.high,this.unsigned)},A.and=function(w){return g(w)||(w=t(w)),f(this.low&w.low,this.high&w.high,this.unsigned)},A.or=function(w){return g(w)||(w=t(w)),f(this.low|w.low,this.high|w.high,this.unsigned)},A.xor=function(w){return g(w)||(w=t(w)),f(this.low^w.low,this.high^w.high,this.unsigned)},A.shiftLeft=function(w){return g(w)&&(w=w.toInt()),(w&=63)==0?this:w<32?f(this.low<>>32-w,this.unsigned):f(0,this.low<>>w|this.high<<32-w,this.high>>w,this.unsigned):f(this.high>>w-32,this.high>=0?0:-1,this.unsigned)},A.shr=A.shiftRight,A.shiftRightUnsigned=function(w){if(g(w)&&(w=w.toInt()),(w&=63)==0)return this;var I=this.high;return w<32?f(this.low>>>w|I<<32-w,I>>>w,this.unsigned):f(w===32?I:I>>>w-32,0,this.unsigned)},A.shru=A.shiftRightUnsigned,A.shr_u=A.shiftRightUnsigned,A.toSigned=function(){return this.unsigned?f(this.low,this.high,!1):this},A.toUnsigned=function(){return this.unsigned?this:f(this.low,this.high,!0)},A.toBytes=function(w){return w?this.toBytesLE():this.toBytesBE()},A.toBytesLE=function(){var w=this.high,I=this.low;return[255&I,I>>>8&255,I>>>16&255,I>>>24,255&w,w>>>8&255,w>>>16&255,w>>>24]},A.toBytesBE=function(){var w=this.high,I=this.low;return[w>>>24,w>>>16&255,w>>>8&255,255&w,I>>>24,I>>>16&255,I>>>8&255,255&I]},b.fromBytes=function(w,I,R){return R?b.fromBytesLE(w,I):b.fromBytesBE(w,I)},b.fromBytesLE=function(w,I){return new b(w[0]|w[1]<<8|w[2]<<16|w[3]<<24,w[4]|w[5]<<8|w[6]<<16|w[7]<<24,I)},b.fromBytesBE=function(w,I){return new b(w[4]<<24|w[5]<<16|w[6]<<8|w[7],w[0]<<24|w[1]<<16|w[2]<<8|w[3],I)}},1446:(D,u,b)=>{var g,p,h,o=b(2100),c=o.Reader,f=o.Writer,s=o.util,i=o.roots.default||(o.roots.default={});i.onnx=((h={}).Version=(g={},(p=Object.create(g))[g[0]="_START_VERSION"]=0,p[g[1]="IR_VERSION_2017_10_10"]=1,p[g[2]="IR_VERSION_2017_10_30"]=2,p[g[3]="IR_VERSION_2017_11_3"]=3,p[g[4]="IR_VERSION_2019_1_22"]=4,p[g[5]="IR_VERSION"]=5,p),h.AttributeProto=function(){function t(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.name=e.string();break;case 21:a.refAttrName=e.string();break;case 13:a.docString=e.string();break;case 20:a.type=e.int32();break;case 2:a.f=e.float();break;case 3:a.i=e.int64();break;case 4:a.s=e.bytes();break;case 5:a.t=i.onnx.TensorProto.decode(e,e.uint32());break;case 6:a.g=i.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(a.floats&&a.floats.length||(a.floats=[]),(7&l)==2)for(var d=e.uint32()+e.pos;e.pos>>0,e.i.high>>>0).toNumber())),e.s!=null&&(typeof e.s=="string"?s.base64.decode(e.s,n.s=s.newBuffer(s.base64.length(e.s)),0):e.s.length&&(n.s=e.s)),e.t!=null){if(typeof e.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");n.t=i.onnx.TensorProto.fromObject(e.t)}if(e.g!=null){if(typeof e.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");n.g=i.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");n.floats=[];for(var r=0;r>>0,e.ints[r].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(n.strings=[],r=0;r>>0,e.i.high>>>0).toNumber():e.i),e.s!=null&&e.hasOwnProperty("s")&&(r.s=n.bytes===String?s.base64.encode(e.s,0,e.s.length):n.bytes===Array?Array.prototype.slice.call(e.s):e.s),e.t!=null&&e.hasOwnProperty("t")&&(r.t=i.onnx.TensorProto.toObject(e.t,n)),e.g!=null&&e.hasOwnProperty("g")&&(r.g=i.onnx.GraphProto.toObject(e.g,n)),e.floats&&e.floats.length){r.floats=[];for(var l=0;l>>0,e.ints[l].high>>>0).toNumber():e.ints[l];if(e.strings&&e.strings.length)for(r.strings=[],l=0;l>>3){case 1:a.name=e.string();break;case 2:a.type=i.onnx.TypeProto.decode(e,e.uint32());break;case 3:a.docString=e.string();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.name!=null&&e.hasOwnProperty("name")&&!s.isString(e.name))return"name: string expected";if(e.type!=null&&e.hasOwnProperty("type")){var n=i.onnx.TypeProto.verify(e.type);if(n)return"type."+n}return e.docString!=null&&e.hasOwnProperty("docString")&&!s.isString(e.docString)?"docString: string expected":null},t.fromObject=function(e){if(e instanceof i.onnx.ValueInfoProto)return e;var n=new i.onnx.ValueInfoProto;if(e.name!=null&&(n.name=String(e.name)),e.type!=null){if(typeof e.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");n.type=i.onnx.TypeProto.fromObject(e.type)}return e.docString!=null&&(n.docString=String(e.docString)),n},t.toObject=function(e,n){n||(n={});var r={};return n.defaults&&(r.name="",r.type=null,r.docString=""),e.name!=null&&e.hasOwnProperty("name")&&(r.name=e.name),e.type!=null&&e.hasOwnProperty("type")&&(r.type=i.onnx.TypeProto.toObject(e.type,n)),e.docString!=null&&e.hasOwnProperty("docString")&&(r.docString=e.docString),r},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t}(),h.NodeProto=function(){function t(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.input&&a.input.length||(a.input=[]),a.input.push(e.string());break;case 2:a.output&&a.output.length||(a.output=[]),a.output.push(e.string());break;case 3:a.name=e.string();break;case 4:a.opType=e.string();break;case 7:a.domain=e.string();break;case 5:a.attribute&&a.attribute.length||(a.attribute=[]),a.attribute.push(i.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:a.docString=e.string();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.input!=null&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var n=0;n>>3){case 1:a.irVersion=e.int64();break;case 8:a.opsetImport&&a.opsetImport.length||(a.opsetImport=[]),a.opsetImport.push(i.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:a.producerName=e.string();break;case 3:a.producerVersion=e.string();break;case 4:a.domain=e.string();break;case 5:a.modelVersion=e.int64();break;case 6:a.docString=e.string();break;case 7:a.graph=i.onnx.GraphProto.decode(e,e.uint32());break;case 14:a.metadataProps&&a.metadataProps.length||(a.metadataProps=[]),a.metadataProps.push(i.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.irVersion!=null&&e.hasOwnProperty("irVersion")&&!(s.isInteger(e.irVersion)||e.irVersion&&s.isInteger(e.irVersion.low)&&s.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(e.opsetImport!=null&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var n=0;n>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");n.opsetImport=[];for(var r=0;r>>0,e.modelVersion.high>>>0).toNumber())),e.docString!=null&&(n.docString=String(e.docString)),e.graph!=null){if(typeof e.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");n.graph=i.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(n.metadataProps=[],r=0;r>>0,e.irVersion.high>>>0).toNumber():e.irVersion),e.producerName!=null&&e.hasOwnProperty("producerName")&&(r.producerName=e.producerName),e.producerVersion!=null&&e.hasOwnProperty("producerVersion")&&(r.producerVersion=e.producerVersion),e.domain!=null&&e.hasOwnProperty("domain")&&(r.domain=e.domain),e.modelVersion!=null&&e.hasOwnProperty("modelVersion")&&(typeof e.modelVersion=="number"?r.modelVersion=n.longs===String?String(e.modelVersion):e.modelVersion:r.modelVersion=n.longs===String?s.Long.prototype.toString.call(e.modelVersion):n.longs===Number?new s.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),e.docString!=null&&e.hasOwnProperty("docString")&&(r.docString=e.docString),e.graph!=null&&e.hasOwnProperty("graph")&&(r.graph=i.onnx.GraphProto.toObject(e.graph,n)),e.opsetImport&&e.opsetImport.length){r.opsetImport=[];for(var l=0;l>>3){case 1:a.key=e.string();break;case 2:a.value=e.string();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.key!=null&&e.hasOwnProperty("key")&&!s.isString(e.key)?"key: string expected":e.value!=null&&e.hasOwnProperty("value")&&!s.isString(e.value)?"value: string expected":null},t.fromObject=function(e){if(e instanceof i.onnx.StringStringEntryProto)return e;var n=new i.onnx.StringStringEntryProto;return e.key!=null&&(n.key=String(e.key)),e.value!=null&&(n.value=String(e.value)),n},t.toObject=function(e,n){n||(n={});var r={};return n.defaults&&(r.key="",r.value=""),e.key!=null&&e.hasOwnProperty("key")&&(r.key=e.key),e.value!=null&&e.hasOwnProperty("value")&&(r.value=e.value),r},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t}(),h.TensorAnnotation=function(){function t(e){if(this.quantParameterTensorNames=[],e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.tensorName=e.string();break;case 2:a.quantParameterTensorNames&&a.quantParameterTensorNames.length||(a.quantParameterTensorNames=[]),a.quantParameterTensorNames.push(i.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.tensorName!=null&&e.hasOwnProperty("tensorName")&&!s.isString(e.tensorName))return"tensorName: string expected";if(e.quantParameterTensorNames!=null&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var n=0;n>>3){case 1:a.node&&a.node.length||(a.node=[]),a.node.push(i.onnx.NodeProto.decode(e,e.uint32()));break;case 2:a.name=e.string();break;case 5:a.initializer&&a.initializer.length||(a.initializer=[]),a.initializer.push(i.onnx.TensorProto.decode(e,e.uint32()));break;case 10:a.docString=e.string();break;case 11:a.input&&a.input.length||(a.input=[]),a.input.push(i.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:a.output&&a.output.length||(a.output=[]),a.output.push(i.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:a.valueInfo&&a.valueInfo.length||(a.valueInfo=[]),a.valueInfo.push(i.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:a.quantizationAnnotation&&a.quantizationAnnotation.length||(a.quantizationAnnotation=[]),a.quantizationAnnotation.push(i.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.node!=null&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var n=0;n>>3){case 1:if(a.dims&&a.dims.length||(a.dims=[]),(7&l)==2)for(var d=e.uint32()+e.pos;e.pos>>0,e.dims[r].high>>>0).toNumber())}if(e.dataType!=null&&(n.dataType=0|e.dataType),e.segment!=null){if(typeof e.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");n.segment=i.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(n.floatData=[],r=0;r>>0,e.int64Data[r].high>>>0).toNumber())}if(e.name!=null&&(n.name=String(e.name)),e.docString!=null&&(n.docString=String(e.docString)),e.rawData!=null&&(typeof e.rawData=="string"?s.base64.decode(e.rawData,n.rawData=s.newBuffer(s.base64.length(e.rawData)),0):e.rawData.length&&(n.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(n.externalData=[],r=0;r>>0,e.uint64Data[r].high>>>0).toNumber(!0))}return n},t.toObject=function(e,n){n||(n={});var r={};if((n.arrays||n.defaults)&&(r.dims=[],r.floatData=[],r.int32Data=[],r.stringData=[],r.int64Data=[],r.doubleData=[],r.uint64Data=[],r.externalData=[]),n.defaults&&(r.dataType=0,r.segment=null,r.name="",n.bytes===String?r.rawData="":(r.rawData=[],n.bytes!==Array&&(r.rawData=s.newBuffer(r.rawData))),r.docString="",r.dataLocation=n.enums===String?"DEFAULT":0),e.dims&&e.dims.length){r.dims=[];for(var a=0;a>>0,e.dims[a].high>>>0).toNumber():e.dims[a]}if(e.dataType!=null&&e.hasOwnProperty("dataType")&&(r.dataType=e.dataType),e.segment!=null&&e.hasOwnProperty("segment")&&(r.segment=i.onnx.TensorProto.Segment.toObject(e.segment,n)),e.floatData&&e.floatData.length)for(r.floatData=[],a=0;a>>0,e.int64Data[a].high>>>0).toNumber():e.int64Data[a];if(e.name!=null&&e.hasOwnProperty("name")&&(r.name=e.name),e.rawData!=null&&e.hasOwnProperty("rawData")&&(r.rawData=n.bytes===String?s.base64.encode(e.rawData,0,e.rawData.length):n.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(r.doubleData=[],a=0;a>>0,e.uint64Data[a].high>>>0).toNumber(!0):e.uint64Data[a];if(e.docString!=null&&e.hasOwnProperty("docString")&&(r.docString=e.docString),e.externalData&&e.externalData.length)for(r.externalData=[],a=0;a>>3){case 1:l.begin=n.int64();break;case 2:l.end=n.int64();break;default:n.skipType(7&d)}}return l},e.decodeDelimited=function(n){return n instanceof c||(n=new c(n)),this.decode(n,n.uint32())},e.verify=function(n){return typeof n!="object"||n===null?"object expected":n.begin!=null&&n.hasOwnProperty("begin")&&!(s.isInteger(n.begin)||n.begin&&s.isInteger(n.begin.low)&&s.isInteger(n.begin.high))?"begin: integer|Long expected":n.end!=null&&n.hasOwnProperty("end")&&!(s.isInteger(n.end)||n.end&&s.isInteger(n.end.low)&&s.isInteger(n.end.high))?"end: integer|Long expected":null},e.fromObject=function(n){if(n instanceof i.onnx.TensorProto.Segment)return n;var r=new i.onnx.TensorProto.Segment;return n.begin!=null&&(s.Long?(r.begin=s.Long.fromValue(n.begin)).unsigned=!1:typeof n.begin=="string"?r.begin=parseInt(n.begin,10):typeof n.begin=="number"?r.begin=n.begin:typeof n.begin=="object"&&(r.begin=new s.LongBits(n.begin.low>>>0,n.begin.high>>>0).toNumber())),n.end!=null&&(s.Long?(r.end=s.Long.fromValue(n.end)).unsigned=!1:typeof n.end=="string"?r.end=parseInt(n.end,10):typeof n.end=="number"?r.end=n.end:typeof n.end=="object"&&(r.end=new s.LongBits(n.end.low>>>0,n.end.high>>>0).toNumber())),r},e.toObject=function(n,r){r||(r={});var a={};if(r.defaults){if(s.Long){var l=new s.Long(0,0,!1);a.begin=r.longs===String?l.toString():r.longs===Number?l.toNumber():l}else a.begin=r.longs===String?"0":0;s.Long?(l=new s.Long(0,0,!1),a.end=r.longs===String?l.toString():r.longs===Number?l.toNumber():l):a.end=r.longs===String?"0":0}return n.begin!=null&&n.hasOwnProperty("begin")&&(typeof n.begin=="number"?a.begin=r.longs===String?String(n.begin):n.begin:a.begin=r.longs===String?s.Long.prototype.toString.call(n.begin):r.longs===Number?new s.LongBits(n.begin.low>>>0,n.begin.high>>>0).toNumber():n.begin),n.end!=null&&n.hasOwnProperty("end")&&(typeof n.end=="number"?a.end=r.longs===String?String(n.end):n.end:a.end=r.longs===String?s.Long.prototype.toString.call(n.end):r.longs===Number?new s.LongBits(n.end.low>>>0,n.end.high>>>0).toNumber():n.end),a},e.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},e}(),t.DataLocation=function(){var e={},n=Object.create(e);return n[e[0]="DEFAULT"]=0,n[e[1]="EXTERNAL"]=1,n}(),t}(),h.TensorShapeProto=function(){function t(e){if(this.dim=[],e)for(var n=Object.keys(e),r=0;r>>3==1?(a.dim&&a.dim.length||(a.dim=[]),a.dim.push(i.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&l)}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.dim!=null&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var n=0;n>>3){case 1:d.dimValue=r.int64();break;case 2:d.dimParam=r.string();break;case 3:d.denotation=r.string();break;default:r.skipType(7&m)}}return d},e.decodeDelimited=function(r){return r instanceof c||(r=new c(r)),this.decode(r,r.uint32())},e.verify=function(r){if(typeof r!="object"||r===null)return"object expected";var a={};if(r.dimValue!=null&&r.hasOwnProperty("dimValue")&&(a.value=1,!(s.isInteger(r.dimValue)||r.dimValue&&s.isInteger(r.dimValue.low)&&s.isInteger(r.dimValue.high))))return"dimValue: integer|Long expected";if(r.dimParam!=null&&r.hasOwnProperty("dimParam")){if(a.value===1)return"value: multiple values";if(a.value=1,!s.isString(r.dimParam))return"dimParam: string expected"}return r.denotation!=null&&r.hasOwnProperty("denotation")&&!s.isString(r.denotation)?"denotation: string expected":null},e.fromObject=function(r){if(r instanceof i.onnx.TensorShapeProto.Dimension)return r;var a=new i.onnx.TensorShapeProto.Dimension;return r.dimValue!=null&&(s.Long?(a.dimValue=s.Long.fromValue(r.dimValue)).unsigned=!1:typeof r.dimValue=="string"?a.dimValue=parseInt(r.dimValue,10):typeof r.dimValue=="number"?a.dimValue=r.dimValue:typeof r.dimValue=="object"&&(a.dimValue=new s.LongBits(r.dimValue.low>>>0,r.dimValue.high>>>0).toNumber())),r.dimParam!=null&&(a.dimParam=String(r.dimParam)),r.denotation!=null&&(a.denotation=String(r.denotation)),a},e.toObject=function(r,a){a||(a={});var l={};return a.defaults&&(l.denotation=""),r.dimValue!=null&&r.hasOwnProperty("dimValue")&&(typeof r.dimValue=="number"?l.dimValue=a.longs===String?String(r.dimValue):r.dimValue:l.dimValue=a.longs===String?s.Long.prototype.toString.call(r.dimValue):a.longs===Number?new s.LongBits(r.dimValue.low>>>0,r.dimValue.high>>>0).toNumber():r.dimValue,a.oneofs&&(l.value="dimValue")),r.dimParam!=null&&r.hasOwnProperty("dimParam")&&(l.dimParam=r.dimParam,a.oneofs&&(l.value="dimParam")),r.denotation!=null&&r.hasOwnProperty("denotation")&&(l.denotation=r.denotation),l},e.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},e}(),t}(),h.TypeProto=function(){function t(n){if(n)for(var r=Object.keys(n),a=0;a>>3){case 1:l.tensorType=i.onnx.TypeProto.Tensor.decode(n,n.uint32());break;case 6:l.denotation=n.string();break;default:n.skipType(7&d)}}return l},t.decodeDelimited=function(n){return n instanceof c||(n=new c(n)),this.decode(n,n.uint32())},t.verify=function(n){if(typeof n!="object"||n===null)return"object expected";if(n.tensorType!=null&&n.hasOwnProperty("tensorType")){var r=i.onnx.TypeProto.Tensor.verify(n.tensorType);if(r)return"tensorType."+r}return n.denotation!=null&&n.hasOwnProperty("denotation")&&!s.isString(n.denotation)?"denotation: string expected":null},t.fromObject=function(n){if(n instanceof i.onnx.TypeProto)return n;var r=new i.onnx.TypeProto;if(n.tensorType!=null){if(typeof n.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");r.tensorType=i.onnx.TypeProto.Tensor.fromObject(n.tensorType)}return n.denotation!=null&&(r.denotation=String(n.denotation)),r},t.toObject=function(n,r){r||(r={});var a={};return r.defaults&&(a.denotation=""),n.tensorType!=null&&n.hasOwnProperty("tensorType")&&(a.tensorType=i.onnx.TypeProto.Tensor.toObject(n.tensorType,r),r.oneofs&&(a.value="tensorType")),n.denotation!=null&&n.hasOwnProperty("denotation")&&(a.denotation=n.denotation),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t.Tensor=function(){function n(r){if(r)for(var a=Object.keys(r),l=0;l>>3){case 1:d.elemType=r.int32();break;case 2:d.shape=i.onnx.TensorShapeProto.decode(r,r.uint32());break;default:r.skipType(7&m)}}return d},n.decodeDelimited=function(r){return r instanceof c||(r=new c(r)),this.decode(r,r.uint32())},n.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.elemType!=null&&r.hasOwnProperty("elemType")&&!s.isInteger(r.elemType))return"elemType: integer expected";if(r.shape!=null&&r.hasOwnProperty("shape")){var a=i.onnx.TensorShapeProto.verify(r.shape);if(a)return"shape."+a}return null},n.fromObject=function(r){if(r instanceof i.onnx.TypeProto.Tensor)return r;var a=new i.onnx.TypeProto.Tensor;if(r.elemType!=null&&(a.elemType=0|r.elemType),r.shape!=null){if(typeof r.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");a.shape=i.onnx.TensorShapeProto.fromObject(r.shape)}return a},n.toObject=function(r,a){a||(a={});var l={};return a.defaults&&(l.elemType=0,l.shape=null),r.elemType!=null&&r.hasOwnProperty("elemType")&&(l.elemType=r.elemType),r.shape!=null&&r.hasOwnProperty("shape")&&(l.shape=i.onnx.TensorShapeProto.toObject(r.shape,a)),l},n.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},n}(),t}(),h.OperatorSetIdProto=function(){function t(e){if(e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.domain=e.string();break;case 2:a.version=e.int64();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.domain!=null&&e.hasOwnProperty("domain")&&!s.isString(e.domain)?"domain: string expected":e.version!=null&&e.hasOwnProperty("version")&&!(s.isInteger(e.version)||e.version&&s.isInteger(e.version.low)&&s.isInteger(e.version.high))?"version: integer|Long expected":null},t.fromObject=function(e){if(e instanceof i.onnx.OperatorSetIdProto)return e;var n=new i.onnx.OperatorSetIdProto;return e.domain!=null&&(n.domain=String(e.domain)),e.version!=null&&(s.Long?(n.version=s.Long.fromValue(e.version)).unsigned=!1:typeof e.version=="string"?n.version=parseInt(e.version,10):typeof e.version=="number"?n.version=e.version:typeof e.version=="object"&&(n.version=new s.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),n},t.toObject=function(e,n){n||(n={});var r={};if(n.defaults)if(r.domain="",s.Long){var a=new s.Long(0,0,!1);r.version=n.longs===String?a.toString():n.longs===Number?a.toNumber():a}else r.version=n.longs===String?"0":0;return e.domain!=null&&e.hasOwnProperty("domain")&&(r.domain=e.domain),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?r.version=n.longs===String?String(e.version):e.version:r.version=n.longs===String?s.Long.prototype.toString.call(e.version):n.longs===Number?new s.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),r},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t}(),h),D.exports=i},2100:(D,u,b)=>{D.exports=b(9482)},9482:(D,u,b)=>{var g=u;function p(){g.util._configure(),g.Writer._configure(g.BufferWriter),g.Reader._configure(g.BufferReader)}g.build="minimal",g.Writer=b(1173),g.BufferWriter=b(3155),g.Reader=b(1408),g.BufferReader=b(593),g.util=b(9693),g.rpc=b(5994),g.roots=b(5054),g.configure=p,p()},1408:(D,u,b)=>{D.exports=f;var g,p=b(9693),h=p.LongBits,o=p.utf8;function c(a,l){return RangeError("index out of range: "+a.pos+" + "+(l||1)+" > "+a.len)}function f(a){this.buf=a,this.pos=0,this.len=a.length}var s,i=typeof Uint8Array<"u"?function(a){if(a instanceof Uint8Array||Array.isArray(a))return new f(a);throw Error("illegal buffer")}:function(a){if(Array.isArray(a))return new f(a);throw Error("illegal buffer")},t=function(){return p.Buffer?function(a){return(f.create=function(l){return p.Buffer.isBuffer(l)?new g(l):i(l)})(a)}:i};function e(){var a=new h(0,0),l=0;if(!(this.len-this.pos>4)){for(;l<3;++l){if(this.pos>=this.len)throw c(this);if(a.lo=(a.lo|(127&this.buf[this.pos])<<7*l)>>>0,this.buf[this.pos++]<128)return a}return a.lo=(a.lo|(127&this.buf[this.pos++])<<7*l)>>>0,a}for(;l<4;++l)if(a.lo=(a.lo|(127&this.buf[this.pos])<<7*l)>>>0,this.buf[this.pos++]<128)return a;if(a.lo=(a.lo|(127&this.buf[this.pos])<<28)>>>0,a.hi=(a.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return a;if(l=0,this.len-this.pos>4){for(;l<5;++l)if(a.hi=(a.hi|(127&this.buf[this.pos])<<7*l+3)>>>0,this.buf[this.pos++]<128)return a}else for(;l<5;++l){if(this.pos>=this.len)throw c(this);if(a.hi=(a.hi|(127&this.buf[this.pos])<<7*l+3)>>>0,this.buf[this.pos++]<128)return a}throw Error("invalid varint encoding")}function n(a,l){return(a[l-4]|a[l-3]<<8|a[l-2]<<16|a[l-1]<<24)>>>0}function r(){if(this.pos+8>this.len)throw c(this,8);return new h(n(this.buf,this.pos+=4),n(this.buf,this.pos+=4))}f.create=t(),f.prototype._slice=p.Array.prototype.subarray||p.Array.prototype.slice,f.prototype.uint32=(s=4294967295,function(){if(s=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(s=(s|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(s=(s|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(s=(s|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(s=(s|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return s;if((this.pos+=5)>this.len)throw this.pos=this.len,c(this,10);return s}),f.prototype.int32=function(){return 0|this.uint32()},f.prototype.sint32=function(){var a=this.uint32();return a>>>1^-(1&a)|0},f.prototype.bool=function(){return this.uint32()!==0},f.prototype.fixed32=function(){if(this.pos+4>this.len)throw c(this,4);return n(this.buf,this.pos+=4)},f.prototype.sfixed32=function(){if(this.pos+4>this.len)throw c(this,4);return 0|n(this.buf,this.pos+=4)},f.prototype.float=function(){if(this.pos+4>this.len)throw c(this,4);var a=p.float.readFloatLE(this.buf,this.pos);return this.pos+=4,a},f.prototype.double=function(){if(this.pos+8>this.len)throw c(this,4);var a=p.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,a},f.prototype.bytes=function(){var a=this.uint32(),l=this.pos,d=this.pos+a;if(d>this.len)throw c(this,a);return this.pos+=a,Array.isArray(this.buf)?this.buf.slice(l,d):l===d?new this.buf.constructor(0):this._slice.call(this.buf,l,d)},f.prototype.string=function(){var a=this.bytes();return o.read(a,0,a.length)},f.prototype.skip=function(a){if(typeof a=="number"){if(this.pos+a>this.len)throw c(this,a);this.pos+=a}else do if(this.pos>=this.len)throw c(this);while(128&this.buf[this.pos++]);return this},f.prototype.skipType=function(a){switch(a){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(a=7&this.uint32())!=4;)this.skipType(a);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+a+" at offset "+this.pos)}return this},f._configure=function(a){g=a,f.create=t(),g._configure();var l=p.Long?"toLong":"toNumber";p.merge(f.prototype,{int64:function(){return e.call(this)[l](!1)},uint64:function(){return e.call(this)[l](!0)},sint64:function(){return e.call(this).zzDecode()[l](!1)},fixed64:function(){return r.call(this)[l](!0)},sfixed64:function(){return r.call(this)[l](!1)}})}},593:(D,u,b)=>{D.exports=h;var g=b(1408);(h.prototype=Object.create(g.prototype)).constructor=h;var p=b(9693);function h(o){g.call(this,o)}h._configure=function(){p.Buffer&&(h.prototype._slice=p.Buffer.prototype.slice)},h.prototype.string=function(){var o=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+o,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+o,this.len))},h._configure()},5054:D=>{D.exports={}},5994:(D,u,b)=>{u.Service=b(7948)},7948:(D,u,b)=>{D.exports=p;var g=b(9693);function p(h,o,c){if(typeof h!="function")throw TypeError("rpcImpl must be a function");g.EventEmitter.call(this),this.rpcImpl=h,this.requestDelimited=!!o,this.responseDelimited=!!c}(p.prototype=Object.create(g.EventEmitter.prototype)).constructor=p,p.prototype.rpcCall=function h(o,c,f,s,i){if(!s)throw TypeError("request must be specified");var t=this;if(!i)return g.asPromise(h,t,o,c,f,s);if(t.rpcImpl)try{return t.rpcImpl(o,c[t.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(e,n){if(e)return t.emit("error",e,o),i(e);if(n!==null){if(!(n instanceof f))try{n=f[t.responseDelimited?"decodeDelimited":"decode"](n)}catch(r){return t.emit("error",r,o),i(r)}return t.emit("data",n,o),i(null,n)}t.end(!0)})}catch(e){return t.emit("error",e,o),void setTimeout(function(){i(e)},0)}else setTimeout(function(){i(Error("already ended"))},0)},p.prototype.end=function(h){return this.rpcImpl&&(h||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(D,u,b)=>{D.exports=p;var g=b(9693);function p(f,s){this.lo=f>>>0,this.hi=s>>>0}var h=p.zero=new p(0,0);h.toNumber=function(){return 0},h.zzEncode=h.zzDecode=function(){return this},h.length=function(){return 1};var o=p.zeroHash="\0\0\0\0\0\0\0\0";p.fromNumber=function(f){if(f===0)return h;var s=f<0;s&&(f=-f);var i=f>>>0,t=(f-i)/4294967296>>>0;return s&&(t=~t>>>0,i=~i>>>0,++i>4294967295&&(i=0,++t>4294967295&&(t=0))),new p(i,t)},p.from=function(f){if(typeof f=="number")return p.fromNumber(f);if(g.isString(f)){if(!g.Long)return p.fromNumber(parseInt(f,10));f=g.Long.fromString(f)}return f.low||f.high?new p(f.low>>>0,f.high>>>0):h},p.prototype.toNumber=function(f){if(!f&&this.hi>>>31){var s=1+~this.lo>>>0,i=~this.hi>>>0;return s||(i=i+1>>>0),-(s+4294967296*i)}return this.lo+4294967296*this.hi},p.prototype.toLong=function(f){return g.Long?new g.Long(0|this.lo,0|this.hi,!!f):{low:0|this.lo,high:0|this.hi,unsigned:!!f}};var c=String.prototype.charCodeAt;p.fromHash=function(f){return f===o?h:new p((c.call(f,0)|c.call(f,1)<<8|c.call(f,2)<<16|c.call(f,3)<<24)>>>0,(c.call(f,4)|c.call(f,5)<<8|c.call(f,6)<<16|c.call(f,7)<<24)>>>0)},p.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},p.prototype.zzEncode=function(){var f=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^f)>>>0,this.lo=(this.lo<<1^f)>>>0,this},p.prototype.zzDecode=function(){var f=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^f)>>>0,this.hi=(this.hi>>>1^f)>>>0,this},p.prototype.length=function(){var f=this.lo,s=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return i===0?s===0?f<16384?f<128?1:2:f<2097152?3:4:s<16384?s<128?5:6:s<2097152?7:8:i<128?9:10}},9693:function(D,u,b){var g=u;function p(o,c,f){for(var s=Object.keys(c),i=0;i0)},g.Buffer=function(){try{var o=g.inquire("buffer").Buffer;return o.prototype.utf8Write?o:null}catch{return null}}(),g._Buffer_from=null,g._Buffer_allocUnsafe=null,g.newBuffer=function(o){return typeof o=="number"?g.Buffer?g._Buffer_allocUnsafe(o):new g.Array(o):g.Buffer?g._Buffer_from(o):typeof Uint8Array>"u"?o:new Uint8Array(o)},g.Array=typeof Uint8Array<"u"?Uint8Array:Array,g.Long=g.global.dcodeIO&&g.global.dcodeIO.Long||g.global.Long||g.inquire("long"),g.key2Re=/^true|false|0|1$/,g.key32Re=/^-?(?:0|[1-9][0-9]*)$/,g.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,g.longToHash=function(o){return o?g.LongBits.from(o).toHash():g.LongBits.zeroHash},g.longFromHash=function(o,c){var f=g.LongBits.fromHash(o);return g.Long?g.Long.fromBits(f.lo,f.hi,c):f.toNumber(!!c)},g.merge=p,g.lcFirst=function(o){return o.charAt(0).toLowerCase()+o.substring(1)},g.newError=h,g.ProtocolError=h("ProtocolError"),g.oneOfGetter=function(o){for(var c={},f=0;f-1;--i)if(c[s[i]]===1&&this[s[i]]!==void 0&&this[s[i]]!==null)return s[i]}},g.oneOfSetter=function(o){return function(c){for(var f=0;f{D.exports=t;var g,p=b(9693),h=p.LongBits,o=p.base64,c=p.utf8;function f(m,y,v){this.fn=m,this.len=y,this.next=void 0,this.val=v}function s(){}function i(m){this.head=m.head,this.tail=m.tail,this.len=m.len,this.next=m.states}function t(){this.len=0,this.head=new f(s,0,0),this.tail=this.head,this.states=null}var e=function(){return p.Buffer?function(){return(t.create=function(){return new g})()}:function(){return new t}};function n(m,y,v){y[v]=255&m}function r(m,y){this.len=m,this.next=void 0,this.val=y}function a(m,y,v){for(;m.hi;)y[v++]=127&m.lo|128,m.lo=(m.lo>>>7|m.hi<<25)>>>0,m.hi>>>=7;for(;m.lo>127;)y[v++]=127&m.lo|128,m.lo=m.lo>>>7;y[v++]=m.lo}function l(m,y,v){y[v]=255&m,y[v+1]=m>>>8&255,y[v+2]=m>>>16&255,y[v+3]=m>>>24}t.create=e(),t.alloc=function(m){return new p.Array(m)},p.Array!==Array&&(t.alloc=p.pool(t.alloc,p.Array.prototype.subarray)),t.prototype._push=function(m,y,v){return this.tail=this.tail.next=new f(m,y,v),this.len+=y,this},r.prototype=Object.create(f.prototype),r.prototype.fn=function(m,y,v){for(;m>127;)y[v++]=127&m|128,m>>>=7;y[v]=m},t.prototype.uint32=function(m){return this.len+=(this.tail=this.tail.next=new r((m>>>=0)<128?1:m<16384?2:m<2097152?3:m<268435456?4:5,m)).len,this},t.prototype.int32=function(m){return m<0?this._push(a,10,h.fromNumber(m)):this.uint32(m)},t.prototype.sint32=function(m){return this.uint32((m<<1^m>>31)>>>0)},t.prototype.uint64=function(m){var y=h.from(m);return this._push(a,y.length(),y)},t.prototype.int64=t.prototype.uint64,t.prototype.sint64=function(m){var y=h.from(m).zzEncode();return this._push(a,y.length(),y)},t.prototype.bool=function(m){return this._push(n,1,m?1:0)},t.prototype.fixed32=function(m){return this._push(l,4,m>>>0)},t.prototype.sfixed32=t.prototype.fixed32,t.prototype.fixed64=function(m){var y=h.from(m);return this._push(l,4,y.lo)._push(l,4,y.hi)},t.prototype.sfixed64=t.prototype.fixed64,t.prototype.float=function(m){return this._push(p.float.writeFloatLE,4,m)},t.prototype.double=function(m){return this._push(p.float.writeDoubleLE,8,m)};var d=p.Array.prototype.set?function(m,y,v){y.set(m,v)}:function(m,y,v){for(var _=0;_>>0;if(!y)return this._push(n,1,0);if(p.isString(m)){var v=t.alloc(y=o.length(m));o.decode(m,v,0),m=v}return this.uint32(y)._push(d,y,m)},t.prototype.string=function(m){var y=c.length(m);return y?this.uint32(y)._push(c.write,y,m):this._push(n,1,0)},t.prototype.fork=function(){return this.states=new i(this),this.head=this.tail=new f(s,0,0),this.len=0,this},t.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new f(s,0,0),this.len=0),this},t.prototype.ldelim=function(){var m=this.head,y=this.tail,v=this.len;return this.reset().uint32(v),v&&(this.tail.next=m.next,this.tail=y,this.len+=v),this},t.prototype.finish=function(){for(var m=this.head.next,y=this.constructor.alloc(this.len),v=0;m;)m.fn(m.val,y,v),v+=m.len,m=m.next;return y},t._configure=function(m){g=m,t.create=e(),g._configure()}},3155:(D,u,b)=>{D.exports=h;var g=b(1173);(h.prototype=Object.create(g.prototype)).constructor=h;var p=b(9693);function h(){g.call(this)}function o(c,f,s){c.length<40?p.utf8.write(c,f,s):f.utf8Write?f.utf8Write(c,s):f.write(c,s)}h._configure=function(){h.alloc=p._Buffer_allocUnsafe,h.writeBytesBuffer=p.Buffer&&p.Buffer.prototype instanceof Uint8Array&&p.Buffer.prototype.set.name==="set"?function(c,f,s){f.set(c,s)}:function(c,f,s){if(c.copy)c.copy(f,s,0,c.length);else for(var i=0;i>>0;return this.uint32(f),f&&this._push(h.writeBytesBuffer,f,c),this},h.prototype.string=function(c){var f=p.Buffer.byteLength(c);return this.uint32(f),f&&this._push(o,f,c),this},h._configure()},7714:(D,u,b)=>{u.R=void 0;const g=b(6919),p=b(7448);u.R=new class{async init(){}async createSessionHandler(h,o){const c=new g.Session(o);return await c.loadModel(h),new p.OnnxjsSessionHandler(c)}}},4200:(D,u,b)=>{u.c8=u.rX=void 0;const g=b(1670),p=b(5381),h=b(2157),o=b(2306);u.rX=()=>{if((typeof g.env.wasm.initTimeout!="number"||g.env.wasm.initTimeout<0)&&(g.env.wasm.initTimeout=0),typeof g.env.wasm.simd!="boolean"&&(g.env.wasm.simd=!0),typeof g.env.wasm.proxy!="boolean"&&(g.env.wasm.proxy=!1),typeof g.env.wasm.numThreads!="number"||!Number.isInteger(g.env.wasm.numThreads)||g.env.wasm.numThreads<=0){const c=typeof navigator>"u"?(0,p.cpus)().length:navigator.hardwareConcurrency;g.env.wasm.numThreads=Math.min(4,Math.ceil((c||1)/2))}},u.c8=new class{async init(){(0,u.rX)(),await(0,h.initWasm)()}async createSessionHandler(c,f){const s=new o.OnnxruntimeWebAssemblySessionHandler;return await s.loadModel(c,f),Promise.resolve(s)}}},6018:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(o,c,f,s){s===void 0&&(s=f);var i=Object.getOwnPropertyDescriptor(c,f);i&&!("get"in i?!c.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return c[f]}}),Object.defineProperty(o,s,i)}:function(o,c,f,s){s===void 0&&(s=f),o[s]=c[f]}),p=this&&this.__exportStar||function(o,c){for(var f in o)f==="default"||Object.prototype.hasOwnProperty.call(c,f)||g(c,o,f)};Object.defineProperty(u,"__esModule",{value:!0}),p(b(1670),u);const h=b(1670);{const o=b(7714).R;(0,h.registerBackend)("webgl",o,-10)}{const o=b(4200).c8;(0,h.registerBackend)("cpu",o,10),(0,h.registerBackend)("wasm",o,10),(0,h.registerBackend)("xnnpack",o,9)}},246:(D,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createAttributeWithCacheKey=void 0;class b{constructor(p){Object.assign(this,p)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(p=>`${this[p]}`).join(";")),this._cacheKey}}u.createAttributeWithCacheKey=g=>new b(g)},7778:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Attribute=void 0;const g=b(1446),p=b(9395),h=b(9162),o=b(2517);var c=p.onnxruntime.experimental.fbs;class f{constructor(i){if(this._attributes=new Map,i!=null){for(const t of i)t instanceof g.onnx.AttributeProto?this._attributes.set(t.name,[f.getValue(t),f.getType(t)]):t instanceof c.Attribute&&this._attributes.set(t.name(),[f.getValue(t),f.getType(t)]);if(this._attributes.sizeh.Tensor.fromProto(n));if(i instanceof c.Attribute)return e.map(n=>h.Tensor.fromOrtTensor(n))}if(t===g.onnx.AttributeProto.AttributeType.STRING&&i instanceof g.onnx.AttributeProto){const n=e;return(0,o.decodeUtf8String)(n)}return t===g.onnx.AttributeProto.AttributeType.STRINGS&&i instanceof g.onnx.AttributeProto?e.map(o.decodeUtf8String):e}static getValueNoCheck(i){return i instanceof g.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(i):this.getValueNoCheckFromOrtFormat(i)}static getValueNoCheckFromOnnxFormat(i){switch(i.type){case g.onnx.AttributeProto.AttributeType.FLOAT:return i.f;case g.onnx.AttributeProto.AttributeType.INT:return i.i;case g.onnx.AttributeProto.AttributeType.STRING:return i.s;case g.onnx.AttributeProto.AttributeType.TENSOR:return i.t;case g.onnx.AttributeProto.AttributeType.GRAPH:return i.g;case g.onnx.AttributeProto.AttributeType.FLOATS:return i.floats;case g.onnx.AttributeProto.AttributeType.INTS:return i.ints;case g.onnx.AttributeProto.AttributeType.STRINGS:return i.strings;case g.onnx.AttributeProto.AttributeType.TENSORS:return i.tensors;case g.onnx.AttributeProto.AttributeType.GRAPHS:return i.graphs;default:throw new Error(`unsupported attribute type: ${g.onnx.AttributeProto.AttributeType[i.type]}`)}}static getValueNoCheckFromOrtFormat(i){switch(i.type()){case c.AttributeType.FLOAT:return i.f();case c.AttributeType.INT:return i.i();case c.AttributeType.STRING:return i.s();case c.AttributeType.TENSOR:return i.t();case c.AttributeType.GRAPH:return i.g();case c.AttributeType.FLOATS:return i.floatsArray();case c.AttributeType.INTS:{const t=[];for(let e=0;e{Object.defineProperty(u,"__esModule",{value:!0}),u.resolveBackend=u.backend=void 0;const g=b(5038),p=new Map;async function h(o){const c=u.backend;if(c[o]!==void 0&&function(f){const s=f;return"initialize"in s&&typeof s.initialize=="function"&&"createSessionHandler"in s&&typeof s.createSessionHandler=="function"&&"dispose"in s&&typeof s.dispose=="function"}(c[o])){const f=c[o];let s=f.initialize();if(typeof s=="object"&&"then"in s&&(s=await s),s)return p.set(o,f),f}}u.backend={webgl:new g.WebGLBackend},u.resolveBackend=async function o(c){if(!c)return o(["webgl"]);{const f=typeof c=="string"?[c]:c;for(const s of f){const i=p.get(s);if(i)return i;const t=await h(s);if(t)return t}}throw new Error("no available backend to use")}},5038:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.WebGLBackend=void 0;const g=b(1670),p=b(6231),h=b(6416),o=b(7305);u.WebGLBackend=class{get contextId(){return g.env.webgl.contextId}set contextId(c){g.env.webgl.contextId=c}get matmulMaxBatchSize(){return g.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(c){g.env.webgl.matmulMaxBatchSize=c}get textureCacheMode(){return g.env.webgl.textureCacheMode}set textureCacheMode(c){g.env.webgl.textureCacheMode=c}get pack(){return g.env.webgl.pack}set pack(c){g.env.webgl.pack=c}get async(){return g.env.webgl.async}set async(c){g.env.webgl.async=c}initialize(){try{return this.glContext=(0,o.createWebGLContext)(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),p.Logger.setWithEnv(g.env),p.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(c){return p.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${c}`),!1}}createSessionHandler(c){return new h.WebGLSessionHandler(this,c)}dispose(){this.glContext.dispose()}}},5107:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.CoordsGlslLib=void 0;const g=b(2517),p=b(8520),h=b(5060),o=b(7859),c=b(9390);class f extends p.GlslLib{constructor(i){super(i)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new p.GlslLibRoutine(` +`));var W,k=t.print||j,V=t.printErr||N;Object.assign(t,_),_=null,t.thisProgram&&(v=t.thisProgram),t.quit&&(T=t.quit),t.wasmBinary&&(W=t.wasmBinary);var J=t.noExitRuntime||!1;typeof WebAssembly!="object"&&pe("no native wasm support detected");var Y,te,ne,me,Pe,Oe,le,xe,_e=!1,Ne=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function He(x,A,P){var F=(A>>>=0)+P;for(P=A;x[P]&&!(P>=F);)++P;if(16(L=(240&L)==224?(15&L)<<12|z<<6|K:(7&L)<<18|z<<12|K<<6|63&x[A++])?F+=String.fromCharCode(L):(L-=65536,F+=String.fromCharCode(55296|L>>10,56320|1023&L))}}else F+=String.fromCharCode(L)}return F}function Ae(x,A){return(x>>>=0)?He(c(),x,A):""}function Ce(x,A,P,F){if(!(0>>=0;F=P+F-1;for(var z=0;z=K&&(K=65536+((1023&K)<<10)|1023&x.charCodeAt(++z)),127>=K){if(P>=F)break;A[P++>>>0]=K}else{if(2047>=K){if(P+1>=F)break;A[P++>>>0]=192|K>>6}else{if(65535>=K){if(P+2>=F)break;A[P++>>>0]=224|K>>12}else{if(P+3>=F)break;A[P++>>>0]=240|K>>18,A[P++>>>0]=128|K>>12&63}A[P++>>>0]=128|K>>6&63}A[P++>>>0]=128|63&K}}return A[P>>>0]=0,P-L}function Fe(x){for(var A=0,P=0;P=F?A++:2047>=F?A+=2:55296<=F&&57343>=F?(A+=4,++P):A+=3}return A}function Ee(x){ne=x,t.HEAP8=me=new Int8Array(x),t.HEAP16=new Int16Array(x),t.HEAP32=Oe=new Int32Array(x),t.HEAPU8=Pe=new Uint8Array(x),t.HEAPU16=new Uint16Array(x),t.HEAPU32=le=new Uint32Array(x),t.HEAPF32=new Float32Array(x),t.HEAPF64=xe=new Float64Array(x)}I&&(ne=t.buffer);var we=t.INITIAL_MEMORY||16777216;if(I)Y=t.wasmMemory,ne=t.buffer;else if(t.wasmMemory)Y=t.wasmMemory;else if(!((Y=new WebAssembly.Memory({initial:we/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw V("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Y&&(ne=Y.buffer),we=ne.byteLength,Ee(ne);var je,Ue=[],Be=[],We=[],Ke=[];function ze(){return J||!1}function Ve(){var x=t.preRun.shift();Ue.unshift(x)}var Se,Me=0,Ye=null;function pe(x){throw I?postMessage({cmd:"onAbort",arg:x}):t.onAbort&&t.onAbort(x),V(x="Aborted("+x+")"),_e=!0,x=new WebAssembly.RuntimeError(x+". Build with -sASSERTIONS for more info."),n(x),x}function ft(){return Se.startsWith("data:application/octet-stream;base64,")}function st(){var x=Se;try{if(x==Se&&W)return new Uint8Array(W);if(l)return l(x);throw"both async and sync fetching of the wasm failed"}catch(A){pe(A)}}Se="ort-wasm-threaded.wasm",ft()||(Se=B(Se));var At={};function Ze(x){this.name="ExitStatus",this.message="Program terminated with exit("+x+")",this.status=x}function ut(x){(x=re.Vb[x])||pe(),re.mc(x)}function ct(x){var A=re.Cc();if(!A)return 6;re.ac.push(A),re.Vb[x.Ub]=A,A.Ub=x.Ub;var P={cmd:"run",start_routine:x.Ic,arg:x.zc,pthread_ptr:x.Ub};return A.$b=()=>{P.time=performance.now(),A.postMessage(P,x.Nc)},A.loaded&&(A.$b(),delete A.$b),0}function Re(x){if(I)return Z(1,1,x);ze()||(re.oc(),t.onExit&&t.onExit(x),_e=!0),T(x,new Ze(x))}function nt(x,A){if(!A&&I)throw It(x),"unwind";ze()||I||(Gt(),tt(We),zt(0),kt[1].length&&Ct(1,10),kt[2].length&&Ct(2,10),re.oc()),Re(x)}var re={Yb:[],ac:[],qc:[],Vb:{},fc:function(){I&&re.Ec()},Pc:function(){},Ec:function(){re.receiveObjectTransfer=re.Gc,re.threadInitTLS=re.pc,re.setExitStatus=re.nc,J=!1},nc:function(){},oc:function(){for(var x of Object.values(re.Vb))re.mc(x);for(x of re.Yb)x.terminate();re.Yb=[]},mc:function(x){var A=x.Ub;delete re.Vb[A],re.Yb.push(x),re.ac.splice(re.ac.indexOf(x),1),x.Ub=0,Nt(A)},Gc:function(){},pc:function(){re.qc.forEach(x=>x())},Fc:function(x,A){x.onmessage=P=>{var F=(P=P.data).cmd;if(x.Ub&&(re.Bc=x.Ub),P.targetThread&&P.targetThread!=Dt()){var L=re.Vb[P.Qc];L?L.postMessage(P,P.transferList):V('Internal error! Worker sent a message "'+F+'" to target pthread '+P.targetThread+", but that thread no longer exists!")}else F==="processProxyingQueue"?C(P.queue):F==="spawnThread"?ct(P):F==="cleanupThread"?ut(P.thread):F==="killThread"?(P=P.thread,F=re.Vb[P],delete re.Vb[P],F.terminate(),Nt(P),re.ac.splice(re.ac.indexOf(F),1),F.Ub=0):F==="cancelThread"?re.Vb[P.thread].postMessage({cmd:"cancel"}):F==="loaded"?(x.loaded=!0,A&&A(x),x.$b&&(x.$b(),delete x.$b)):F==="print"?k("Thread "+P.threadId+": "+P.text):F==="printErr"?V("Thread "+P.threadId+": "+P.text):F==="alert"?alert("Thread "+P.threadId+": "+P.text):P.target==="setimmediate"?x.postMessage(P):F==="onAbort"?t.onAbort&&t.onAbort(P.arg):F&&V("worker sent an unknown command "+F);re.Bc=void 0},x.onerror=P=>{throw V("worker sent an error! "+P.filename+":"+P.lineno+": "+P.message),P},w&&(x.on("message",function(P){x.onmessage({data:P})}),x.on("error",function(P){x.onerror(P)}),x.on("detachedExit",function(){})),x.postMessage({cmd:"load",urlOrBlob:t.mainScriptUrlOrBlob||g,wasmMemory:Y,wasmModule:te})},yc:function(){var x=B("ort-wasm-threaded.worker.js");re.Yb.push(new Worker(x))},Cc:function(){return re.Yb.length==0&&(re.yc(),re.Fc(re.Yb[0])),re.Yb.pop()}};function tt(x){for(;0>2>>>0];x=f()[x+48>>2>>>0],Xt(A,A-x),ue(A)};var Je=[];function ye(x){var A=Je[x];return A||(x>=Je.length&&(Je.length=x+1),Je[x]=A=je.get(x)),A}t.invokeEntryPoint=function(x,A){x=ye(x)(A),ze()?re.nc(x):Yt(x)};var rt,dt,it=[],ae=0,ie=0;function oe(x){this.Zb=x,this.Sb=x-24,this.xc=function(A){s()[this.Sb+4>>2>>>0]=A},this.bc=function(){return s()[this.Sb+4>>2>>>0]},this.wc=function(A){s()[this.Sb+8>>2>>>0]=A},this.Dc=function(){return s()[this.Sb+8>>2>>>0]},this.rc=function(){f()[this.Sb>>2>>>0]=0},this.hc=function(A){A=A?1:0,o()[this.Sb+12>>0>>>0]=A},this.uc=function(){return o()[this.Sb+12>>0>>>0]!=0},this.ic=function(A){A=A?1:0,o()[this.Sb+13>>0>>>0]=A},this.kc=function(){return o()[this.Sb+13>>0>>>0]!=0},this.fc=function(A,P){this.cc(0),this.xc(A),this.wc(P),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(f(),this.Sb>>2,1)},this.Hc=function(){return Atomics.sub(f(),this.Sb>>2,1)===1},this.cc=function(A){s()[this.Sb+16>>2>>>0]=A},this.tc=function(){return s()[this.Sb+16>>2>>>0]},this.vc=function(){if(Kt(this.bc()))return s()[this.Zb>>2>>>0];var A=this.tc();return A!==0?A:this.Zb}}function pt(x){return Bt(new oe(x).Sb)}function ot(x,A,P,F){return I?Z(3,1,x,A,P,F):ht(x,A,P,F)}function ht(x,A,P,F){if(typeof SharedArrayBuffer>"u")return V("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var L=[];return I&&L.length===0?ot(x,A,P,F):(x={Ic:P,Ub:x,zc:F,Nc:L},I?(x.Oc="spawnThread",postMessage(x,L),0):ct(x))}function gt(x,A,P){return I?Z(4,1,x,A,P):0}function mt(x,A){if(I)return Z(5,1,x,A)}function bt(x,A){if(I)return Z(6,1,x,A)}function yt(x,A,P){if(I)return Z(7,1,x,A,P)}function _t(x,A,P){return I?Z(8,1,x,A,P):0}function vt(x,A){if(I)return Z(9,1,x,A)}function wt(x,A,P){if(I)return Z(10,1,x,A,P)}function xt(x,A,P,F){if(I)return Z(11,1,x,A,P,F)}function Tt(x,A,P,F){if(I)return Z(12,1,x,A,P,F)}function St(x,A,P,F){if(I)return Z(13,1,x,A,P,F)}function Ot(x){if(I)return Z(14,1,x)}function E(x,A){if(I)return Z(15,1,x,A)}function $(x,A,P){if(I)return Z(16,1,x,A,P)}function C(x){Atomics.store(f(),x>>2,1),Dt()&&Wt(x),Atomics.compareExchange(f(),x>>2,1,0)}function M(x){return s()[x>>>2]+4294967296*f()[x+4>>>2]}function U(x,A,P,F,L,z){return I?Z(17,1,x,A,P,F,L,z):-52}function H(x,A,P,F,L,z){if(I)return Z(18,1,x,A,P,F,L,z)}function X(x){var A=Fe(x)+1,P=Rt(A);return P&&Ce(x,o(),P,A),P}function Q(x,A,P){function F(he){return(he=he.toTimeString().match(/\(([A-Za-z ]+)\)$/))?he[1]:"GMT"}if(I)return Z(19,1,x,A,P);var L=new Date().getFullYear(),z=new Date(L,0,1),K=new Date(L,6,1);L=z.getTimezoneOffset();var ee=K.getTimezoneOffset(),de=Math.max(L,ee);f()[x>>2>>>0]=60*de,f()[A>>2>>>0]=+(L!=ee),x=F(z),A=F(K),x=X(x),A=X(A),ee>2>>>0]=x,s()[P+4>>2>>>0]=A):(s()[P>>2>>>0]=A,s()[P+4>>2>>>0]=x)}function Z(x,A){var P=arguments.length-2,F=arguments;return Et(()=>{for(var L=Mt(8*P),z=L>>3,K=0;K>>0]=ee}return Ht(x,P,L,A)})}t.executeNotifiedProxyingQueue=C,dt=w?()=>{var x=process.hrtime();return 1e3*x[0]+x[1]/1e6}:I?()=>performance.now()-t.__performance_now_clock_drift:()=>performance.now();var se,ve=[],ke={};function $e(){if(!se){var x,A={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",_:v||"./this.program"};for(x in ke)ke[x]===void 0?delete A[x]:A[x]=ke[x];var P=[];for(x in A)P.push(x+"="+A[x]);se=P}return se}function G(x,A){if(I)return Z(20,1,x,A);var P=0;return $e().forEach(function(F,L){var z=A+P;for(L=s()[x+4*L>>2>>>0]=z,z=0;z>0>>>0]=F.charCodeAt(z);o()[L>>0>>>0]=0,P+=F.length+1}),0}function ge(x,A){if(I)return Z(21,1,x,A);var P=$e();s()[x>>2>>>0]=P.length;var F=0;return P.forEach(function(L){F+=L.length+1}),s()[A>>2>>>0]=F,0}function Te(x){return I?Z(22,1,x):52}function Ge(x,A,P,F){return I?Z(23,1,x,A,P,F):52}function Qe(x,A,P,F,L){return I?Z(24,1,x,A,P,F,L):70}var kt=[null,[],[]];function Ct(x,A){var P=kt[x];A===0||A===10?((x===1?k:V)(He(P,0)),P.length=0):P.push(A)}function Lt(x,A,P,F){if(I)return Z(25,1,x,A,P,F);for(var L=0,z=0;z>2>>>0],ee=s()[A+4>>2>>>0];A+=8;for(var de=0;de>>0]);L+=ee}return s()[F>>2>>>0]=L,0}var Le=0;function Pt(x){return x%4==0&&(x%100!=0||x%400==0)}var jt=[31,29,31,30,31,30,31,31,30,31,30,31],Vt=[31,28,31,30,31,30,31,31,30,31,30,31];function Ut(x,A,P,F){function L(q,be,Ie){for(q=typeof q=="number"?q.toString():q||"";q.lengthlt?-1:0et-q.getDate())){q.setDate(q.getDate()+be);break}be-=et-q.getDate()+1,q.setDate(1),11>Ie?q.setMonth(Ie+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1))}return Ie=new Date(q.getFullYear()+1,0,4),be=ee(new Date(q.getFullYear(),0,4)),Ie=ee(Ie),0>=K(be,q)?0>=K(Ie,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}var he=f()[F+40>>2>>>0];for(var De in F={Lc:f()[F>>2>>>0],Kc:f()[F+4>>2>>>0],dc:f()[F+8>>2>>>0],jc:f()[F+12>>2>>>0],ec:f()[F+16>>2>>>0],Xb:f()[F+20>>2>>>0],Tb:f()[F+24>>2>>>0],Wb:f()[F+28>>2>>>0],Rc:f()[F+32>>2>>>0],Jc:f()[F+36>>2>>>0],Mc:he?Ae(he):""},P=Ae(P),he={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})P=P.replace(new RegExp(De,"g"),he[De]);var Xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),qe="January February March April May June July August September October November December".split(" ");for(De in he={"%a":function(q){return Xe[q.Tb].substring(0,3)},"%A":function(q){return Xe[q.Tb]},"%b":function(q){return qe[q.ec].substring(0,3)},"%B":function(q){return qe[q.ec]},"%C":function(q){return z((q.Xb+1900)/100|0,2)},"%d":function(q){return z(q.jc,2)},"%e":function(q){return L(q.jc,2," ")},"%g":function(q){return de(q).toString().substring(2)},"%G":function(q){return de(q)},"%H":function(q){return z(q.dc,2)},"%I":function(q){return(q=q.dc)==0?q=12:12q.dc?"AM":"PM"},"%S":function(q){return z(q.Lc,2)},"%t":function(){return" "},"%u":function(q){return q.Tb||7},"%U":function(q){return z(Math.floor((q.Wb+7-q.Tb)/7),2)},"%V":function(q){var be=Math.floor((q.Wb+7-(q.Tb+6)%7)/7);if(2>=(q.Tb+371-q.Wb-2)%7&&be++,be)be==53&&((Ie=(q.Tb+371-q.Wb)%7)==4||Ie==3&&Pt(q.Xb)||(be=1));else{be=52;var Ie=(q.Tb+7-q.Wb-1)%7;(Ie==4||Ie==5&&Pt(q.Xb%400-1))&&be++}return z(be,2)},"%w":function(q){return q.Tb},"%W":function(q){return z(Math.floor((q.Wb+7-(q.Tb+6)%7)/7),2)},"%y":function(q){return(q.Xb+1900).toString().substring(2)},"%Y":function(q){return q.Xb+1900},"%z":function(q){var be=0<=(q=q.Jc);return q=Math.abs(q)/60,(be?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":function(q){return q.Mc},"%%":function(){return"%"}},P=P.replace(/%%/g,"\0\0"),he)P.includes(De)&&(P=P.replace(new RegExp(De,"g"),he[De](F)));return De=function(q){var be=Array(Fe(q)+1);return Ce(q,be,0,be.length),be}(P=P.replace(/\0\0/g,"%")),De.length>A?0:(function(q,be){o().set(q,be>>>0)}(De,x),De.length-1)}re.fc();var ln=[null,Re,It,ot,gt,mt,bt,yt,_t,vt,wt,xt,Tt,St,Ot,E,$,U,H,Q,G,ge,Te,Ge,Qe,Lt],fn={b:function(x){return Rt(x+24)+24},n:function(x){return(x=new oe(x)).uc()||(x.hc(!0),ae--),x.ic(!1),it.push(x),x.sc(),x.vc()},ma:function(x){throw V("Unexpected exception thrown, this is not properly supported - aborting"),_e=!0,x},x:function(){fe(0);var x=it.pop();if(x.Hc()&&!x.kc()){var A=x.Dc();A&&ye(A)(x.Zb),pt(x.Zb)}ie=0},e:function(){var x=ie;if(!x)return Le=0;var A=new oe(x);A.cc(x);var P=A.bc();if(!P)return Le=0,x;for(var F=Array.prototype.slice.call(arguments),L=0;LC(F));else if(I)postMessage({targetThread:x,cmd:"processProxyingQueue",queue:F});else{if(!(x=re.Vb[x]))return;x.postMessage({cmd:"processProxyingQueue",queue:F})}return 1},Ea:function(){return-1},Pa:function(x,A){x=new Date(1e3*M(x)),f()[A>>2>>>0]=x.getUTCSeconds(),f()[A+4>>2>>>0]=x.getUTCMinutes(),f()[A+8>>2>>>0]=x.getUTCHours(),f()[A+12>>2>>>0]=x.getUTCDate(),f()[A+16>>2>>>0]=x.getUTCMonth(),f()[A+20>>2>>>0]=x.getUTCFullYear()-1900,f()[A+24>>2>>>0]=x.getUTCDay(),x=(x.getTime()-Date.UTC(x.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,f()[A+28>>2>>>0]=x},Qa:function(x,A){x=new Date(1e3*M(x)),f()[A>>2>>>0]=x.getSeconds(),f()[A+4>>2>>>0]=x.getMinutes(),f()[A+8>>2>>>0]=x.getHours(),f()[A+12>>2>>>0]=x.getDate(),f()[A+16>>2>>>0]=x.getMonth(),f()[A+20>>2>>>0]=x.getFullYear()-1900,f()[A+24>>2>>>0]=x.getDay();var P=new Date(x.getFullYear(),0,1),F=(x.getTime()-P.getTime())/864e5|0;f()[A+28>>2>>>0]=F,f()[A+36>>2>>>0]=-60*x.getTimezoneOffset(),F=new Date(x.getFullYear(),6,1).getTimezoneOffset(),x=0|(F!=(P=P.getTimezoneOffset())&&x.getTimezoneOffset()==Math.min(P,F)),f()[A+32>>2>>>0]=x},Ra:function(x){var A=new Date(f()[x+20>>2>>>0]+1900,f()[x+16>>2>>>0],f()[x+12>>2>>>0],f()[x+8>>2>>>0],f()[x+4>>2>>>0],f()[x>>2>>>0],0),P=f()[x+32>>2>>>0],F=A.getTimezoneOffset(),L=new Date(A.getFullYear(),0,1),z=new Date(A.getFullYear(),6,1).getTimezoneOffset(),K=L.getTimezoneOffset(),ee=Math.min(K,z);return 0>P?f()[x+32>>2>>>0]=+(z!=K&&ee==F):0>2>>>0]=A.getDay(),P=(A.getTime()-L.getTime())/864e5|0,f()[x+28>>2>>>0]=P,f()[x>>2>>>0]=A.getSeconds(),f()[x+4>>2>>>0]=A.getMinutes(),f()[x+8>>2>>>0]=A.getHours(),f()[x+12>>2>>>0]=A.getDate(),f()[x+16>>2>>>0]=A.getMonth(),A.getTime()/1e3|0},Aa:U,Ba:H,Sa:function x(A,P,F){x.Ac||(x.Ac=!0,Q(A,P,F))},y:function(){pe("")},U:function(){if(!w&&!O){var x="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";rt||(rt={}),rt[x]||(rt[x]=1,w&&(x="warning: "+x),V(x))}},ra:function(){return 4294901760},B:dt,Ia:function(x,A,P){c().copyWithin(x>>>0,A>>>0,A+P>>>0)},F:function(){return w?b(3993).cpus().length:navigator.hardwareConcurrency},Da:function(x,A,P){ve.length=A,P>>=3;for(var F=0;F>>0];return(0>x?At[-x-1]:ln[x]).apply(null,ve)},qa:function(x){var A=c().length;if((x>>>=0)<=A||4294901760=P;P*=2){var F=A*(1+.2/P);F=Math.min(F,x+100663296);var L=Math;F=Math.max(x,F),L=L.min.call(L,4294901760,F+(65536-F%65536)%65536);e:{try{Y.grow(L-ne.byteLength+65535>>>16),Ee(Y.buffer);var z=1;break e}catch{}z=void 0}if(z)return!0}return!1},Na:function(){throw"unwind"},Ga:G,Ha:ge,J:nt,I:Te,S:Ge,ga:Qe,R:Lt,d:function(){return Le},na:function x(A,P){x.lc||(x.lc=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var L=new Uint8Array(1);return()=>(crypto.getRandomValues(L),L[0])}if(w)try{var z=b(Object(function(){var K=new Error("Cannot find module 'crypto'");throw K.code="MODULE_NOT_FOUND",K}()));return()=>z.randomBytes(1)[0]}catch{}return()=>pe("randomDevice")}());for(var F=0;F>0>>>0]=x.lc();return 0},ia:function(x,A,P){var F=ce();try{return ye(x)(A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},ja:function(x,A,P){var F=ce();try{return ye(x)(A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},K:function(x){var A=ce();try{return ye(x)()}catch(P){if(ue(A),P!==P+0)throw P;fe(1,0)}},f:function(x,A){var P=ce();try{return ye(x)(A)}catch(F){if(ue(P),F!==F+0)throw F;fe(1,0)}},P:function(x,A,P){var F=ce();try{return ye(x)(A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},Q:function(x,A,P){var F=ce();try{return ye(x)(A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},k:function(x,A,P){var F=ce();try{return ye(x)(A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},p:function(x,A,P,F){var L=ce();try{return ye(x)(A,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},q:function(x,A,P,F,L){var z=ce();try{return ye(x)(A,P,F,L)}catch(K){if(ue(z),K!==K+0)throw K;fe(1,0)}},N:function(x,A,P,F,L,z){var K=ce();try{return ye(x)(A,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},s:function(x,A,P,F,L,z){var K=ce();try{return ye(x)(A,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},w:function(x,A,P,F,L,z,K){var ee=ce();try{return ye(x)(A,P,F,L,z,K)}catch(de){if(ue(ee),de!==de+0)throw de;fe(1,0)}},L:function(x,A,P,F,L,z,K,ee){var de=ce();try{return ye(x)(A,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},E:function(x,A,P,F,L,z,K,ee,de,he,De,Xe){var qe=ce();try{return ye(x)(A,P,F,L,z,K,ee,de,he,De,Xe)}catch(q){if(ue(qe),q!==q+0)throw q;fe(1,0)}},aa:function(x,A,P,F,L,z,K,ee){var de=ce();try{return an(x,A,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},_:function(x,A,P,F,L,z,K){var ee=ce();try{return Jt(x,A,P,F,L,z,K)}catch(de){if(ue(ee),de!==de+0)throw de;fe(1,0)}},Z:function(x,A,P,F,L){var z=ce();try{return sn(x,A,P,F,L)}catch(K){if(ue(z),K!==K+0)throw K;fe(1,0)}},ca:function(x,A,P,F){var L=ce();try{return rn(x,A,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},$:function(x){var A=ce();try{return Zt(x)}catch(P){if(ue(A),P!==P+0)throw P;fe(1,0)}},ba:function(x,A){var P=ce();try{return on(x,A)}catch(F){if(ue(P),F!==F+0)throw F;fe(1,0)}},Y:function(x,A,P){var F=ce();try{return Qt(x,A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},g:function(x){var A=ce();try{ye(x)()}catch(P){if(ue(A),P!==P+0)throw P;fe(1,0)}},r:function(x,A){var P=ce();try{ye(x)(A)}catch(F){if(ue(P),F!==F+0)throw F;fe(1,0)}},i:function(x,A,P){var F=ce();try{ye(x)(A,P)}catch(L){if(ue(F),L!==L+0)throw L;fe(1,0)}},ha:function(x,A,P,F){var L=ce();try{ye(x)(A,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},m:function(x,A,P,F){var L=ce();try{ye(x)(A,P,F)}catch(z){if(ue(L),z!==z+0)throw z;fe(1,0)}},v:function(x,A,P,F,L){var z=ce();try{ye(x)(A,P,F,L)}catch(K){if(ue(z),K!==K+0)throw K;fe(1,0)}},u:function(x,A,P,F,L,z){var K=ce();try{ye(x)(A,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},O:function(x,A,P,F,L,z,K){var ee=ce();try{ye(x)(A,P,F,L,z,K)}catch(de){if(ue(ee),de!==de+0)throw de;fe(1,0)}},A:function(x,A,P,F,L,z,K,ee){var de=ce();try{ye(x)(A,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},ka:function(x,A,P,F,L,z,K,ee,de){var he=ce();try{ye(x)(A,P,F,L,z,K,ee,de)}catch(De){if(ue(he),De!==De+0)throw De;fe(1,0)}},C:function(x,A,P,F,L,z,K,ee,de,he,De){var Xe=ce();try{ye(x)(A,P,F,L,z,K,ee,de,he,De)}catch(qe){if(ue(Xe),qe!==qe+0)throw qe;fe(1,0)}},D:function(x,A,P,F,L,z,K,ee,de,he,De,Xe,qe,q,be,Ie){var et=ce();try{ye(x)(A,P,F,L,z,K,ee,de,he,De,Xe,qe,q,be,Ie)}catch(lt){if(ue(et),lt!==lt+0)throw lt;fe(1,0)}},fa:function(x,A,P,F,L,z,K,ee){var de=ce();try{en(x,A,P,F,L,z,K,ee)}catch(he){if(ue(de),he!==he+0)throw he;fe(1,0)}},da:function(x,A,P,F,L,z,K,ee,de,he,De,Xe){var qe=ce();try{nn(x,A,P,F,L,z,K,ee,de,he,De,Xe)}catch(q){if(ue(qe),q!==q+0)throw q;fe(1,0)}},ea:function(x,A,P,F,L,z){var K=ce();try{tn(x,A,P,F,L,z)}catch(ee){if(ue(K),ee!==ee+0)throw ee;fe(1,0)}},o:function(x){return x},a:Y||t.wasmMemory,G:function(x){Le=x},la:Ut,z:function(x,A,P,F){return Ut(x,A,P,F)}};(function(){function x(L,z){t.asm=L.exports,re.qc.push(t.asm.sb),je=t.asm.ub,Be.unshift(t.asm.Va),te=z,I||(Me--,t.monitorRunDependencies&&t.monitorRunDependencies(Me),Me==0&&Ye&&(L=Ye,Ye=null,L()))}function A(L){x(L.instance,L.module)}function P(L){return function(){if(!W&&(S||O)){if(typeof fetch=="function"&&!Se.startsWith("file://"))return fetch(Se,{credentials:"same-origin"}).then(function(z){if(!z.ok)throw"failed to load wasm binary file at '"+Se+"'";return z.arrayBuffer()}).catch(function(){return st()});if(a)return new Promise(function(z,K){a(Se,function(ee){z(new Uint8Array(ee))},K)})}return Promise.resolve().then(function(){return st()})}().then(function(z){return WebAssembly.instantiate(z,F)}).then(function(z){return z}).then(L,function(z){V("failed to asynchronously prepare wasm: "+z),pe(z)})}var F={a:fn};if(I||(Me++,t.monitorRunDependencies&&t.monitorRunDependencies(Me)),t.instantiateWasm)try{return t.instantiateWasm(F,x)}catch(L){return V("Module.instantiateWasm callback failed with error: "+L),!1}(W||typeof WebAssembly.instantiateStreaming!="function"||ft()||Se.startsWith("file://")||w||typeof fetch!="function"?P(A):fetch(Se,{credentials:"same-origin"}).then(function(L){return WebAssembly.instantiateStreaming(L,F).then(A,function(z){return V("wasm streaming compile failed: "+z),V("falling back to ArrayBuffer instantiation"),P(A)})})).catch(n)})(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Va).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.Wa).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.Xa).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.Ya).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.Za).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm._a).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.$a).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.ab).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.bb).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.cb).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm.db).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.eb).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.fb).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.gb).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.hb).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.ib).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.jb).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.kb).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.lb).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.mb).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.nb).apply(null,arguments)};var Dt=t._pthread_self=function(){return(Dt=t._pthread_self=t.asm.ob).apply(null,arguments)},Rt=t._malloc=function(){return(Rt=t._malloc=t.asm.pb).apply(null,arguments)},Bt=t._free=function(){return(Bt=t._free=t.asm.qb).apply(null,arguments)},zt=t._fflush=function(){return(zt=t._fflush=t.asm.rb).apply(null,arguments)};t.__emscripten_tls_init=function(){return(t.__emscripten_tls_init=t.asm.sb).apply(null,arguments)};var Gt=t.___funcs_on_exit=function(){return(Gt=t.___funcs_on_exit=t.asm.tb).apply(null,arguments)},qt=t.__emscripten_thread_init=function(){return(qt=t.__emscripten_thread_init=t.asm.vb).apply(null,arguments)};t.__emscripten_thread_crashed=function(){return(t.__emscripten_thread_crashed=t.asm.wb).apply(null,arguments)};var $t,Ht=t._emscripten_run_in_main_runtime_thread_js=function(){return(Ht=t._emscripten_run_in_main_runtime_thread_js=t.asm.xb).apply(null,arguments)},Wt=t.__emscripten_proxy_execute_task_queue=function(){return(Wt=t.__emscripten_proxy_execute_task_queue=t.asm.yb).apply(null,arguments)},Nt=t.__emscripten_thread_free_data=function(){return(Nt=t.__emscripten_thread_free_data=t.asm.zb).apply(null,arguments)},Yt=t.__emscripten_thread_exit=function(){return(Yt=t.__emscripten_thread_exit=t.asm.Ab).apply(null,arguments)},fe=t._setThrew=function(){return(fe=t._setThrew=t.asm.Bb).apply(null,arguments)},Xt=t._emscripten_stack_set_limits=function(){return(Xt=t._emscripten_stack_set_limits=t.asm.Cb).apply(null,arguments)},ce=t.stackSave=function(){return(ce=t.stackSave=t.asm.Db).apply(null,arguments)},ue=t.stackRestore=function(){return(ue=t.stackRestore=t.asm.Eb).apply(null,arguments)},Mt=t.stackAlloc=function(){return(Mt=t.stackAlloc=t.asm.Fb).apply(null,arguments)},Ft=t.___cxa_can_catch=function(){return(Ft=t.___cxa_can_catch=t.asm.Gb).apply(null,arguments)},Kt=t.___cxa_is_pointer_type=function(){return(Kt=t.___cxa_is_pointer_type=t.asm.Hb).apply(null,arguments)},Zt=t.dynCall_j=function(){return(Zt=t.dynCall_j=t.asm.Ib).apply(null,arguments)},Jt=t.dynCall_iiiiij=function(){return(Jt=t.dynCall_iiiiij=t.asm.Jb).apply(null,arguments)},Qt=t.dynCall_jii=function(){return(Qt=t.dynCall_jii=t.asm.Kb).apply(null,arguments)},en=t.dynCall_viiiiij=function(){return(en=t.dynCall_viiiiij=t.asm.Lb).apply(null,arguments)},tn=t.dynCall_vjji=function(){return(tn=t.dynCall_vjji=t.asm.Mb).apply(null,arguments)},nn=t.dynCall_viiijjjii=function(){return(nn=t.dynCall_viiijjjii=t.asm.Nb).apply(null,arguments)},rn=t.dynCall_iij=function(){return(rn=t.dynCall_iij=t.asm.Ob).apply(null,arguments)},on=t.dynCall_ji=function(){return(on=t.dynCall_ji=t.asm.Pb).apply(null,arguments)},an=t.dynCall_iiiiiij=function(){return(an=t.dynCall_iiiiiij=t.asm.Qb).apply(null,arguments)},sn=t.dynCall_iiij=function(){return(sn=t.dynCall_iiij=t.asm.Rb).apply(null,arguments)};function un(){function x(){if(!$t&&($t=!0,t.calledRun=!0,!_e)&&(I||tt(Be),e(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),!I)){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;){var A=t.postRun.shift();Ke.unshift(A)}tt(Ke)}}if(!(0{var g,p=(g=(g=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(h){var o,c,f;h=h||{},o||(o=h!==void 0?h:{}),o.ready=new Promise(function(E,$){c=E,f=$});var s,i,t,e,n,r,a=Object.assign({},o),l="./this.program",d=(E,$)=>{throw $},m=typeof window=="object",y=typeof importScripts=="function",_=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",v="";_?(v=y?b(908).dirname(v)+"/":"//",r=()=>{n||(e=b(1384),n=b(908))},s=function(E,$){return r(),E=n.normalize(E),e.readFileSync(E,$?void 0:"utf8")},t=E=>((E=s(E,!0)).buffer||(E=new Uint8Array(E)),E),i=(E,$,C)=>{r(),E=n.normalize(E),e.readFile(E,function(M,U){M?C(M):$(U.buffer)})},1{if(w||0{var $=new XMLHttpRequest;return $.open("GET",E,!1),$.send(null),$.responseText},y&&(t=E=>{var $=new XMLHttpRequest;return $.open("GET",E,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),i=(E,$,C)=>{var M=new XMLHttpRequest;M.open("GET",E,!0),M.responseType="arraybuffer",M.onload=()=>{M.status==200||M.status==0&&M.response?$(M.response):C()},M.onerror=C,M.send(null)});var T,S=o.print||console.log.bind(console),O=o.printErr||console.warn.bind(console);Object.assign(o,a),a=null,o.thisProgram&&(l=o.thisProgram),o.quit&&(d=o.quit),o.wasmBinary&&(T=o.wasmBinary);var w=o.noExitRuntime||!1;typeof WebAssembly!="object"&&Ee("no native wasm support detected");var I,R,B,j,N,W,k=!1,V=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function J(E,$,C){var M=($>>>=0)+C;for(C=$;E[C]&&!(C>=M);)++C;if(16(U=(240&U)==224?(15&U)<<12|H<<6|X:(7&U)<<18|H<<12|X<<6|63&E[$++])?M+=String.fromCharCode(U):(U-=65536,M+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else M+=String.fromCharCode(U)}return M}function Y(E,$){return(E>>>=0)?J(j,E,$):""}function te(E,$,C,M){if(!(0>>=0;M=C+M-1;for(var H=0;H=X&&(X=65536+((1023&X)<<10)|1023&E.charCodeAt(++H)),127>=X){if(C>=M)break;$[C++>>>0]=X}else{if(2047>=X){if(C+1>=M)break;$[C++>>>0]=192|X>>6}else{if(65535>=X){if(C+2>=M)break;$[C++>>>0]=224|X>>12}else{if(C+3>=M)break;$[C++>>>0]=240|X>>18,$[C++>>>0]=128|X>>12&63}$[C++>>>0]=128|X>>6&63}$[C++>>>0]=128|63&X}}return $[C>>>0]=0,C-U}function ne(E){for(var $=0,C=0;C=M?$++:2047>=M?$+=2:55296<=M&&57343>=M?($+=4,++C):$+=3}return $}function me(){var E=I.buffer;R=E,o.HEAP8=B=new Int8Array(E),o.HEAP16=new Int16Array(E),o.HEAP32=N=new Int32Array(E),o.HEAPU8=j=new Uint8Array(E),o.HEAPU16=new Uint16Array(E),o.HEAPU32=W=new Uint32Array(E),o.HEAPF32=new Float32Array(E),o.HEAPF64=new Float64Array(E)}var Pe,Oe=[],le=[],xe=[],_e=[],Ne=0;function He(){var E=o.preRun.shift();Oe.unshift(E)}var Ae,Ce=0,Fe=null;function Ee(E){throw o.onAbort&&o.onAbort(E),O(E="Aborted("+E+")"),k=!0,E=new WebAssembly.RuntimeError(E+". Build with -sASSERTIONS for more info."),f(E),E}function we(){return Ae.startsWith("data:application/octet-stream;base64,")}if(Ae="ort-wasm.wasm",!we()){var je=Ae;Ae=o.locateFile?o.locateFile(je,v):v+je}function Ue(){var E=Ae;try{if(E==Ae&&T)return new Uint8Array(T);if(t)return t(E);throw"both async and sync fetching of the wasm failed"}catch($){Ee($)}}function Be(E){this.name="ExitStatus",this.message="Program terminated with exit("+E+")",this.status=E}function We(E){for(;0>2>>>0]=$},this.Eb=function(){return W[this.zb+4>>2>>>0]},this.Sb=function($){W[this.zb+8>>2>>>0]=$},this.Wb=function(){return W[this.zb+8>>2>>>0]},this.Tb=function(){N[this.zb>>2>>>0]=0},this.Ib=function($){B[this.zb+12>>0>>>0]=$?1:0},this.Pb=function(){return B[this.zb+12>>0>>>0]!=0},this.Jb=function($){B[this.zb+13>>0>>>0]=$?1:0},this.Lb=function(){return B[this.zb+13>>0>>>0]!=0},this.Rb=function($,C){this.Fb(0),this.Ub($),this.Sb(C),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){N[this.zb>>2>>>0]+=1},this.Xb=function(){var $=N[this.zb>>2>>>0];return N[this.zb>>2>>>0]=$-1,$===1},this.Fb=function($){W[this.zb+16>>2>>>0]=$},this.Ob=function(){return W[this.zb+16>>2>>>0]},this.Qb=function(){if(ht(this.Eb()))return W[this.Db>>2>>>0];var $=this.Ob();return $!==0?$:this.Db}}function Me(E){return rt(new Se(E).zb)}var Ye=[];function pe(E){var $=Ye[E];return $||(E>=Ye.length&&(Ye.length=E+1),Ye[E]=$=Pe.get(E)),$}function ft(E){var $=ne(E)+1,C=ye($);return C&&te(E,B,C,$),C}var st={};function At(){if(!Ze){var E,$={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",_:l||"./this.program"};for(E in st)st[E]===void 0?delete $[E]:$[E]=st[E];var C=[];for(E in $)C.push(E+"="+$[E]);Ze=C}return Ze}var Ze,ut=[null,[],[]];function ct(E,$){var C=ut[E];$===0||$===10?((E===1?S:O)(J(C,0)),C.length=0):C.push($)}var Re=0;function nt(E){return E%4==0&&(E%100!=0||E%400==0)}var re=[31,29,31,30,31,30,31,31,30,31,30,31],tt=[31,28,31,30,31,30,31,31,30,31,30,31];function Et(E,$,C,M){function U(G,ge,Te){for(G=typeof G=="number"?G.toString():G||"";G.lengthQe?-1:0Ge-G.getDate())){G.setDate(G.getDate()+ge);break}ge-=Ge-G.getDate()+1,G.setDate(1),11>Te?G.setMonth(Te+1):(G.setMonth(0),G.setFullYear(G.getFullYear()+1))}return Te=new Date(G.getFullYear()+1,0,4),ge=Q(new Date(G.getFullYear(),0,4)),Te=Q(Te),0>=X(ge,G)?0>=X(Te,G)?G.getFullYear()+1:G.getFullYear():G.getFullYear()-1}var se=N[M+40>>2>>>0];for(var ve in M={$b:N[M>>2>>>0],Zb:N[M+4>>2>>>0],Gb:N[M+8>>2>>>0],Kb:N[M+12>>2>>>0],Hb:N[M+16>>2>>>0],Cb:N[M+20>>2>>>0],Ab:N[M+24>>2>>>0],Bb:N[M+28>>2>>>0],bc:N[M+32>>2>>>0],Yb:N[M+36>>2>>>0],ac:se?Y(se):""},C=Y(C),se={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})C=C.replace(new RegExp(ve,"g"),se[ve]);var ke="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),$e="January February March April May June July August September October November December".split(" ");for(ve in se={"%a":function(G){return ke[G.Ab].substring(0,3)},"%A":function(G){return ke[G.Ab]},"%b":function(G){return $e[G.Hb].substring(0,3)},"%B":function(G){return $e[G.Hb]},"%C":function(G){return H((G.Cb+1900)/100|0,2)},"%d":function(G){return H(G.Kb,2)},"%e":function(G){return U(G.Kb,2," ")},"%g":function(G){return Z(G).toString().substring(2)},"%G":function(G){return Z(G)},"%H":function(G){return H(G.Gb,2)},"%I":function(G){return(G=G.Gb)==0?G=12:12G.Gb?"AM":"PM"},"%S":function(G){return H(G.$b,2)},"%t":function(){return" "},"%u":function(G){return G.Ab||7},"%U":function(G){return H(Math.floor((G.Bb+7-G.Ab)/7),2)},"%V":function(G){var ge=Math.floor((G.Bb+7-(G.Ab+6)%7)/7);if(2>=(G.Ab+371-G.Bb-2)%7&&ge++,ge)ge==53&&((Te=(G.Ab+371-G.Bb)%7)==4||Te==3&&nt(G.Cb)||(ge=1));else{ge=52;var Te=(G.Ab+7-G.Bb-1)%7;(Te==4||Te==5&&nt(G.Cb%400-1))&&ge++}return H(ge,2)},"%w":function(G){return G.Ab},"%W":function(G){return H(Math.floor((G.Bb+7-(G.Ab+6)%7)/7),2)},"%y":function(G){return(G.Cb+1900).toString().substring(2)},"%Y":function(G){return G.Cb+1900},"%z":function(G){var ge=0<=(G=G.Yb);return G=Math.abs(G)/60,(ge?"+":"-")+("0000"+(G/60*100+G%60)).slice(-4)},"%Z":function(G){return G.ac},"%%":function(){return"%"}},C=C.replace(/%%/g,"\0\0"),se)C.includes(ve)&&(C=C.replace(new RegExp(ve,"g"),se[ve](M)));return ve=function(G){var ge=Array(ne(G)+1);return te(G,ge,0,ge.length),ge}(C=C.replace(/\0\0/g,"%")),ve.length>$?0:(B.set(ve,E>>>0),ve.length-1)}var It={a:function(E){return ye(E+24)+24},m:function(E){return(E=new Se(E)).Pb()||(E.Ib(!0),ze--),E.Jb(!1),Ke.push(E),E.Nb(),E.Qb()},ia:function(E){throw O("Unexpected exception thrown, this is not properly supported - aborting"),k=!0,E},w:function(){ae(0);var E=Ke.pop();if(E.Xb()&&!E.Lb()){var $=E.Wb();$&&pe($)(E.Db),Me(E.Db)}Ve=0},d:function(){var E=Ve;if(!E)return Re=0;var $=new Se(E);$.Fb(E);var C=$.Eb();if(!C)return Re=0,E;for(var M=Array.prototype.slice.call(arguments),U=0;U>>2]+4294967296*N[E+4>>>2])),N[$>>2>>>0]=E.getUTCSeconds(),N[$+4>>2>>>0]=E.getUTCMinutes(),N[$+8>>2>>>0]=E.getUTCHours(),N[$+12>>2>>>0]=E.getUTCDate(),N[$+16>>2>>>0]=E.getUTCMonth(),N[$+20>>2>>>0]=E.getUTCFullYear()-1900,N[$+24>>2>>>0]=E.getUTCDay(),N[$+28>>2>>>0]=(E.getTime()-Date.UTC(E.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(E,$){E=new Date(1e3*(W[E>>>2]+4294967296*N[E+4>>>2])),N[$>>2>>>0]=E.getSeconds(),N[$+4>>2>>>0]=E.getMinutes(),N[$+8>>2>>>0]=E.getHours(),N[$+12>>2>>>0]=E.getDate(),N[$+16>>2>>>0]=E.getMonth(),N[$+20>>2>>>0]=E.getFullYear()-1900,N[$+24>>2>>>0]=E.getDay();var C=new Date(E.getFullYear(),0,1);N[$+28>>2>>>0]=(E.getTime()-C.getTime())/864e5|0,N[$+36>>2>>>0]=-60*E.getTimezoneOffset();var M=new Date(E.getFullYear(),6,1).getTimezoneOffset();C=C.getTimezoneOffset(),N[$+32>>2>>>0]=0|(M!=C&&E.getTimezoneOffset()==Math.min(C,M))},Fa:function(E){var $=new Date(N[E+20>>2>>>0]+1900,N[E+16>>2>>>0],N[E+12>>2>>>0],N[E+8>>2>>>0],N[E+4>>2>>>0],N[E>>2>>>0],0),C=N[E+32>>2>>>0],M=$.getTimezoneOffset(),U=new Date($.getFullYear(),0,1),H=new Date($.getFullYear(),6,1).getTimezoneOffset(),X=U.getTimezoneOffset(),Q=Math.min(X,H);return 0>C?N[E+32>>2>>>0]=+(H!=X&&Q==M):0>2>>>0]=$.getDay(),N[E+28>>2>>>0]=($.getTime()-U.getTime())/864e5|0,N[E>>2>>>0]=$.getSeconds(),N[E+4>>2>>>0]=$.getMinutes(),N[E+8>>2>>>0]=$.getHours(),N[E+12>>2>>>0]=$.getDate(),N[E+16>>2>>>0]=$.getMonth(),$.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function E($,C,M){E.Vb||(E.Vb=!0,function(U,H,X){function Q($e){return($e=$e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?$e[1]:"GMT"}var Z=new Date().getFullYear(),se=new Date(Z,0,1),ve=new Date(Z,6,1);Z=se.getTimezoneOffset();var ke=ve.getTimezoneOffset();N[U>>2>>>0]=60*Math.max(Z,ke),N[H>>2>>>0]=+(Z!=ke),U=Q(se),H=Q(ve),U=ft(U),H=ft(H),ke>2>>>0]=U,W[X+4>>2>>>0]=H):(W[X>>2>>>0]=H,W[X+4>>2>>>0]=U)}($,C,M))},B:function(){Ee("")},ma:function(){return 4294901760},I:_?()=>{var E=process.hrtime();return 1e3*E[0]+E[1]/1e6}:()=>performance.now(),xa:function(E,$,C){j.copyWithin(E>>>0,$>>>0,$+C>>>0)},G:function(E){var $=j.length;if(4294901760<(E>>>=0))return!1;for(var C=1;4>=C;C*=2){var M=$*(1+.2/C);M=Math.min(M,E+100663296);var U=Math;M=Math.max(E,M),U=U.min.call(U,4294901760,M+(65536-M%65536)%65536);e:{try{I.grow(U-R.byteLength+65535>>>16),me();var H=1;break e}catch{}H=void 0}if(H)return!0}return!1},va:function(E,$){var C=0;return At().forEach(function(M,U){var H=$+C;for(U=W[E+4*U>>2>>>0]=H,H=0;H>0>>>0]=M.charCodeAt(H);B[U>>0>>>0]=0,C+=M.length+1}),0},wa:function(E,$){var C=At();W[E>>2>>>0]=C.length;var M=0;return C.forEach(function(U){M+=U.length+1}),W[$>>2>>>0]=M,0},ba:function(E){w||0>2>>>0],Q=W[$+4>>2>>>0];$+=8;for(var Z=0;Z>>0]);U+=Q}return W[M>>2>>>0]=U,0},c:function(){return Re},ja:function E($,C){E.Mb||(E.Mb=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var U=new Uint8Array(1);return()=>(crypto.getRandomValues(U),U[0])}if(_)try{var H=b(Object(function(){var X=new Error("Cannot find module 'crypto'");throw X.code="MODULE_NOT_FOUND",X}()));return()=>H.randomBytes(1)[0]}catch{}return()=>Ee("randomDevice")}());for(var M=0;M>0>>>0]=E.Mb();return 0},ea:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},fa:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},J:function(E){var $=ie();try{return pe(E)()}catch(C){if(oe($),C!==C+0)throw C;ae(1,0)}},e:function(E,$){var C=ie();try{return pe(E)($)}catch(M){if(oe(C),M!==M+0)throw M;ae(1,0)}},N:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},O:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},j:function(E,$,C){var M=ie();try{return pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},o:function(E,$,C,M){var U=ie();try{return pe(E)($,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},p:function(E,$,C,M,U){var H=ie();try{return pe(E)($,C,M,U)}catch(X){if(oe(H),X!==X+0)throw X;ae(1,0)}},M:function(E,$,C,M,U,H){var X=ie();try{return pe(E)($,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},r:function(E,$,C,M,U,H){var X=ie();try{return pe(E)($,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},v:function(E,$,C,M,U,H,X){var Q=ie();try{return pe(E)($,C,M,U,H,X)}catch(Z){if(oe(Q),Z!==Z+0)throw Z;ae(1,0)}},K:function(E,$,C,M,U,H,X,Q){var Z=ie();try{return pe(E)($,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},D:function(E,$,C,M,U,H,X,Q,Z,se,ve,ke){var $e=ie();try{return pe(E)($,C,M,U,H,X,Q,Z,se,ve,ke)}catch(G){if(oe($e),G!==G+0)throw G;ae(1,0)}},X:function(E,$,C,M,U,H,X,Q){var Z=ie();try{return Tt(E,$,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},V:function(E,$,C,M,U,H,X){var Q=ie();try{return mt(E,$,C,M,U,H,X)}catch(Z){if(oe(Q),Z!==Z+0)throw Z;ae(1,0)}},U:function(E,$,C,M,U){var H=ie();try{return St(E,$,C,M,U)}catch(X){if(oe(H),X!==X+0)throw X;ae(1,0)}},Z:function(E,$,C,M){var U=ie();try{return wt(E,$,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},W:function(E){var $=ie();try{return gt(E)}catch(C){if(oe($),C!==C+0)throw C;ae(1,0)}},Y:function(E,$){var C=ie();try{return xt(E,$)}catch(M){if(oe(C),M!==M+0)throw M;ae(1,0)}},T:function(E,$,C){var M=ie();try{return bt(E,$,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},f:function(E){var $=ie();try{pe(E)()}catch(C){if(oe($),C!==C+0)throw C;ae(1,0)}},q:function(E,$){var C=ie();try{pe(E)($)}catch(M){if(oe(C),M!==M+0)throw M;ae(1,0)}},h:function(E,$,C){var M=ie();try{pe(E)($,C)}catch(U){if(oe(M),U!==U+0)throw U;ae(1,0)}},da:function(E,$,C,M){var U=ie();try{pe(E)($,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},l:function(E,$,C,M){var U=ie();try{pe(E)($,C,M)}catch(H){if(oe(U),H!==H+0)throw H;ae(1,0)}},t:function(E,$,C,M,U){var H=ie();try{pe(E)($,C,M,U)}catch(X){if(oe(H),X!==X+0)throw X;ae(1,0)}},u:function(E,$,C,M,U,H){var X=ie();try{pe(E)($,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},x:function(E,$,C,M,U,H,X){var Q=ie();try{pe(E)($,C,M,U,H,X)}catch(Z){if(oe(Q),Z!==Z+0)throw Z;ae(1,0)}},z:function(E,$,C,M,U,H,X,Q){var Z=ie();try{pe(E)($,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},ga:function(E,$,C,M,U,H,X,Q,Z){var se=ie();try{pe(E)($,C,M,U,H,X,Q,Z)}catch(ve){if(oe(se),ve!==ve+0)throw ve;ae(1,0)}},A:function(E,$,C,M,U,H,X,Q,Z,se,ve){var ke=ie();try{pe(E)($,C,M,U,H,X,Q,Z,se,ve)}catch($e){if(oe(ke),$e!==$e+0)throw $e;ae(1,0)}},C:function(E,$,C,M,U,H,X,Q,Z,se,ve,ke,$e,G,ge,Te){var Ge=ie();try{pe(E)($,C,M,U,H,X,Q,Z,se,ve,ke,$e,G,ge,Te)}catch(Qe){if(oe(Ge),Qe!==Qe+0)throw Qe;ae(1,0)}},aa:function(E,$,C,M,U,H,X,Q){var Z=ie();try{yt(E,$,C,M,U,H,X,Q)}catch(se){if(oe(Z),se!==se+0)throw se;ae(1,0)}},_:function(E,$,C,M,U,H,X,Q,Z,se,ve,ke){var $e=ie();try{vt(E,$,C,M,U,H,X,Q,Z,se,ve,ke)}catch(G){if(oe($e),G!==G+0)throw G;ae(1,0)}},$:function(E,$,C,M,U,H){var X=ie();try{_t(E,$,C,M,U,H)}catch(Q){if(oe(X),Q!==Q+0)throw Q;ae(1,0)}},n:function(E){return E},F:function(E){Re=E},ha:Et,y:function(E,$,C,M){return Et(E,$,C,M)}};(function(){function E(U){o.asm=U.exports,I=o.asm.Ka,me(),Pe=o.asm.ib,le.unshift(o.asm.La),Ce--,o.monitorRunDependencies&&o.monitorRunDependencies(Ce),Ce==0&&Fe&&(U=Fe,Fe=null,U())}function $(U){E(U.instance)}function C(U){return function(){if(!T&&(m||y)){if(typeof fetch=="function"&&!Ae.startsWith("file://"))return fetch(Ae,{credentials:"same-origin"}).then(function(H){if(!H.ok)throw"failed to load wasm binary file at '"+Ae+"'";return H.arrayBuffer()}).catch(function(){return Ue()});if(i)return new Promise(function(H,X){i(Ae,function(Q){H(new Uint8Array(Q))},X)})}return Promise.resolve().then(function(){return Ue()})}().then(function(H){return WebAssembly.instantiate(H,M)}).then(function(H){return H}).then(U,function(H){O("failed to asynchronously prepare wasm: "+H),Ee(H)})}var M={a:It};if(Ce++,o.monitorRunDependencies&&o.monitorRunDependencies(Ce),o.instantiateWasm)try{return o.instantiateWasm(M,E)}catch(U){return O("Module.instantiateWasm callback failed with error: "+U),!1}(T||typeof WebAssembly.instantiateStreaming!="function"||we()||Ae.startsWith("file://")||_||typeof fetch!="function"?C($):fetch(Ae,{credentials:"same-origin"}).then(function(U){return WebAssembly.instantiateStreaming(U,M).then($,function(H){return O("wasm streaming compile failed: "+H),O("falling back to ArrayBuffer instantiation"),C($)})})).catch(f)})(),o.___wasm_call_ctors=function(){return(o.___wasm_call_ctors=o.asm.La).apply(null,arguments)},o._OrtInit=function(){return(o._OrtInit=o.asm.Ma).apply(null,arguments)},o._OrtCreateSessionOptions=function(){return(o._OrtCreateSessionOptions=o.asm.Na).apply(null,arguments)},o._OrtAppendExecutionProvider=function(){return(o._OrtAppendExecutionProvider=o.asm.Oa).apply(null,arguments)},o._OrtAddSessionConfigEntry=function(){return(o._OrtAddSessionConfigEntry=o.asm.Pa).apply(null,arguments)},o._OrtReleaseSessionOptions=function(){return(o._OrtReleaseSessionOptions=o.asm.Qa).apply(null,arguments)},o._OrtCreateSession=function(){return(o._OrtCreateSession=o.asm.Ra).apply(null,arguments)},o._OrtReleaseSession=function(){return(o._OrtReleaseSession=o.asm.Sa).apply(null,arguments)},o._OrtGetInputCount=function(){return(o._OrtGetInputCount=o.asm.Ta).apply(null,arguments)},o._OrtGetOutputCount=function(){return(o._OrtGetOutputCount=o.asm.Ua).apply(null,arguments)},o._OrtGetInputName=function(){return(o._OrtGetInputName=o.asm.Va).apply(null,arguments)},o._OrtGetOutputName=function(){return(o._OrtGetOutputName=o.asm.Wa).apply(null,arguments)},o._OrtFree=function(){return(o._OrtFree=o.asm.Xa).apply(null,arguments)},o._OrtCreateTensor=function(){return(o._OrtCreateTensor=o.asm.Ya).apply(null,arguments)},o._OrtGetTensorData=function(){return(o._OrtGetTensorData=o.asm.Za).apply(null,arguments)},o._OrtReleaseTensor=function(){return(o._OrtReleaseTensor=o.asm._a).apply(null,arguments)},o._OrtCreateRunOptions=function(){return(o._OrtCreateRunOptions=o.asm.$a).apply(null,arguments)},o._OrtAddRunConfigEntry=function(){return(o._OrtAddRunConfigEntry=o.asm.ab).apply(null,arguments)},o._OrtReleaseRunOptions=function(){return(o._OrtReleaseRunOptions=o.asm.bb).apply(null,arguments)},o._OrtRun=function(){return(o._OrtRun=o.asm.cb).apply(null,arguments)},o._OrtEndProfiling=function(){return(o._OrtEndProfiling=o.asm.db).apply(null,arguments)};var Je,ye=o._malloc=function(){return(ye=o._malloc=o.asm.eb).apply(null,arguments)},rt=o._free=function(){return(rt=o._free=o.asm.fb).apply(null,arguments)},dt=o._fflush=function(){return(dt=o._fflush=o.asm.gb).apply(null,arguments)},it=o.___funcs_on_exit=function(){return(it=o.___funcs_on_exit=o.asm.hb).apply(null,arguments)},ae=o._setThrew=function(){return(ae=o._setThrew=o.asm.jb).apply(null,arguments)},ie=o.stackSave=function(){return(ie=o.stackSave=o.asm.kb).apply(null,arguments)},oe=o.stackRestore=function(){return(oe=o.stackRestore=o.asm.lb).apply(null,arguments)},pt=o.stackAlloc=function(){return(pt=o.stackAlloc=o.asm.mb).apply(null,arguments)},ot=o.___cxa_can_catch=function(){return(ot=o.___cxa_can_catch=o.asm.nb).apply(null,arguments)},ht=o.___cxa_is_pointer_type=function(){return(ht=o.___cxa_is_pointer_type=o.asm.ob).apply(null,arguments)},gt=o.dynCall_j=function(){return(gt=o.dynCall_j=o.asm.pb).apply(null,arguments)},mt=o.dynCall_iiiiij=function(){return(mt=o.dynCall_iiiiij=o.asm.qb).apply(null,arguments)},bt=o.dynCall_jii=function(){return(bt=o.dynCall_jii=o.asm.rb).apply(null,arguments)},yt=o.dynCall_viiiiij=function(){return(yt=o.dynCall_viiiiij=o.asm.sb).apply(null,arguments)},_t=o.dynCall_vjji=function(){return(_t=o.dynCall_vjji=o.asm.tb).apply(null,arguments)},vt=o.dynCall_viiijjjii=function(){return(vt=o.dynCall_viiijjjii=o.asm.ub).apply(null,arguments)},wt=o.dynCall_iij=function(){return(wt=o.dynCall_iij=o.asm.vb).apply(null,arguments)},xt=o.dynCall_ji=function(){return(xt=o.dynCall_ji=o.asm.wb).apply(null,arguments)},Tt=o.dynCall_iiiiiij=function(){return(Tt=o.dynCall_iiiiiij=o.asm.xb).apply(null,arguments)},St=o.dynCall_iiij=function(){return(St=o.dynCall_iiij=o.asm.yb).apply(null,arguments)};function Ot(){function E(){if(!Je&&(Je=!0,o.calledRun=!0,!k)){if(We(le),c(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;){var $=o.postRun.shift();_e.unshift($)}We(_e)}}if(!(0{D.exports=function(u,b){for(var g=new Array(arguments.length-1),p=0,h=2,o=!0;h{var b=u;b.length=function(c){var f=c.length;if(!f)return 0;for(var s=0;--f%4>1&&c.charAt(f)==="=";)++s;return Math.ceil(3*c.length)/4-s};for(var g=new Array(64),p=new Array(123),h=0;h<64;)p[g[h]=h<26?h+65:h<52?h+71:h<62?h-4:h-59|43]=h++;b.encode=function(c,f,s){for(var i,t=null,e=[],n=0,r=0;f>2],i=(3&a)<<4,r=1;break;case 1:e[n++]=g[i|a>>4],i=(15&a)<<2,r=2;break;case 2:e[n++]=g[i|a>>6],e[n++]=g[63&a],r=0}n>8191&&((t||(t=[])).push(String.fromCharCode.apply(String,e)),n=0)}return r&&(e[n++]=g[i],e[n++]=61,r===1&&(e[n++]=61)),t?(n&&t.push(String.fromCharCode.apply(String,e.slice(0,n))),t.join("")):String.fromCharCode.apply(String,e.slice(0,n))};var o="invalid encoding";b.decode=function(c,f,s){for(var i,t=s,e=0,n=0;n1)break;if((r=p[r])===void 0)throw Error(o);switch(e){case 0:i=r,e=1;break;case 1:f[s++]=i<<2|(48&r)>>4,i=r,e=2;break;case 2:f[s++]=(15&i)<<4|(60&r)>>2,i=r,e=3;break;case 3:f[s++]=(3&i)<<6|r,e=0}}if(e===1)throw Error(o);return s-t},b.test=function(c){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(c)}},9211:D=>{function u(){this._listeners={}}D.exports=u,u.prototype.on=function(b,g,p){return(this._listeners[b]||(this._listeners[b]=[])).push({fn:g,ctx:p||this}),this},u.prototype.off=function(b,g){if(b===void 0)this._listeners={};else if(g===void 0)this._listeners[b]=[];else for(var p=this._listeners[b],h=0;h{function u(o){return typeof Float32Array<"u"?function(){var c=new Float32Array([-0]),f=new Uint8Array(c.buffer),s=f[3]===128;function i(r,a,l){c[0]=r,a[l]=f[0],a[l+1]=f[1],a[l+2]=f[2],a[l+3]=f[3]}function t(r,a,l){c[0]=r,a[l]=f[3],a[l+1]=f[2],a[l+2]=f[1],a[l+3]=f[0]}function e(r,a){return f[0]=r[a],f[1]=r[a+1],f[2]=r[a+2],f[3]=r[a+3],c[0]}function n(r,a){return f[3]=r[a],f[2]=r[a+1],f[1]=r[a+2],f[0]=r[a+3],c[0]}o.writeFloatLE=s?i:t,o.writeFloatBE=s?t:i,o.readFloatLE=s?e:n,o.readFloatBE=s?n:e}():function(){function c(s,i,t,e){var n=i<0?1:0;if(n&&(i=-i),i===0)s(1/i>0?0:2147483648,t,e);else if(isNaN(i))s(2143289344,t,e);else if(i>34028234663852886e22)s((n<<31|2139095040)>>>0,t,e);else if(i<11754943508222875e-54)s((n<<31|Math.round(i/1401298464324817e-60))>>>0,t,e);else{var r=Math.floor(Math.log(i)/Math.LN2);s((n<<31|r+127<<23|8388607&Math.round(i*Math.pow(2,-r)*8388608))>>>0,t,e)}}function f(s,i,t){var e=s(i,t),n=2*(e>>31)+1,r=e>>>23&255,a=8388607&e;return r===255?a?NaN:n*(1/0):r===0?1401298464324817e-60*n*a:n*Math.pow(2,r-150)*(a+8388608)}o.writeFloatLE=c.bind(null,b),o.writeFloatBE=c.bind(null,g),o.readFloatLE=f.bind(null,p),o.readFloatBE=f.bind(null,h)}(),typeof Float64Array<"u"?function(){var c=new Float64Array([-0]),f=new Uint8Array(c.buffer),s=f[7]===128;function i(r,a,l){c[0]=r,a[l]=f[0],a[l+1]=f[1],a[l+2]=f[2],a[l+3]=f[3],a[l+4]=f[4],a[l+5]=f[5],a[l+6]=f[6],a[l+7]=f[7]}function t(r,a,l){c[0]=r,a[l]=f[7],a[l+1]=f[6],a[l+2]=f[5],a[l+3]=f[4],a[l+4]=f[3],a[l+5]=f[2],a[l+6]=f[1],a[l+7]=f[0]}function e(r,a){return f[0]=r[a],f[1]=r[a+1],f[2]=r[a+2],f[3]=r[a+3],f[4]=r[a+4],f[5]=r[a+5],f[6]=r[a+6],f[7]=r[a+7],c[0]}function n(r,a){return f[7]=r[a],f[6]=r[a+1],f[5]=r[a+2],f[4]=r[a+3],f[3]=r[a+4],f[2]=r[a+5],f[1]=r[a+6],f[0]=r[a+7],c[0]}o.writeDoubleLE=s?i:t,o.writeDoubleBE=s?t:i,o.readDoubleLE=s?e:n,o.readDoubleBE=s?n:e}():function(){function c(s,i,t,e,n,r){var a=e<0?1:0;if(a&&(e=-e),e===0)s(0,n,r+i),s(1/e>0?0:2147483648,n,r+t);else if(isNaN(e))s(0,n,r+i),s(2146959360,n,r+t);else if(e>17976931348623157e292)s(0,n,r+i),s((a<<31|2146435072)>>>0,n,r+t);else{var l;if(e<22250738585072014e-324)s((l=e/5e-324)>>>0,n,r+i),s((a<<31|l/4294967296)>>>0,n,r+t);else{var d=Math.floor(Math.log(e)/Math.LN2);d===1024&&(d=1023),s(4503599627370496*(l=e*Math.pow(2,-d))>>>0,n,r+i),s((a<<31|d+1023<<20|1048576*l&1048575)>>>0,n,r+t)}}}function f(s,i,t,e,n){var r=s(e,n+i),a=s(e,n+t),l=2*(a>>31)+1,d=a>>>20&2047,m=4294967296*(1048575&a)+r;return d===2047?m?NaN:l*(1/0):d===0?5e-324*l*m:l*Math.pow(2,d-1075)*(m+4503599627370496)}o.writeDoubleLE=c.bind(null,b,0,4),o.writeDoubleBE=c.bind(null,g,4,0),o.readDoubleLE=f.bind(null,p,0,4),o.readDoubleBE=f.bind(null,h,4,0)}(),o}function b(o,c,f){c[f]=255&o,c[f+1]=o>>>8&255,c[f+2]=o>>>16&255,c[f+3]=o>>>24}function g(o,c,f){c[f]=o>>>24,c[f+1]=o>>>16&255,c[f+2]=o>>>8&255,c[f+3]=255&o}function p(o,c){return(o[c]|o[c+1]<<8|o[c+2]<<16|o[c+3]<<24)>>>0}function h(o,c){return(o[c]<<24|o[c+1]<<16|o[c+2]<<8|o[c+3])>>>0}D.exports=u(u)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(D){}return null}module.exports=inquire},6662:D=>{D.exports=function(u,b,g){var p=g||8192,h=p>>>1,o=null,c=p;return function(f){if(f<1||f>h)return u(f);c+f>p&&(o=u(p),c=0);var s=b.call(o,c,c+=f);return 7&c&&(c=1+(7|c)),s}}},4997:(D,u)=>{var b=u;b.length=function(g){for(var p=0,h=0,o=0;o191&&o<224?f[s++]=(31&o)<<6|63&g[p++]:o>239&&o<365?(o=((7&o)<<18|(63&g[p++])<<12|(63&g[p++])<<6|63&g[p++])-65536,f[s++]=55296+(o>>10),f[s++]=56320+(1023&o)):f[s++]=(15&o)<<12|(63&g[p++])<<6|63&g[p++],s>8191&&((c||(c=[])).push(String.fromCharCode.apply(String,f)),s=0);return c?(s&&c.push(String.fromCharCode.apply(String,f.slice(0,s))),c.join("")):String.fromCharCode.apply(String,f.slice(0,s))},b.write=function(g,p,h){for(var o,c,f=h,s=0;s>6|192,p[h++]=63&o|128):(64512&o)==55296&&(64512&(c=g.charCodeAt(s+1)))==56320?(o=65536+((1023&o)<<10)+(1023&c),++s,p[h++]=o>>18|240,p[h++]=o>>12&63|128,p[h++]=o>>6&63|128,p[h++]=63&o|128):(p[h++]=o>>12|224,p[h++]=o>>6&63|128,p[h++]=63&o|128);return h-f}},3442:(D,u)=>{u.__esModule=!0;var b=function(){function g(p){if(!p)throw new TypeError("Invalid argument; `value` has no value.");this.value=g.EMPTY,p&&g.isGuid(p)&&(this.value=p)}return g.isGuid=function(p){var h=p.toString();return p&&(p instanceof g||g.validator.test(h))},g.create=function(){return new g([g.gen(2),g.gen(1),g.gen(1),g.gen(1),g.gen(3)].join("-"))},g.createEmpty=function(){return new g("emptyguid")},g.parse=function(p){return new g(p)},g.raw=function(){return[g.gen(2),g.gen(1),g.gen(1),g.gen(1),g.gen(3)].join("-")},g.gen=function(p){for(var h="",o=0;o{D.exports=b;var u=null;try{u=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function b(w,I,R){this.low=0|w,this.high=0|I,this.unsigned=!!R}function g(w){return(w&&w.__isLong__)===!0}b.prototype.__isLong__,Object.defineProperty(b.prototype,"__isLong__",{value:!0}),b.isLong=g;var p={},h={};function o(w,I){var R,B,j;return I?(j=0<=(w>>>=0)&&w<256)&&(B=h[w])?B:(R=f(w,(0|w)<0?-1:0,!0),j&&(h[w]=R),R):(j=-128<=(w|=0)&&w<128)&&(B=p[w])?B:(R=f(w,w<0?-1:0,!1),j&&(p[w]=R),R)}function c(w,I){if(isNaN(w))return I?d:l;if(I){if(w<0)return d;if(w>=n)return T}else{if(w<=-9223372036854776e3)return S;if(w+1>=r)return v}return w<0?c(-w,I).neg():f(w%e|0,w/e|0,I)}function f(w,I,R){return new b(w,I,R)}b.fromInt=o,b.fromNumber=c,b.fromBits=f;var s=Math.pow;function i(w,I,R){if(w.length===0)throw Error("empty string");if(w==="NaN"||w==="Infinity"||w==="+Infinity"||w==="-Infinity")return l;if(typeof I=="number"?(R=I,I=!1):I=!!I,(R=R||10)<2||360)throw Error("interior hyphen");if(B===0)return i(w.substring(1),I,R).neg();for(var j=c(s(R,8)),N=l,W=0;W>>0:this.low},O.toNumber=function(){return this.unsigned?(this.high>>>0)*e+(this.low>>>0):this.high*e+(this.low>>>0)},O.toString=function(w){if((w=w||10)<2||36>>0).toString(w);if((N=k).isZero())return V+W;for(;V.length<6;)V="0"+V;W=""+V+W}},O.getHighBits=function(){return this.high},O.getHighBitsUnsigned=function(){return this.high>>>0},O.getLowBits=function(){return this.low},O.getLowBitsUnsigned=function(){return this.low>>>0},O.getNumBitsAbs=function(){if(this.isNegative())return this.eq(S)?64:this.neg().getNumBitsAbs();for(var w=this.high!=0?this.high:this.low,I=31;I>0&&(w&1<=0},O.isOdd=function(){return(1&this.low)==1},O.isEven=function(){return(1&this.low)==0},O.equals=function(w){return g(w)||(w=t(w)),(this.unsigned===w.unsigned||this.high>>>31!=1||w.high>>>31!=1)&&this.high===w.high&&this.low===w.low},O.eq=O.equals,O.notEquals=function(w){return!this.eq(w)},O.neq=O.notEquals,O.ne=O.notEquals,O.lessThan=function(w){return this.comp(w)<0},O.lt=O.lessThan,O.lessThanOrEqual=function(w){return this.comp(w)<=0},O.lte=O.lessThanOrEqual,O.le=O.lessThanOrEqual,O.greaterThan=function(w){return this.comp(w)>0},O.gt=O.greaterThan,O.greaterThanOrEqual=function(w){return this.comp(w)>=0},O.gte=O.greaterThanOrEqual,O.ge=O.greaterThanOrEqual,O.compare=function(w){if(g(w)||(w=t(w)),this.eq(w))return 0;var I=this.isNegative(),R=w.isNegative();return I&&!R?-1:!I&&R?1:this.unsigned?w.high>>>0>this.high>>>0||w.high===this.high&&w.low>>>0>this.low>>>0?-1:1:this.sub(w).isNegative()?-1:1},O.comp=O.compare,O.negate=function(){return!this.unsigned&&this.eq(S)?S:this.not().add(m)},O.neg=O.negate,O.add=function(w){g(w)||(w=t(w));var I=this.high>>>16,R=65535&this.high,B=this.low>>>16,j=65535&this.low,N=w.high>>>16,W=65535&w.high,k=w.low>>>16,V=0,J=0,Y=0,te=0;return Y+=(te+=j+(65535&w.low))>>>16,J+=(Y+=B+k)>>>16,V+=(J+=R+W)>>>16,V+=I+N,f((Y&=65535)<<16|(te&=65535),(V&=65535)<<16|(J&=65535),this.unsigned)},O.subtract=function(w){return g(w)||(w=t(w)),this.add(w.neg())},O.sub=O.subtract,O.multiply=function(w){if(this.isZero())return l;if(g(w)||(w=t(w)),u)return f(u.mul(this.low,this.high,w.low,w.high),u.get_high(),this.unsigned);if(w.isZero())return l;if(this.eq(S))return w.isOdd()?S:l;if(w.eq(S))return this.isOdd()?S:l;if(this.isNegative())return w.isNegative()?this.neg().mul(w.neg()):this.neg().mul(w).neg();if(w.isNegative())return this.mul(w.neg()).neg();if(this.lt(a)&&w.lt(a))return c(this.toNumber()*w.toNumber(),this.unsigned);var I=this.high>>>16,R=65535&this.high,B=this.low>>>16,j=65535&this.low,N=w.high>>>16,W=65535&w.high,k=w.low>>>16,V=65535&w.low,J=0,Y=0,te=0,ne=0;return te+=(ne+=j*V)>>>16,Y+=(te+=B*V)>>>16,te&=65535,Y+=(te+=j*k)>>>16,J+=(Y+=R*V)>>>16,Y&=65535,J+=(Y+=B*k)>>>16,Y&=65535,J+=(Y+=j*W)>>>16,J+=I*V+R*k+B*W+j*N,f((te&=65535)<<16|(ne&=65535),(J&=65535)<<16|(Y&=65535),this.unsigned)},O.mul=O.multiply,O.divide=function(w){if(g(w)||(w=t(w)),w.isZero())throw Error("division by zero");var I,R,B;if(u)return this.unsigned||this.high!==-2147483648||w.low!==-1||w.high!==-1?f((this.unsigned?u.div_u:u.div_s)(this.low,this.high,w.low,w.high),u.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?d:l;if(this.unsigned){if(w.unsigned||(w=w.toUnsigned()),w.gt(this))return d;if(w.gt(this.shru(1)))return y;B=d}else{if(this.eq(S))return w.eq(m)||w.eq(_)?S:w.eq(S)?m:(I=this.shr(1).div(w).shl(1)).eq(l)?w.isNegative()?m:_:(R=this.sub(w.mul(I)),B=I.add(R.div(w)));if(w.eq(S))return this.unsigned?d:l;if(this.isNegative())return w.isNegative()?this.neg().div(w.neg()):this.neg().div(w).neg();if(w.isNegative())return this.div(w.neg()).neg();B=l}for(R=this;R.gte(w);){I=Math.max(1,Math.floor(R.toNumber()/w.toNumber()));for(var j=Math.ceil(Math.log(I)/Math.LN2),N=j<=48?1:s(2,j-48),W=c(I),k=W.mul(w);k.isNegative()||k.gt(R);)k=(W=c(I-=N,this.unsigned)).mul(w);W.isZero()&&(W=m),B=B.add(W),R=R.sub(k)}return B},O.div=O.divide,O.modulo=function(w){return g(w)||(w=t(w)),u?f((this.unsigned?u.rem_u:u.rem_s)(this.low,this.high,w.low,w.high),u.get_high(),this.unsigned):this.sub(this.div(w).mul(w))},O.mod=O.modulo,O.rem=O.modulo,O.not=function(){return f(~this.low,~this.high,this.unsigned)},O.and=function(w){return g(w)||(w=t(w)),f(this.low&w.low,this.high&w.high,this.unsigned)},O.or=function(w){return g(w)||(w=t(w)),f(this.low|w.low,this.high|w.high,this.unsigned)},O.xor=function(w){return g(w)||(w=t(w)),f(this.low^w.low,this.high^w.high,this.unsigned)},O.shiftLeft=function(w){return g(w)&&(w=w.toInt()),(w&=63)==0?this:w<32?f(this.low<>>32-w,this.unsigned):f(0,this.low<>>w|this.high<<32-w,this.high>>w,this.unsigned):f(this.high>>w-32,this.high>=0?0:-1,this.unsigned)},O.shr=O.shiftRight,O.shiftRightUnsigned=function(w){if(g(w)&&(w=w.toInt()),(w&=63)==0)return this;var I=this.high;return w<32?f(this.low>>>w|I<<32-w,I>>>w,this.unsigned):f(w===32?I:I>>>w-32,0,this.unsigned)},O.shru=O.shiftRightUnsigned,O.shr_u=O.shiftRightUnsigned,O.toSigned=function(){return this.unsigned?f(this.low,this.high,!1):this},O.toUnsigned=function(){return this.unsigned?this:f(this.low,this.high,!0)},O.toBytes=function(w){return w?this.toBytesLE():this.toBytesBE()},O.toBytesLE=function(){var w=this.high,I=this.low;return[255&I,I>>>8&255,I>>>16&255,I>>>24,255&w,w>>>8&255,w>>>16&255,w>>>24]},O.toBytesBE=function(){var w=this.high,I=this.low;return[w>>>24,w>>>16&255,w>>>8&255,255&w,I>>>24,I>>>16&255,I>>>8&255,255&I]},b.fromBytes=function(w,I,R){return R?b.fromBytesLE(w,I):b.fromBytesBE(w,I)},b.fromBytesLE=function(w,I){return new b(w[0]|w[1]<<8|w[2]<<16|w[3]<<24,w[4]|w[5]<<8|w[6]<<16|w[7]<<24,I)},b.fromBytesBE=function(w,I){return new b(w[4]<<24|w[5]<<16|w[6]<<8|w[7],w[0]<<24|w[1]<<16|w[2]<<8|w[3],I)}},1446:(D,u,b)=>{var g,p,h,o=b(2100),c=o.Reader,f=o.Writer,s=o.util,i=o.roots.default||(o.roots.default={});i.onnx=((h={}).Version=(g={},(p=Object.create(g))[g[0]="_START_VERSION"]=0,p[g[1]="IR_VERSION_2017_10_10"]=1,p[g[2]="IR_VERSION_2017_10_30"]=2,p[g[3]="IR_VERSION_2017_11_3"]=3,p[g[4]="IR_VERSION_2019_1_22"]=4,p[g[5]="IR_VERSION"]=5,p),h.AttributeProto=function(){function t(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.name=e.string();break;case 21:a.refAttrName=e.string();break;case 13:a.docString=e.string();break;case 20:a.type=e.int32();break;case 2:a.f=e.float();break;case 3:a.i=e.int64();break;case 4:a.s=e.bytes();break;case 5:a.t=i.onnx.TensorProto.decode(e,e.uint32());break;case 6:a.g=i.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(a.floats&&a.floats.length||(a.floats=[]),(7&l)==2)for(var d=e.uint32()+e.pos;e.pos>>0,e.i.high>>>0).toNumber())),e.s!=null&&(typeof e.s=="string"?s.base64.decode(e.s,n.s=s.newBuffer(s.base64.length(e.s)),0):e.s.length&&(n.s=e.s)),e.t!=null){if(typeof e.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");n.t=i.onnx.TensorProto.fromObject(e.t)}if(e.g!=null){if(typeof e.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");n.g=i.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");n.floats=[];for(var r=0;r>>0,e.ints[r].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(n.strings=[],r=0;r>>0,e.i.high>>>0).toNumber():e.i),e.s!=null&&e.hasOwnProperty("s")&&(r.s=n.bytes===String?s.base64.encode(e.s,0,e.s.length):n.bytes===Array?Array.prototype.slice.call(e.s):e.s),e.t!=null&&e.hasOwnProperty("t")&&(r.t=i.onnx.TensorProto.toObject(e.t,n)),e.g!=null&&e.hasOwnProperty("g")&&(r.g=i.onnx.GraphProto.toObject(e.g,n)),e.floats&&e.floats.length){r.floats=[];for(var l=0;l>>0,e.ints[l].high>>>0).toNumber():e.ints[l];if(e.strings&&e.strings.length)for(r.strings=[],l=0;l>>3){case 1:a.name=e.string();break;case 2:a.type=i.onnx.TypeProto.decode(e,e.uint32());break;case 3:a.docString=e.string();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.name!=null&&e.hasOwnProperty("name")&&!s.isString(e.name))return"name: string expected";if(e.type!=null&&e.hasOwnProperty("type")){var n=i.onnx.TypeProto.verify(e.type);if(n)return"type."+n}return e.docString!=null&&e.hasOwnProperty("docString")&&!s.isString(e.docString)?"docString: string expected":null},t.fromObject=function(e){if(e instanceof i.onnx.ValueInfoProto)return e;var n=new i.onnx.ValueInfoProto;if(e.name!=null&&(n.name=String(e.name)),e.type!=null){if(typeof e.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");n.type=i.onnx.TypeProto.fromObject(e.type)}return e.docString!=null&&(n.docString=String(e.docString)),n},t.toObject=function(e,n){n||(n={});var r={};return n.defaults&&(r.name="",r.type=null,r.docString=""),e.name!=null&&e.hasOwnProperty("name")&&(r.name=e.name),e.type!=null&&e.hasOwnProperty("type")&&(r.type=i.onnx.TypeProto.toObject(e.type,n)),e.docString!=null&&e.hasOwnProperty("docString")&&(r.docString=e.docString),r},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t}(),h.NodeProto=function(){function t(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.input&&a.input.length||(a.input=[]),a.input.push(e.string());break;case 2:a.output&&a.output.length||(a.output=[]),a.output.push(e.string());break;case 3:a.name=e.string();break;case 4:a.opType=e.string();break;case 7:a.domain=e.string();break;case 5:a.attribute&&a.attribute.length||(a.attribute=[]),a.attribute.push(i.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:a.docString=e.string();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.input!=null&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var n=0;n>>3){case 1:a.irVersion=e.int64();break;case 8:a.opsetImport&&a.opsetImport.length||(a.opsetImport=[]),a.opsetImport.push(i.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:a.producerName=e.string();break;case 3:a.producerVersion=e.string();break;case 4:a.domain=e.string();break;case 5:a.modelVersion=e.int64();break;case 6:a.docString=e.string();break;case 7:a.graph=i.onnx.GraphProto.decode(e,e.uint32());break;case 14:a.metadataProps&&a.metadataProps.length||(a.metadataProps=[]),a.metadataProps.push(i.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.irVersion!=null&&e.hasOwnProperty("irVersion")&&!(s.isInteger(e.irVersion)||e.irVersion&&s.isInteger(e.irVersion.low)&&s.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(e.opsetImport!=null&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var n=0;n>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");n.opsetImport=[];for(var r=0;r>>0,e.modelVersion.high>>>0).toNumber())),e.docString!=null&&(n.docString=String(e.docString)),e.graph!=null){if(typeof e.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");n.graph=i.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(n.metadataProps=[],r=0;r>>0,e.irVersion.high>>>0).toNumber():e.irVersion),e.producerName!=null&&e.hasOwnProperty("producerName")&&(r.producerName=e.producerName),e.producerVersion!=null&&e.hasOwnProperty("producerVersion")&&(r.producerVersion=e.producerVersion),e.domain!=null&&e.hasOwnProperty("domain")&&(r.domain=e.domain),e.modelVersion!=null&&e.hasOwnProperty("modelVersion")&&(typeof e.modelVersion=="number"?r.modelVersion=n.longs===String?String(e.modelVersion):e.modelVersion:r.modelVersion=n.longs===String?s.Long.prototype.toString.call(e.modelVersion):n.longs===Number?new s.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),e.docString!=null&&e.hasOwnProperty("docString")&&(r.docString=e.docString),e.graph!=null&&e.hasOwnProperty("graph")&&(r.graph=i.onnx.GraphProto.toObject(e.graph,n)),e.opsetImport&&e.opsetImport.length){r.opsetImport=[];for(var l=0;l>>3){case 1:a.key=e.string();break;case 2:a.value=e.string();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.key!=null&&e.hasOwnProperty("key")&&!s.isString(e.key)?"key: string expected":e.value!=null&&e.hasOwnProperty("value")&&!s.isString(e.value)?"value: string expected":null},t.fromObject=function(e){if(e instanceof i.onnx.StringStringEntryProto)return e;var n=new i.onnx.StringStringEntryProto;return e.key!=null&&(n.key=String(e.key)),e.value!=null&&(n.value=String(e.value)),n},t.toObject=function(e,n){n||(n={});var r={};return n.defaults&&(r.key="",r.value=""),e.key!=null&&e.hasOwnProperty("key")&&(r.key=e.key),e.value!=null&&e.hasOwnProperty("value")&&(r.value=e.value),r},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t}(),h.TensorAnnotation=function(){function t(e){if(this.quantParameterTensorNames=[],e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.tensorName=e.string();break;case 2:a.quantParameterTensorNames&&a.quantParameterTensorNames.length||(a.quantParameterTensorNames=[]),a.quantParameterTensorNames.push(i.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.tensorName!=null&&e.hasOwnProperty("tensorName")&&!s.isString(e.tensorName))return"tensorName: string expected";if(e.quantParameterTensorNames!=null&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var n=0;n>>3){case 1:a.node&&a.node.length||(a.node=[]),a.node.push(i.onnx.NodeProto.decode(e,e.uint32()));break;case 2:a.name=e.string();break;case 5:a.initializer&&a.initializer.length||(a.initializer=[]),a.initializer.push(i.onnx.TensorProto.decode(e,e.uint32()));break;case 10:a.docString=e.string();break;case 11:a.input&&a.input.length||(a.input=[]),a.input.push(i.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:a.output&&a.output.length||(a.output=[]),a.output.push(i.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:a.valueInfo&&a.valueInfo.length||(a.valueInfo=[]),a.valueInfo.push(i.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:a.quantizationAnnotation&&a.quantizationAnnotation.length||(a.quantizationAnnotation=[]),a.quantizationAnnotation.push(i.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.node!=null&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var n=0;n>>3){case 1:if(a.dims&&a.dims.length||(a.dims=[]),(7&l)==2)for(var d=e.uint32()+e.pos;e.pos>>0,e.dims[r].high>>>0).toNumber())}if(e.dataType!=null&&(n.dataType=0|e.dataType),e.segment!=null){if(typeof e.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");n.segment=i.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(n.floatData=[],r=0;r>>0,e.int64Data[r].high>>>0).toNumber())}if(e.name!=null&&(n.name=String(e.name)),e.docString!=null&&(n.docString=String(e.docString)),e.rawData!=null&&(typeof e.rawData=="string"?s.base64.decode(e.rawData,n.rawData=s.newBuffer(s.base64.length(e.rawData)),0):e.rawData.length&&(n.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(n.externalData=[],r=0;r>>0,e.uint64Data[r].high>>>0).toNumber(!0))}return n},t.toObject=function(e,n){n||(n={});var r={};if((n.arrays||n.defaults)&&(r.dims=[],r.floatData=[],r.int32Data=[],r.stringData=[],r.int64Data=[],r.doubleData=[],r.uint64Data=[],r.externalData=[]),n.defaults&&(r.dataType=0,r.segment=null,r.name="",n.bytes===String?r.rawData="":(r.rawData=[],n.bytes!==Array&&(r.rawData=s.newBuffer(r.rawData))),r.docString="",r.dataLocation=n.enums===String?"DEFAULT":0),e.dims&&e.dims.length){r.dims=[];for(var a=0;a>>0,e.dims[a].high>>>0).toNumber():e.dims[a]}if(e.dataType!=null&&e.hasOwnProperty("dataType")&&(r.dataType=e.dataType),e.segment!=null&&e.hasOwnProperty("segment")&&(r.segment=i.onnx.TensorProto.Segment.toObject(e.segment,n)),e.floatData&&e.floatData.length)for(r.floatData=[],a=0;a>>0,e.int64Data[a].high>>>0).toNumber():e.int64Data[a];if(e.name!=null&&e.hasOwnProperty("name")&&(r.name=e.name),e.rawData!=null&&e.hasOwnProperty("rawData")&&(r.rawData=n.bytes===String?s.base64.encode(e.rawData,0,e.rawData.length):n.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(r.doubleData=[],a=0;a>>0,e.uint64Data[a].high>>>0).toNumber(!0):e.uint64Data[a];if(e.docString!=null&&e.hasOwnProperty("docString")&&(r.docString=e.docString),e.externalData&&e.externalData.length)for(r.externalData=[],a=0;a>>3){case 1:l.begin=n.int64();break;case 2:l.end=n.int64();break;default:n.skipType(7&d)}}return l},e.decodeDelimited=function(n){return n instanceof c||(n=new c(n)),this.decode(n,n.uint32())},e.verify=function(n){return typeof n!="object"||n===null?"object expected":n.begin!=null&&n.hasOwnProperty("begin")&&!(s.isInteger(n.begin)||n.begin&&s.isInteger(n.begin.low)&&s.isInteger(n.begin.high))?"begin: integer|Long expected":n.end!=null&&n.hasOwnProperty("end")&&!(s.isInteger(n.end)||n.end&&s.isInteger(n.end.low)&&s.isInteger(n.end.high))?"end: integer|Long expected":null},e.fromObject=function(n){if(n instanceof i.onnx.TensorProto.Segment)return n;var r=new i.onnx.TensorProto.Segment;return n.begin!=null&&(s.Long?(r.begin=s.Long.fromValue(n.begin)).unsigned=!1:typeof n.begin=="string"?r.begin=parseInt(n.begin,10):typeof n.begin=="number"?r.begin=n.begin:typeof n.begin=="object"&&(r.begin=new s.LongBits(n.begin.low>>>0,n.begin.high>>>0).toNumber())),n.end!=null&&(s.Long?(r.end=s.Long.fromValue(n.end)).unsigned=!1:typeof n.end=="string"?r.end=parseInt(n.end,10):typeof n.end=="number"?r.end=n.end:typeof n.end=="object"&&(r.end=new s.LongBits(n.end.low>>>0,n.end.high>>>0).toNumber())),r},e.toObject=function(n,r){r||(r={});var a={};if(r.defaults){if(s.Long){var l=new s.Long(0,0,!1);a.begin=r.longs===String?l.toString():r.longs===Number?l.toNumber():l}else a.begin=r.longs===String?"0":0;s.Long?(l=new s.Long(0,0,!1),a.end=r.longs===String?l.toString():r.longs===Number?l.toNumber():l):a.end=r.longs===String?"0":0}return n.begin!=null&&n.hasOwnProperty("begin")&&(typeof n.begin=="number"?a.begin=r.longs===String?String(n.begin):n.begin:a.begin=r.longs===String?s.Long.prototype.toString.call(n.begin):r.longs===Number?new s.LongBits(n.begin.low>>>0,n.begin.high>>>0).toNumber():n.begin),n.end!=null&&n.hasOwnProperty("end")&&(typeof n.end=="number"?a.end=r.longs===String?String(n.end):n.end:a.end=r.longs===String?s.Long.prototype.toString.call(n.end):r.longs===Number?new s.LongBits(n.end.low>>>0,n.end.high>>>0).toNumber():n.end),a},e.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},e}(),t.DataLocation=function(){var e={},n=Object.create(e);return n[e[0]="DEFAULT"]=0,n[e[1]="EXTERNAL"]=1,n}(),t}(),h.TensorShapeProto=function(){function t(e){if(this.dim=[],e)for(var n=Object.keys(e),r=0;r>>3==1?(a.dim&&a.dim.length||(a.dim=[]),a.dim.push(i.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&l)}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.dim!=null&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var n=0;n>>3){case 1:d.dimValue=r.int64();break;case 2:d.dimParam=r.string();break;case 3:d.denotation=r.string();break;default:r.skipType(7&m)}}return d},e.decodeDelimited=function(r){return r instanceof c||(r=new c(r)),this.decode(r,r.uint32())},e.verify=function(r){if(typeof r!="object"||r===null)return"object expected";var a={};if(r.dimValue!=null&&r.hasOwnProperty("dimValue")&&(a.value=1,!(s.isInteger(r.dimValue)||r.dimValue&&s.isInteger(r.dimValue.low)&&s.isInteger(r.dimValue.high))))return"dimValue: integer|Long expected";if(r.dimParam!=null&&r.hasOwnProperty("dimParam")){if(a.value===1)return"value: multiple values";if(a.value=1,!s.isString(r.dimParam))return"dimParam: string expected"}return r.denotation!=null&&r.hasOwnProperty("denotation")&&!s.isString(r.denotation)?"denotation: string expected":null},e.fromObject=function(r){if(r instanceof i.onnx.TensorShapeProto.Dimension)return r;var a=new i.onnx.TensorShapeProto.Dimension;return r.dimValue!=null&&(s.Long?(a.dimValue=s.Long.fromValue(r.dimValue)).unsigned=!1:typeof r.dimValue=="string"?a.dimValue=parseInt(r.dimValue,10):typeof r.dimValue=="number"?a.dimValue=r.dimValue:typeof r.dimValue=="object"&&(a.dimValue=new s.LongBits(r.dimValue.low>>>0,r.dimValue.high>>>0).toNumber())),r.dimParam!=null&&(a.dimParam=String(r.dimParam)),r.denotation!=null&&(a.denotation=String(r.denotation)),a},e.toObject=function(r,a){a||(a={});var l={};return a.defaults&&(l.denotation=""),r.dimValue!=null&&r.hasOwnProperty("dimValue")&&(typeof r.dimValue=="number"?l.dimValue=a.longs===String?String(r.dimValue):r.dimValue:l.dimValue=a.longs===String?s.Long.prototype.toString.call(r.dimValue):a.longs===Number?new s.LongBits(r.dimValue.low>>>0,r.dimValue.high>>>0).toNumber():r.dimValue,a.oneofs&&(l.value="dimValue")),r.dimParam!=null&&r.hasOwnProperty("dimParam")&&(l.dimParam=r.dimParam,a.oneofs&&(l.value="dimParam")),r.denotation!=null&&r.hasOwnProperty("denotation")&&(l.denotation=r.denotation),l},e.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},e}(),t}(),h.TypeProto=function(){function t(n){if(n)for(var r=Object.keys(n),a=0;a>>3){case 1:l.tensorType=i.onnx.TypeProto.Tensor.decode(n,n.uint32());break;case 6:l.denotation=n.string();break;default:n.skipType(7&d)}}return l},t.decodeDelimited=function(n){return n instanceof c||(n=new c(n)),this.decode(n,n.uint32())},t.verify=function(n){if(typeof n!="object"||n===null)return"object expected";if(n.tensorType!=null&&n.hasOwnProperty("tensorType")){var r=i.onnx.TypeProto.Tensor.verify(n.tensorType);if(r)return"tensorType."+r}return n.denotation!=null&&n.hasOwnProperty("denotation")&&!s.isString(n.denotation)?"denotation: string expected":null},t.fromObject=function(n){if(n instanceof i.onnx.TypeProto)return n;var r=new i.onnx.TypeProto;if(n.tensorType!=null){if(typeof n.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");r.tensorType=i.onnx.TypeProto.Tensor.fromObject(n.tensorType)}return n.denotation!=null&&(r.denotation=String(n.denotation)),r},t.toObject=function(n,r){r||(r={});var a={};return r.defaults&&(a.denotation=""),n.tensorType!=null&&n.hasOwnProperty("tensorType")&&(a.tensorType=i.onnx.TypeProto.Tensor.toObject(n.tensorType,r),r.oneofs&&(a.value="tensorType")),n.denotation!=null&&n.hasOwnProperty("denotation")&&(a.denotation=n.denotation),a},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t.Tensor=function(){function n(r){if(r)for(var a=Object.keys(r),l=0;l>>3){case 1:d.elemType=r.int32();break;case 2:d.shape=i.onnx.TensorShapeProto.decode(r,r.uint32());break;default:r.skipType(7&m)}}return d},n.decodeDelimited=function(r){return r instanceof c||(r=new c(r)),this.decode(r,r.uint32())},n.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.elemType!=null&&r.hasOwnProperty("elemType")&&!s.isInteger(r.elemType))return"elemType: integer expected";if(r.shape!=null&&r.hasOwnProperty("shape")){var a=i.onnx.TensorShapeProto.verify(r.shape);if(a)return"shape."+a}return null},n.fromObject=function(r){if(r instanceof i.onnx.TypeProto.Tensor)return r;var a=new i.onnx.TypeProto.Tensor;if(r.elemType!=null&&(a.elemType=0|r.elemType),r.shape!=null){if(typeof r.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");a.shape=i.onnx.TensorShapeProto.fromObject(r.shape)}return a},n.toObject=function(r,a){a||(a={});var l={};return a.defaults&&(l.elemType=0,l.shape=null),r.elemType!=null&&r.hasOwnProperty("elemType")&&(l.elemType=r.elemType),r.shape!=null&&r.hasOwnProperty("shape")&&(l.shape=i.onnx.TensorShapeProto.toObject(r.shape,a)),l},n.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},n}(),t}(),h.OperatorSetIdProto=function(){function t(e){if(e)for(var n=Object.keys(e),r=0;r>>3){case 1:a.domain=e.string();break;case 2:a.version=e.int64();break;default:e.skipType(7&l)}}return a},t.decodeDelimited=function(e){return e instanceof c||(e=new c(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.domain!=null&&e.hasOwnProperty("domain")&&!s.isString(e.domain)?"domain: string expected":e.version!=null&&e.hasOwnProperty("version")&&!(s.isInteger(e.version)||e.version&&s.isInteger(e.version.low)&&s.isInteger(e.version.high))?"version: integer|Long expected":null},t.fromObject=function(e){if(e instanceof i.onnx.OperatorSetIdProto)return e;var n=new i.onnx.OperatorSetIdProto;return e.domain!=null&&(n.domain=String(e.domain)),e.version!=null&&(s.Long?(n.version=s.Long.fromValue(e.version)).unsigned=!1:typeof e.version=="string"?n.version=parseInt(e.version,10):typeof e.version=="number"?n.version=e.version:typeof e.version=="object"&&(n.version=new s.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),n},t.toObject=function(e,n){n||(n={});var r={};if(n.defaults)if(r.domain="",s.Long){var a=new s.Long(0,0,!1);r.version=n.longs===String?a.toString():n.longs===Number?a.toNumber():a}else r.version=n.longs===String?"0":0;return e.domain!=null&&e.hasOwnProperty("domain")&&(r.domain=e.domain),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?r.version=n.longs===String?String(e.version):e.version:r.version=n.longs===String?s.Long.prototype.toString.call(e.version):n.longs===Number?new s.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),r},t.prototype.toJSON=function(){return this.constructor.toObject(this,o.util.toJSONOptions)},t}(),h),D.exports=i},2100:(D,u,b)=>{D.exports=b(9482)},9482:(D,u,b)=>{var g=u;function p(){g.util._configure(),g.Writer._configure(g.BufferWriter),g.Reader._configure(g.BufferReader)}g.build="minimal",g.Writer=b(1173),g.BufferWriter=b(3155),g.Reader=b(1408),g.BufferReader=b(593),g.util=b(9693),g.rpc=b(5994),g.roots=b(5054),g.configure=p,p()},1408:(D,u,b)=>{D.exports=f;var g,p=b(9693),h=p.LongBits,o=p.utf8;function c(a,l){return RangeError("index out of range: "+a.pos+" + "+(l||1)+" > "+a.len)}function f(a){this.buf=a,this.pos=0,this.len=a.length}var s,i=typeof Uint8Array<"u"?function(a){if(a instanceof Uint8Array||Array.isArray(a))return new f(a);throw Error("illegal buffer")}:function(a){if(Array.isArray(a))return new f(a);throw Error("illegal buffer")},t=function(){return p.Buffer?function(a){return(f.create=function(l){return p.Buffer.isBuffer(l)?new g(l):i(l)})(a)}:i};function e(){var a=new h(0,0),l=0;if(!(this.len-this.pos>4)){for(;l<3;++l){if(this.pos>=this.len)throw c(this);if(a.lo=(a.lo|(127&this.buf[this.pos])<<7*l)>>>0,this.buf[this.pos++]<128)return a}return a.lo=(a.lo|(127&this.buf[this.pos++])<<7*l)>>>0,a}for(;l<4;++l)if(a.lo=(a.lo|(127&this.buf[this.pos])<<7*l)>>>0,this.buf[this.pos++]<128)return a;if(a.lo=(a.lo|(127&this.buf[this.pos])<<28)>>>0,a.hi=(a.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return a;if(l=0,this.len-this.pos>4){for(;l<5;++l)if(a.hi=(a.hi|(127&this.buf[this.pos])<<7*l+3)>>>0,this.buf[this.pos++]<128)return a}else for(;l<5;++l){if(this.pos>=this.len)throw c(this);if(a.hi=(a.hi|(127&this.buf[this.pos])<<7*l+3)>>>0,this.buf[this.pos++]<128)return a}throw Error("invalid varint encoding")}function n(a,l){return(a[l-4]|a[l-3]<<8|a[l-2]<<16|a[l-1]<<24)>>>0}function r(){if(this.pos+8>this.len)throw c(this,8);return new h(n(this.buf,this.pos+=4),n(this.buf,this.pos+=4))}f.create=t(),f.prototype._slice=p.Array.prototype.subarray||p.Array.prototype.slice,f.prototype.uint32=(s=4294967295,function(){if(s=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(s=(s|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(s=(s|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(s=(s|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(s=(s|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return s;if((this.pos+=5)>this.len)throw this.pos=this.len,c(this,10);return s}),f.prototype.int32=function(){return 0|this.uint32()},f.prototype.sint32=function(){var a=this.uint32();return a>>>1^-(1&a)|0},f.prototype.bool=function(){return this.uint32()!==0},f.prototype.fixed32=function(){if(this.pos+4>this.len)throw c(this,4);return n(this.buf,this.pos+=4)},f.prototype.sfixed32=function(){if(this.pos+4>this.len)throw c(this,4);return 0|n(this.buf,this.pos+=4)},f.prototype.float=function(){if(this.pos+4>this.len)throw c(this,4);var a=p.float.readFloatLE(this.buf,this.pos);return this.pos+=4,a},f.prototype.double=function(){if(this.pos+8>this.len)throw c(this,4);var a=p.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,a},f.prototype.bytes=function(){var a=this.uint32(),l=this.pos,d=this.pos+a;if(d>this.len)throw c(this,a);return this.pos+=a,Array.isArray(this.buf)?this.buf.slice(l,d):l===d?new this.buf.constructor(0):this._slice.call(this.buf,l,d)},f.prototype.string=function(){var a=this.bytes();return o.read(a,0,a.length)},f.prototype.skip=function(a){if(typeof a=="number"){if(this.pos+a>this.len)throw c(this,a);this.pos+=a}else do if(this.pos>=this.len)throw c(this);while(128&this.buf[this.pos++]);return this},f.prototype.skipType=function(a){switch(a){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(a=7&this.uint32())!=4;)this.skipType(a);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+a+" at offset "+this.pos)}return this},f._configure=function(a){g=a,f.create=t(),g._configure();var l=p.Long?"toLong":"toNumber";p.merge(f.prototype,{int64:function(){return e.call(this)[l](!1)},uint64:function(){return e.call(this)[l](!0)},sint64:function(){return e.call(this).zzDecode()[l](!1)},fixed64:function(){return r.call(this)[l](!0)},sfixed64:function(){return r.call(this)[l](!1)}})}},593:(D,u,b)=>{D.exports=h;var g=b(1408);(h.prototype=Object.create(g.prototype)).constructor=h;var p=b(9693);function h(o){g.call(this,o)}h._configure=function(){p.Buffer&&(h.prototype._slice=p.Buffer.prototype.slice)},h.prototype.string=function(){var o=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+o,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+o,this.len))},h._configure()},5054:D=>{D.exports={}},5994:(D,u,b)=>{u.Service=b(7948)},7948:(D,u,b)=>{D.exports=p;var g=b(9693);function p(h,o,c){if(typeof h!="function")throw TypeError("rpcImpl must be a function");g.EventEmitter.call(this),this.rpcImpl=h,this.requestDelimited=!!o,this.responseDelimited=!!c}(p.prototype=Object.create(g.EventEmitter.prototype)).constructor=p,p.prototype.rpcCall=function h(o,c,f,s,i){if(!s)throw TypeError("request must be specified");var t=this;if(!i)return g.asPromise(h,t,o,c,f,s);if(t.rpcImpl)try{return t.rpcImpl(o,c[t.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(e,n){if(e)return t.emit("error",e,o),i(e);if(n!==null){if(!(n instanceof f))try{n=f[t.responseDelimited?"decodeDelimited":"decode"](n)}catch(r){return t.emit("error",r,o),i(r)}return t.emit("data",n,o),i(null,n)}t.end(!0)})}catch(e){return t.emit("error",e,o),void setTimeout(function(){i(e)},0)}else setTimeout(function(){i(Error("already ended"))},0)},p.prototype.end=function(h){return this.rpcImpl&&(h||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(D,u,b)=>{D.exports=p;var g=b(9693);function p(f,s){this.lo=f>>>0,this.hi=s>>>0}var h=p.zero=new p(0,0);h.toNumber=function(){return 0},h.zzEncode=h.zzDecode=function(){return this},h.length=function(){return 1};var o=p.zeroHash="\0\0\0\0\0\0\0\0";p.fromNumber=function(f){if(f===0)return h;var s=f<0;s&&(f=-f);var i=f>>>0,t=(f-i)/4294967296>>>0;return s&&(t=~t>>>0,i=~i>>>0,++i>4294967295&&(i=0,++t>4294967295&&(t=0))),new p(i,t)},p.from=function(f){if(typeof f=="number")return p.fromNumber(f);if(g.isString(f)){if(!g.Long)return p.fromNumber(parseInt(f,10));f=g.Long.fromString(f)}return f.low||f.high?new p(f.low>>>0,f.high>>>0):h},p.prototype.toNumber=function(f){if(!f&&this.hi>>>31){var s=1+~this.lo>>>0,i=~this.hi>>>0;return s||(i=i+1>>>0),-(s+4294967296*i)}return this.lo+4294967296*this.hi},p.prototype.toLong=function(f){return g.Long?new g.Long(0|this.lo,0|this.hi,!!f):{low:0|this.lo,high:0|this.hi,unsigned:!!f}};var c=String.prototype.charCodeAt;p.fromHash=function(f){return f===o?h:new p((c.call(f,0)|c.call(f,1)<<8|c.call(f,2)<<16|c.call(f,3)<<24)>>>0,(c.call(f,4)|c.call(f,5)<<8|c.call(f,6)<<16|c.call(f,7)<<24)>>>0)},p.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},p.prototype.zzEncode=function(){var f=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^f)>>>0,this.lo=(this.lo<<1^f)>>>0,this},p.prototype.zzDecode=function(){var f=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^f)>>>0,this.hi=(this.hi>>>1^f)>>>0,this},p.prototype.length=function(){var f=this.lo,s=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return i===0?s===0?f<16384?f<128?1:2:f<2097152?3:4:s<16384?s<128?5:6:s<2097152?7:8:i<128?9:10}},9693:function(D,u,b){var g=u;function p(o,c,f){for(var s=Object.keys(c),i=0;i0)},g.Buffer=function(){try{var o=g.inquire("buffer").Buffer;return o.prototype.utf8Write?o:null}catch{return null}}(),g._Buffer_from=null,g._Buffer_allocUnsafe=null,g.newBuffer=function(o){return typeof o=="number"?g.Buffer?g._Buffer_allocUnsafe(o):new g.Array(o):g.Buffer?g._Buffer_from(o):typeof Uint8Array>"u"?o:new Uint8Array(o)},g.Array=typeof Uint8Array<"u"?Uint8Array:Array,g.Long=g.global.dcodeIO&&g.global.dcodeIO.Long||g.global.Long||g.inquire("long"),g.key2Re=/^true|false|0|1$/,g.key32Re=/^-?(?:0|[1-9][0-9]*)$/,g.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,g.longToHash=function(o){return o?g.LongBits.from(o).toHash():g.LongBits.zeroHash},g.longFromHash=function(o,c){var f=g.LongBits.fromHash(o);return g.Long?g.Long.fromBits(f.lo,f.hi,c):f.toNumber(!!c)},g.merge=p,g.lcFirst=function(o){return o.charAt(0).toLowerCase()+o.substring(1)},g.newError=h,g.ProtocolError=h("ProtocolError"),g.oneOfGetter=function(o){for(var c={},f=0;f-1;--i)if(c[s[i]]===1&&this[s[i]]!==void 0&&this[s[i]]!==null)return s[i]}},g.oneOfSetter=function(o){return function(c){for(var f=0;f{D.exports=t;var g,p=b(9693),h=p.LongBits,o=p.base64,c=p.utf8;function f(m,y,_){this.fn=m,this.len=y,this.next=void 0,this.val=_}function s(){}function i(m){this.head=m.head,this.tail=m.tail,this.len=m.len,this.next=m.states}function t(){this.len=0,this.head=new f(s,0,0),this.tail=this.head,this.states=null}var e=function(){return p.Buffer?function(){return(t.create=function(){return new g})()}:function(){return new t}};function n(m,y,_){y[_]=255&m}function r(m,y){this.len=m,this.next=void 0,this.val=y}function a(m,y,_){for(;m.hi;)y[_++]=127&m.lo|128,m.lo=(m.lo>>>7|m.hi<<25)>>>0,m.hi>>>=7;for(;m.lo>127;)y[_++]=127&m.lo|128,m.lo=m.lo>>>7;y[_++]=m.lo}function l(m,y,_){y[_]=255&m,y[_+1]=m>>>8&255,y[_+2]=m>>>16&255,y[_+3]=m>>>24}t.create=e(),t.alloc=function(m){return new p.Array(m)},p.Array!==Array&&(t.alloc=p.pool(t.alloc,p.Array.prototype.subarray)),t.prototype._push=function(m,y,_){return this.tail=this.tail.next=new f(m,y,_),this.len+=y,this},r.prototype=Object.create(f.prototype),r.prototype.fn=function(m,y,_){for(;m>127;)y[_++]=127&m|128,m>>>=7;y[_]=m},t.prototype.uint32=function(m){return this.len+=(this.tail=this.tail.next=new r((m>>>=0)<128?1:m<16384?2:m<2097152?3:m<268435456?4:5,m)).len,this},t.prototype.int32=function(m){return m<0?this._push(a,10,h.fromNumber(m)):this.uint32(m)},t.prototype.sint32=function(m){return this.uint32((m<<1^m>>31)>>>0)},t.prototype.uint64=function(m){var y=h.from(m);return this._push(a,y.length(),y)},t.prototype.int64=t.prototype.uint64,t.prototype.sint64=function(m){var y=h.from(m).zzEncode();return this._push(a,y.length(),y)},t.prototype.bool=function(m){return this._push(n,1,m?1:0)},t.prototype.fixed32=function(m){return this._push(l,4,m>>>0)},t.prototype.sfixed32=t.prototype.fixed32,t.prototype.fixed64=function(m){var y=h.from(m);return this._push(l,4,y.lo)._push(l,4,y.hi)},t.prototype.sfixed64=t.prototype.fixed64,t.prototype.float=function(m){return this._push(p.float.writeFloatLE,4,m)},t.prototype.double=function(m){return this._push(p.float.writeDoubleLE,8,m)};var d=p.Array.prototype.set?function(m,y,_){y.set(m,_)}:function(m,y,_){for(var v=0;v>>0;if(!y)return this._push(n,1,0);if(p.isString(m)){var _=t.alloc(y=o.length(m));o.decode(m,_,0),m=_}return this.uint32(y)._push(d,y,m)},t.prototype.string=function(m){var y=c.length(m);return y?this.uint32(y)._push(c.write,y,m):this._push(n,1,0)},t.prototype.fork=function(){return this.states=new i(this),this.head=this.tail=new f(s,0,0),this.len=0,this},t.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new f(s,0,0),this.len=0),this},t.prototype.ldelim=function(){var m=this.head,y=this.tail,_=this.len;return this.reset().uint32(_),_&&(this.tail.next=m.next,this.tail=y,this.len+=_),this},t.prototype.finish=function(){for(var m=this.head.next,y=this.constructor.alloc(this.len),_=0;m;)m.fn(m.val,y,_),_+=m.len,m=m.next;return y},t._configure=function(m){g=m,t.create=e(),g._configure()}},3155:(D,u,b)=>{D.exports=h;var g=b(1173);(h.prototype=Object.create(g.prototype)).constructor=h;var p=b(9693);function h(){g.call(this)}function o(c,f,s){c.length<40?p.utf8.write(c,f,s):f.utf8Write?f.utf8Write(c,s):f.write(c,s)}h._configure=function(){h.alloc=p._Buffer_allocUnsafe,h.writeBytesBuffer=p.Buffer&&p.Buffer.prototype instanceof Uint8Array&&p.Buffer.prototype.set.name==="set"?function(c,f,s){f.set(c,s)}:function(c,f,s){if(c.copy)c.copy(f,s,0,c.length);else for(var i=0;i>>0;return this.uint32(f),f&&this._push(h.writeBytesBuffer,f,c),this},h.prototype.string=function(c){var f=p.Buffer.byteLength(c);return this.uint32(f),f&&this._push(o,f,c),this},h._configure()},7714:(D,u,b)=>{u.R=void 0;const g=b(6919),p=b(7448);u.R=new class{async init(){}async createSessionHandler(h,o){const c=new g.Session(o);return await c.loadModel(h),new p.OnnxjsSessionHandler(c)}}},4200:(D,u,b)=>{u.c8=u.rX=void 0;const g=b(1670),p=b(5381),h=b(2157),o=b(2306);u.rX=()=>{if((typeof g.env.wasm.initTimeout!="number"||g.env.wasm.initTimeout<0)&&(g.env.wasm.initTimeout=0),typeof g.env.wasm.simd!="boolean"&&(g.env.wasm.simd=!0),typeof g.env.wasm.proxy!="boolean"&&(g.env.wasm.proxy=!1),typeof g.env.wasm.numThreads!="number"||!Number.isInteger(g.env.wasm.numThreads)||g.env.wasm.numThreads<=0){const c=typeof navigator>"u"?(0,p.cpus)().length:navigator.hardwareConcurrency;g.env.wasm.numThreads=Math.min(4,Math.ceil((c||1)/2))}},u.c8=new class{async init(){(0,u.rX)(),await(0,h.initWasm)()}async createSessionHandler(c,f){const s=new o.OnnxruntimeWebAssemblySessionHandler;return await s.loadModel(c,f),Promise.resolve(s)}}},6018:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(o,c,f,s){s===void 0&&(s=f);var i=Object.getOwnPropertyDescriptor(c,f);i&&!("get"in i?!c.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return c[f]}}),Object.defineProperty(o,s,i)}:function(o,c,f,s){s===void 0&&(s=f),o[s]=c[f]}),p=this&&this.__exportStar||function(o,c){for(var f in o)f==="default"||Object.prototype.hasOwnProperty.call(c,f)||g(c,o,f)};Object.defineProperty(u,"__esModule",{value:!0}),p(b(1670),u);const h=b(1670);{const o=b(7714).R;(0,h.registerBackend)("webgl",o,-10)}{const o=b(4200).c8;(0,h.registerBackend)("cpu",o,10),(0,h.registerBackend)("wasm",o,10),(0,h.registerBackend)("xnnpack",o,9)}},246:(D,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createAttributeWithCacheKey=void 0;class b{constructor(p){Object.assign(this,p)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(p=>`${this[p]}`).join(";")),this._cacheKey}}u.createAttributeWithCacheKey=g=>new b(g)},7778:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Attribute=void 0;const g=b(1446),p=b(9395),h=b(9162),o=b(2517);var c=p.onnxruntime.experimental.fbs;class f{constructor(i){if(this._attributes=new Map,i!=null){for(const t of i)t instanceof g.onnx.AttributeProto?this._attributes.set(t.name,[f.getValue(t),f.getType(t)]):t instanceof c.Attribute&&this._attributes.set(t.name(),[f.getValue(t),f.getType(t)]);if(this._attributes.sizeh.Tensor.fromProto(n));if(i instanceof c.Attribute)return e.map(n=>h.Tensor.fromOrtTensor(n))}if(t===g.onnx.AttributeProto.AttributeType.STRING&&i instanceof g.onnx.AttributeProto){const n=e;return(0,o.decodeUtf8String)(n)}return t===g.onnx.AttributeProto.AttributeType.STRINGS&&i instanceof g.onnx.AttributeProto?e.map(o.decodeUtf8String):e}static getValueNoCheck(i){return i instanceof g.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(i):this.getValueNoCheckFromOrtFormat(i)}static getValueNoCheckFromOnnxFormat(i){switch(i.type){case g.onnx.AttributeProto.AttributeType.FLOAT:return i.f;case g.onnx.AttributeProto.AttributeType.INT:return i.i;case g.onnx.AttributeProto.AttributeType.STRING:return i.s;case g.onnx.AttributeProto.AttributeType.TENSOR:return i.t;case g.onnx.AttributeProto.AttributeType.GRAPH:return i.g;case g.onnx.AttributeProto.AttributeType.FLOATS:return i.floats;case g.onnx.AttributeProto.AttributeType.INTS:return i.ints;case g.onnx.AttributeProto.AttributeType.STRINGS:return i.strings;case g.onnx.AttributeProto.AttributeType.TENSORS:return i.tensors;case g.onnx.AttributeProto.AttributeType.GRAPHS:return i.graphs;default:throw new Error(`unsupported attribute type: ${g.onnx.AttributeProto.AttributeType[i.type]}`)}}static getValueNoCheckFromOrtFormat(i){switch(i.type()){case c.AttributeType.FLOAT:return i.f();case c.AttributeType.INT:return i.i();case c.AttributeType.STRING:return i.s();case c.AttributeType.TENSOR:return i.t();case c.AttributeType.GRAPH:return i.g();case c.AttributeType.FLOATS:return i.floatsArray();case c.AttributeType.INTS:{const t=[];for(let e=0;e{Object.defineProperty(u,"__esModule",{value:!0}),u.resolveBackend=u.backend=void 0;const g=b(5038),p=new Map;async function h(o){const c=u.backend;if(c[o]!==void 0&&function(f){const s=f;return"initialize"in s&&typeof s.initialize=="function"&&"createSessionHandler"in s&&typeof s.createSessionHandler=="function"&&"dispose"in s&&typeof s.dispose=="function"}(c[o])){const f=c[o];let s=f.initialize();if(typeof s=="object"&&"then"in s&&(s=await s),s)return p.set(o,f),f}}u.backend={webgl:new g.WebGLBackend},u.resolveBackend=async function o(c){if(!c)return o(["webgl"]);{const f=typeof c=="string"?[c]:c;for(const s of f){const i=p.get(s);if(i)return i;const t=await h(s);if(t)return t}}throw new Error("no available backend to use")}},5038:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.WebGLBackend=void 0;const g=b(1670),p=b(6231),h=b(6416),o=b(7305);u.WebGLBackend=class{get contextId(){return g.env.webgl.contextId}set contextId(c){g.env.webgl.contextId=c}get matmulMaxBatchSize(){return g.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(c){g.env.webgl.matmulMaxBatchSize=c}get textureCacheMode(){return g.env.webgl.textureCacheMode}set textureCacheMode(c){g.env.webgl.textureCacheMode=c}get pack(){return g.env.webgl.pack}set pack(c){g.env.webgl.pack=c}get async(){return g.env.webgl.async}set async(c){g.env.webgl.async=c}initialize(){try{return this.glContext=(0,o.createWebGLContext)(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),p.Logger.setWithEnv(g.env),p.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(c){return p.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${c}`),!1}}createSessionHandler(c){return new h.WebGLSessionHandler(this,c)}dispose(){this.glContext.dispose()}}},5107:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.CoordsGlslLib=void 0;const g=b(2517),p=b(8520),h=b(5060),o=b(7859),c=b(9390);class f extends p.GlslLib{constructor(i){super(i)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new p.GlslLibRoutine(` vec2 offsetToCoords(int offset, int width, int height) { int t = offset / width; int s = offset - t*width; @@ -179,35 +179,35 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ `),t="sampleTexture";const e=(0,h.getGlsl)(this.context.glContext.version);return i[t]=new p.GlslLibRoutine(` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${e.texture2D}(textureSampler, uv).r; - }`),i}getInputsSamplingSnippets(){const i={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((e,n)=>{const r=this.context.inputTextureLayouts[n],a=(0,c.generateShaderFuncNameFromInputSamplerName)(e);r.isPacked?i[a]=this.getPackedSamplerFromInput(a,e,r):i[a]=this.getUnpackedSamplerFromInput(a,e,r);const l=(0,c.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);r.unpackedShape.length<=t.unpackedShape.length&&(r.isPacked?i[l]=this.getPackedSamplerAtOutputCoords(l,r,t,e):i[l]=this.getUnpackedSamplerAtOutputCoords(l,r,t,e))}),i}getPackedSamplerAtOutputCoords(i,t,e,n){const r=t.unpackedShape,a=e.unpackedShape,l=n,d=(0,c.generateShaderFuncNameFromInputSamplerName)(l),m=r.length,y=a.length,v=g.BroadcastUtil.getBroadcastDims(r,a),_=(0,c.getCoordsDataType)(y),T=y-m;let S;const A=(0,c.getGlChannels)();S=m===0?"":y<2&&v.length>=1?"coords = 0;":v.map(N=>`coords.${A[N+T]} = 0;`).join(` -`);let w="";w=y<2&&m>0?"coords":r.map((N,W)=>`coords.${A[W+T]}`).join(", ");let I="return outputValue;";const R=g.ShapeUtil.size(r)===1,B=g.ShapeUtil.size(a)===1;if(m!==1||R||B){if(R&&!B)I=y===1?` + }`),i}getInputsSamplingSnippets(){const i={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((e,n)=>{const r=this.context.inputTextureLayouts[n],a=(0,c.generateShaderFuncNameFromInputSamplerName)(e);r.isPacked?i[a]=this.getPackedSamplerFromInput(a,e,r):i[a]=this.getUnpackedSamplerFromInput(a,e,r);const l=(0,c.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);r.unpackedShape.length<=t.unpackedShape.length&&(r.isPacked?i[l]=this.getPackedSamplerAtOutputCoords(l,r,t,e):i[l]=this.getUnpackedSamplerAtOutputCoords(l,r,t,e))}),i}getPackedSamplerAtOutputCoords(i,t,e,n){const r=t.unpackedShape,a=e.unpackedShape,l=n,d=(0,c.generateShaderFuncNameFromInputSamplerName)(l),m=r.length,y=a.length,_=g.BroadcastUtil.getBroadcastDims(r,a),v=(0,c.getCoordsDataType)(y),T=y-m;let S;const O=(0,c.getGlChannels)();S=m===0?"":y<2&&_.length>=1?"coords = 0;":_.map(N=>`coords.${O[N+T]} = 0;`).join(` +`);let w="";w=y<2&&m>0?"coords":r.map((N,W)=>`coords.${O[W+T]}`).join(", ");let I="return outputValue;";const R=g.ShapeUtil.size(r)===1,B=g.ShapeUtil.size(a)===1;if(m!==1||R||B){if(R&&!B)I=y===1?` return vec4(outputValue.x, outputValue.x, 0., 0.); `:` return vec4(outputValue.x); - `;else if(v.length){const N=m-2,W=m-1;v.indexOf(N)>-1&&v.indexOf(W)>-1?I="return vec4(outputValue.x);":v.indexOf(N)>-1?I="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":v.indexOf(W)>-1&&(I="return vec4(outputValue.xx, outputValue.zz);")}}else I=` + `;else if(_.length){const N=m-2,W=m-1;_.indexOf(N)>-1&&_.indexOf(W)>-1?I="return vec4(outputValue.x);":_.indexOf(N)>-1?I="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":_.indexOf(W)>-1&&(I="return vec4(outputValue.xx, outputValue.zz);")}}else I=` return vec4(outputValue.xy, outputValue.xy); `;const j=` vec4 ${i}() { - ${_} coords = getOutputCoords(); + ${v} coords = getOutputCoords(); - int lastDim = coords.${A[y-1]}; - coords.${A[y-1]} = coords.${A[y-2]}; - coords.${A[y-2]} = lastDim; + int lastDim = coords.${O[y-1]}; + coords.${O[y-1]} = coords.${O[y-2]}; + coords.${O[y-2]} = lastDim; ${S} vec4 outputValue = ${d}(${w}); ${I} } - `;return new p.GlslLibRoutine(j,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(i,t,e,n){const r=[e.width,e.height],a=[t.width,t.height],l=t.unpackedShape.length,d=e.unpackedShape.length,m=t.unpackedShape,y=e.unpackedShape,v=(0,c.generateShaderFuncNameFromInputSamplerName)(n);if(l===d&&g.ArrayUtil.arraysEqual(a,r)){const B=` + `;return new p.GlslLibRoutine(j,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(i,t,e,n){const r=[e.width,e.height],a=[t.width,t.height],l=t.unpackedShape.length,d=e.unpackedShape.length,m=t.unpackedShape,y=e.unpackedShape,_=(0,c.generateShaderFuncNameFromInputSamplerName)(n);if(l===d&&g.ArrayUtil.arraysEqual(a,r)){const B=` float ${i}() { return sampleTexture(${n}, TexCoords); } - `;return new p.GlslLibRoutine(B,["coordinates.sampleTexture"])}const _=(0,c.getCoordsDataType)(d),T=g.BroadcastUtil.getBroadcastDims(m,y),S=d-l;let A;const w=(0,c.getGlChannels)();A=l===0?"":d<2&&T.length>=1?"coords = 0;":T.map(B=>`coords.${w[B+S]} = 0;`).join(` + `;return new p.GlslLibRoutine(B,["coordinates.sampleTexture"])}const v=(0,c.getCoordsDataType)(d),T=g.BroadcastUtil.getBroadcastDims(m,y),S=d-l;let O;const w=(0,c.getGlChannels)();O=l===0?"":d<2&&T.length>=1?"coords = 0;":T.map(B=>`coords.${w[B+S]} = 0;`).join(` `);let I="";I=d<2&&l>0?"coords":t.unpackedShape.map((B,j)=>`coords.${w[j+S]}`).join(", ");const R=` float ${i}() { - ${_} coords = getOutputCoords(); - ${A} - return ${v}(${I}); + ${v} coords = getOutputCoords(); + ${O} + return ${_}(${I}); } `;return new p.GlslLibRoutine(R,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(i,t,e){switch(e.unpackedShape.length){case 0:return this.getPackedSamplerScalar(i,t);case 1:return this.getPackedSampler1D(i,t,e);case 2:return this.getPackedSampler2D(i,t,e);case 3:return this.getPackedSampler3D(i,t,e);default:return this.getPackedSamplerND(i,t,e)}}getUnpackedSamplerFromInput(i,t,e){const n=e.unpackedShape;switch(n.length){case 0:return this.getUnpackedSamplerScalar(i,t,e);case 1:return this.getUnpackedSampler1D(i,t,e);case 2:return this.getUnpackedSampler2D(i,t,e);case 3:return this.getUnpackedSampler3D(i,t,e);case 4:return this.getUnpackedSampler4D(i,t,e);case 5:return this.getUnpackedSampler5D(i,t,e);case 6:return this.getUnpackedSampler6D(i,t,e);default:throw new Error(`Unsupported dimension ${n.length}-D`)}}getPackedSamplerScalar(i,t){const e=` vec4 ${i}() { @@ -217,25 +217,25 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ vec2 uv = packedUVfrom1D( ${r[0]}, ${r[1]}, index); return ${a.texture2D}(${t}, uv); - }`;return new p.GlslLibRoutine(l,["coordinates.packedUVfrom1D"])}getPackedSampler2D(i,t,e){const n=e.unpackedShape,r=[e.width,e.height],a=(0,h.getGlsl)(this.context.glContext.version),l=r[0],d=r[1];if(r!=null&&g.ArrayUtil.arraysEqual(n,r)){const _=`vec4 ${i}(int row, int col) { + }`;return new p.GlslLibRoutine(l,["coordinates.packedUVfrom1D"])}getPackedSampler2D(i,t,e){const n=e.unpackedShape,r=[e.width,e.height],a=(0,h.getGlsl)(this.context.glContext.version),l=r[0],d=r[1];if(r!=null&&g.ArrayUtil.arraysEqual(n,r)){const v=`vec4 ${i}(int row, int col) { vec2 uv = (vec2(col, row) + halfCR) / vec2(${d}.0, ${l}.0); return ${a.texture2D}(${t}, uv); - }`;return new p.GlslLibRoutine(_)}const m=r,y=Math.ceil(n[1]/2),v=`vec4 ${i}(int row, int col) { + }`;return new p.GlslLibRoutine(v)}const m=r,y=Math.ceil(n[1]/2),_=`vec4 ${i}(int row, int col) { vec2 uv = packedUVfrom2D(${m[1]}, ${m[0]}, ${y}, row, col); return ${a.texture2D}(${t}, uv); - }`;return new p.GlslLibRoutine(v,["coordinates.packedUVfrom2D"])}getPackedSampler3D(i,t,e){const n=e.unpackedShape,r=[e.width,e.height],a=[r[0],r[1]],l=(0,h.getGlsl)(this.context.glContext.version);if(n[0]===1){const _=n.slice(1),T=[1,2],S=(0,c.squeezeInputShape)(n,_),A=["b","row","col"],w=JSON.parse(JSON.stringify(e));w.unpackedShape=S;const I=this.getPackedSamplerFromInput(i,t,w),R=`${I.routineBody} + }`;return new p.GlslLibRoutine(_,["coordinates.packedUVfrom2D"])}getPackedSampler3D(i,t,e){const n=e.unpackedShape,r=[e.width,e.height],a=[r[0],r[1]],l=(0,h.getGlsl)(this.context.glContext.version);if(n[0]===1){const v=n.slice(1),T=[1,2],S=(0,c.squeezeInputShape)(n,v),O=["b","row","col"],w=JSON.parse(JSON.stringify(e));w.unpackedShape=S;const I=this.getPackedSamplerFromInput(i,t,w),R=`${I.routineBody} vec4 ${i}(int b, int row, int col) { - return ${i}(${(0,c.getSqueezedParams)(A,T)}); - } `;return new p.GlslLibRoutine(R,I.dependencies)}const d=a[0],m=a[1],y=Math.ceil(n[2]/2),v=`vec4 ${i}(int b, int row, int col) { + return ${i}(${(0,c.getSqueezedParams)(O,T)}); + } `;return new p.GlslLibRoutine(R,I.dependencies)}const d=a[0],m=a[1],y=Math.ceil(n[2]/2),_=`vec4 ${i}(int b, int row, int col) { vec2 uv = packedUVfrom3D( ${m}, ${d}, ${y*Math.ceil(n[1]/2)}, ${y}, b, row, col); - return ${l.texture2D}(${t}, uv);}`;return new p.GlslLibRoutine(v,["coordinates.packedUVfrom3D"])}getPackedSamplerND(i,t,e){const n=e.unpackedShape,r=n.length,a=[e.width,e.height],l=(0,h.getGlsl)(this.context.glContext.version),d=[a[0],a[1]],m=d[1],y=d[0],v=Math.ceil(n[r-1]/2);let _=v*Math.ceil(n[r-2]/2),T="int b, int row, int col",S=`b * ${_} + (row / 2) * ${v} + (col / 2)`;for(let w=2;w{Object.defineProperty(u,"__esModule",{value:!0}),u.WebGLInferenceHandler=void 0;const g=b(6231),p=b(9162),h=b(2517),o=b(2403),c=b(7019),f=b(8710),s=b(5611),i=b(4057),t=b(2039);u.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,n){return(0,i.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,n)}executeProgram(e,n){if(n.length{const T=_.map(A=>`${A.unpackedShape.join(",")};${A.width}x${A.height}`).join("_");let S=v.name;return v.cacheHint&&(S+="["+v.cacheHint+"]"),S+=":"+T,S})(e,r);let l=this.session.programManager.getArtifact(a);const d=l?l.programInfo:typeof e.get=="function"?e.get():e,m=(0,i.createTextureLayoutFromTextureType)(this.session.layoutStrategy,d.output.dims,d.output.textureType),y=this.createTextureData(m,d.output.type);return l||(l=this.session.programManager.build(d,r,y),this.session.programManager.setArtifact(a,l)),this.runProgram(l,r,y),y}run(e,n){return this.executeProgram(e,n).tensor}runProgram(e,n,r){for(let a=0;athis.readTexture(d),async m=>this.readTextureAsync(d),void 0,l),texture:r});return this.setTextureData(d.tensor.dataId,d,e.isPacked),d}getTextureData(e,n=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,n):n?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,n,r=!1){this.session.isInitializer(e)?this.session.setTextureData(e,n,r):(r?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,n)}isTextureLayoutCached(e,n=!1){return!!this.getTextureData(e.dataId,n)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,f.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,f.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,o.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,s.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(Y,te,ne,me){me===void 0&&(me=ne);var Pe=Object.getOwnPropertyDescriptor(te,ne);Pe&&!("get"in Pe?!te.__esModule:Pe.writable||Pe.configurable)||(Pe={enumerable:!0,get:function(){return te[ne]}}),Object.defineProperty(Y,me,Pe)}:function(Y,te,ne,me){me===void 0&&(me=ne),Y[me]=te[ne]}),p=this&&this.__setModuleDefault||(Object.create?function(Y,te){Object.defineProperty(Y,"default",{enumerable:!0,value:te})}:function(Y,te){Y.default=te}),h=this&&this.__importStar||function(Y){if(Y&&Y.__esModule)return Y;var te={};if(Y!=null)for(var ne in Y)ne!=="default"&&Object.prototype.hasOwnProperty.call(Y,ne)&&g(te,Y,ne);return p(te,Y),te};Object.defineProperty(u,"__esModule",{value:!0}),u.WEBGL_OP_RESOLVE_RULES=void 0;const o=b(2898),c=h(b(7839)),f=b(4196),s=b(2069),i=b(8138),t=b(9663),e=b(5193),n=b(7992),r=b(1253),a=b(4776),l=b(6572),d=b(3346),m=b(5623),y=b(2870),v=b(2143),_=b(4939),T=b(718),S=b(2268),A=b(8117),w=b(2278),I=b(5524),R=b(5975),B=b(3933),j=b(6558),N=b(5723),W=b(3738),k=h(b(4909)),V=b(8428),J=b(9793);u.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",c.add],["And","","7+",c.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",v.averagePool,v.parseAveragePoolAttributes],["BatchNormalization","","7+",o.batchNormalization,o.parseBatchNormalizationAttributes],["Cast","","6+",f.cast,f.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",s.concat,s.parseConcatAttributes],["Conv","","1+",i.conv,i.parseConvAttributes],["ConvTranspose","","1+",t.convTranspose,t.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",c.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",e.depthToSpace,e.parseDepthToSpaceAttributes],["Equal","","7+",c.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",n.flatten,n.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",i.conv,i.parseConvAttributes],["Gather","","1+",r.gather,r.parseGatherAttributes],["Gemm","","7-10",a.gemm,a.parseGemmAttributesV7],["Gemm","","11+",a.gemm,a.parseGemmAttributesV11],["GlobalAveragePool","","1+",v.globalAveragePool,v.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",v.globalMaxPool],["Greater","","7+",c.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",l.imageScaler,l.parseImageScalerAttributes],["InstanceNormalization","","6+",d.instanceNormalization,d.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",c.less],["Log","","6+",k.log],["MatMul","","1+",m.matMul,m.parseMatMulAttributes],["MaxPool","","1+",v.maxPool,v.parseMaxPoolAttributes],["Mul","","7+",c.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",c.or],["Pad","","2-10",y.padV2,y.parsePadAttributesV2],["Pad","","11+",y.padV11,y.parsePadAttributesV11],["Pow","","7+",c.pow],["PRelu","","7+",c.pRelu],["ReduceLogSum","","1+",_.reduceLogSum,_.parseReduceAttributes],["ReduceMax","","1+",_.reduceMax,_.parseReduceAttributes],["ReduceMean","","1+",_.reduceMean,_.parseReduceAttributes],["ReduceMin","","1+",_.reduceMin,_.parseReduceAttributes],["ReduceProd","","1+",_.reduceProd,_.parseReduceAttributes],["ReduceSum","","1-12",_.reduceSum,_.parseReduceAttributes],["ReduceSumSquare","","1+",_.reduceLogSumSquare,_.parseReduceAttributes],["Relu","","6+",k.relu],["Reshape","","5+",T.reshape],["Resize","","10",S.resize,S.parseResizeAttributesV10],["Resize","","11+",S.resize,S.parseResizeAttributesV11],["Shape","","1+",A.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",w.sliceV10],["Slice","","1-9",w.slice,w.parseSliceAttributes],["Softmax","","1-12",I.softmax,I.parseSoftmaxAttributes],["Softmax","","13+",I.softmaxV13,I.parseSoftmaxAttributesV13],["Split","","2-12",R.split,R.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",B.squeeze,B.parseSqueezeAttributes],["Squeeze","","13+",B.squeezeV13],["Sub","","7+",c.sub],["Sum","","6+",j.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",N.tile],["Transpose","","1+",W.transpose,W.parseTransposeAttributes],["Upsample","","7-8",J.upsample,J.parseUpsampleAttributesV7],["Upsample","","9",J.upsample,J.parseUpsampleAttributesV9],["Unsqueeze","","1-12",V.unsqueeze,V.parseUnsqueezeAttributes],["Unsqueeze","","13+",V.unsqueezeV13],["Xor","","7+",c.xor]]},2898:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseBatchNormalizationAttributes=u.batchNormalization=void 0;const g=b(246),p=b(5060),h=b(2039),o={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]};u.batchNormalization=(s,i,t)=>(f(i),[s.run(Object.assign(Object.assign({},o),{cacheHint:t.cacheKey,get:()=>c(s,i,t)}),i)]),u.parseBatchNormalizationAttributes=s=>{const i=s.attributes.getFloat("epsilon",1e-5),t=s.attributes.getFloat("momentum",.9),e=s.attributes.getInt("spatial",1);return(0,g.createAttributeWithCacheKey)({epsilon:i,momentum:t,spatial:e})};const c=(s,i,t)=>{const e=(0,p.getGlsl)(s.session.backend.glContext.version),n=i[0].dims.length,[r,a]=s.calculateTextureWidthAndHeight(i[1].dims,h.TextureType.unpacked),l=` + `;return{getVecItem:new g.GlslLibRoutine(f)}}}u.VecGlslLib=p},8316:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.WebGLInferenceHandler=void 0;const g=b(6231),p=b(9162),h=b(2517),o=b(2403),c=b(7019),f=b(8710),s=b(5611),i=b(4057),t=b(2039);u.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,n){return(0,i.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,n)}executeProgram(e,n){if(n.length{const T=v.map(O=>`${O.unpackedShape.join(",")};${O.width}x${O.height}`).join("_");let S=_.name;return _.cacheHint&&(S+="["+_.cacheHint+"]"),S+=":"+T,S})(e,r);let l=this.session.programManager.getArtifact(a);const d=l?l.programInfo:typeof e.get=="function"?e.get():e,m=(0,i.createTextureLayoutFromTextureType)(this.session.layoutStrategy,d.output.dims,d.output.textureType),y=this.createTextureData(m,d.output.type);return l||(l=this.session.programManager.build(d,r,y),this.session.programManager.setArtifact(a,l)),this.runProgram(l,r,y),y}run(e,n){return this.executeProgram(e,n).tensor}runProgram(e,n,r){for(let a=0;athis.readTexture(d),async m=>this.readTextureAsync(d),void 0,l),texture:r});return this.setTextureData(d.tensor.dataId,d,e.isPacked),d}getTextureData(e,n=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,n):n?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,n,r=!1){this.session.isInitializer(e)?this.session.setTextureData(e,n,r):(r?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,n)}isTextureLayoutCached(e,n=!1){return!!this.getTextureData(e.dataId,n)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,f.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,f.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,o.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,s.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(Y,te,ne,me){me===void 0&&(me=ne);var Pe=Object.getOwnPropertyDescriptor(te,ne);Pe&&!("get"in Pe?!te.__esModule:Pe.writable||Pe.configurable)||(Pe={enumerable:!0,get:function(){return te[ne]}}),Object.defineProperty(Y,me,Pe)}:function(Y,te,ne,me){me===void 0&&(me=ne),Y[me]=te[ne]}),p=this&&this.__setModuleDefault||(Object.create?function(Y,te){Object.defineProperty(Y,"default",{enumerable:!0,value:te})}:function(Y,te){Y.default=te}),h=this&&this.__importStar||function(Y){if(Y&&Y.__esModule)return Y;var te={};if(Y!=null)for(var ne in Y)ne!=="default"&&Object.prototype.hasOwnProperty.call(Y,ne)&&g(te,Y,ne);return p(te,Y),te};Object.defineProperty(u,"__esModule",{value:!0}),u.WEBGL_OP_RESOLVE_RULES=void 0;const o=b(2898),c=h(b(7839)),f=b(4196),s=b(2069),i=b(8138),t=b(9663),e=b(5193),n=b(7992),r=b(1253),a=b(4776),l=b(6572),d=b(3346),m=b(5623),y=b(2870),_=b(2143),v=b(4939),T=b(718),S=b(2268),O=b(8117),w=b(2278),I=b(5524),R=b(5975),B=b(3933),j=b(6558),N=b(5723),W=b(3738),k=h(b(4909)),V=b(8428),J=b(9793);u.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",c.add],["And","","7+",c.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",_.averagePool,_.parseAveragePoolAttributes],["BatchNormalization","","7+",o.batchNormalization,o.parseBatchNormalizationAttributes],["Cast","","6+",f.cast,f.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",s.concat,s.parseConcatAttributes],["Conv","","1+",i.conv,i.parseConvAttributes],["ConvTranspose","","1+",t.convTranspose,t.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",c.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",e.depthToSpace,e.parseDepthToSpaceAttributes],["Equal","","7+",c.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",n.flatten,n.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",i.conv,i.parseConvAttributes],["Gather","","1+",r.gather,r.parseGatherAttributes],["Gemm","","7-10",a.gemm,a.parseGemmAttributesV7],["Gemm","","11+",a.gemm,a.parseGemmAttributesV11],["GlobalAveragePool","","1+",_.globalAveragePool,_.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",_.globalMaxPool],["Greater","","7+",c.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",l.imageScaler,l.parseImageScalerAttributes],["InstanceNormalization","","6+",d.instanceNormalization,d.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",c.less],["Log","","6+",k.log],["MatMul","","1+",m.matMul,m.parseMatMulAttributes],["MaxPool","","1+",_.maxPool,_.parseMaxPoolAttributes],["Mul","","7+",c.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",c.or],["Pad","","2-10",y.padV2,y.parsePadAttributesV2],["Pad","","11+",y.padV11,y.parsePadAttributesV11],["Pow","","7+",c.pow],["PRelu","","7+",c.pRelu],["ReduceLogSum","","1+",v.reduceLogSum,v.parseReduceAttributes],["ReduceMax","","1+",v.reduceMax,v.parseReduceAttributes],["ReduceMean","","1+",v.reduceMean,v.parseReduceAttributes],["ReduceMin","","1+",v.reduceMin,v.parseReduceAttributes],["ReduceProd","","1+",v.reduceProd,v.parseReduceAttributes],["ReduceSum","","1-12",v.reduceSum,v.parseReduceAttributes],["ReduceSumSquare","","1+",v.reduceLogSumSquare,v.parseReduceAttributes],["Relu","","6+",k.relu],["Reshape","","5+",T.reshape],["Resize","","10",S.resize,S.parseResizeAttributesV10],["Resize","","11+",S.resize,S.parseResizeAttributesV11],["Shape","","1+",O.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",w.sliceV10],["Slice","","1-9",w.slice,w.parseSliceAttributes],["Softmax","","1-12",I.softmax,I.parseSoftmaxAttributes],["Softmax","","13+",I.softmaxV13,I.parseSoftmaxAttributesV13],["Split","","2-12",R.split,R.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",B.squeeze,B.parseSqueezeAttributes],["Squeeze","","13+",B.squeezeV13],["Sub","","7+",c.sub],["Sum","","6+",j.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",N.tile],["Transpose","","1+",W.transpose,W.parseTransposeAttributes],["Upsample","","7-8",J.upsample,J.parseUpsampleAttributesV7],["Upsample","","9",J.upsample,J.parseUpsampleAttributesV9],["Unsqueeze","","1-12",V.unsqueeze,V.parseUnsqueezeAttributes],["Unsqueeze","","13+",V.unsqueezeV13],["Xor","","7+",c.xor]]},2898:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseBatchNormalizationAttributes=u.batchNormalization=void 0;const g=b(246),p=b(5060),h=b(2039),o={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]};u.batchNormalization=(s,i,t)=>(f(i),[s.run(Object.assign(Object.assign({},o),{cacheHint:t.cacheKey,get:()=>c(s,i,t)}),i)]),u.parseBatchNormalizationAttributes=s=>{const i=s.attributes.getFloat("epsilon",1e-5),t=s.attributes.getFloat("momentum",.9),e=s.attributes.getInt("spatial",1);return(0,g.createAttributeWithCacheKey)({epsilon:i,momentum:t,spatial:e})};const c=(s,i,t)=>{const e=(0,p.getGlsl)(s.session.backend.glContext.version),n=i[0].dims.length,[r,a]=s.calculateTextureWidthAndHeight(i[1].dims,h.TextureType.unpacked),l=` float process(int[${n}] indices) { vec2 position = offsetToCoords(indices[1], ${r}, ${a}); float scale = getColorAsFloat(${e.texture2D}(Scale, position)); @@ -560,66 +560,66 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ float b = getColorAsFloat(${e.texture2D}(B, position)); return scale * ( (_A(indices) - mean) / sqrt(variance + float(${t.epsilon})) ) + b; - }`;return Object.assign(Object.assign({},o),{output:{dims:i[0].dims,type:i[0].type,textureType:h.TextureType.unpacked},shaderSource:l})},f=s=>{if(!s||s.length!==5)throw new Error("BatchNormalization requires 5 inputs.");const i=s[0],t=s[1],e=s[2],n=s[3],r=s[4];if(i.dims.length<3||t.dims.length!==1||e.dims.length!==1||n.dims.length!==1||r.dims.length!==1)throw new Error("invalid input shape.");if(t.dims[0]!==i.dims[1]||e.dims[0]!==i.dims[1]||n.dims[0]!==i.dims[1]||r.dims[0]!==i.dims[1])throw new Error("invalid input shape.");if(i.type!=="float32"&&i.type!=="float64"||t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("invalid input tensor types.")}},7839:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.xor=u.sub=u.pRelu=u.pow=u.or=u.mul=u.less=u.greater=u.equal=u.div=u.and=u.add=u.glslPRelu=u.glslPow=u.glslXor=u.glslOr=u.glslAnd=u.glslLess=u.glslGreater=u.glslEqual=u.glslSub=u.glslMul=u.glslDiv=u.glslAdd=void 0;const g=b(2517),p=b(8520),h=b(5060),o=b(2039);function c(){const _="add_";return{body:` - float ${_}(float a, float b) { + }`;return Object.assign(Object.assign({},o),{output:{dims:i[0].dims,type:i[0].type,textureType:h.TextureType.unpacked},shaderSource:l})},f=s=>{if(!s||s.length!==5)throw new Error("BatchNormalization requires 5 inputs.");const i=s[0],t=s[1],e=s[2],n=s[3],r=s[4];if(i.dims.length<3||t.dims.length!==1||e.dims.length!==1||n.dims.length!==1||r.dims.length!==1)throw new Error("invalid input shape.");if(t.dims[0]!==i.dims[1]||e.dims[0]!==i.dims[1]||n.dims[0]!==i.dims[1]||r.dims[0]!==i.dims[1])throw new Error("invalid input shape.");if(i.type!=="float32"&&i.type!=="float64"||t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("invalid input tensor types.")}},7839:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.xor=u.sub=u.pRelu=u.pow=u.or=u.mul=u.less=u.greater=u.equal=u.div=u.and=u.add=u.glslPRelu=u.glslPow=u.glslXor=u.glslOr=u.glslAnd=u.glslLess=u.glslGreater=u.glslEqual=u.glslSub=u.glslMul=u.glslDiv=u.glslAdd=void 0;const g=b(2517),p=b(8520),h=b(5060),o=b(2039);function c(){const v="add_";return{body:` + float ${v}(float a, float b) { return a + b; } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return v1 + v2; } - `,name:_,type:p.FunctionType.ValueBased}}function f(){const _="div_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function f(){const v="div_";return{body:` + float ${v}(float a, float b) { return a / b; } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return v1 / v2; } - `,name:_,type:p.FunctionType.ValueBased}}function s(){const _="mul_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function s(){const v="mul_";return{body:` + float ${v}(float a, float b) { return a * b; } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return v1 * v2; } - `,name:_,type:p.FunctionType.ValueBased}}function i(){const _="sub_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function i(){const v="sub_";return{body:` + float ${v}(float a, float b) { return a - b; } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return v1 - v2; } - `,name:_,type:p.FunctionType.ValueBased}}function t(){const _="equal_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function t(){const v="equal_";return{body:` + float ${v}(float a, float b) { return float(a == b); } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return vec4(equal(v1, v2)); } - `,name:_,type:p.FunctionType.ValueBased}}function e(){const _="greater_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function e(){const v="greater_";return{body:` + float ${v}(float a, float b) { return float(a > b); } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return vec4( v1.r > v2.r , v1.g > v2.g, v1.b > v2.b, v1.a > v2.a ); } - `,name:_,type:p.FunctionType.ValueBased}}function n(){const _="less_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function n(){const v="less_";return{body:` + float ${v}(float a, float b) { return float(a < b); } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return vec4( v1.r < v2.r , v1.g < v2.g, v1.b < v2.b, v1.a < v2.a ); } - `,name:_,type:p.FunctionType.ValueBased}}function r(){const _="and_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function r(){const v="and_";return{body:` + float ${v}(float a, float b) { return float( bool(a) && bool(b) ); } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r && b2.r , @@ -627,11 +627,11 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ b1.b && b2.b, b1.a && b2.a ); } - `,name:_,type:p.FunctionType.ValueBased}}function a(){const _="or_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function a(){const v="or_";return{body:` + float ${v}(float a, float b) { return float( bool(a) || bool(b) ); } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r || b2.r , @@ -639,11 +639,11 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ b1.b || b2.b, b1.a || b2.a ); } - `,name:_,type:p.FunctionType.ValueBased}}function l(){const _="xor_";return{body:` - float ${_}(float a, float b) { + `,name:v,type:p.FunctionType.ValueBased}}function l(){const v="xor_";return{body:` + float ${v}(float a, float b) { return float( bool(a) ^^ bool(b) ); } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { bvec4 b1 = bvec4(v1); bvec4 b2 = bvec4(v2); return vec4( b1.r ^^ b2.r , @@ -651,18 +651,18 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ b1.b ^^ b2.b, b1.a ^^ b2.a ); } - `,name:_,type:p.FunctionType.ValueBased}}function d(){return function(_){const T=`${_}_`;return{body:` + `,name:v,type:p.FunctionType.ValueBased}}function d(){return function(v){const T=`${v}_`;return{body:` float ${T}(float a, float b) { - return ${_}(a, b); + return ${v}(a, b); } vec4 ${T}(vec4 v1, vec4 v2) { - return ${_}(v1, v2); + return ${v}(v1, v2); } - `,name:T,type:p.FunctionType.ValueBased}}("pow")}function m(){const _="prelu_";return{body:` - float ${_}(float a, float b) { + `,name:T,type:p.FunctionType.ValueBased}}("pow")}function m(){const v="prelu_";return{body:` + float ${v}(float a, float b) { return a < 0.0 ? a * b: a; } - vec4 ${_}(vec4 v1, vec4 v2) { + vec4 ${v}(vec4 v1, vec4 v2) { return vec4( v1.r < 0.0 ? v1.r * v2.r: v1.r, v1.g < 0.0 ? v1.g * v2.g: v1.g, @@ -670,7 +670,7 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ v1.a < 0.0 ? v1.a * v2.a: v1.a ); } - `,name:_,type:p.FunctionType.ValueBased}}u.glslAdd=c,u.glslDiv=f,u.glslMul=s,u.glslSub=i,u.glslEqual=t,u.glslGreater=e,u.glslLess=n,u.glslAnd=r,u.glslOr=a,u.glslXor=l,u.glslPow=d,u.glslPRelu=m;const y=(_,T,S,A=T[0].type,w)=>{const I=_.session.pack?o.TextureType.packed:o.TextureType.unpacked;return{name:S.name,inputNames:["A","B"],inputTypes:[I,I],cacheHint:w,get:()=>v(_,T,S,A)}},v=(_,T,S,A=T[0].type)=>{const w=_.session.pack?o.TextureType.packed:o.TextureType.unpacked,I=!g.ShapeUtil.areEqual(T[0].dims,T[1].dims);let R=T[0].dims;const B=_.session.pack;if(I){const W=g.BroadcastUtil.calcShape(T[0].dims,T[1].dims,!1);if(!W)throw new Error("Can't perform binary op on the given tensors");R=W;const k=R.length,V=T[0].dims.length!==0?T[0].dims.length:1,J=T[1].dims.length!==0?T[1].dims.length:1,Y=T[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",te=T[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",ne=(0,h.getGlsl)(_.session.backend.glContext.version),me=B?` + `,name:v,type:p.FunctionType.ValueBased}}u.glslAdd=c,u.glslDiv=f,u.glslMul=s,u.glslSub=i,u.glslEqual=t,u.glslGreater=e,u.glslLess=n,u.glslAnd=r,u.glslOr=a,u.glslXor=l,u.glslPow=d,u.glslPRelu=m;const y=(v,T,S,O=T[0].type,w)=>{const I=v.session.pack?o.TextureType.packed:o.TextureType.unpacked;return{name:S.name,inputNames:["A","B"],inputTypes:[I,I],cacheHint:w,get:()=>_(v,T,S,O)}},_=(v,T,S,O=T[0].type)=>{const w=v.session.pack?o.TextureType.packed:o.TextureType.unpacked,I=!g.ShapeUtil.areEqual(T[0].dims,T[1].dims);let R=T[0].dims;const B=v.session.pack;if(I){const W=g.BroadcastUtil.calcShape(T[0].dims,T[1].dims,!1);if(!W)throw new Error("Can't perform binary op on the given tensors");R=W;const k=R.length,V=T[0].dims.length!==0?T[0].dims.length:1,J=T[1].dims.length!==0?T[1].dims.length:1,Y=T[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",te=T[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",ne=(0,h.getGlsl)(v.session.backend.glContext.version),me=B?` ${S.body} void main() { vec4 a = getAAtOutCoords(); @@ -685,7 +685,7 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ ${Y} ${te} return ${S.name}(_A(aindices), _B(bindices)); - }`;return{name:S.name,inputNames:["A","B"],inputTypes:[w,w],output:{dims:R,type:A,textureType:w},shaderSource:me,hasMain:B}}const j=(0,h.getGlsl)(_.session.backend.glContext.version),N=` + }`;return{name:S.name,inputNames:["A","B"],inputTypes:[w,w],output:{dims:R,type:O,textureType:w},shaderSource:me,hasMain:B}}const j=(0,h.getGlsl)(v.session.backend.glContext.version),N=` ${S.body} void main() { vec4 v1 = ${j.texture2D}(A, TexCoords); @@ -693,7 +693,7 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ vec4 result = ${S.name}(v1, v2); ${j.output} = result; } - `;return{name:S.name,inputNames:["A","B"],inputTypes:[w,w],output:{dims:T[0].dims,type:A,textureType:w},shaderSource:N,hasMain:!0}};u.add=(_,T)=>[_.run(y(_,T,c()),T)],u.and=(_,T)=>[_.run(y(_,T,r(),"bool"),T)],u.div=(_,T)=>[_.run(y(_,T,f()),T)],u.equal=(_,T)=>[_.run(y(_,T,t(),"bool"),T)],u.greater=(_,T)=>[_.run(y(_,T,e(),"bool"),T)],u.less=(_,T)=>[_.run(y(_,T,n(),"bool"),T)],u.mul=(_,T)=>[_.run(y(_,T,s()),T)],u.or=(_,T)=>[_.run(y(_,T,a(),"bool"),T)],u.pow=(_,T)=>[_.run(y(_,T,d()),T)],u.pRelu=(_,T)=>[_.run(y(_,T,m()),T)],u.sub=(_,T)=>[_.run(y(_,T,i()),T)],u.xor=(_,T)=>[_.run(y(_,T,l(),"bool"),T)]},4196:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseCastAttributes=u.cast=void 0;const g=b(2517);u.cast=(h,o,c)=>(p(o),[h.cast(o[0],c)]),u.parseCastAttributes=h=>g.ProtoUtil.tensorDataTypeFromProto(h.attributes.getInt("to"));const p=h=>{if(!h||h.length!==1)throw new Error("Cast requires 1 input.");if(h[0].type==="string")throw new Error("Invalid input type.")}},1163:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackedConcatProgramInfoLoader=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827);u.createPackedConcatProgramInfoLoader=(f,s,i)=>{const t=(e=s.length,n=i.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:e},(r,a)=>`X${a}`),inputTypes:Array(e).fill(p.TextureType.packed),cacheHint:n});var e,n;return Object.assign(Object.assign({},t),{get:()=>((r,a,l,d)=>{const m=l[0].dims.slice();if(d>=m.length||d<-1*m.length)throw new Error("axis specified for concat doesn't match input dimensionality");d<0&&(d=m.length+d);const y=m.slice(0);for(let Y=1;YY.dims),w=(0,h.getGlChannels)(v),I=new Array(A.length-1);I[0]=A[0][d];for(let Y=1;Y[v.run(y(v,T,c()),T)],u.and=(v,T)=>[v.run(y(v,T,r(),"bool"),T)],u.div=(v,T)=>[v.run(y(v,T,f()),T)],u.equal=(v,T)=>[v.run(y(v,T,t(),"bool"),T)],u.greater=(v,T)=>[v.run(y(v,T,e(),"bool"),T)],u.less=(v,T)=>[v.run(y(v,T,n(),"bool"),T)],u.mul=(v,T)=>[v.run(y(v,T,s()),T)],u.or=(v,T)=>[v.run(y(v,T,a(),"bool"),T)],u.pow=(v,T)=>[v.run(y(v,T,d()),T)],u.pRelu=(v,T)=>[v.run(y(v,T,m()),T)],u.sub=(v,T)=>[v.run(y(v,T,i()),T)],u.xor=(v,T)=>[v.run(y(v,T,l(),"bool"),T)]},4196:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseCastAttributes=u.cast=void 0;const g=b(2517);u.cast=(h,o,c)=>(p(o),[h.cast(o[0],c)]),u.parseCastAttributes=h=>g.ProtoUtil.tensorDataTypeFromProto(h.attributes.getInt("to"));const p=h=>{if(!h||h.length!==1)throw new Error("Cast requires 1 input.");if(h[0].type==="string")throw new Error("Invalid input type.")}},1163:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackedConcatProgramInfoLoader=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827);u.createPackedConcatProgramInfoLoader=(f,s,i)=>{const t=(e=s.length,n=i.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:e},(r,a)=>`X${a}`),inputTypes:Array(e).fill(p.TextureType.packed),cacheHint:n});var e,n;return Object.assign(Object.assign({},t),{get:()=>((r,a,l,d)=>{const m=l[0].dims.slice();if(d>=m.length||d<-1*m.length)throw new Error("axis specified for concat doesn't match input dimensionality");d<0&&(d=m.length+d);const y=m.slice(0);for(let Y=1;YY.dims),w=(0,h.getGlChannels)(_),I=new Array(O.length-1);I[0]=O[0][d];for(let Y=1;Y{const t=f.indexOf(s);return f.map((e,n)=>n===t?`${e} - ${i}`:e).join()}},2069:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseConcatAttributes=u.concat=void 0;const g=b(246),p=b(2039),h=b(1163);u.concat=(e,n,r)=>(t(n),e.session.pack&&n[0].dims.length>1?[e.run((0,h.createPackedConcatProgramInfoLoader)(e,n,r),n)]:[e.run(o(e,n,r),n)]);const o=(e,n,r)=>{const a=(l=n.length,d=r.cacheKey,{name:"Concat",inputNames:Array.from({length:l},(m,y)=>`X${y}`),inputTypes:Array(l).fill(p.TextureType.unpacked),cacheHint:d});var l,d;return Object.assign(Object.assign({},a),{get:()=>((m,y,v,_)=>{const T=v[0].dims.slice();if(_>=T.length||_<-1*T.length)throw new Error("axis specified for concat doesn't match input dimensionality");_<0&&(_=T.length+_);const S=T.slice(0);for(let j=1;j{const t=f.indexOf(s);return f.map((e,n)=>n===t?`${e} - ${i}`:e).join()}},2069:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseConcatAttributes=u.concat=void 0;const g=b(246),p=b(2039),h=b(1163);u.concat=(e,n,r)=>(t(n),e.session.pack&&n[0].dims.length>1?[e.run((0,h.createPackedConcatProgramInfoLoader)(e,n,r),n)]:[e.run(o(e,n,r),n)]);const o=(e,n,r)=>{const a=(l=n.length,d=r.cacheKey,{name:"Concat",inputNames:Array.from({length:l},(m,y)=>`X${y}`),inputTypes:Array(l).fill(p.TextureType.unpacked),cacheHint:d});var l,d;return Object.assign(Object.assign({},a),{get:()=>((m,y,_,v)=>{const T=_[0].dims.slice();if(v>=T.length||v<-1*T.length)throw new Error("axis specified for concat doesn't match input dimensionality");v<0&&(v=T.length+v);const S=T.slice(0);for(let j=1;j<_.length;j++){const N=_[j].dims.slice();for(let W=0;W`int getTextureWhereDataResides(int index) { + }`;return Object.assign(Object.assign({},y),{output:{dims:S,type:_[0].type,textureType:p.TextureType.unpacked},shaderSource:B})})(0,a,n,r.axis)})},c=e=>`int getTextureWhereDataResides(int index) { ${e.map((n,r)=>`if(index<${n}) {return ${r};} `).join("")} }`,f=e=>c(e),s=(e,n)=>{const r=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${n}]) {`];for(let a=0;a{const n=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let r=0;r(0,g.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const t=e=>{if(!e||e.length<1)throw new Error("too few inputs");const n=e[0].type,r=e[0].dims.length;if(n==="string")throw new Error("string tensor is not supported yet");for(const a of e){if(a.type!==n)throw new Error("input tensors should be one type");if(a.dims.length!==r)throw new Error("input tensors should have the same shape")}}},4770:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createUnpackedGroupedConvProgramInfoLoader=void 0;const g=b(6231),p=b(5060),h=b(2039),o=b(8138),c=b(2823);u.createUnpackedGroupedConvProgramInfoLoader=(f,s,i)=>{const t=(e=s.length>2,n=i.cacheKey,{name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.unpacked],cacheHint:n});var e,n;return Object.assign(Object.assign({},t),{get:()=>((r,a,l,d)=>{const m=a.length>2?"value += getBias(output_channel);":"",y=a[0].dims.slice(),v=a[1].dims.slice(),_=v[0]/d.group;g.Logger.verbose("GroupedConv",`autpPad:${d.autoPad}, dilations:${d.dilations}, group:${d.group}, kernelShape:${d.kernelShape}, pads:${d.pads}, strides:${d.strides}`);const T=(0,o.calculateOutputShape)(y,v,d.dilations,d.pads,d.strides),S=(0,p.getGlsl)(r.session.backend.glContext.version),{activationFunction:A,applyActivation:w}=(0,c.getActivationSnippet)(d),I=` +`)};u.parseConcatAttributes=e=>(0,g.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const t=e=>{if(!e||e.length<1)throw new Error("too few inputs");const n=e[0].type,r=e[0].dims.length;if(n==="string")throw new Error("string tensor is not supported yet");for(const a of e){if(a.type!==n)throw new Error("input tensors should be one type");if(a.dims.length!==r)throw new Error("input tensors should have the same shape")}}},4770:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createUnpackedGroupedConvProgramInfoLoader=void 0;const g=b(6231),p=b(5060),h=b(2039),o=b(8138),c=b(2823);u.createUnpackedGroupedConvProgramInfoLoader=(f,s,i)=>{const t=(e=s.length>2,n=i.cacheKey,{name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.unpacked],cacheHint:n});var e,n;return Object.assign(Object.assign({},t),{get:()=>((r,a,l,d)=>{const m=a.length>2?"value += getBias(output_channel);":"",y=a[0].dims.slice(),_=a[1].dims.slice(),v=_[0]/d.group;g.Logger.verbose("GroupedConv",`autpPad:${d.autoPad}, dilations:${d.dilations}, group:${d.group}, kernelShape:${d.kernelShape}, pads:${d.pads}, strides:${d.strides}`);const T=(0,o.calculateOutputShape)(y,_,d.dilations,d.pads,d.strides),S=(0,p.getGlsl)(r.session.backend.glContext.version),{activationFunction:O,applyActivation:w}=(0,c.getActivationSnippet)(d),I=` const ivec2 strides = ivec2(${d.strides[0]}, ${d.strides[1]}); const ivec2 pads = ivec2(${d.pads[0]}, ${d.pads[1]}); - ${A} + ${O} void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int output_channel = coords.y; ivec2 xRCCorner = coords.zw * strides - pads; - int group_id = output_channel / ${_}; + int group_id = output_channel / ${v}; float value = 0.0; - for (int wInChannel = 0; wInChannel < ${v[1]}; wInChannel++) { - int input_channel = group_id * ${v[1]} + wInChannel; - for (int wHeight = 0; wHeight < ${v[2]}; wHeight++) { + for (int wInChannel = 0; wInChannel < ${_[1]}; wInChannel++) { + int input_channel = group_id * ${_[1]} + wInChannel; + for (int wHeight = 0; wHeight < ${_[2]}; wHeight++) { int xHeight = xRCCorner.x + wHeight * ${d.dilations[0]}; if (xHeight < 0 || xHeight >= ${y[2]}) { continue; } - for (int wWidth = 0; wWidth < ${v[3]}; wWidth++) { + for (int wWidth = 0; wWidth < ${_[3]}; wWidth++) { int xWidth = xRCCorner.y + wWidth * ${d.dilations[1]}; if (xWidth < 0 || xWidth >= ${y[3]}) { continue; @@ -789,7 +789,7 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ ${w} ${S.output} = vec4(value, .0, .0, .0); } -`;return Object.assign(Object.assign({},l),{output:{dims:T,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:I,hasMain:!0})})(f,s,t,i)})}},1386:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.conv2DPacked=u.conv2DPackedPointwise=void 0;const g=b(8138),p=b(8555),h=b(708);u.conv2DPackedPointwise=(o,c,f)=>{const s=c[0].dims,i=c[1].dims,t=(0,g.calculateOutputShape)(s,i,f.dilations,f.pads,f.strides),e=o.reshapePacked(c[0],[s[1],s[2]*s[3]]),n=o.reshapePacked(c[1],[i[0],i[1]]),r=c.length>2?[n,e,c[2]]:[n,e],a=o.run((0,h.createPackedMatmulProgramInfoLoader)(o,r,f),r);return o.reshapePacked(a,t)},u.conv2DPacked=(o,c,f)=>{const s=c[0].dims,i=c[1].dims,t=(0,g.calculateOutputShape)(s,i,f.dilations,f.pads,f.strides),e=o.run((0,p.createPackedIm2ColProgramInfoLoader)(o,c[0],c[1],t,f),[c[0]]),n=o.reshapePacked(c[1],[i[0],i[1]*i[2]*i[3]]),r=c.length===3?[n,e,c[2]]:[n,e],a=o.run((0,h.createPackedMatmulProgramInfoLoader)(o,r,f),r);return o.reshapePacked(a,t)}},9663:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseConvTransposeAttributes=u.convTranspose=void 0;const g=b(246),p=b(5060),h=b(2039),o=b(2823),c=(n,r,a,l,d,m)=>(n-1)*r+a+(l-1)*d+1-m,f=(n,r,a,l,d)=>{const m=Math.floor(n/2);r==="SAME_UPPER"?(a[l]=m,a[d]=n-m):r==="SAME_LOWER"&&(a[l]=n-m,a[d]=m)};u.convTranspose=(n,r,a)=>(e(r,a),s(n,r,a));const s=(n,r,a)=>{const l=t(a,r);return[i(n,r,l)]},i=(n,r,a)=>n.run(((l,d,m)=>{const y=(v=d.length>2,_=m.cacheKey,{name:"ConvTranspose",inputNames:v?["X","W","B"]:["X","W"],inputTypes:v?[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.unpacked],cacheHint:_});var v,_;return Object.assign(Object.assign({},y),{get:()=>((T,S,A,w)=>{const I=S.length>2?"getB(output_channel)":"0.0",R=S[0].dims,B=S[1].dims,j=B[1],N=B[0]/w.group,W=[S[0].dims[0],S[1].dims[1]*w.group,...w.outputShape],k=(0,p.getGlsl)(T.session.backend.glContext.version),{activationFunction:V,applyActivation:J}=(0,o.getActivationSnippet)(w),Y=` +`;return Object.assign(Object.assign({},l),{output:{dims:T,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:I,hasMain:!0})})(f,s,t,i)})}},1386:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.conv2DPacked=u.conv2DPackedPointwise=void 0;const g=b(8138),p=b(8555),h=b(708);u.conv2DPackedPointwise=(o,c,f)=>{const s=c[0].dims,i=c[1].dims,t=(0,g.calculateOutputShape)(s,i,f.dilations,f.pads,f.strides),e=o.reshapePacked(c[0],[s[1],s[2]*s[3]]),n=o.reshapePacked(c[1],[i[0],i[1]]),r=c.length>2?[n,e,c[2]]:[n,e],a=o.run((0,h.createPackedMatmulProgramInfoLoader)(o,r,f),r);return o.reshapePacked(a,t)},u.conv2DPacked=(o,c,f)=>{const s=c[0].dims,i=c[1].dims,t=(0,g.calculateOutputShape)(s,i,f.dilations,f.pads,f.strides),e=o.run((0,p.createPackedIm2ColProgramInfoLoader)(o,c[0],c[1],t,f),[c[0]]),n=o.reshapePacked(c[1],[i[0],i[1]*i[2]*i[3]]),r=c.length===3?[n,e,c[2]]:[n,e],a=o.run((0,h.createPackedMatmulProgramInfoLoader)(o,r,f),r);return o.reshapePacked(a,t)}},9663:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseConvTransposeAttributes=u.convTranspose=void 0;const g=b(246),p=b(5060),h=b(2039),o=b(2823),c=(n,r,a,l,d,m)=>(n-1)*r+a+(l-1)*d+1-m,f=(n,r,a,l,d)=>{const m=Math.floor(n/2);r==="SAME_UPPER"?(a[l]=m,a[d]=n-m):r==="SAME_LOWER"&&(a[l]=n-m,a[d]=m)};u.convTranspose=(n,r,a)=>(e(r,a),s(n,r,a));const s=(n,r,a)=>{const l=t(a,r);return[i(n,r,l)]},i=(n,r,a)=>n.run(((l,d,m)=>{const y=(_=d.length>2,v=m.cacheKey,{name:"ConvTranspose",inputNames:_?["X","W","B"]:["X","W"],inputTypes:_?[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.unpacked],cacheHint:v});var _,v;return Object.assign(Object.assign({},y),{get:()=>((T,S,O,w)=>{const I=S.length>2?"getB(output_channel)":"0.0",R=S[0].dims,B=S[1].dims,j=B[1],N=B[0]/w.group,W=[S[0].dims[0],S[1].dims[1]*w.group,...w.outputShape],k=(0,p.getGlsl)(T.session.backend.glContext.version),{activationFunction:V,applyActivation:J}=(0,o.getActivationSnippet)(w),Y=` const ivec2 strides = ivec2(${w.strides[0]}, ${w.strides[1]}); const ivec2 pads = ivec2(${w.pads[0]}, ${w.pads[1]}); ${V} @@ -826,7 +826,7 @@ import{bL as getAugmentedNamespace}from"./index-BQKiy4UR.js";var dist={},ortWeb_ ${J} ${k.output} = vec4(value, .0, .0, .0); } -`;return Object.assign(Object.assign({},A),{output:{dims:W,type:S[0].type,textureType:h.TextureType.unpacked},shaderSource:Y,hasMain:!0})})(l,d,y,m)})})(n,r,a),r),t=(n,r)=>{const a=n.kernelShape.slice();if(n.kernelShape.length===0)for(let y=2;y{const R=y.length-2,B=I.length===0;for(let j=0;j{const r=n.attributes,a=(0,o.parseInternalActivationAttributes)(r),l=r.getString("auto_pad","NOTSET"),d=r.getInts("dilations",[1,1]),m=r.getInt("group",1),y=r.getInts("kernel_shape",[]),v=r.getInts("output_padding",[0,0]),_=r.getInts("output_shape",[]),T=r.getInts("pads",[0,0,0,0]),S=r.getInts("strides",[1,1]);return(0,g.createAttributeWithCacheKey)(Object.assign({autoPad:l,dilations:d,group:m,kernelShape:y,outputPadding:v,outputShape:_,pads:T,strides:S},a))};const e=(n,r)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4||n[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(n[0].dims[1]!==n[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const a=n[1].dims[1]*r.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==a))throw new Error("invalid bias");const l=n[0].dims.length-2;if(r.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(r.strides.length!==l)throw new Error(`strides should be ${l}D`);if(r.pads.length!==2*l)throw new Error(`pads should be ${2*l}D`);if(r.outputPadding.length!==l)throw new Error(`output_padding should be ${l}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape");if(n[0].type!=="float32"||n[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(n.length===3&&n[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseConvAttributes=u.conv=u.calculateOutputShape=void 0;const g=b(246),p=b(2517),h=b(4770),o=b(1386),c=b(9828),f=b(2823),s=b(3248),i=b(5623);u.calculateOutputShape=(l,d,m,y,v)=>{const _=l[0],T=l.slice(2),S=T.length,A=d[0],w=d.slice(2).map((R,B)=>R+(R-1)*(m[B]-1)),I=T.map((R,B)=>R+y[B]+y[B+S]).map((R,B)=>Math.floor((R-w[B]+v[B])/v[B]));return[_,A].concat(...I)},u.conv=(l,d,m)=>(a(d,m),t(l,d,m));const t=(l,d,m)=>{const y=r(m,d),v=l.session.pack,_=y.kernelShape[0]===1&&y.kernelShape[1]===1;return y.group>1?[l.run((0,h.createUnpackedGroupedConvProgramInfoLoader)(l,d,y),d)]:_&&v?[e(l,d,y)]:v&&d[0].dims.length===4&&d[0].dims[0]===1&&!_?[(0,o.conv2DPacked)(l,d,y)]:[n(l,d,y)]},e=(l,d,m)=>{const y=d[0].dims,v=d[1].dims,_=(0,u.calculateOutputShape)(y,v,m.dilations,m.pads,m.strides),T=l.reshapeUnpacked(d[0],[y[1],y[2]*y[3]]),S=l.reshapeUnpacked(d[1],[v[0],v[1]]),A=d.length>2?[S,T,d[2]]:[S,T],w=l.run((0,i.createMatmulProgramInfoLoader)(A,m),A);return l.reshapeUnpacked(w,_)},n=(l,d,m)=>{const y=d[0].dims,v=d[1].dims,_=(0,u.calculateOutputShape)(y,v,m.dilations,m.pads,m.strides),T=l.run((0,s.createIm2ColProgramInfoLoader)(l,d[0],d[1],_,m),[d[0]]),S=d.length===3?[T,d[1],d[2]]:[T,d[1]];return l.run((0,c.createDotProductProgramInfoLoader)(l,d,_,m),S)},r=(l,d)=>{const m=l.kernelShape.slice();if(l.kernelShape.length===0)for(let _=2;_{const d=l.attributes,m=(0,f.parseInternalActivationAttributes)(d),y=d.getString("auto_pad","NOTSET"),v=d.getInts("dilations",[1,1]),_=d.getInt("group",1),T=d.getInts("kernel_shape",[]),S=d.getInts("pads",[0,0,0,0]),A=d.getInts("strides",[1,1]);return(0,g.createAttributeWithCacheKey)(Object.assign({autoPad:y,dilations:v,group:_,kernelShape:T,pads:S,strides:A},m))};const a=(l,d)=>{if(!l||l.length!==2&&l.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(l[0].dims.length!==4||l[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(l[0].dims[1]!==l[1].dims[1]*d.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(l.length===3&&(l[2].dims.length!==1||l[1].dims[0]!==l[2].dims[0]))throw new Error("invalid bias");const m=l[0].dims.length-2;if(d.dilations.length!==m)throw new Error(`dilations should be ${m}D`);if(d.strides.length!==m)throw new Error(`strides should be ${m}D`);if(d.pads.length!==2*m)throw new Error(`pads should be ${2*m}D`);if(d.kernelShape.length!==0&&d.kernelShape.length!==l[1].dims.length-2)throw new Error("invalid kernel shape");if(l[0].type!=="float32"||l[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(l.length===3&&l[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}},5193:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseDepthToSpaceAttributes=u.depthToSpace=void 0;const g=b(3738);u.depthToSpace=(h,o,c)=>{p(o);const f=c.blocksize,s=f*f,i=c.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],t=c.mode==="DCR"?[o[0].dims[0],f,f,o[0].dims[1]/s,o[0].dims[2],o[0].dims[3]]:[o[0].dims[0],o[0].dims[1]/s,f,f,o[0].dims[2],o[0].dims[3]],e=h.reshapeUnpacked(o[0],t),n={perm:i,cacheKey:`${i}`},[r]=(0,g.transpose)(h,[e],n),a=[o[0].dims[0],o[0].dims[1]/s,o[0].dims[2]*f,o[0].dims[3]*f];return[h.reshapeUnpacked(r,a)]},u.parseDepthToSpaceAttributes=h=>{const o=h.attributes.getInt("blocksize");if(o<1)throw new Error(`blocksize must be >= 1, but got : ${o} for DepthToSpace`);const c=h.attributes.getString("mode","DCR");if(c!=="DCR"&&c!=="CRD")throw new Error(`unrecognized mode: ${c} for DepthToSpace`);return{mode:c,blocksize:o}};const p=h=>{if(h.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${h.length}`);if(h[0].type==="string"||h[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createDotProductProgramInfoLoader=void 0;const g=b(2517),p=b(5060),h=b(2039),o=b(2823),c=b(3248);u.createDotProductProgramInfoLoader=(f,s,i,t)=>{const e=((n,r)=>({name:"ConvDotProduct",inputNames:n?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:n?[h.TextureType.unpacked,h.TextureType.packedLastDimension,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.packedLastDimension],cacheKey:r.activationCacheKey}))(s.length>2,t);return Object.assign(Object.assign({},e),{get:()=>((n,r,a,l,d)=>{const m=a[0].dims,y=a[1].dims,v=[y[0],Math.ceil(m[1]*y[2]*y[3]/4)],_=(0,c.calculateIm2ColDims)(m,y,l),[T,S]=n.calculateTextureWidthAndHeight(v,h.TextureType.packedLastDimension),A=g.ShapeUtil.computeStrides(_),[w,I]=n.calculateTextureWidthAndHeight(_,h.TextureType.packedLastDimension),R=l.length,B=a.length<3?"0.0":"_B(b)",j=Math.ceil(m[1]*y[2]*y[3]/4),{activationFunction:N,applyActivation:W}=(0,o.getActivationSnippet)(d),k=(0,p.getGlsl)(n.session.backend.glContext.version),V=` +`;return Object.assign(Object.assign({},O),{output:{dims:W,type:S[0].type,textureType:h.TextureType.unpacked},shaderSource:Y,hasMain:!0})})(l,d,y,m)})})(n,r,a),r),t=(n,r)=>{const a=n.kernelShape.slice();if(n.kernelShape.length===0)for(let y=2;y{const R=y.length-2,B=I.length===0;for(let j=0;j{const r=n.attributes,a=(0,o.parseInternalActivationAttributes)(r),l=r.getString("auto_pad","NOTSET"),d=r.getInts("dilations",[1,1]),m=r.getInt("group",1),y=r.getInts("kernel_shape",[]),_=r.getInts("output_padding",[0,0]),v=r.getInts("output_shape",[]),T=r.getInts("pads",[0,0,0,0]),S=r.getInts("strides",[1,1]);return(0,g.createAttributeWithCacheKey)(Object.assign({autoPad:l,dilations:d,group:m,kernelShape:y,outputPadding:_,outputShape:v,pads:T,strides:S},a))};const e=(n,r)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4||n[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(n[0].dims[1]!==n[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const a=n[1].dims[1]*r.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==a))throw new Error("invalid bias");const l=n[0].dims.length-2;if(r.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(r.strides.length!==l)throw new Error(`strides should be ${l}D`);if(r.pads.length!==2*l)throw new Error(`pads should be ${2*l}D`);if(r.outputPadding.length!==l)throw new Error(`output_padding should be ${l}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape");if(n[0].type!=="float32"||n[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(n.length===3&&n[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseConvAttributes=u.conv=u.calculateOutputShape=void 0;const g=b(246),p=b(2517),h=b(4770),o=b(1386),c=b(9828),f=b(2823),s=b(3248),i=b(5623);u.calculateOutputShape=(l,d,m,y,_)=>{const v=l[0],T=l.slice(2),S=T.length,O=d[0],w=d.slice(2).map((R,B)=>R+(R-1)*(m[B]-1)),I=T.map((R,B)=>R+y[B]+y[B+S]).map((R,B)=>Math.floor((R-w[B]+_[B])/_[B]));return[v,O].concat(...I)},u.conv=(l,d,m)=>(a(d,m),t(l,d,m));const t=(l,d,m)=>{const y=r(m,d),_=l.session.pack,v=y.kernelShape[0]===1&&y.kernelShape[1]===1;return y.group>1?[l.run((0,h.createUnpackedGroupedConvProgramInfoLoader)(l,d,y),d)]:v&&_?[e(l,d,y)]:_&&d[0].dims.length===4&&d[0].dims[0]===1&&!v?[(0,o.conv2DPacked)(l,d,y)]:[n(l,d,y)]},e=(l,d,m)=>{const y=d[0].dims,_=d[1].dims,v=(0,u.calculateOutputShape)(y,_,m.dilations,m.pads,m.strides),T=l.reshapeUnpacked(d[0],[y[1],y[2]*y[3]]),S=l.reshapeUnpacked(d[1],[_[0],_[1]]),O=d.length>2?[S,T,d[2]]:[S,T],w=l.run((0,i.createMatmulProgramInfoLoader)(O,m),O);return l.reshapeUnpacked(w,v)},n=(l,d,m)=>{const y=d[0].dims,_=d[1].dims,v=(0,u.calculateOutputShape)(y,_,m.dilations,m.pads,m.strides),T=l.run((0,s.createIm2ColProgramInfoLoader)(l,d[0],d[1],v,m),[d[0]]),S=d.length===3?[T,d[1],d[2]]:[T,d[1]];return l.run((0,c.createDotProductProgramInfoLoader)(l,d,v,m),S)},r=(l,d)=>{const m=l.kernelShape.slice();if(l.kernelShape.length===0)for(let v=2;v{const d=l.attributes,m=(0,f.parseInternalActivationAttributes)(d),y=d.getString("auto_pad","NOTSET"),_=d.getInts("dilations",[1,1]),v=d.getInt("group",1),T=d.getInts("kernel_shape",[]),S=d.getInts("pads",[0,0,0,0]),O=d.getInts("strides",[1,1]);return(0,g.createAttributeWithCacheKey)(Object.assign({autoPad:y,dilations:_,group:v,kernelShape:T,pads:S,strides:O},m))};const a=(l,d)=>{if(!l||l.length!==2&&l.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(l[0].dims.length!==4||l[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(l[0].dims[1]!==l[1].dims[1]*d.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(l.length===3&&(l[2].dims.length!==1||l[1].dims[0]!==l[2].dims[0]))throw new Error("invalid bias");const m=l[0].dims.length-2;if(d.dilations.length!==m)throw new Error(`dilations should be ${m}D`);if(d.strides.length!==m)throw new Error(`strides should be ${m}D`);if(d.pads.length!==2*m)throw new Error(`pads should be ${2*m}D`);if(d.kernelShape.length!==0&&d.kernelShape.length!==l[1].dims.length-2)throw new Error("invalid kernel shape");if(l[0].type!=="float32"||l[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(l.length===3&&l[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}},5193:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseDepthToSpaceAttributes=u.depthToSpace=void 0;const g=b(3738);u.depthToSpace=(h,o,c)=>{p(o);const f=c.blocksize,s=f*f,i=c.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],t=c.mode==="DCR"?[o[0].dims[0],f,f,o[0].dims[1]/s,o[0].dims[2],o[0].dims[3]]:[o[0].dims[0],o[0].dims[1]/s,f,f,o[0].dims[2],o[0].dims[3]],e=h.reshapeUnpacked(o[0],t),n={perm:i,cacheKey:`${i}`},[r]=(0,g.transpose)(h,[e],n),a=[o[0].dims[0],o[0].dims[1]/s,o[0].dims[2]*f,o[0].dims[3]*f];return[h.reshapeUnpacked(r,a)]},u.parseDepthToSpaceAttributes=h=>{const o=h.attributes.getInt("blocksize");if(o<1)throw new Error(`blocksize must be >= 1, but got : ${o} for DepthToSpace`);const c=h.attributes.getString("mode","DCR");if(c!=="DCR"&&c!=="CRD")throw new Error(`unrecognized mode: ${c} for DepthToSpace`);return{mode:c,blocksize:o}};const p=h=>{if(h.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${h.length}`);if(h[0].type==="string"||h[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createDotProductProgramInfoLoader=void 0;const g=b(2517),p=b(5060),h=b(2039),o=b(2823),c=b(3248);u.createDotProductProgramInfoLoader=(f,s,i,t)=>{const e=((n,r)=>({name:"ConvDotProduct",inputNames:n?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:n?[h.TextureType.unpacked,h.TextureType.packedLastDimension,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.packedLastDimension],cacheKey:r.activationCacheKey}))(s.length>2,t);return Object.assign(Object.assign({},e),{get:()=>((n,r,a,l,d)=>{const m=a[0].dims,y=a[1].dims,_=[y[0],Math.ceil(m[1]*y[2]*y[3]/4)],v=(0,c.calculateIm2ColDims)(m,y,l),[T,S]=n.calculateTextureWidthAndHeight(_,h.TextureType.packedLastDimension),O=g.ShapeUtil.computeStrides(v),[w,I]=n.calculateTextureWidthAndHeight(v,h.TextureType.packedLastDimension),R=l.length,B=a.length<3?"0.0":"_B(b)",j=Math.ceil(m[1]*y[2]*y[3]/4),{activationFunction:N,applyActivation:W}=(0,o.getActivationSnippet)(d),k=(0,p.getGlsl)(n.session.backend.glContext.version),V=` ${N} float process(int indices[${R}]) { int b[1]; @@ -835,8 +835,8 @@ float process(int indices[${R}]) { im2col[0] = indices[0]; im2col[1] = indices[2]; im2col[2] = indices[3]; - int im2colOffset = im2col[0] * ${A[0]} + im2col[1] * ${A[1]} + im2col[2] * ${A[2]}; - int kernelOffset = indices[1] * ${v[1]}; + int im2colOffset = im2col[0] * ${O[0]} + im2col[1] * ${O[1]} + im2col[2] * ${O[2]}; + int kernelOffset = indices[1] * ${_[1]}; float value = ${B}; for (int i = 0; i < ${j}; ++i) { vec2 im2colCoords = offsetToCoords(im2colOffset, ${w}, ${I}); @@ -847,20 +847,20 @@ float process(int indices[${R}]) { } ${W} return value; -}`;return Object.assign(Object.assign({},r),{output:{dims:l,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:V})})(f,e,s,i,t)})}},7992:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseFlattenAttributes=u.flatten=void 0;const g=b(2517);u.flatten=(h,o,c)=>{p(o,c);const f=g.ShapeUtil.flattenShape(o[0].dims,c);return[h.reshapeUnpacked(o[0],f)]},u.parseFlattenAttributes=h=>h.attributes.getInt("axis",1);const p=(h,o)=>{if(!h||h.length!==1)throw new Error("Flatten requires 1 input.");const c=h[0].dims.length;if(c===0)throw new Error("scalar tensor is not supported.");if(o<-c||o>c)throw new Error("Invalid axis");if(h[0].type==="string")throw new Error("string tensor is not supported.")}},2823:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseInternalActivationAttributes=u.getActivationSnippet=void 0;const g=b(2517),p=b(4909);u.getActivationSnippet=function(h){let o;switch(h.activation){case"Relu":o=(0,p.glslRelu)();break;case"Sigmoid":o=(0,p.glslSigmoid)();break;case"Clip":o=(0,p.glslClip)(h.clipMin,h.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const c=o.name;return{activationFunction:o.body,applyActivation:`value = ${c}_(value);`}},u.parseInternalActivationAttributes=h=>{const o=h.getString("activation","");if(o==="Clip"){const[c,f]=h.getFloats("activation_params",[g.MIN_CLIP,g.MAX_CLIP]);return{activation:o,clipMax:f,clipMin:c,activationCacheKey:`${o}:${c},${f}`}}return{activation:o,activationCacheKey:o}}},1253:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseGatherAttributes=u.gather=void 0;const g=b(246),p=b(782),h=b(2517),o=b(2039);u.gather=(i,t,e)=>(s(t,e.axis),[i.run(f(i,t,e),t)]),u.parseGatherAttributes=i=>(0,g.createAttributeWithCacheKey)({axis:i.attributes.getInt("axis",0)});const c={name:"Gather",inputNames:["A","B"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked]},f=(i,t,e)=>{const n=Object.assign(Object.assign({},c),{cacheHint:e.cacheKey});return Object.assign(Object.assign({},n),{get:()=>((r,a,l,d)=>{const m=l[0].dims.slice(),y=l[1].dims.slice(),v=new Array(m.length+y.length-1);d=h.ShapeUtil.normalizeAxis(d,m.length);const _=[];for(let S=0;S{Object.defineProperty(u,"__esModule",{value:!0}),u.parseFlattenAttributes=u.flatten=void 0;const g=b(2517);u.flatten=(h,o,c)=>{p(o,c);const f=g.ShapeUtil.flattenShape(o[0].dims,c);return[h.reshapeUnpacked(o[0],f)]},u.parseFlattenAttributes=h=>h.attributes.getInt("axis",1);const p=(h,o)=>{if(!h||h.length!==1)throw new Error("Flatten requires 1 input.");const c=h[0].dims.length;if(c===0)throw new Error("scalar tensor is not supported.");if(o<-c||o>c)throw new Error("Invalid axis");if(h[0].type==="string")throw new Error("string tensor is not supported.")}},2823:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseInternalActivationAttributes=u.getActivationSnippet=void 0;const g=b(2517),p=b(4909);u.getActivationSnippet=function(h){let o;switch(h.activation){case"Relu":o=(0,p.glslRelu)();break;case"Sigmoid":o=(0,p.glslSigmoid)();break;case"Clip":o=(0,p.glslClip)(h.clipMin,h.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const c=o.name;return{activationFunction:o.body,applyActivation:`value = ${c}_(value);`}},u.parseInternalActivationAttributes=h=>{const o=h.getString("activation","");if(o==="Clip"){const[c,f]=h.getFloats("activation_params",[g.MIN_CLIP,g.MAX_CLIP]);return{activation:o,clipMax:f,clipMin:c,activationCacheKey:`${o}:${c},${f}`}}return{activation:o,activationCacheKey:o}}},1253:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseGatherAttributes=u.gather=void 0;const g=b(246),p=b(782),h=b(2517),o=b(2039);u.gather=(i,t,e)=>(s(t,e.axis),[i.run(f(i,t,e),t)]),u.parseGatherAttributes=i=>(0,g.createAttributeWithCacheKey)({axis:i.attributes.getInt("axis",0)});const c={name:"Gather",inputNames:["A","B"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked]},f=(i,t,e)=>{const n=Object.assign(Object.assign({},c),{cacheHint:e.cacheKey});return Object.assign(Object.assign({},n),{get:()=>((r,a,l,d)=>{const m=l[0].dims.slice(),y=l[1].dims.slice(),_=new Array(m.length+y.length-1);d=h.ShapeUtil.normalizeAxis(d,m.length);const v=[];for(let S=0;S<_.length;S++)S{if(!i||i.length!==2)throw new Error("Gather requires 2 inputs.");const e=i[0].dims.length;if(e<1)throw new Error("Invalid input shape.");if(t<-e||t>e-1)throw new Error("Invalid axis.");if(p.NUMBER_TYPES.indexOf(i[0].type)===-1)throw new Error("Invaid input type.");if(i[1].type!=="int32"&&i[1].type!=="int16")throw new Error("Invaid input type.")}},4776:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseGemmAttributesV11=u.parseGemmAttributesV7=u.gemm=void 0;const g=b(246),p=b(2517),h=b(2039);u.gemm=(i,t,e)=>(s(t,e),[i.run(c(t,e),t)]);const o=(i,t)=>{const e=i.attributes.getInt("transA",0)!==0,n=i.attributes.getInt("transB",0)!==0,r=i.attributes.getFloat("alpha",1),a=i.attributes.getFloat("beta",1);return(0,g.createAttributeWithCacheKey)({transA:e,transB:n,alpha:r,beta:a,isOptionalC:t})};u.parseGemmAttributesV7=i=>o(i,!1),u.parseGemmAttributesV11=i=>o(i,!0);const c=(i,t)=>{const e={name:"Gemm",inputNames:i.length===3?["A","B","C"]:["A","B"],inputTypes:i.length===3?[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},e),{get:()=>f(e,i,t)})},f=(i,t,e)=>{const n=t[0].dims.slice(),r=t[1].dims.slice(),[a,l]=p.GemmUtil.getShapeOfGemmResult(n,e.transA,r,e.transB,t.length===3?t[2].dims:void 0),d=[a,l];if(!d)throw new Error("Can't use gemm on the given tensors");let m=n[n.length-1],y="";e.transA&&(m=n[0]),e.transA&&e.transB?y="value += _A_T(a) * _B_T(b);":e.transA&&!e.transB?y="value += _A_T(a) * _B(b);":!e.transA&&e.transB?y="value += _A(a) * _B_T(b);":e.transA||e.transB||(y="value += _A(a) * _B(b);");const v=d.length,_=` - float process(int indices[${v}]) { - int a[${v}]; - int b[${v}]; + }`;return Object.assign(Object.assign({},a),{output:{dims:_,type:l[0].type,textureType:o.TextureType.unpacked},shaderSource:T})})(0,n,t,e.axis)})},s=(i,t)=>{if(!i||i.length!==2)throw new Error("Gather requires 2 inputs.");const e=i[0].dims.length;if(e<1)throw new Error("Invalid input shape.");if(t<-e||t>e-1)throw new Error("Invalid axis.");if(p.NUMBER_TYPES.indexOf(i[0].type)===-1)throw new Error("Invaid input type.");if(i[1].type!=="int32"&&i[1].type!=="int16")throw new Error("Invaid input type.")}},4776:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseGemmAttributesV11=u.parseGemmAttributesV7=u.gemm=void 0;const g=b(246),p=b(2517),h=b(2039);u.gemm=(i,t,e)=>(s(t,e),[i.run(c(t,e),t)]);const o=(i,t)=>{const e=i.attributes.getInt("transA",0)!==0,n=i.attributes.getInt("transB",0)!==0,r=i.attributes.getFloat("alpha",1),a=i.attributes.getFloat("beta",1);return(0,g.createAttributeWithCacheKey)({transA:e,transB:n,alpha:r,beta:a,isOptionalC:t})};u.parseGemmAttributesV7=i=>o(i,!1),u.parseGemmAttributesV11=i=>o(i,!0);const c=(i,t)=>{const e={name:"Gemm",inputNames:i.length===3?["A","B","C"]:["A","B"],inputTypes:i.length===3?[h.TextureType.unpacked,h.TextureType.unpacked,h.TextureType.unpacked]:[h.TextureType.unpacked,h.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},e),{get:()=>f(e,i,t)})},f=(i,t,e)=>{const n=t[0].dims.slice(),r=t[1].dims.slice(),[a,l]=p.GemmUtil.getShapeOfGemmResult(n,e.transA,r,e.transB,t.length===3?t[2].dims:void 0),d=[a,l];if(!d)throw new Error("Can't use gemm on the given tensors");let m=n[n.length-1],y="";e.transA&&(m=n[0]),e.transA&&e.transB?y="value += _A_T(a) * _B_T(b);":e.transA&&!e.transB?y="value += _A_T(a) * _B(b);":!e.transA&&e.transB?y="value += _A(a) * _B_T(b);":e.transA||e.transB||(y="value += _A(a) * _B(b);");const _=d.length,v=` + float process(int indices[${_}]) { + int a[${_}]; + int b[${_}]; ${t.length===3?`int c[${t[2].dims.length}];`:""} copyVec(indices, a); @@ -869,27 +869,27 @@ float process(int indices[${R}]) { float value = 0.0; for (int k=0; k<${m}; ++k) { - a[${v-1}] = k; - b[${v-2}] = k; + a[${_-1}] = k; + b[${_-2}] = k; ${y} } value = value * alpha; ${t.length===3?"value += beta * _C(c);":""} return value; - }`;return Object.assign(Object.assign({},i),{output:{dims:d,type:t[0].type,textureType:h.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:e.alpha},{name:"beta",type:"float",data:e.beta}],shaderSource:_})},s=(i,t)=>{if(!i)throw new Error("Input is missing");if(t.isOptionalC&&(i.length<2||i.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&i.length!==3)throw new Error("Gemm requires 3 inputs");if(i.length===3&&i[2].dims.length!==1&&i[2].dims.length!==2)throw new Error("Invalid input shape of C");if(i[0].type!=="float32"&&i[0].type!=="float64"||i[1].type!=="float32"&&i[1].type!=="float64"||i.length===3&&i[2].type!=="float32"&&i[2].type!=="float64")throw new Error("Invalid input type.");if(i[0].type!==i[1].type||i.length===3&&i[0].type!==i[2].type)throw new Error("Input types are mismatched")}},8555:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackedIm2ColProgramInfoLoader=void 0;const g=b(5060),p=b(2039),h=b(2827);u.createPackedIm2ColProgramInfoLoader=(o,c,f,s,i)=>{const t=(e=i.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[p.TextureType.packed],cacheHint:e});var e;return Object.assign(Object.assign({},t),{get:()=>((n,r,a,l,d,m)=>{const y=a.dims,v=l.dims,_=d.length,T=[v[1]*v[2]*v[3],d[2]*d[3]],S=v[2]*v[3],A=(0,h.unpackFromChannel)(),w=(0,g.getGlsl)(n.session.backend.glContext.version);let I="";for(let B=0;B<=1;B++)for(let j=0;j<=1;j++)I+=` + }`;return Object.assign(Object.assign({},i),{output:{dims:d,type:t[0].type,textureType:h.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:e.alpha},{name:"beta",type:"float",data:e.beta}],shaderSource:v})},s=(i,t)=>{if(!i)throw new Error("Input is missing");if(t.isOptionalC&&(i.length<2||i.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&i.length!==3)throw new Error("Gemm requires 3 inputs");if(i.length===3&&i[2].dims.length!==1&&i[2].dims.length!==2)throw new Error("Invalid input shape of C");if(i[0].type!=="float32"&&i[0].type!=="float64"||i[1].type!=="float32"&&i[1].type!=="float64"||i.length===3&&i[2].type!=="float32"&&i[2].type!=="float64")throw new Error("Invalid input type.");if(i[0].type!==i[1].type||i.length===3&&i[0].type!==i[2].type)throw new Error("Input types are mismatched")}},8555:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackedIm2ColProgramInfoLoader=void 0;const g=b(5060),p=b(2039),h=b(2827);u.createPackedIm2ColProgramInfoLoader=(o,c,f,s,i)=>{const t=(e=i.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[p.TextureType.packed],cacheHint:e});var e;return Object.assign(Object.assign({},t),{get:()=>((n,r,a,l,d,m)=>{const y=a.dims,_=l.dims,v=d.length,T=[_[1]*_[2]*_[3],d[2]*d[3]],S=_[2]*_[3],O=(0,h.unpackFromChannel)(),w=(0,g.getGlsl)(n.session.backend.glContext.version);let I="";for(let B=0;B<=1;B++)for(let j=0;j<=1;j++)I+=` blockIndex = rc.x + ${j}; pos = rc.y + ${B}; if(blockIndex < ${T[1]} && pos < ${T[0]}) { - offsetY = int(blockIndex / (${d[_-1]})) * ${m.strides[0]} - + offsetY = int(blockIndex / (${d[v-1]})) * ${m.strides[0]} - ${m.pads[0]}; - d0 = offsetY + ${m.dilations[0]} * (imod(pos, ${S}) / ${v[2]}); + d0 = offsetY + ${m.dilations[0]} * (imod(pos, ${S}) / ${_[2]}); if(d0 < ${y[2]} && d0 >= 0) { - offsetX = imod(blockIndex, ${d[_-1]}) * ${m.strides[1]} - + offsetX = imod(blockIndex, ${d[v-1]}) * ${m.strides[1]} - ${m.pads[1]}; - d1 = offsetX + ${m.dilations[1]} * imod(imod(pos, ${S}), ${v[2]}); + d1 = offsetX + ${m.dilations[1]} * imod(imod(pos, ${S}), ${_[2]}); if(d1 < ${y[3]} && d1 >= 0) { @@ -903,7 +903,7 @@ float process(int indices[${R}]) { } `;const R=` - ${A} + ${O} void main() { ivec2 rc = getOutputCoords(); @@ -913,7 +913,7 @@ float process(int indices[${R}]) { ${I} ${w.output} = result; } - `;return Object.assign(Object.assign({},r),{output:{dims:T,type:a.type,textureType:p.TextureType.packed},shaderSource:R,hasMain:!0})})(o,t,c,f,s,i)})}},3248:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.calculateIm2ColDims=u.createIm2ColProgramInfoLoader=void 0;const g=b(2039);u.createIm2ColProgramInfoLoader=(p,h,o,c,f)=>{const s=(i=f.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[g.TextureType.unpacked],cacheHint:i});var i;return Object.assign(Object.assign({},s),{get:()=>((t,e,n,r,a,l)=>{const d=n.dims,m=r.dims,y=a.length,v=(0,u.calculateIm2ColDims)(d,m,a,4),_=` + `;return Object.assign(Object.assign({},r),{output:{dims:T,type:a.type,textureType:p.TextureType.packed},shaderSource:R,hasMain:!0})})(o,t,c,f,s,i)})}},3248:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.calculateIm2ColDims=u.createIm2ColProgramInfoLoader=void 0;const g=b(2039);u.createIm2ColProgramInfoLoader=(p,h,o,c,f)=>{const s=(i=f.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[g.TextureType.unpacked],cacheHint:i});var i;return Object.assign(Object.assign({},s),{get:()=>((t,e,n,r,a,l)=>{const d=n.dims,m=r.dims,y=a.length,_=(0,u.calculateIm2ColDims)(d,m,a,4),v=` const int XC = ${d[1]}; const int XH = ${d[2]}; const int XW = ${d[3]}; @@ -957,7 +957,7 @@ float process(int indices[${R}]) { } return value; } - `;return Object.assign(Object.assign({},e),{output:{dims:v,type:n.type,textureType:g.TextureType.packedLastDimension},shaderSource:_})})(0,s,h,o,c,f)})},u.calculateIm2ColDims=(p,h,o,c=4)=>[o[0],o[2],o[3],Math.ceil(p[1]*h[2]*h[3]/c)]},6572:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseImageScalerAttributes=u.imageScaler=void 0;const g=b(246),p=b(2039);u.imageScaler=(s,i,t)=>(f(i),[s.run(o(s,i,t),i)]),u.parseImageScalerAttributes=s=>{const i=s.attributes.getFloat("scale"),t=s.attributes.getFloats("bias");return(0,g.createAttributeWithCacheKey)({scale:i,bias:t})};const h={name:"ImageScaler",inputNames:["X"],inputTypes:[p.TextureType.unpacked]},o=(s,i,t)=>{const e=Object.assign(Object.assign({},h),{cacheHint:t.cacheKey});return Object.assign(Object.assign({},e),{get:()=>((n,r,a,l)=>{const d=a[0].dims.slice(),m=d.length,y=` + `;return Object.assign(Object.assign({},e),{output:{dims:_,type:n.type,textureType:g.TextureType.packedLastDimension},shaderSource:v})})(0,s,h,o,c,f)})},u.calculateIm2ColDims=(p,h,o,c=4)=>[o[0],o[2],o[3],Math.ceil(p[1]*h[2]*h[3]/c)]},6572:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseImageScalerAttributes=u.imageScaler=void 0;const g=b(246),p=b(2039);u.imageScaler=(s,i,t)=>(f(i),[s.run(o(s,i,t),i)]),u.parseImageScalerAttributes=s=>{const i=s.attributes.getFloat("scale"),t=s.attributes.getFloats("bias");return(0,g.createAttributeWithCacheKey)({scale:i,bias:t})};const h={name:"ImageScaler",inputNames:["X"],inputTypes:[p.TextureType.unpacked]},o=(s,i,t)=>{const e=Object.assign(Object.assign({},h),{cacheHint:t.cacheKey});return Object.assign(Object.assign({},e),{get:()=>((n,r,a,l)=>{const d=a[0].dims.slice(),m=d.length,y=` ${c(l.bias.length)} float process(int indices[${m}]) { return _X(indices) * scale + getBias(bias, indices[1]); @@ -991,11 +991,11 @@ float process(int indices[${R}]) { v.g = temp / float(${a}); return v; - }`;return Object.assign(Object.assign({},t),{output:{dims:l,type:e.type,textureType:p.TextureType.packedLastDimension},shaderSource:d})})(h,i)}),c={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[p.TextureType.unpacked,p.TextureType.packedLastDimension,p.TextureType.unpacked,p.TextureType.unpacked]},f=(i,t,e,n)=>{const r=Object.assign(Object.assign({},c),{cacheHint:`${e}`});return Object.assign(Object.assign({},r),{get:()=>((a,l,d,m,y)=>{const v=(0,g.getGlsl)(a.session.backend.glContext.version),[_,T]=a.calculateTextureWidthAndHeight(y,p.TextureType.packedLastDimension),[S,A]=[_/4,T],w=` + }`;return Object.assign(Object.assign({},t),{output:{dims:l,type:e.type,textureType:p.TextureType.packedLastDimension},shaderSource:d})})(h,i)}),c={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[p.TextureType.unpacked,p.TextureType.packedLastDimension,p.TextureType.unpacked,p.TextureType.unpacked]},f=(i,t,e,n)=>{const r=Object.assign(Object.assign({},c),{cacheHint:`${e}`});return Object.assign(Object.assign({},r),{get:()=>((a,l,d,m,y)=>{const _=(0,g.getGlsl)(a.session.backend.glContext.version),[v,T]=a.calculateTextureWidthAndHeight(y,p.TextureType.packedLastDimension),[S,O]=[v/4,T],w=` vec4 get_MeanAndVariance(int[2] mv) { int offset = indicesToOffset_MeanAndVariance(mv); - vec2 coords = offsetToCoords(offset, ${S}, ${A}); - return ${v.texture2D}(MeanAndVariance, coords); + vec2 coords = offsetToCoords(offset, ${S}, ${O}); + return ${_.texture2D}(MeanAndVariance, coords); } float process(int[4] indices) { @@ -1012,7 +1012,7 @@ float process(int indices[${R}]) { float b = _B(sb); return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; - }`;return Object.assign(Object.assign({},l),{output:{dims:d.dims,type:d.type,textureType:p.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:m}],shaderSource:w})})(i,r,t,e,n)})},s=i=>{if(!i||i.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");const t=i[0],e=i[1],n=i[2];if(t.dims.length<3||e.dims.length!==1||n.dims.length!==1)throw new Error("Invalid input shape.");if(e.dims[0]!==t.dims[1]||n.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||n.type!=="float32"&&n.type!=="float64")throw new Error("Invalid input type.");if(i[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}},708:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackedMatmulProgramInfoLoader=void 0;const g=b(2517),p=b(5060),h=b(2039),o=b(9390),c=b(2823),f=b(5623);u.createPackedMatmulProgramInfoLoader=(s,i,t)=>{const e=(n=i.length>2,r=t.activationCacheKey,{name:"MatMul (packed)",inputNames:n?["A","B","Bias"]:["A","B"],inputTypes:n?[h.TextureType.packed,h.TextureType.packed,h.TextureType.packed]:[h.TextureType.packed,h.TextureType.packed],cacheHint:r});var n,r;return Object.assign(Object.assign({},e),{get:()=>((a,l,d,m)=>{const y=d.length>2,v=y?"value += getBiasForMatmul();":"",_=d[0].dims,T=d[1].dims,S=g.BroadcastUtil.calcShape(_,T,!0),A=!g.ShapeUtil.areEqual(d[0].dims,d[1].dims);if(!S)throw new Error("Can't use matmul on the given tensors");const w=_[_.length-1],I=Math.ceil(w/2),R=_.length,B=T.length,j=(0,p.getGlsl)(a.session.backend.glContext.version),N=(0,o.getCoordsDataType)(S.length),W=S.length,k=(0,o.getGlChannels)(),{activationFunction:V,applyActivation:J}=(0,c.getActivationSnippet)(m),Y=y?`${(0,f.getBiasForMatmul)(N,k,d[2].dims,S,!0)}`:"",te=A?`${function(Oe,le,xe,_e){let Ne=[],He=[];const Ae=xe[0].dims,Ce=xe[1].dims,Fe=Ae.length,Ee=Ce.length,we=_e.length,je=we-Fe,Ue=we-Ee;Ne=Ae.map((Se,Me)=>`coords.${le[Me+je]}`),Ne[Fe-1]="i*2",Ne.join(", "),He=Ce.map((Se,Me)=>`coords.${le[Me+Ue]}`),He[Ee-2]="i*2",He.join(", ");const Be=g.BroadcastUtil.getBroadcastDims(Ae,_e),We=g.BroadcastUtil.getBroadcastDims(Ce,_e),Ke=Be.map(Se=>`coords.${le[Se+je]} = 0;`).join(` + }`;return Object.assign(Object.assign({},l),{output:{dims:d.dims,type:d.type,textureType:p.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:m}],shaderSource:w})})(i,r,t,e,n)})},s=i=>{if(!i||i.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");const t=i[0],e=i[1],n=i[2];if(t.dims.length<3||e.dims.length!==1||n.dims.length!==1)throw new Error("Invalid input shape.");if(e.dims[0]!==t.dims[1]||n.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||n.type!=="float32"&&n.type!=="float64")throw new Error("Invalid input type.");if(i[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}},708:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackedMatmulProgramInfoLoader=void 0;const g=b(2517),p=b(5060),h=b(2039),o=b(9390),c=b(2823),f=b(5623);u.createPackedMatmulProgramInfoLoader=(s,i,t)=>{const e=(n=i.length>2,r=t.activationCacheKey,{name:"MatMul (packed)",inputNames:n?["A","B","Bias"]:["A","B"],inputTypes:n?[h.TextureType.packed,h.TextureType.packed,h.TextureType.packed]:[h.TextureType.packed,h.TextureType.packed],cacheHint:r});var n,r;return Object.assign(Object.assign({},e),{get:()=>((a,l,d,m)=>{const y=d.length>2,_=y?"value += getBiasForMatmul();":"",v=d[0].dims,T=d[1].dims,S=g.BroadcastUtil.calcShape(v,T,!0),O=!g.ShapeUtil.areEqual(d[0].dims,d[1].dims);if(!S)throw new Error("Can't use matmul on the given tensors");const w=v[v.length-1],I=Math.ceil(w/2),R=v.length,B=T.length,j=(0,p.getGlsl)(a.session.backend.glContext.version),N=(0,o.getCoordsDataType)(S.length),W=S.length,k=(0,o.getGlChannels)(),{activationFunction:V,applyActivation:J}=(0,c.getActivationSnippet)(m),Y=y?`${(0,f.getBiasForMatmul)(N,k,d[2].dims,S,!0)}`:"",te=O?`${function(Oe,le,xe,_e){let Ne=[],He=[];const Ae=xe[0].dims,Ce=xe[1].dims,Fe=Ae.length,Ee=Ce.length,we=_e.length,je=we-Fe,Ue=we-Ee;Ne=Ae.map((Se,Me)=>`coords.${le[Me+je]}`),Ne[Fe-1]="i*2",Ne.join(", "),He=Ce.map((Se,Me)=>`coords.${le[Me+Ue]}`),He[Ee-2]="i*2",He.join(", ");const Be=g.BroadcastUtil.getBroadcastDims(Ae,_e),We=g.BroadcastUtil.getBroadcastDims(Ce,_e),Ke=Be.map(Se=>`coords.${le[Se+je]} = 0;`).join(` `),ze=We.map(Se=>`coords.${le[Se+Ue]} = 0;`).join(` `),Ve=`int lastDim = coords.${le[we-1]}; coords.${le[we-1]} = coords.${le[we-2]}; @@ -1031,12 +1031,12 @@ vec4 getBAtOutCoordsMatmul(int i) { ${ze} vec4 outputValue = getB(${He}); return outputValue; -}`}(N,k,d,S)}`:"",ne=A?"getAAtOutCoordsMatmul(i)":`getA(${function(Oe,le){let xe="";for(let _e=0;_e{Object.defineProperty(u,"__esModule",{value:!0}),u.getBiasForMatmul=u.createMatmulProgramInfoLoader=u.parseMatMulAttributes=u.matMul=void 0;const g=b(2517),p=b(2039),h=b(9390),o=b(2823),c=b(708);function f(t,e){const n=(r=t.length>2,a=e.activationCacheKey,{name:"MatMul",inputNames:r?["A","B","Bias"]:["A","B"],inputTypes:r?[p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked]:[p.TextureType.unpacked,p.TextureType.unpacked],cacheHint:a});var r,a;return Object.assign(Object.assign({},n),{get:()=>function(l,d,m){const y=d[0].dims,v=d[1].dims,_=g.BroadcastUtil.calcShape(y,v,!0);if(!_)throw new Error("Can't use matmul on the given tensors");const T=(0,h.getCoordsDataType)(_.length),S=(0,h.getGlChannels)(),{activationFunction:A,applyActivation:w}=(0,o.getActivationSnippet)(m),I=d.length>2,R=I?"value += getBiasForMatmul();":"",B=I?`${i(T,S,d[2].dims,_,!1)}`:"",j=_.length,N=y.length,W=v.length,k=` - ${A} + }`;return Object.assign(Object.assign({},l),{output:{dims:S,type:d[0].type,textureType:h.TextureType.packed},shaderSource:Pe,hasMain:!0})})(s,e,i,t)})}},5623:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.getBiasForMatmul=u.createMatmulProgramInfoLoader=u.parseMatMulAttributes=u.matMul=void 0;const g=b(2517),p=b(2039),h=b(9390),o=b(2823),c=b(708);function f(t,e){const n=(r=t.length>2,a=e.activationCacheKey,{name:"MatMul",inputNames:r?["A","B","Bias"]:["A","B"],inputTypes:r?[p.TextureType.unpacked,p.TextureType.unpacked,p.TextureType.unpacked]:[p.TextureType.unpacked,p.TextureType.unpacked],cacheHint:a});var r,a;return Object.assign(Object.assign({},n),{get:()=>function(l,d,m){const y=d[0].dims,_=d[1].dims,v=g.BroadcastUtil.calcShape(y,_,!0);if(!v)throw new Error("Can't use matmul on the given tensors");const T=(0,h.getCoordsDataType)(v.length),S=(0,h.getGlChannels)(),{activationFunction:O,applyActivation:w}=(0,o.getActivationSnippet)(m),I=d.length>2,R=I?"value += getBiasForMatmul();":"",B=I?`${i(T,S,d[2].dims,v,!1)}`:"",j=v.length,N=y.length,W=_.length,k=` + ${O} ${B} float process(int indices[${j}]) { int a[${N}]; @@ -1070,26 +1070,26 @@ vec4 getBAtOutCoordsMatmul(int i) { ${R} ${w} return value; - }`;return Object.assign(Object.assign({},l),{output:{dims:_,type:d[0].type,textureType:p.TextureType.unpacked},shaderSource:k})}(n,t,e)})}u.matMul=(t,e,n)=>(s(e),t.session.pack?[t.run((0,c.createPackedMatmulProgramInfoLoader)(t,e,n),e)]:[t.run(f(e,n),e)]),u.parseMatMulAttributes=t=>(0,o.parseInternalActivationAttributes)(t.attributes),u.createMatmulProgramInfoLoader=f;const s=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function i(t,e,n,r,a){let l="";const d=n.length,m=r.length,y=m-d;l=m<2&&d>0?"coords":n.map((T,S)=>`coords.${e[S+y]}`).join(", ");const v=g.BroadcastUtil.getBroadcastDims(n,r).map(T=>`coords.${e[T+y]} = 0;`).join(` -`);let _="vec4(outputValue.xx, outputValue.yy)";return g.ShapeUtil.size(n)===1&&(_="vec4(outputValue.x)"),a?` + }`;return Object.assign(Object.assign({},l),{output:{dims:v,type:d[0].type,textureType:p.TextureType.unpacked},shaderSource:k})}(n,t,e)})}u.matMul=(t,e,n)=>(s(e),t.session.pack?[t.run((0,c.createPackedMatmulProgramInfoLoader)(t,e,n),e)]:[t.run(f(e,n),e)]),u.parseMatMulAttributes=t=>(0,o.parseInternalActivationAttributes)(t.attributes),u.createMatmulProgramInfoLoader=f;const s=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function i(t,e,n,r,a){let l="";const d=n.length,m=r.length,y=m-d;l=m<2&&d>0?"coords":n.map((T,S)=>`coords.${e[S+y]}`).join(", ");const _=g.BroadcastUtil.getBroadcastDims(n,r).map(T=>`coords.${e[T+y]} = 0;`).join(` +`);let v="vec4(outputValue.xx, outputValue.yy)";return g.ShapeUtil.size(n)===1&&(v="vec4(outputValue.x)"),a?` vec4 getBiasForMatmul() { ${t} coords = getOutputCoords(); - ${v} + ${_} vec4 outputValue = getBias(${l}); - return ${_}; + return ${v}; }`:` float getBiasForMatmul() { ${t} coords = getOutputCoords(); - ${v} + ${_} return getBias(coords.x); -}`}u.getBiasForMatmul=i},2403:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackProgramInfoLoader=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827),c={name:"pack",inputNames:["A"],inputTypes:[p.TextureType.unpackedReversed]};u.createPackProgramInfoLoader=(f,s)=>Object.assign(Object.assign({},c),{get:()=>((i,t)=>{const e=(0,g.getGlsl)(i.session.backend.glContext.version),n=t.dims,r=n.length,a=t.dims.length,l=(0,h.getCoordsDataType)(a),d=(0,o.getChannels)("rc",a),m=(y=a,v=d,_=n[n.length-2],T=n[n.length-1],y===0||y===1?"":` - int r = ${v[y-2]}; - int c = ${v[y-1]}; - int rp1 = ${v[y-2]} + 1; - int cp1 = ${v[y-1]} + 1; +}`}u.getBiasForMatmul=i},2403:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createPackProgramInfoLoader=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827),c={name:"pack",inputNames:["A"],inputTypes:[p.TextureType.unpackedReversed]};u.createPackProgramInfoLoader=(f,s)=>Object.assign(Object.assign({},c),{get:()=>((i,t)=>{const e=(0,g.getGlsl)(i.session.backend.glContext.version),n=t.dims,r=n.length,a=t.dims.length,l=(0,h.getCoordsDataType)(a),d=(0,o.getChannels)("rc",a),m=(y=a,_=d,v=n[n.length-2],T=n[n.length-1],y===0||y===1?"":` + int r = ${_[y-2]}; + int c = ${_[y-1]}; + int rp1 = ${_[y-2]} + 1; + int cp1 = ${_[y-1]} + 1; bool rEdge = rp1 >= ${T}; - bool cEdge = cp1 >= ${_}; - `);var y,v,_,T;let S;S=r===0?[1,1]:r===1?[n[0],1]:[n[a-1],n[a-2]];const A=function(R,B,j){if(R===0)return"false";if(R===1)return`rc > ${B[0]}`;let N="";for(let W=R-2;W= ${B[W-R+2]}`,W= ${v}; + `);var y,_,v,T;let S;S=r===0?[1,1]:r===1?[n[0],1]:[n[a-1],n[a-2]];const O=function(R,B,j){if(R===0)return"false";if(R===1)return`rc > ${B[0]}`;let N="";for(let W=R-2;W= ${B[W-R+2]}`,W= ${R[0]} ? 0. : getA(rc + 1), 0, 0`;let N="";if(j>2)for(let W=0;W{Object.defineProperty(u,"__esModule",{value:!0}),u.parsePadAttributesV11=u.padV11=u.parsePadAttributesV2=u.padV2=void 0;const g=b(246),p=b(2517),h=b(5060),o=b(2039),c={name:"Pad",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};u.padV2=(l,d,m)=>(i(d),[l.run(Object.assign(Object.assign({},c),{cacheHint:m.cacheKey,get:()=>s(l,d[0],m)}),d)]),u.parsePadAttributesV2=l=>{const d=l.attributes.getString("mode","constant"),m=l.attributes.getFloat("value",0),y=l.attributes.getInts("pads");return(0,g.createAttributeWithCacheKey)({mode:d,value:m,pads:y})},u.padV11=(l,d,m)=>{t(d);const y=f(l,d,m);return(0,u.padV2)(l,[d[0]],y)},u.parsePadAttributesV11=l=>l.attributes.getString("mode","constant");const f=(l,d,m)=>{if(!l.session.isInitializer(d[1].dataId)||d.length>=3&&!l.session.isInitializer(d[2].dataId))throw new Error("dynamic pad attributes are not allowed");const y=Array.from(d[1].integerData),v=d.length>=3?d[2].floatData[0]:0;return(0,g.createAttributeWithCacheKey)({mode:m,pads:y,value:v})},s=(l,d,m)=>{const y=p.ShapeUtil.padShape(d.dims.slice(),m.pads),v=y.length,_=` + `}},2870:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parsePadAttributesV11=u.padV11=u.parsePadAttributesV2=u.padV2=void 0;const g=b(246),p=b(2517),h=b(5060),o=b(2039),c={name:"Pad",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};u.padV2=(l,d,m)=>(i(d),[l.run(Object.assign(Object.assign({},c),{cacheHint:m.cacheKey,get:()=>s(l,d[0],m)}),d)]),u.parsePadAttributesV2=l=>{const d=l.attributes.getString("mode","constant"),m=l.attributes.getFloat("value",0),y=l.attributes.getInts("pads");return(0,g.createAttributeWithCacheKey)({mode:d,value:m,pads:y})},u.padV11=(l,d,m)=>{t(d);const y=f(l,d,m);return(0,u.padV2)(l,[d[0]],y)},u.parsePadAttributesV11=l=>l.attributes.getString("mode","constant");const f=(l,d,m)=>{if(!l.session.isInitializer(d[1].dataId)||d.length>=3&&!l.session.isInitializer(d[2].dataId))throw new Error("dynamic pad attributes are not allowed");const y=Array.from(d[1].integerData),_=d.length>=3?d[2].floatData[0]:0;return(0,g.createAttributeWithCacheKey)({mode:m,pads:y,value:_})},s=(l,d,m)=>{const y=p.ShapeUtil.padShape(d.dims.slice(),m.pads),_=y.length,v=` ${e(l,d,m)} - float process(int[${v}] indices) { + float process(int[${_}] indices) { return padA(indices); - }`;return{name:"Pad",inputNames:["A"],inputTypes:[o.TextureType.unpacked],output:{dims:y,type:d.type,textureType:o.TextureType.unpacked},shaderSource:_}},i=l=>{if(!l||l.length!==1)throw new Error("Pad requires 1 input");if(l[0].type!=="float32"&&l[0].type!=="float64")throw new Error("Invalid input type.")},t=l=>{if(!l||l.length!==2&&l.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(l[1].type!=="int32")throw new Error("Invalid input type.");if(l.length>=3&&l[2].type==="string")throw new Error("Invalid input type.")},e=(l,d,m)=>{const y=(0,h.getGlsl)(l.session.backend.glContext.version),[v,_]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),T=p.ShapeUtil.computeStrides(d.dims);switch(m.mode){case"constant":return n(y,d.dims,T,v,_,m.pads,m.value);case"reflect":return r(y,d.dims,T,v,_,m.pads);case"edge":return a(y,d.dims,T,v,_,m.pads);default:throw new Error("Invalid mode")}},n=(l,d,m,y,v,_,T)=>{const S=d.length;let A="";for(let w=S-1;w>=0;--w)A+=` - k = m[${w}] - ${_[w]}; + }`;return{name:"Pad",inputNames:["A"],inputTypes:[o.TextureType.unpacked],output:{dims:y,type:d.type,textureType:o.TextureType.unpacked},shaderSource:v}},i=l=>{if(!l||l.length!==1)throw new Error("Pad requires 1 input");if(l[0].type!=="float32"&&l[0].type!=="float64")throw new Error("Invalid input type.")},t=l=>{if(!l||l.length!==2&&l.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(l[1].type!=="int32")throw new Error("Invalid input type.");if(l.length>=3&&l[2].type==="string")throw new Error("Invalid input type.")},e=(l,d,m)=>{const y=(0,h.getGlsl)(l.session.backend.glContext.version),[_,v]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),T=p.ShapeUtil.computeStrides(d.dims);switch(m.mode){case"constant":return n(y,d.dims,T,_,v,m.pads,m.value);case"reflect":return r(y,d.dims,T,_,v,m.pads);case"edge":return a(y,d.dims,T,_,v,m.pads);default:throw new Error("Invalid mode")}},n=(l,d,m,y,_,v,T)=>{const S=d.length;let O="";for(let w=S-1;w>=0;--w)O+=` + k = m[${w}] - ${v[w]}; if (k < 0) return constant; if (k >= ${d[w]}) return constant; offset += k * ${m[w]}; @@ -1132,76 +1132,76 @@ float getBiasForMatmul() { const float constant = float(${T}); int offset = 0; int k = 0; - ${A} - vec2 coords = offsetToCoords(offset, ${y}, ${v}); + ${O} + vec2 coords = offsetToCoords(offset, ${y}, ${_}); float value = getColorAsFloat(${l.texture2D}(A, coords)); return value; } - `},r=(l,d,m,y,v,_)=>{const T=d.length;let S="";for(let A=T-1;A>=0;--A)S+=` - k = m[${A}] - ${_[A]}; + `},r=(l,d,m,y,_,v)=>{const T=d.length;let S="";for(let O=T-1;O>=0;--O)S+=` + k = m[${O}] - ${v[O]}; if (k < 0) { k = -k; } { - const int _2n_1 = ${2*(d[A]-1)}; + const int _2n_1 = ${2*(d[O]-1)}; k = int( mod( float(k), float(_2n_1) ) ) ; - if(k >= ${d[A]}) { k = _2n_1 - k; } + if(k >= ${d[O]}) { k = _2n_1 - k; } } - offset += k * ${m[A]}; + offset += k * ${m[O]}; `;return` float padA(int m[${T}]) { int offset = 0; int k = 0; ${S} - vec2 coords = offsetToCoords(offset, ${y}, ${v}); + vec2 coords = offsetToCoords(offset, ${y}, ${_}); float value = getColorAsFloat(${l.texture2D}(A, coords)); return value; } - `},a=(l,d,m,y,v,_)=>{const T=d.length;let S="";for(let A=T-1;A>=0;--A)S+=` - k = m[${A}] - ${_[A]}; + `},a=(l,d,m,y,_,v)=>{const T=d.length;let S="";for(let O=T-1;O>=0;--O)S+=` + k = m[${O}] - ${v[O]}; if (k < 0) k = 0; - if (k >= ${d[A]}) k = ${d[A]-1}; - offset += k * ${m[A]}; + if (k >= ${d[O]}) k = ${d[O]-1}; + offset += k * ${m[O]}; `;return` float padA(int m[${T}]) { int offset = 0; int k = 0; ${S} - vec2 coords = offsetToCoords(offset, ${y}, ${v}); + vec2 coords = offsetToCoords(offset, ${y}, ${_}); float value = getColorAsFloat(${l.texture2D}(A, coords)); return value; } - `}},2143:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.globalMaxPool=u.parseMaxPoolAttributes=u.maxPool=u.parseGlobalAveragePoolAttributes=u.globalAveragePool=u.parseAveragePoolAttributes=u.averagePool=void 0;const g=b(246),p=b(2517),h=b(2039);u.averagePool=(a,l,d)=>{t(l);const m={name:"AveragePool",inputNames:["X"],inputTypes:[h.TextureType.unpacked],cacheHint:d.cacheKey};return[a.run(Object.assign(Object.assign({},m),{get:()=>o(l,m,!1,d)}),l)]},u.parseAveragePoolAttributes=a=>{const l=a.attributes.getString("auto_pad","NOTSET"),d=a.attributes.getInt("ceil_mode",0),m=a.attributes.getInt("count_include_pad",0)!==0,y=a.attributes.getInts("kernel_shape"),v=a.attributes.getInts("strides",[]),_=a.attributes.getInts("pads",[]);if(d!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,g.createAttributeWithCacheKey)({autoPad:l,ceilMode:d,countIncludePad:m,kernelShape:y,strides:v,pads:_})};const o=(a,l,d,m)=>{const[y,v]=f(a,m,d),_=p.ShapeUtil.size(y.kernelShape);let T="";y.countIncludePad?T+=`value /= float(${_});`:T+=`value /= float(${_} - pad);`;const S=` + `}},2143:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.globalMaxPool=u.parseMaxPoolAttributes=u.maxPool=u.parseGlobalAveragePoolAttributes=u.globalAveragePool=u.parseAveragePoolAttributes=u.averagePool=void 0;const g=b(246),p=b(2517),h=b(2039);u.averagePool=(a,l,d)=>{t(l);const m={name:"AveragePool",inputNames:["X"],inputTypes:[h.TextureType.unpacked],cacheHint:d.cacheKey};return[a.run(Object.assign(Object.assign({},m),{get:()=>o(l,m,!1,d)}),l)]},u.parseAveragePoolAttributes=a=>{const l=a.attributes.getString("auto_pad","NOTSET"),d=a.attributes.getInt("ceil_mode",0),m=a.attributes.getInt("count_include_pad",0)!==0,y=a.attributes.getInts("kernel_shape"),_=a.attributes.getInts("strides",[]),v=a.attributes.getInts("pads",[]);if(d!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,g.createAttributeWithCacheKey)({autoPad:l,ceilMode:d,countIncludePad:m,kernelShape:y,strides:_,pads:v})};const o=(a,l,d,m)=>{const[y,_]=f(a,m,d),v=p.ShapeUtil.size(y.kernelShape);let T="";y.countIncludePad?T+=`value /= float(${v});`:T+=`value /= float(${v} - pad);`;const S=` ${e(a[0].dims,y,"value += _X(x);",T,"0.0")} - `;return Object.assign(Object.assign({},l),{output:{dims:v,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:S})};u.globalAveragePool=(a,l,d)=>{t(l);const m={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[h.TextureType.unpacked],cacheHint:`${d.countIncludePad}`};return[a.run(Object.assign(Object.assign({},m),{get:()=>o(l,m,!0,d)}),l)]},u.parseGlobalAveragePoolAttributes=a=>{const l=a.attributes.getInt("count_include_pad",0)!==0;return(0,g.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:l,kernelShape:[],strides:[],pads:[]})},u.maxPool=(a,l,d)=>{t(l);const m={name:"MaxPool",inputNames:["X"],inputTypes:[h.TextureType.unpacked],cacheHint:d.cacheKey};return[a.run(Object.assign(Object.assign({},m),{get:()=>c(l,m,!1,d)}),l)]},u.parseMaxPoolAttributes=a=>{const l=a.attributes.getString("auto_pad","NOTSET"),d=a.attributes.getInt("ceil_mode",0),m=a.attributes.getInts("kernel_shape"),y=a.attributes.getInts("strides",[]),v=a.attributes.getInts("pads",[]),_=a.attributes.getInt("storage_order",0),T=a.attributes.getInts("dilations",[]);if(_!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(d!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,g.createAttributeWithCacheKey)({autoPad:l,ceilMode:d,countIncludePad:!1,kernelShape:m,strides:y,pads:v,storageOrder:_,dilations:T})};const c=(a,l,d,m)=>{const[y,v]=f(a,m,d),_=` + `;return Object.assign(Object.assign({},l),{output:{dims:_,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:S})};u.globalAveragePool=(a,l,d)=>{t(l);const m={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[h.TextureType.unpacked],cacheHint:`${d.countIncludePad}`};return[a.run(Object.assign(Object.assign({},m),{get:()=>o(l,m,!0,d)}),l)]},u.parseGlobalAveragePoolAttributes=a=>{const l=a.attributes.getInt("count_include_pad",0)!==0;return(0,g.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:l,kernelShape:[],strides:[],pads:[]})},u.maxPool=(a,l,d)=>{t(l);const m={name:"MaxPool",inputNames:["X"],inputTypes:[h.TextureType.unpacked],cacheHint:d.cacheKey};return[a.run(Object.assign(Object.assign({},m),{get:()=>c(l,m,!1,d)}),l)]},u.parseMaxPoolAttributes=a=>{const l=a.attributes.getString("auto_pad","NOTSET"),d=a.attributes.getInt("ceil_mode",0),m=a.attributes.getInts("kernel_shape"),y=a.attributes.getInts("strides",[]),_=a.attributes.getInts("pads",[]),v=a.attributes.getInt("storage_order",0),T=a.attributes.getInts("dilations",[]);if(v!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(d!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,g.createAttributeWithCacheKey)({autoPad:l,ceilMode:d,countIncludePad:!1,kernelShape:m,strides:y,pads:_,storageOrder:v,dilations:T})};const c=(a,l,d,m)=>{const[y,_]=f(a,m,d),v=` ${e(a[0].dims,y,` value = max(_X(x), value); `,"","-1e5")} - `;return Object.assign(Object.assign({},l),{output:{dims:v,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:_})},f=(a,l,d)=>{const m=a[0].dims.slice(),y=Object.hasOwnProperty.call(l,"dilations"),v=l.kernelShape.slice(),_=l.strides.slice(),T=y?l.dilations.slice():[],S=l.pads.slice();p.PoolConvUtil.adjustPoolAttributes(d,m,v,_,T,S);const A=p.PoolConvUtil.computePoolOutputShape(d,m,_,T,v,S,l.autoPad),w=Object.assign({},l);return y?Object.assign(w,{kernelShape:v,strides:_,pads:S,dilations:T,cacheKey:l.cacheKey}):Object.assign(w,{kernelShape:v,strides:_,pads:S,cacheKey:l.cacheKey}),[w,A]},s={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},i={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[h.TextureType.unpacked]};u.globalMaxPool=(a,l)=>(t(l),[a.run(Object.assign(Object.assign({},i),{get:()=>c(l,i,!0,s)}),l)]);const t=a=>{if(!a||a.length!==1)throw new Error("Pool ops requires 1 input.");if(a[0].type!=="float32"&&a[0].type!=="float64")throw new Error("Invalid input type.")},e=(a,l,d,m,y)=>{const v=a.length;if(l.kernelShape.length<=2){const _=l.kernelShape[l.kernelShape.length-1],T=l.strides[l.strides.length-1],S=l.pads[l.pads.length/2-1],A=l.pads[l.pads.length-1],w=a[v-1];let I="",R="",B="";if(I=S+A!==0?` - for (int i = 0; i < ${_}; i++) { - x[${v} - 1] = indices[${v} - 1] * ${T} - ${S} + i; - if (x[${v} - 1] < 0 || x[${v} - 1] >= ${w}) { + `;return Object.assign(Object.assign({},l),{output:{dims:_,type:a[0].type,textureType:h.TextureType.unpacked},shaderSource:v})},f=(a,l,d)=>{const m=a[0].dims.slice(),y=Object.hasOwnProperty.call(l,"dilations"),_=l.kernelShape.slice(),v=l.strides.slice(),T=y?l.dilations.slice():[],S=l.pads.slice();p.PoolConvUtil.adjustPoolAttributes(d,m,_,v,T,S);const O=p.PoolConvUtil.computePoolOutputShape(d,m,v,T,_,S,l.autoPad),w=Object.assign({},l);return y?Object.assign(w,{kernelShape:_,strides:v,pads:S,dilations:T,cacheKey:l.cacheKey}):Object.assign(w,{kernelShape:_,strides:v,pads:S,cacheKey:l.cacheKey}),[w,O]},s={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},i={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[h.TextureType.unpacked]};u.globalMaxPool=(a,l)=>(t(l),[a.run(Object.assign(Object.assign({},i),{get:()=>c(l,i,!0,s)}),l)]);const t=a=>{if(!a||a.length!==1)throw new Error("Pool ops requires 1 input.");if(a[0].type!=="float32"&&a[0].type!=="float64")throw new Error("Invalid input type.")},e=(a,l,d,m,y)=>{const _=a.length;if(l.kernelShape.length<=2){const v=l.kernelShape[l.kernelShape.length-1],T=l.strides[l.strides.length-1],S=l.pads[l.pads.length/2-1],O=l.pads[l.pads.length-1],w=a[_-1];let I="",R="",B="";if(I=S+O!==0?` + for (int i = 0; i < ${v}; i++) { + x[${_} - 1] = indices[${_} - 1] * ${T} - ${S} + i; + if (x[${_} - 1] < 0 || x[${_} - 1] >= ${w}) { pad++; continue; } ${d} }`:` - for (int i = 0; i < ${_}; i++) { - x[${v} - 1] = indices[${v} - 1] * ${T} - ${S} + i; + for (int i = 0; i < ${v}; i++) { + x[${_} - 1] = indices[${_} - 1] * ${T} - ${S} + i; ${d} - }`,l.kernelShape.length===2){const j=l.kernelShape[l.kernelShape.length-2],N=l.strides[l.strides.length-2],W=l.pads[l.pads.length/2-2],k=l.pads[l.pads.length-2],V=a[v-2];R=W+k!==0?` + }`,l.kernelShape.length===2){const j=l.kernelShape[l.kernelShape.length-2],N=l.strides[l.strides.length-2],W=l.pads[l.pads.length/2-2],k=l.pads[l.pads.length-2],V=a[_-2];R=W+k!==0?` for (int j = 0; j < ${j}; j++) { - x[${v} - 2] = indices[${v} - 2] * ${N} - ${W} + j; - if (x[${v} - 2] < 0 || x[${v} - 2] >= ${V}) { - pad+= ${_}; + x[${_} - 2] = indices[${_} - 2] * ${N} - ${W} + j; + if (x[${_} - 2] < 0 || x[${_} - 2] >= ${V}) { + pad+= ${v}; continue; } `:` for (int j = 0; j < ${j}; j++) { - x[${v} - 2] = indices[${v} - 2] * ${N} - ${W} + j; + x[${_} - 2] = indices[${_} - 2] * ${N} - ${W} + j; `,B=` } `}return` - float process(int indices[${v}]) { - int x[${v}]; + float process(int indices[${_}]) { + int x[${_}]; copyVec(indices, x); float value = ${y}; @@ -1212,7 +1212,7 @@ float getBiasForMatmul() { ${m} return value; } - `}{const _=p.ShapeUtil.size(l.kernelShape),T=p.ShapeUtil.computeStrides(l.kernelShape),S=T.length,A=l.pads.length,w=r(S),I=n(a,"inputDims"),R=n(l.pads,"pads"),B=n(T,"kernelStrides"),j=n(l.strides,"strides");let N="";return N=l.pads.reduce((W,k)=>W+k)?` + `}{const v=p.ShapeUtil.size(l.kernelShape),T=p.ShapeUtil.computeStrides(l.kernelShape),S=T.length,O=l.pads.length,w=r(S),I=n(a,"inputDims"),R=n(l.pads,"pads"),B=n(T,"kernelStrides"),j=n(l.strides,"strides");let N="";return N=l.pads.reduce((W,k)=>W+k)?` if (x[j] >= inputDims[j] || x[j] < 0) { pad++; isPad = true; @@ -1226,12 +1226,12 @@ float getBiasForMatmul() { ${d} `,` ${w} - float process(int indices[${v}]) { - int x[${v}]; + float process(int indices[${_}]) { + int x[${_}]; copyVec(indices, x); int offset[${S}]; - int pads[${A}]; - int inputDims[${v}]; + int pads[${O}]; + int inputDims[${_}]; int kernelStrides[${S}]; int strides[${S}]; ${R} @@ -1242,12 +1242,12 @@ float getBiasForMatmul() { float value = ${y}; int pad = 0; bool isPad = false; - for (int i = 0; i < ${_}; i++) { + for (int i = 0; i < ${v}; i++) { offsetToIndices(i, kernelStrides, offset); isPad = false; - for (int j = ${v} - ${S}; j < ${v}; j++) { - x[j] = indices[j] * strides[j - ${v} + ${S}] - + offset[j - ${v} + ${S}] - pads[j - 2]; + for (int j = ${_} - ${S}; j < ${_}; j++) { + x[j] = indices[j] * strides[j - ${_} + ${S}] + + offset[j - ${_} + ${S}] - pads[j - 2]; ${N} } ${m} @@ -1266,46 +1266,46 @@ float getBiasForMatmul() { offset -= indices[i] * strides[i]; } indices[${a} - 1] = offset; - }`},4939:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.reduceLogSumSquare=u.reduceLogSum=u.reduceProd=u.reduceMin=u.reduceMax=u.reduceMean=u.reduceSum=u.parseReduceAttributes=void 0;const g=b(246),p=b(782),h=b(2517),o=b(2039),c=(i,t,e,n,r)=>{s(t);const a={name:n,inputNames:["A"],inputTypes:[o.TextureType.unpacked]};return[i.run(Object.assign(Object.assign({},a),{cacheHint:e.cacheKey,get:()=>f(i,t,e,n,r,a)}),t)]};u.parseReduceAttributes=i=>{const t=i.attributes.getInts("axes",[]),e=i.attributes.getInt("keepdims",1)===1;return(0,g.createAttributeWithCacheKey)({axes:t,keepDims:e})};const f=(i,t,e,n,r,a)=>{const l=[],d=t[0].dims.length||1,m=[],y=h.ShapeUtil.normalizeAxes(e.axes,t[0].dims.length),v=r(t,y);let _=v[1];for(let S=0;S=0||y.length===0?(e.keepDims&&l.push(1),_=` + }`},4939:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.reduceLogSumSquare=u.reduceLogSum=u.reduceProd=u.reduceMin=u.reduceMax=u.reduceMean=u.reduceSum=u.parseReduceAttributes=void 0;const g=b(246),p=b(782),h=b(2517),o=b(2039),c=(i,t,e,n,r)=>{s(t);const a={name:n,inputNames:["A"],inputTypes:[o.TextureType.unpacked]};return[i.run(Object.assign(Object.assign({},a),{cacheHint:e.cacheKey,get:()=>f(i,t,e,n,r,a)}),t)]};u.parseReduceAttributes=i=>{const t=i.attributes.getInts("axes",[]),e=i.attributes.getInt("keepdims",1)===1;return(0,g.createAttributeWithCacheKey)({axes:t,keepDims:e})};const f=(i,t,e,n,r,a)=>{const l=[],d=t[0].dims.length||1,m=[],y=h.ShapeUtil.normalizeAxes(e.axes,t[0].dims.length),_=r(t,y);let v=_[1];for(let S=0;S=0||y.length===0?(e.keepDims&&l.push(1),v=` for(int j${S} = 0; j${S} < ${t[0].dims[S]}; j${S}++) { inputIdx[${S}] = j${S}; - ${_} + ${v} }`):(m.push(`inputIdx[${S}] = outputIdx[${l.length}];`),l.push(t[0].dims[S]));const T=` float process(int outputIdx[${l.length||1}]) { float value; // final result int inputIdx[${d}]; // addressing input data ${m.join(` `)} - ${v[0]} // init ops for reduce max/min - ${_} - ${v[2]} // final computation for reduce mean + ${_[0]} // init ops for reduce max/min + ${v} + ${_[2]} // final computation for reduce mean return value; }`;return Object.assign(Object.assign({},a),{output:{dims:l,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:T})},s=i=>{if(!i||i.length!==1)throw new Error("Reduce op requires 1 input.");if(p.NUMBER_TYPES.indexOf(i[0].type)===-1)throw new Error("Invalid input type.")};u.reduceSum=(i,t,e)=>c(i,t,e,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),u.reduceMean=(i,t,e)=>c(i,t,e,"ReduceMean",(n,r)=>{let a=1;for(let l=0;l=0||r.length===0)&&(a*=n[0].dims[l]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${a}.;`]}),u.reduceMax=(i,t,e)=>c(i,t,e,"ReduceMax",(n,r)=>{const a=[];for(let l=0;l=0||r.length===0)&&a.push(`inputIdx[${l}] = 0;`);return[`${a.join(` `)} value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),u.reduceMin=(i,t,e)=>c(i,t,e,"ReduceMin",(n,r)=>{const a=[];for(let l=0;l=0||r.length===0)&&a.push(`inputIdx[${l}] = 0;`);return[`${a.join(` `)} -value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i,t,e)=>c(i,t,e,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),u.reduceLogSum=(i,t,e)=>c(i,t,e,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),u.reduceLogSumSquare=(i,t,e)=>c(i,t,e,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.isReshapeCheap=u.processDims3D=u.createPackedReshape3DProgramInfoLoader=void 0;const g=b(2517),p=b(5060),h=b(2039),o=b(2827);u.createPackedReshape3DProgramInfoLoader=(c,f,s)=>{const i=(t=>({name:"Reshape (packed)",inputTypes:[h.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(s);return Object.assign(Object.assign({},i),{get:()=>((t,e,n,r)=>{const a=e.dims,l=r;let d="";for(let v=0;v<4;v++){let _="";switch(v){case 0:_="outputCoords = rc;";break;case 1:_="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:_="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:_="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}d+=` - ${_} - ${v>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} +value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i,t,e)=>c(i,t,e,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),u.reduceLogSum=(i,t,e)=>c(i,t,e,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),u.reduceLogSumSquare=(i,t,e)=>c(i,t,e,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.isReshapeCheap=u.processDims3D=u.createPackedReshape3DProgramInfoLoader=void 0;const g=b(2517),p=b(5060),h=b(2039),o=b(2827);u.createPackedReshape3DProgramInfoLoader=(c,f,s)=>{const i=(t=>({name:"Reshape (packed)",inputTypes:[h.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(s);return Object.assign(Object.assign({},i),{get:()=>((t,e,n,r)=>{const a=e.dims,l=r;let d="";for(let _=0;_<4;_++){let v="";switch(_){case 0:v="outputCoords = rc;";break;case 1:v="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:v="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:v="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}d+=` + ${v} + ${_>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} int flattenedIndex = getFlattenedIndex(outputCoords); ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); - result[${v}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); + result[${_}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); - ${v>0?"}":""} + ${_>0?"}":""} `}const m=(0,p.getGlsl)(t.session.backend.glContext.version),y=` - ${function(v){const _=g.ShapeUtil.computeStrides(v),T=["b","r","c"],S="index";return` + ${function(_){const v=g.ShapeUtil.computeStrides(_),T=["b","r","c"],S="index";return` ivec3 inputCoordsFromReshapedOutCoords(int index) { - ${_.map((A,w)=>`int ${T[w]} = ${S} / ${A}; ${w===_.length-1?`int ${T[w+1]} = ${S} - ${T[w]} * ${A}`:`index -= ${T[w]} * ${A}`};`).join("")} + ${v.map((O,w)=>`int ${T[w]} = ${S} / ${O}; ${w===v.length-1?`int ${T[w+1]} = ${S} - ${T[w]} * ${O}`:`index -= ${T[w]} * ${O}`};`).join("")} return ivec3(b, r, c); } `}(a)} - ${function(v){const _=g.ShapeUtil.computeStrides(v);return` + ${function(_){const v=g.ShapeUtil.computeStrides(_);return` int getFlattenedIndex(ivec3 coords) { // reverse y, z order - return coords.x * ${_[0]} + coords.z * ${_[1]} + coords.y; + return coords.x * ${v[0]} + coords.z * ${v[1]} + coords.y; } `}(l)} ${(0,o.unpackFromChannel)()} @@ -1325,7 +1325,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i `;return Object.assign(Object.assign({},n),{output:{dims:l,type:e.type,textureType:h.TextureType.packed},shaderSource:y,hasMain:!0})})(c,f,i,s)})},u.processDims3D=function(c){if(c.length===0)return[1,1,1];let f=1;for(let s=0;s1?c[c.length-2]:1,c[c.length-1]]},u.isReshapeCheap=function(c,f){let s=!1;return s=c.length===0||f.length===0||(c.length<2||f.length<2?c[c.length-1]===f[f.length-1]:c[c.length-1]===f[f.length-1]&&c[c.length-2]===f[f.length-2]),s}},718:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.reshape=void 0;const g=b(2517);u.reshape=(p,h)=>{const o=g.ShapeUtil.calculateReshapedDims(h[0].dims,h[1].integerData);return p.session.pack?[p.reshapePacked(h[0],o)]:[p.reshapeUnpacked(h[0],o)]}},2268:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseResizeAttributesV11=u.parseResizeAttributesV10=u.resize=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827),c=b(9793),f={name:"Resize",inputNames:["A"],inputTypes:[p.TextureType.packed]};u.resize=(n,r,a)=>((0,c.validateInputs)(r,a),[n.run(Object.assign(Object.assign({},f),{cacheHint:a.cacheKey,get:()=>s(n,r,a)}),r)]),u.parseResizeAttributesV10=n=>(0,c.parseUpsampleAttributes)(n,10),u.parseResizeAttributesV11=n=>(0,c.parseUpsampleAttributes)(n,11);const s=(n,r,a)=>{const l=(0,g.getGlsl)(n.session.backend.glContext.version),[d,m]=i(r,a);if(d.every(N=>N===1)&&a.coordinateTransformMode!=="tf_crop_and_resize")return Object.assign(Object.assign({},f),{output:{dims:m,type:r[0].type,textureType:p.TextureType.packed},hasMain:!0,shaderSource:`void main() { vec4 v = ${l.texture2D}(X, TexCoords); ${l.output} = v; - }`});const y=m.length;if(y<2)throw new Error(`output dimension should be at least 2, but got ${y}`);const v=m[y-2],_=m[y-1],T=r[0].dims;if(y!==T.length)throw new Error(`output dimension should match input ${T.length}, but got ${y}`);const S=T[y-2],A=T[y-1],w=d[y-2],I=d[y-1];let R="";if(a.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${a.mode}'`);switch(a.coordinateTransformMode){case"asymmetric":R=` + }`});const y=m.length;if(y<2)throw new Error(`output dimension should be at least 2, but got ${y}`);const _=m[y-2],v=m[y-1],T=r[0].dims;if(y!==T.length)throw new Error(`output dimension should match input ${T.length}, but got ${y}`);const S=T[y-2],O=T[y-1],w=d[y-2],I=d[y-1];let R="";if(a.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${a.mode}'`);switch(a.coordinateTransformMode){case"asymmetric":R=` vec4 getSourceFracIndex(ivec4 coords) { return vec4(coords) / scaleWHWH; } @@ -1337,23 +1337,23 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i vec4 getSourceFracIndex(ivec4 coords) { vec4 fcoords = vec4(coords); return vec4( - ${_}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, - ${v}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, - ${_}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, - ${v}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 + ${v}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, + ${_}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, + ${v}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, + ${_}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 ); } `;break;case"align_corners":R=` vec4 getSourceFracIndex(ivec4 coords) { - vec4 resized = vec4(${_}.0 - 1.0, ${v}.0 - 1.0, ${_}.0 - 1.0, - ${v}.0 - 1.0); - vec4 original = vec4(${A}.0 - 1.0, ${S}.0 - 1.0, ${A}.0 - 1.0, + vec4 resized = vec4(${v}.0 - 1.0, ${_}.0 - 1.0, ${v}.0 - 1.0, + ${_}.0 - 1.0); + vec4 original = vec4(${O}.0 - 1.0, ${S}.0 - 1.0, ${O}.0 - 1.0, ${S}.0 - 1.0); vec4 new_scale = original / resized; return vec4(coords) * new_scale; } `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${a.coordinateTransformMode}'`)}const B=(0,h.getCoordsDataType)(y),j=` - const vec2 inputWH = vec2(${S}.0, ${A}.0); + const vec2 inputWH = vec2(${S}.0, ${O}.0); const vec4 scaleWHWH = vec4(float(${w}), float(${I}), float(${w}), float(${I})); ${(0,o.unpackFromChannel)()} ${R} @@ -1378,8 +1378,8 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); - bool hasNextRow = rc.w < ${v-1}; - bool hasNextCol = rc.z < ${_-1}; + bool hasNextRow = rc.w < ${_-1}; + bool hasNextCol = rc.z < ${v-1}; // pack x00, x01, x10, x11's top-left corner into one vec4 structure vec4 topLeft = vec4( @@ -1419,28 +1419,28 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i ${l.output} = vec4(newValue); } - `;return Object.assign(Object.assign({},f),{output:{dims:m,type:r[0].type,textureType:p.TextureType.packed},hasMain:!0,shaderSource:j})},i=(n,r)=>{const a=n[0].dims;let l,d=r.scales;if(d.length===0){const y=n[r.scalesInputIdx];if(y&&y.size!==0){if(n[r.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");d=t(y,r.mode,r.isResize)}else{const v=n[r.sizesInputIdx];if(!v||v.size===0)throw new Error("Either scales or sizes MUST be provided as input.");l=Array.from(v.integerData),d=e(l,a,r.mode,r.isResize)}}else if(n[r.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const m=l||a.map((y,v)=>Math.floor(y*d[v]));return[d,m]},t=(n,r,a)=>{const l=Array.from(n.floatData);return(0,c.scalesValidation)(l,r,a),l},e=(n,r,a,l)=>{const d=r.length,m=new Array(d);for(let y=0,v=d;y{Object.defineProperty(u,"__esModule",{value:!0}),u.shape=void 0;const g=b(9162);u.shape=(h,o)=>(p(o),[new g.Tensor([o[0].dims.length],"int32",void 0,void 0,new Int32Array(o[0].dims))]);const p=h=>{if(!h||h.length!==1)throw new Error("Shape requires 1 input.")}},2278:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.sliceV10=u.parseSliceAttributes=u.slice=void 0;const g=b(246),p=b(782),h=b(2517),o=b(2039),c={name:"Slice",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};u.slice=(e,n,r)=>(s(n),[e.run(Object.assign(Object.assign({},c),{cacheHint:r.cacheKey,get:()=>f(e,n[0],r)}),n)]),u.parseSliceAttributes=e=>{const n=e.attributes.getInts("starts"),r=e.attributes.getInts("ends"),a=e.attributes.getInts("axes",[]);return(0,g.createAttributeWithCacheKey)({starts:n,ends:r,axes:a})};const f=(e,n,r)=>{const a=r.axes.length===0?n.dims.slice(0).map((T,S)=>S):r.axes,l=h.ShapeUtil.normalizeAxes(a,n.dims.length),d=r.starts.map((T,S)=>T>n.dims[l[S]]-1?n.dims[l[S]]:h.ShapeUtil.normalizeAxis(T,n.dims[l[S]])),m=r.ends.map((T,S)=>T>n.dims[l[S]]-1?n.dims[l[S]]:h.ShapeUtil.normalizeAxis(T,n.dims[l[S]])),y=n.dims.slice(),v=[];for(let T=0;T0&&v.push(`outputIdx[${l[T]}] += ${d[T]};`);const _=` + `;return Object.assign(Object.assign({},f),{output:{dims:m,type:r[0].type,textureType:p.TextureType.packed},hasMain:!0,shaderSource:j})},i=(n,r)=>{const a=n[0].dims;let l,d=r.scales;if(d.length===0){const y=n[r.scalesInputIdx];if(y&&y.size!==0){if(n[r.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");d=t(y,r.mode,r.isResize)}else{const _=n[r.sizesInputIdx];if(!_||_.size===0)throw new Error("Either scales or sizes MUST be provided as input.");l=Array.from(_.integerData),d=e(l,a,r.mode,r.isResize)}}else if(n[r.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const m=l||a.map((y,_)=>Math.floor(y*d[_]));return[d,m]},t=(n,r,a)=>{const l=Array.from(n.floatData);return(0,c.scalesValidation)(l,r,a),l},e=(n,r,a,l)=>{const d=r.length,m=new Array(d);for(let y=0,_=d;y<_;y++)if(r[y]===0){if(n[y]!==0)throw new Error("Input dim is zero but required output dim is non-zero.");m[y]=1}else m[y]=n[y]/r[y];return(0,c.scalesValidation)(m,a,l),m}},8117:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.shape=void 0;const g=b(9162);u.shape=(h,o)=>(p(o),[new g.Tensor([o[0].dims.length],"int32",void 0,void 0,new Int32Array(o[0].dims))]);const p=h=>{if(!h||h.length!==1)throw new Error("Shape requires 1 input.")}},2278:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.sliceV10=u.parseSliceAttributes=u.slice=void 0;const g=b(246),p=b(782),h=b(2517),o=b(2039),c={name:"Slice",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};u.slice=(e,n,r)=>(s(n),[e.run(Object.assign(Object.assign({},c),{cacheHint:r.cacheKey,get:()=>f(e,n[0],r)}),n)]),u.parseSliceAttributes=e=>{const n=e.attributes.getInts("starts"),r=e.attributes.getInts("ends"),a=e.attributes.getInts("axes",[]);return(0,g.createAttributeWithCacheKey)({starts:n,ends:r,axes:a})};const f=(e,n,r)=>{const a=r.axes.length===0?n.dims.slice(0).map((T,S)=>S):r.axes,l=h.ShapeUtil.normalizeAxes(a,n.dims.length),d=r.starts.map((T,S)=>T>n.dims[l[S]]-1?n.dims[l[S]]:h.ShapeUtil.normalizeAxis(T,n.dims[l[S]])),m=r.ends.map((T,S)=>T>n.dims[l[S]]-1?n.dims[l[S]]:h.ShapeUtil.normalizeAxis(T,n.dims[l[S]])),y=n.dims.slice(),_=[];for(let T=0;T0&&_.push(`outputIdx[${l[T]}] += ${d[T]};`);const v=` float process(int outputIdx[${y.length}]) { - ${v.join(` + ${_.join(` `)} return _A(outputIdx); - }`;return Object.assign(Object.assign({},c),{output:{dims:y,type:n.type,textureType:o.TextureType.unpacked},shaderSource:_})},s=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(p.NUMBER_TYPES.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")};u.sliceV10=(e,n)=>{t(n);const r=i(e,n);return[e.run(Object.assign(Object.assign({},c),{cacheHint:r.cacheKey,get:()=>f(e,n[0],r)}),[n[0]])]};const i=(e,n)=>{if(!e.session.isInitializer(n[1].dataId)||!e.session.isInitializer(n[2].dataId)||n.length>=4&&!e.session.isInitializer(n[3].dataId)||n.length>=5&&!e.session.isInitializer(n[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(n.length>=5&&n[4].integerData.some(d=>d!==1))throw new Error("currently non-1 steps is not supported for Slice");const r=Array.from(n[1].integerData),a=Array.from(n[2].integerData),l=n.length>=4?Array.from(n[3].integerData):[];return{starts:r,ends:a,axes:l,cacheKey:`${l};${r};${a}`}},t=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}},5524:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.softmaxV13=u.parseSoftmaxAttributesV13=u.parseSoftmaxAttributes=u.softmax=void 0;const g=b(246),p=b(2517),h=b(5060),o=b(2039),c=b(3738),f={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[o.TextureType.unpacked]},s={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked]},i={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};u.softmax=(l,d,m)=>{a(d);const y=d[0].dims.slice(),v=p.ShapeUtil.normalizeAxis(m.axis,y.length),_=p.ShapeUtil.sizeToDimension(y,v),T=p.ShapeUtil.sizeFromDimension(y,v);return t(l,d,m,_,T)},u.parseSoftmaxAttributes=l=>(0,g.createAttributeWithCacheKey)({axis:l.attributes.getInt("axis",1)}),u.parseSoftmaxAttributesV13=l=>(0,g.createAttributeWithCacheKey)({axis:l.attributes.getInt("axis",-1)}),u.softmaxV13=(l,d,m)=>{a(d);const y=d[0].dims.slice(),v=p.ShapeUtil.normalizeAxis(m.axis,y.length),_=y.length,T=v!==_-1,S=[];let A,w=[],I=[];T&&(w=Array.from({length:_}).map((N,W)=>W),w[v]=_-1,w[_-1]=v,w.map(N=>S.push(y[N])),A=(0,g.createAttributeWithCacheKey)({perm:w}),I=(0,c.transpose)(l,d,A));const R=T?p.ShapeUtil.sizeToDimension(S,_-1):p.ShapeUtil.sizeToDimension(y,_-1),B=T?p.ShapeUtil.sizeFromDimension(S,_-1):p.ShapeUtil.sizeFromDimension(y,_-1),j=t(l,T?I:d,m,R,B);return T?(0,c.transpose)(l,j,A):j};const t=(l,d,m,y,v)=>{const _=e(l,d[0],y,v,[y]),T=l.run(Object.assign(Object.assign({},f),{cacheHint:m.cacheKey,get:()=>_}),d),S=n(l,d[0],y,v,_.output.dims,[y]),A=l.run(Object.assign(Object.assign({},s),{cacheHint:m.cacheKey,get:()=>S}),[d[0],T]),w=r(l,d[0],y,v,_.output.dims,S.output.dims);return[l.run(Object.assign(Object.assign({},i),{cacheHint:m.cacheKey,get:()=>w}),[d[0],T,A])]},e=(l,d,m,y,v)=>{const[_,T]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),S=v.length;if(m<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(v.length!==1)throw new Error("Dimensionality of the output should be 1");if(v[0]!==m)throw new Error("Shape of the output should be equal to logical row count");const A=(0,h.getGlsl)(l.session.backend.glContext.version),w=` + }`;return Object.assign(Object.assign({},c),{output:{dims:y,type:n.type,textureType:o.TextureType.unpacked},shaderSource:v})},s=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(p.NUMBER_TYPES.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")};u.sliceV10=(e,n)=>{t(n);const r=i(e,n);return[e.run(Object.assign(Object.assign({},c),{cacheHint:r.cacheKey,get:()=>f(e,n[0],r)}),[n[0]])]};const i=(e,n)=>{if(!e.session.isInitializer(n[1].dataId)||!e.session.isInitializer(n[2].dataId)||n.length>=4&&!e.session.isInitializer(n[3].dataId)||n.length>=5&&!e.session.isInitializer(n[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(n.length>=5&&n[4].integerData.some(d=>d!==1))throw new Error("currently non-1 steps is not supported for Slice");const r=Array.from(n[1].integerData),a=Array.from(n[2].integerData),l=n.length>=4?Array.from(n[3].integerData):[];return{starts:r,ends:a,axes:l,cacheKey:`${l};${r};${a}`}},t=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}},5524:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.softmaxV13=u.parseSoftmaxAttributesV13=u.parseSoftmaxAttributes=u.softmax=void 0;const g=b(246),p=b(2517),h=b(5060),o=b(2039),c=b(3738),f={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[o.TextureType.unpacked]},s={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked]},i={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};u.softmax=(l,d,m)=>{a(d);const y=d[0].dims.slice(),_=p.ShapeUtil.normalizeAxis(m.axis,y.length),v=p.ShapeUtil.sizeToDimension(y,_),T=p.ShapeUtil.sizeFromDimension(y,_);return t(l,d,m,v,T)},u.parseSoftmaxAttributes=l=>(0,g.createAttributeWithCacheKey)({axis:l.attributes.getInt("axis",1)}),u.parseSoftmaxAttributesV13=l=>(0,g.createAttributeWithCacheKey)({axis:l.attributes.getInt("axis",-1)}),u.softmaxV13=(l,d,m)=>{a(d);const y=d[0].dims.slice(),_=p.ShapeUtil.normalizeAxis(m.axis,y.length),v=y.length,T=_!==v-1,S=[];let O,w=[],I=[];T&&(w=Array.from({length:v}).map((N,W)=>W),w[_]=v-1,w[v-1]=_,w.map(N=>S.push(y[N])),O=(0,g.createAttributeWithCacheKey)({perm:w}),I=(0,c.transpose)(l,d,O));const R=T?p.ShapeUtil.sizeToDimension(S,v-1):p.ShapeUtil.sizeToDimension(y,v-1),B=T?p.ShapeUtil.sizeFromDimension(S,v-1):p.ShapeUtil.sizeFromDimension(y,v-1),j=t(l,T?I:d,m,R,B);return T?(0,c.transpose)(l,j,O):j};const t=(l,d,m,y,_)=>{const v=e(l,d[0],y,_,[y]),T=l.run(Object.assign(Object.assign({},f),{cacheHint:m.cacheKey,get:()=>v}),d),S=n(l,d[0],y,_,v.output.dims,[y]),O=l.run(Object.assign(Object.assign({},s),{cacheHint:m.cacheKey,get:()=>S}),[d[0],T]),w=r(l,d[0],y,_,v.output.dims,S.output.dims);return[l.run(Object.assign(Object.assign({},i),{cacheHint:m.cacheKey,get:()=>w}),[d[0],T,O])]},e=(l,d,m,y,_)=>{const[v,T]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),S=_.length;if(m<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(_.length!==1)throw new Error("Dimensionality of the output should be 1");if(_[0]!==m)throw new Error("Shape of the output should be equal to logical row count");const O=(0,h.getGlsl)(l.session.backend.glContext.version),w=` float process(int[${S}] indices) { int logical_row_start_offset = indices[0] * ${y}; - float max = getColorAsFloat(${A.texture2D}(A, offsetToCoords(logical_row_start_offset, ${_}, + float max = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset, ${v}, ${T} ))); for(int i=1; i<${y}; ++i) { - float current = getColorAsFloat(${A.texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${_}, ${T}))); + float current = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset + i, + ${v}, ${T}))); if(current > max) max = current; } return max; - }`;return Object.assign(Object.assign({},f),{output:{dims:v,type:d.type,textureType:o.TextureType.unpacked},shaderSource:w})},n=(l,d,m,y,v,_)=>{const[T,S]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),A=_.length;if(m<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(_.length!==1)throw new Error("Dimensionality of the output should be 1");if(_[0]!==m)throw new Error("Shape of the output should be equal to logical row count");if(v.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(v[0]!==m)throw new Error("Shape of the intermediate results should be equal to logical row count");const w=` - float process(int[${A}] indices) { + }`;return Object.assign(Object.assign({},f),{output:{dims:_,type:d.type,textureType:o.TextureType.unpacked},shaderSource:w})},n=(l,d,m,y,_,v)=>{const[T,S]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),O=v.length;if(m<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(v.length!==1)throw new Error("Dimensionality of the output should be 1");if(v[0]!==m)throw new Error("Shape of the output should be equal to logical row count");if(_.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(_[0]!==m)throw new Error("Shape of the intermediate results should be equal to logical row count");const w=` + float process(int[${O}] indices) { int logical_row_start_offset = indices[0] * ${y}; float norm_factor = 0.0; @@ -1452,8 +1452,8 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i } return norm_factor; - }`;return Object.assign(Object.assign({},s),{output:{dims:_,type:d.type,textureType:o.TextureType.unpacked},shaderSource:w})},r=(l,d,m,y,v,_)=>{const[T,S]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),A=d.dims.length;if(m<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(v.length!==1||_.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(v[0]!==m||_[0]!==m)throw new Error("Shape of the intermediate results should be equal to logical row count");const w=` - float process(int[${A}] indices) { + }`;return Object.assign(Object.assign({},s),{output:{dims:v,type:d.type,textureType:o.TextureType.unpacked},shaderSource:w})},r=(l,d,m,y,_,v)=>{const[T,S]=l.calculateTextureWidthAndHeight(d.dims,o.TextureType.unpacked),O=d.dims.length;if(m<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(_.length!==1||v.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(_[0]!==m||v[0]!==m)throw new Error("Shape of the intermediate results should be equal to logical row count");const w=` + float process(int[${O}] indices) { // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) int offset = coordsToOffset(TexCoords, ${T}, ${S}); @@ -1577,7 +1577,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i vec4 ${V}_(vec4 v) { return vec4(${V}_(v.x), ${V}_(v.y), ${V}_(v.z), ${V}_(v.w)); } - `,name:V,type:h.FunctionType.ValueBased}}function v(){return j("log")}function _(){const k="neg";return{body:` + `,name:V,type:h.FunctionType.ValueBased}}function _(){return j("log")}function v(){const k="neg";return{body:` float ${k}_(float a) { return -a; } @@ -1597,7 +1597,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i bvec4 ${k}_(bvec4 v) { return bvec4(!v.x, !v.y, !v.z, !v.w); } - `,name:k,type:h.FunctionType.ValueBased}}function S(){return j("sin")}function A(){const k="relu";return{body:` + `,name:k,type:h.FunctionType.ValueBased}}function S(){return j("sin")}function O(){const k="relu";return{body:` float ${k}_(float a) { return max( a, 0.0 ); } @@ -1629,14 +1629,14 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i vec4 ${k}_(vec4 v) { return ${k}(v); } - `,name:k,type:h.FunctionType.ValueBased}}u.glslAbs=f,u.glslAcos=s,u.glslAsin=i,u.glslAtan=t,u.glslCeil=e,u.glslCos=n,u.glslElu=r,u.glslExp=a,u.glslFloor=l,u.glslClip=d,u.glslIdentity=m,u.glslLeakyRelu=y,u.glslLog=v,u.glslNeg=_,u.glslNot=T,u.glslSin=S,u.glslRelu=A,u.glslSigmoid=w,u.glslSqrt=I,u.glslTan=R,u.glslTanh=B;const N=(k,V,J,Y)=>{const te=k.session.pack?c.TextureType.packed:c.TextureType.unpacked,ne={name:J.name,inputTypes:[te],inputNames:["A"],cacheHint:Y};return Object.assign(Object.assign({},ne),{get:()=>((me,Pe,Oe,le)=>{const xe=me.session.pack?c.TextureType.packed:c.TextureType.unpacked,_e=(0,o.getGlsl)(me.session.backend.glContext.version);return Object.assign(Object.assign({},Pe),{output:{dims:Oe.dims,type:Oe.type,textureType:xe},shaderSource:` + `,name:k,type:h.FunctionType.ValueBased}}u.glslAbs=f,u.glslAcos=s,u.glslAsin=i,u.glslAtan=t,u.glslCeil=e,u.glslCos=n,u.glslElu=r,u.glslExp=a,u.glslFloor=l,u.glslClip=d,u.glslIdentity=m,u.glslLeakyRelu=y,u.glslLog=_,u.glslNeg=v,u.glslNot=T,u.glslSin=S,u.glslRelu=O,u.glslSigmoid=w,u.glslSqrt=I,u.glslTan=R,u.glslTanh=B;const N=(k,V,J,Y)=>{const te=k.session.pack?c.TextureType.packed:c.TextureType.unpacked,ne={name:J.name,inputTypes:[te],inputNames:["A"],cacheHint:Y};return Object.assign(Object.assign({},ne),{get:()=>((me,Pe,Oe,le)=>{const xe=me.session.pack?c.TextureType.packed:c.TextureType.unpacked,_e=(0,o.getGlsl)(me.session.backend.glContext.version);return Object.assign(Object.assign({},Pe),{output:{dims:Oe.dims,type:Oe.type,textureType:xe},shaderSource:` ${le.body} void main() { vec4 v = ${_e.texture2D}(A, TexCoords); v = ${le.name}_(v); ${_e.output} = v; } - `,hasMain:!0})})(k,ne,V,J)})};u.abs=(k,V)=>[k.run(N(k,V[0],f()),V)],u.acos=(k,V)=>[k.run(N(k,V[0],s()),V)],u.asin=(k,V)=>[k.run(N(k,V[0],i()),V)],u.atan=(k,V)=>[k.run(N(k,V[0],t()),V)],u.clip=(k,V,J)=>[k.run(N(k,V[0],d(J.min,J.max),J.cacheKey),V)],u.parseClipAttributes=k=>(0,g.createAttributeWithCacheKey)({min:k.attributes.getFloat("min",p.MIN_CLIP),max:k.attributes.getFloat("max",p.MAX_CLIP)}),u.clipV11=(k,V)=>{const J=W(k,V);return(0,u.clip)(k,[V[0]],J)};const W=(k,V)=>{if(V.length>=3&&(!k.session.isInitializer(V[1].dataId)||!k.session.isInitializer(V[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const J=V.length>=3?V[1].numberData[0]:p.MIN_CLIP,Y=V.length>=3?V[2].numberData[0]:p.MAX_CLIP;return(0,g.createAttributeWithCacheKey)({min:J,max:Y})};u.ceil=(k,V)=>[k.run(N(k,V[0],e()),V)],u.cos=(k,V)=>[k.run(N(k,V[0],n()),V)],u.elu=(k,V,J)=>[k.run(N(k,V[0],r(J.alpha),J.cacheKey),V)],u.parseEluAttributes=k=>(0,g.createAttributeWithCacheKey)({alpha:k.attributes.getFloat("alpha",1)}),u.exp=(k,V)=>[k.run(N(k,V[0],a()),V)],u.floor=(k,V)=>[k.run(N(k,V[0],l()),V)],u.identity=(k,V)=>[k.run(N(k,V[0],m()),V)],u.leakyRelu=(k,V,J)=>[k.run(N(k,V[0],y(J.alpha),J.cacheKey),V)],u.parseLeakyReluAttributes=k=>(0,g.createAttributeWithCacheKey)({alpha:k.attributes.getFloat("alpha",.01)}),u.log=(k,V)=>[k.run(N(k,V[0],v()),V)],u.neg=(k,V)=>[k.run(N(k,V[0],_()),V)],u.not=(k,V)=>[k.run(N(k,V[0],T()),V)],u.relu=(k,V)=>[k.run(N(k,V[0],A()),V)],u.sigmoid=(k,V)=>[k.run(N(k,V[0],w()),V)],u.sin=(k,V)=>[k.run(N(k,V[0],S()),V)],u.sqrt=(k,V)=>[k.run(N(k,V[0],I()),V)],u.tan=(k,V)=>[k.run(N(k,V[0],R()),V)],u.tanh=(k,V)=>[k.run(N(k,V[0],B()),V)]},5611:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createUnpackProgramInfoLoader=u.createUnpackProgramInfo=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827),c={name:"unpack",inputNames:["A"],inputTypes:[p.TextureType.packed]};u.createUnpackProgramInfo=(f,s)=>{const i=s.dims.length,t=(0,o.getChannels)("rc",i),e=t.slice(-2),n=(0,h.getCoordsDataType)(i),r=(0,o.unpackFromChannel)(),a=s.dims.length===0?"":function(m,y){if(m===1)return"rc";let v="";for(let _=0;_[k.run(N(k,V[0],f()),V)],u.acos=(k,V)=>[k.run(N(k,V[0],s()),V)],u.asin=(k,V)=>[k.run(N(k,V[0],i()),V)],u.atan=(k,V)=>[k.run(N(k,V[0],t()),V)],u.clip=(k,V,J)=>[k.run(N(k,V[0],d(J.min,J.max),J.cacheKey),V)],u.parseClipAttributes=k=>(0,g.createAttributeWithCacheKey)({min:k.attributes.getFloat("min",p.MIN_CLIP),max:k.attributes.getFloat("max",p.MAX_CLIP)}),u.clipV11=(k,V)=>{const J=W(k,V);return(0,u.clip)(k,[V[0]],J)};const W=(k,V)=>{if(V.length>=3&&(!k.session.isInitializer(V[1].dataId)||!k.session.isInitializer(V[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const J=V.length>=3?V[1].numberData[0]:p.MIN_CLIP,Y=V.length>=3?V[2].numberData[0]:p.MAX_CLIP;return(0,g.createAttributeWithCacheKey)({min:J,max:Y})};u.ceil=(k,V)=>[k.run(N(k,V[0],e()),V)],u.cos=(k,V)=>[k.run(N(k,V[0],n()),V)],u.elu=(k,V,J)=>[k.run(N(k,V[0],r(J.alpha),J.cacheKey),V)],u.parseEluAttributes=k=>(0,g.createAttributeWithCacheKey)({alpha:k.attributes.getFloat("alpha",1)}),u.exp=(k,V)=>[k.run(N(k,V[0],a()),V)],u.floor=(k,V)=>[k.run(N(k,V[0],l()),V)],u.identity=(k,V)=>[k.run(N(k,V[0],m()),V)],u.leakyRelu=(k,V,J)=>[k.run(N(k,V[0],y(J.alpha),J.cacheKey),V)],u.parseLeakyReluAttributes=k=>(0,g.createAttributeWithCacheKey)({alpha:k.attributes.getFloat("alpha",.01)}),u.log=(k,V)=>[k.run(N(k,V[0],_()),V)],u.neg=(k,V)=>[k.run(N(k,V[0],v()),V)],u.not=(k,V)=>[k.run(N(k,V[0],T()),V)],u.relu=(k,V)=>[k.run(N(k,V[0],O()),V)],u.sigmoid=(k,V)=>[k.run(N(k,V[0],w()),V)],u.sin=(k,V)=>[k.run(N(k,V[0],S()),V)],u.sqrt=(k,V)=>[k.run(N(k,V[0],I()),V)],u.tan=(k,V)=>[k.run(N(k,V[0],R()),V)],u.tanh=(k,V)=>[k.run(N(k,V[0],B()),V)]},5611:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createUnpackProgramInfoLoader=u.createUnpackProgramInfo=void 0;const g=b(5060),p=b(2039),h=b(9390),o=b(2827),c={name:"unpack",inputNames:["A"],inputTypes:[p.TextureType.packed]};u.createUnpackProgramInfo=(f,s)=>{const i=s.dims.length,t=(0,o.getChannels)("rc",i),e=t.slice(-2),n=(0,h.getCoordsDataType)(i),r=(0,o.unpackFromChannel)(),a=s.dims.length===0?"":function(m,y){if(m===1)return"rc";let _="";for(let v=0;vObject.assign(Object.assign({},c),{get:()=>(0,u.createUnpackProgramInfo)(f,s)})},8428:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseUnsqueezeAttributes=u.unsqueezeV13=u.unsqueeze=void 0;const g=b(2517);u.unsqueeze=(o,c,f)=>{p(c);const s=g.ShapeUtil.unsqueezeShape(c[0].dims,f);return[o.reshapeUnpacked(c[0],s)]},u.unsqueezeV13=(o,c)=>(h(c),(0,u.unsqueeze)(o,[c[0]],Array.from(c[1].integerData))),u.parseUnsqueezeAttributes=o=>o.attributes.getInts("axes");const p=o=>{if(!o||o.length!==1)throw new Error("Unsqueeze requires 1 input.");if(o[0].type==="string")throw new Error("invalid input tensor types.")},h=o=>{if(!o||o.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(o[1].type!=="int32")throw new Error("Invalid input type.")}},9793:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.scalesValidation=u.validateInputs=u.parseUpsampleAttributes=u.parseUpsampleAttributesV9=u.parseUpsampleAttributesV7=u.upsample=void 0;const g=b(246),p=b(5060),h=b(2039),o={name:"Upsample",inputNames:["X"],inputTypes:[h.TextureType.unpacked]};u.upsample=(f,s,i)=>((0,u.validateInputs)(s,i),[f.run(Object.assign(Object.assign({},o),{cacheHint:i.cacheKey,get:()=>c(f,s,i)}),s)]),u.parseUpsampleAttributesV7=f=>(0,u.parseUpsampleAttributes)(f,7),u.parseUpsampleAttributesV9=f=>(0,u.parseUpsampleAttributes)(f,9),u.parseUpsampleAttributes=(f,s)=>{const i=s>=10,t=f.attributes.getString("mode","nearest");if(t!=="nearest"&&t!=="linear"&&(s<11||t!=="cubic"))throw new Error(`unrecognized mode: ${t}`);let e=[];s<9&&(e=f.attributes.getFloats("scales"),(0,u.scalesValidation)(e,t,i));const n=f.attributes.getFloat("extrapolation_value",0),r=s>10?f.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(r)===-1)throw new Error(`coordinate_transform_mode '${r}' is not supported`);const a=r==="tf_crop_and_resize",l=a,d=t==="nearest"&&s>=11?f.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(d)===-1)throw new Error(`nearest_mode '${d}' is not supported`);const m=f.attributes.getFloat("cubic_coeff_a",-.75),y=f.attributes.getInt("exclude_outside",0)!==0;if(y&&t!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const v=s<11||t==="nearest"&&r==="asymmetric"&&d==="floor";let _=0,T=0,S=0;return s>10?f.inputs.length>2?(_=1,T=2,S=3):(T=1,S=2):s===9&&(T=1),(0,g.createAttributeWithCacheKey)({opset:s,isResize:i,mode:t,scales:e,extrapolationValue:n,coordinateTransformMode:r,useExtrapolation:l,needRoiInput:a,nearestMode:d,cubicCoefficientA:m,excludeOutside:y,useNearest2xOptimization:v,roiInputIdx:_,scalesInputIdx:T,sizesInputIdx:S})};const c=(f,s,i)=>{const t=(0,p.getGlsl)(f.session.backend.glContext.version),[e,n]=f.calculateTextureWidthAndHeight(s[0].dims,h.TextureType.unpacked),r=s[0].dims.map((S,A)=>Math.floor(S*i.scales[A])),[a,l]=f.calculateTextureWidthAndHeight(r,h.TextureType.unpacked),d=r.length,m=new Array(d),y=new Array(d);let v=` + `;return Object.assign(Object.assign({},c),{hasMain:!0,output:{dims:s.dims,type:s.type,textureType:p.TextureType.unpacked},shaderSource:d})},u.createUnpackProgramInfoLoader=(f,s)=>Object.assign(Object.assign({},c),{get:()=>(0,u.createUnpackProgramInfo)(f,s)})},8428:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.parseUnsqueezeAttributes=u.unsqueezeV13=u.unsqueeze=void 0;const g=b(2517);u.unsqueeze=(o,c,f)=>{p(c);const s=g.ShapeUtil.unsqueezeShape(c[0].dims,f);return[o.reshapeUnpacked(c[0],s)]},u.unsqueezeV13=(o,c)=>(h(c),(0,u.unsqueeze)(o,[c[0]],Array.from(c[1].integerData))),u.parseUnsqueezeAttributes=o=>o.attributes.getInts("axes");const p=o=>{if(!o||o.length!==1)throw new Error("Unsqueeze requires 1 input.");if(o[0].type==="string")throw new Error("invalid input tensor types.")},h=o=>{if(!o||o.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(o[1].type!=="int32")throw new Error("Invalid input type.")}},9793:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.scalesValidation=u.validateInputs=u.parseUpsampleAttributes=u.parseUpsampleAttributesV9=u.parseUpsampleAttributesV7=u.upsample=void 0;const g=b(246),p=b(5060),h=b(2039),o={name:"Upsample",inputNames:["X"],inputTypes:[h.TextureType.unpacked]};u.upsample=(f,s,i)=>((0,u.validateInputs)(s,i),[f.run(Object.assign(Object.assign({},o),{cacheHint:i.cacheKey,get:()=>c(f,s,i)}),s)]),u.parseUpsampleAttributesV7=f=>(0,u.parseUpsampleAttributes)(f,7),u.parseUpsampleAttributesV9=f=>(0,u.parseUpsampleAttributes)(f,9),u.parseUpsampleAttributes=(f,s)=>{const i=s>=10,t=f.attributes.getString("mode","nearest");if(t!=="nearest"&&t!=="linear"&&(s<11||t!=="cubic"))throw new Error(`unrecognized mode: ${t}`);let e=[];s<9&&(e=f.attributes.getFloats("scales"),(0,u.scalesValidation)(e,t,i));const n=f.attributes.getFloat("extrapolation_value",0),r=s>10?f.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(r)===-1)throw new Error(`coordinate_transform_mode '${r}' is not supported`);const a=r==="tf_crop_and_resize",l=a,d=t==="nearest"&&s>=11?f.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(d)===-1)throw new Error(`nearest_mode '${d}' is not supported`);const m=f.attributes.getFloat("cubic_coeff_a",-.75),y=f.attributes.getInt("exclude_outside",0)!==0;if(y&&t!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const _=s<11||t==="nearest"&&r==="asymmetric"&&d==="floor";let v=0,T=0,S=0;return s>10?f.inputs.length>2?(v=1,T=2,S=3):(T=1,S=2):s===9&&(T=1),(0,g.createAttributeWithCacheKey)({opset:s,isResize:i,mode:t,scales:e,extrapolationValue:n,coordinateTransformMode:r,useExtrapolation:l,needRoiInput:a,nearestMode:d,cubicCoefficientA:m,excludeOutside:y,useNearest2xOptimization:_,roiInputIdx:v,scalesInputIdx:T,sizesInputIdx:S})};const c=(f,s,i)=>{const t=(0,p.getGlsl)(f.session.backend.glContext.version),[e,n]=f.calculateTextureWidthAndHeight(s[0].dims,h.TextureType.unpacked),r=s[0].dims.map((S,O)=>Math.floor(S*i.scales[O])),[a,l]=f.calculateTextureWidthAndHeight(r,h.TextureType.unpacked),d=r.length,m=new Array(d),y=new Array(d);let _=` int output_pitches[${d}]; int input_pitches[${d}]; - `;for(let S=d-1;S>=0;S--)m[S]=S===d-1?1:m[S+1]*r[S+1],y[S]=S===d-1?1:y[S+1]*s[0].dims[S+1],v+=` + `;for(let S=d-1;S>=0;S--)m[S]=S===d-1?1:m[S+1]*r[S+1],y[S]=S===d-1?1:y[S+1]*s[0].dims[S+1],_+=` output_pitches[${S}] = ${m[S]}; input_pitches[${S}] = ${y[S]}; - `;const _=` + `;const v=` float getInputFloat(int index) { vec2 coords = offsetToCoords(index, ${e}, ${n}); float value = getColorAsFloat(${t.texture2D}(X, coords)); return value; } `,T=i.mode==="nearest"?` - ${_} + ${v} float process(int indices[${d}]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${a}, ${l}); - ${v} + ${_} int d, m; for (int dim = 0; dim < ${d}; ++dim) { @@ -1682,12 +1682,12 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i return getInputFloat(input_index); }`:d===4?` - ${_} + ${v} float process(int indices[4]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${a}, ${l}); - ${v} + ${_} int m; int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; @@ -1736,12 +1736,12 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); }`:` - ${_} + ${v} float process(int indices[2]) { int input_index = 0; int output_index = coordsToOffset(TexCoords, ${a}, ${l}); - ${v} + ${_} int m; int index_of_dim0, index_of_dim1; @@ -1786,5 +1786,5 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),u.reduceProd=(i ${c} `);const f=this.glContext.compileShader(c,this.glContext.gl.FRAGMENT_SHADER),s=this.glContext.createProgram(this.vertexShader,f);return this.glContext.deleteShader(f),s}bindOutput(c){const f=c.width,s=c.height;p.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${f}/${s}, shape=${c.shape}, type=${c.tensor.type}`),this.glContext.attachFramebuffer(c.texture,f,s)}bindAttributes(c){const f=c.position,s=c.textureCoord;this.glContext.setVertexAttributes(f,s),this.attributesBound=!0}bindUniforms(c,f,s){var i;const t=this.glContext.gl;let e=0;for(const{name:n,type:r,location:a,arrayLength:l}of c){const d=(i=f.find(m=>m.name===n))===null||i===void 0?void 0:i.data;if(r!=="sampler2D"&&!d)throw new Error(`variable '${n}' does not have data defined in program info`);switch(r){case"sampler2D":this.bindTexture(s[e],a,e),e++;break;case"float":l?t.uniform1fv(a,d):t.uniform1f(a,d);break;case"int":l?t.uniform1iv(a,d):t.uniform1i(a,d);break;default:throw new Error(`Uniform not implemented: ${r}`)}}}bindTexture(c,f,s){this.glContext.bindTextureToUniform(c.texture,s,f)}getAttribLocations(c){return{position:this.getAttribLocation(c,"position"),textureCoord:this.getAttribLocation(c,"textureCoord")}}getUniformLocations(c,f,s){const i=[];if(f)for(const t of f)i.push({name:t,type:"sampler2D",location:this.getUniformLocation(c,t)});if(s)for(const t of s)i.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(c,t.name)}));return i}getUniformLocation(c,f){const s=this.glContext.gl.getUniformLocation(c,f);if(s===null)throw new Error(`Uniform ${f} not found.`);return s}getAttribLocation(c,f){return this.glContext.gl.getAttribLocation(c,f)}}},6416:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.WebGLSessionHandler=void 0;const g=b(6231),p=b(1047),h=b(8316),o=b(1640),c=b(1958),f=b(7859),s=b(5702);u.WebGLSessionHandler=class{constructor(i,t){this.backend=i,this.context=t,this.layoutStrategy=new f.PreferLogicalStrategy(i.glContext.maxTextureSize),this.programManager=new c.ProgramManager(this.context.profiler,i.glContext,this.layoutStrategy),this.textureManager=new s.TextureManager(i.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:i.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=i.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new h.WebGLInferenceHandler(this)}onGraphInitialized(i){const t=i.getValues().filter(e=>e.from===-1&&e.tensor).map(e=>e.tensor.dataId);this.initializers=new Set(t)}isInitializer(i){return!!this.initializers&&this.initializers.has(i)}addInitializer(i){this.initializers.add(i)}getTextureData(i,t){return t?this.packedTextureDataCache.get(i):this.unpackedTextureDataCache.get(i)}setTextureData(i,t,e=!1){g.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),e?this.packedTextureDataCache.set(i,t):this.unpackedTextureDataCache.set(i,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(i=>this.textureManager.releaseTexture(i,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(i=>this.textureManager.releaseTexture(i,!0)),this.unpackedTextureDataCache=new Map}resolve(i,t,e){const n=(0,p.resolveOperator)(i,t,o.WEBGL_OP_RESOLVE_RULES);return{impl:n.opImpl,context:n.opInit?n.opInit(i,e):i}}}},7769:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Uint8DataEncoder=u.RGBAFloatDataEncoder=u.RedFloat32DataEncoder=void 0;const g=b(6231);u.RedFloat32DataEncoder=class{constructor(p,h=1){if(h===1)this.internalFormat=p.R32F,this.format=p.RED,this.textureType=p.FLOAT,this.channelSize=h;else{if(h!==4)throw new Error(`Invalid number of channels: ${h}`);this.internalFormat=p.RGBA32F,this.format=p.RGBA,this.textureType=p.FLOAT,this.channelSize=h}}encode(p,h){let o,c;return p.constructor!==Float32Array&&(g.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),c=new Float32Array(p)),h*this.channelSize>p.length?(g.Logger.warning("Encoder","Source data too small. Allocating larger array"),c=p,o=this.allocate(h*this.channelSize),c.forEach((f,s)=>o[s]=f)):(c=p,o=c),o}allocate(p){return new Float32Array(4*p)}decode(p,h){return this.channelSize===1?p.filter((o,c)=>c%4==0).subarray(0,h):p.subarray(0,h)}},u.RGBAFloatDataEncoder=class{constructor(p,h=1,o){if(h!==1&&h!==4)throw new Error(`Invalid number of channels: ${h}`);this.internalFormat=p.RGBA,this.format=p.RGBA,this.channelSize=h,this.textureType=o||p.FLOAT}encode(p,h){let o=p;return this.channelSize===1&&(g.Logger.verbose("Encoder","Exploding into a larger array"),o=this.allocate(h),p.forEach((c,f)=>o[4*f]=c)),o}allocate(p){return new Float32Array(4*p)}decode(p,h){return this.channelSize===1?p.filter((o,c)=>c%4==0).subarray(0,h):p.subarray(0,h)}},u.Uint8DataEncoder=class{constructor(p,h=1){if(this.channelSize=4,h===1)this.internalFormat=p.ALPHA,this.format=p.ALPHA,this.textureType=p.UNSIGNED_BYTE,this.channelSize=h;else{if(h!==4)throw new Error(`Invalid number of channels: ${h}`);this.internalFormat=p.RGBA,this.format=p.RGBA,this.textureType=p.UNSIGNED_BYTE,this.channelSize=h}}encode(p,h){return new Uint8Array(p.buffer,p.byteOffset,p.byteLength)}allocate(p){return new Uint8Array(p*this.channelSize)}decode(p,h){if(p instanceof Uint8Array)return p.subarray(0,h);throw new Error(`Invalid array type: ${p.constructor}`)}}},7859:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.getBatchDim=u.sizeToSquarishShape=u.getRowsCols=u.sizeFromShape=u.isInt=u.parseAxisParam=u.squeezeShape=u.PreferLogicalStrategy=u.AlwaysKeepOriginalSizeStrategy=void 0;const g=b(6231),p=b(2517);function h(i,t){const e=[],n=[],r=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||r?null:o(t,i).sort();let l=0;for(let d=0;dd)&&i[d]===1&&(e.push(i[d]),n.push(d)),a[l]<=d&&l++}i[d]!==1&&(e.push(i[d]),n.push(d))}return{newShape:e,keptDims:n}}function o(i,t){const e=t.length;return i=i==null?t.map((n,r)=>r):[].concat(i),(0,p.assert)(i.every(n=>n>=-e&&n`All values in axis param must be in range [-${e}, ${e}) but got axis ${i}`),(0,p.assert)(i.every(c),()=>`All values in axis param must be integers but got axis ${i}`),i.map(n=>n<0?e+n:n)}function c(i){return i%1==0}function f(i){if(i.length===0)return 1;let t=i[0];for(let e=1;e=i.length?1:i.slice(t.breakAxis).reduce((d,m)=>d*m),l=t.breakAxis<=0?1:i.slice(0,t.breakAxis).reduce((d,m)=>d*m);if(!(a>e||l>e))return[a,l];g.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${i}, breakAxis:${t.breakAxis}`)}const n=i.reduce((a,l)=>a*l);let r=Math.floor(Math.sqrt(n));for(;r=e||n%r!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${i}`);return[r,n/r]}},u.PreferLogicalStrategy=class{constructor(i){this.maxTextureSize=i}computeTextureWH(i,t){const e=this.computeTexture(i,t);return t&&t.isPacked&&(e[0]/=2,e[1]/=2),t&&t.reverseWH?[e[1],e[0]]:e}computeTexture(i,t){const e=t&&t.isPacked;if(i.length===0)return e?[2,2]:[1,1];let n=this.maxTextureSize;if(t&&t.breakAxis!==void 0){const l=t.breakAxis>=i.length?1:i.slice(t.breakAxis).reduce((m,y)=>m*y),d=t.breakAxis<=0?1:i.slice(0,t.breakAxis).reduce((m,y)=>m*y);if(!(l>n||d>n))return[l,d];g.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${i}, breakAxis:${t.breakAxis}`)}let r=i.slice(0);e&&(n*=2,r=r.map((l,d)=>d>=r.length-2?r[d]%2==0?r[d]:r[d]+1:r[d]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=h(r).newShape);const a=f(r);return r.length<=1&&a<=n?[1,a]:r.length===2&&r[0]<=n&&r[1]<=n?r:r.length===3&&r[0]*r[1]<=n&&r[2]<=n?[r[0]*r[1],r[2]]:r.length===3&&r[0]<=n&&r[1]*r[2]<=n?[r[0],r[1]*r[2]]:r.length===4&&r[0]*r[1]*r[2]<=n&&r[3]<=n?[r[0]*r[1]*r[2],r[3]]:r.length===4&&r[0]<=n&&r[1]*r[2]*r[3]<=n?[r[0],r[1]*r[2]*r[3]]:e?s(a/4).map(l=>2*l):s(a)}},u.squeezeShape=h,u.parseAxisParam=o,u.isInt=c,u.sizeFromShape=f,u.getRowsCols=function(i){if(i.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[i.length>1?i[i.length-2]:1,i[i.length-1]]},u.sizeToSquarishShape=s,u.getBatchDim=function(i,t=2){return f(i.slice(0,i.length-t))}},4057:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createTextureLayoutFromShape=u.calculateTextureWidthAndHeight=u.createTextureLayoutFromTextureType=void 0;const g=b(2517),p=b(2039);u.createTextureLayoutFromTextureType=(h,o,c)=>{const f=c===p.TextureType.unpacked||c===p.TextureType.unpackedReversed?1:4,s=c===p.TextureType.packed,i=c===p.TextureType.unpackedReversed||c===p.TextureType.packed,t=c===p.TextureType.packedLastDimension?o.length-1:void 0,e=c===p.TextureType.packedLastDimension?o.map((n,r)=>r===o.length-1?4*n:n):void 0;return(0,u.createTextureLayoutFromShape)(h,o,f,e,{isPacked:s,reverseWH:i,breakAxis:t})},u.calculateTextureWidthAndHeight=(h,o,c)=>{const f=(0,u.createTextureLayoutFromTextureType)(h,o,c);return[f.width,f.height]},u.createTextureLayoutFromShape=(h,o,c=1,f,s)=>{const i=!(!s||!s.isPacked),[t,e]=h.computeTextureWH(i&&f||o,s),n=o.length;let r=o.slice(0);if(n===0&&(r=[1]),c===1)f=o;else if(i){if(c!==4)throw new Error("a packed texture must be 4-channel");f=o,n>0&&(r[n-1]=Math.ceil(r[n-1]/2)),n>1&&(r[n-2]=Math.ceil(r[n-2]/2))}else if(!f)throw new Error("Unpacked shape is needed when using channels > 1");return{width:t,height:e,channels:c,isPacked:i,shape:r,strides:g.ShapeUtil.computeStrides(r),unpackedShape:f,reversedWH:s&&s.reverseWH}}},5702:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.TextureManager=void 0;const g=b(6231);u.TextureManager=class{constructor(p,h,o,c){this.glContext=p,this.layoutStrategy=h,this.profiler=o,this.config=c,this.pendingRead=new Map,c.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(p,h,o,c){const f=this.toEncoderType(p),s=this.glContext.getEncoder(f,h.channels||1,c);if(h.isPacked&&c===1)throw new Error("not implemented");const i=h.width,t=h.height;let e,n;if(this.config.reuseTextures){e=`${i}x${t}_${s.format}_${s.internalFormat}_${s.textureType}`,n=this.inUseTextures.get(e),n||(n=[],this.inUseTextures.set(e,n));const a=this.idleTextures.get(e);if(a&&a.length>0){const l=a.pop();return n.push(l),c===1&&this.glContext.updateTexture(l,i,t,s,this.toTextureData(p,o)),l}}g.Logger.verbose("TextureManager",`Creating new texture of size ${h.width}x${h.height}`);const r=this.glContext.allocateTexture(i,t,s,this.toTextureData(p,o));return this.config.reuseTextures&&(n.push(r),this.textureLookup.set(r,e)),r}readTexture(p,h,o){return o||(o=1),this.profiler.event("backend","TextureManager.readTexture",()=>{const c=p.shape.reduce((s,i)=>s*i)*o,f=this.glContext.readTexture(p.texture,p.width,p.height,c,this.toEncoderType(h),o);return this.toTensorData(h,f)})}async readTextureAsync(p,h,o){const c=p.tensor.dataId;if(o||(o=1),this.pendingRead.has(c)){const f=this.pendingRead.get(c);return new Promise(s=>f==null?void 0:f.push(s))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(c,[]);const f=p.shape.reduce((e,n)=>e*n)*o;await this.glContext.createAndWaitForFence();const s=this.glContext.readTexture(p.texture,p.width,p.height,f,this.toEncoderType(h),o),i=this.toTensorData(h,s),t=this.pendingRead.get(c);return this.pendingRead.delete(c),t==null||t.forEach(e=>e(i)),i})}readUint8TextureAsFloat(p){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{const h=p.shape.reduce((c,f)=>c*f),o=this.glContext.readTexture(p.texture,p.width,p.height,4*h,"byte",4);return new Float32Array(o.buffer,o.byteOffset,h)})}releaseTexture(p,h){let o;if(this.config.reuseTextures&&(o=this.textureLookup.get(p.texture),o)){h&&this.textureLookup.delete(o);const c=this.inUseTextures.get(o);if(c){const f=c.indexOf(p.texture);if(f!==-1){c.splice(f,1);let s=this.idleTextures.get(o);s||(s=[],this.idleTextures.set(o,s)),s.push(p.texture)}}}o&&!h||(g.Logger.verbose("TextureManager",`Deleting texture of size ${p.width}x${p.height}`),this.glContext.deleteTexture(p.texture))}toTensorData(p,h){switch(p){case"int16":return h instanceof Int16Array?h:Int16Array.from(h);case"int32":return h instanceof Int32Array?h:Int32Array.from(h);case"int8":return h instanceof Int8Array?h:Int8Array.from(h);case"uint16":return h instanceof Uint16Array?h:Uint16Array.from(h);case"uint32":return h instanceof Uint32Array?h:Uint32Array.from(h);case"uint8":case"bool":return h instanceof Uint8Array?h:Uint8Array.from(h);case"float32":return h instanceof Float32Array?h:Float32Array.from(h);case"float64":return h instanceof Float64Array?h:Float64Array.from(h);default:throw new Error(`TensorData type ${p} is not supported`)}}toTextureData(p,h){if(h)return h instanceof Float32Array?h:new Float32Array(h)}toEncoderType(p){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(D,u)=>{var b;Object.defineProperty(u,"__esModule",{value:!0}),u.TextureType=void 0,(b=u.TextureType||(u.TextureType={}))[b.unpacked=0]="unpacked",b[b.unpackedReversed=1]="unpackedReversed",b[b.packed=2]="packed",b[b.downloadUint8AsFloat=3]="downloadUint8AsFloat",b[b.packedLastDimension=4]="packedLastDimension"},9390:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.getGlChannels=u.getCoordsDataType=u.getSqueezedParams=u.squeezeInputShape=u.generateShaderFuncNameFromInputSamplerNameAtOutCoords=u.generateShaderFuncNameFromInputSamplerName=u.repeatedTry=u.getPackedShape=void 0;const g=b(2517);u.getPackedShape=function(p){const h=p.length;return p.slice(0,h-1).concat(p[h-1]/4)},u.repeatedTry=async function(p,h=c=>0,o){return new Promise((c,f)=>{let s=0;const i=()=>{if(p())return void c();s++;const t=h(s);o!=null&&s>=o?f():setTimeout(i,t)};i()})},u.generateShaderFuncNameFromInputSamplerName=function(p){return(0,g.assert)(p!==void 0&&p.length!==0,()=>"empty string found for sampler name"),"get"+p.charAt(0).toUpperCase()+p.slice(1)},u.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(p){return(0,g.assert)(p!==void 0&&p.length!==0,()=>"empty string found for sampler name"),"get"+p.charAt(0).toUpperCase()+p.slice(1)+"AtOutCoords"},u.squeezeInputShape=function(p,h){let o=JSON.parse(JSON.stringify(p));return o=h,o},u.getSqueezedParams=function(p,h){return h.map(o=>p[o]).join(", ")},u.getCoordsDataType=function(p){if(p<=1)return"int";if(p===2)return"ivec2";if(p===3)return"ivec3";if(p===4)return"ivec4";if(p===5)return"ivec5";if(p===6)return"ivec6";throw Error(`GPU for rank ${p} is not yet supported`)},u.getGlChannels=function(p=6){return["x","y","z","w","u","v"].slice(0,p)}},7305:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.createNewWebGLContext=u.createWebGLContext=void 0;const g=b(6231),p=b(1713),h={};function o(c){const f=function(){if(typeof document>"u"){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const t=document.createElement("canvas");return t.width=1,t.height=1,t}();let s;const i={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!c||c==="webgl2")&&(s=f.getContext("webgl2",i),s))try{return new p.WebGLContext(s,2)}catch(t){g.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!c||c==="webgl")&&(s=f.getContext("webgl",i)||f.getContext("experimental-webgl",i),s))try{return new p.WebGLContext(s,1)}catch(t){g.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}u.createWebGLContext=function c(f){let s;f&&f!=="webgl2"||!("webgl2"in h)?f&&f!=="webgl"||!("webgl"in h)||(s=h.webgl):s=h.webgl2,s=s||o(f),f=f||s.version===1?"webgl":"webgl2";const i=s.gl;return h[f]=s,i.isContextLost()?(delete h[f],c(f)):(i.disable(i.DEPTH_TEST),i.disable(i.STENCIL_TEST),i.disable(i.BLEND),i.disable(i.DITHER),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SAMPLE_COVERAGE),i.enable(i.SCISSOR_TEST),i.enable(i.CULL_FACE),i.cullFace(i.BACK),s)},u.createNewWebGLContext=o},1713:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(i,t,e,n){n===void 0&&(n=e);var r=Object.getOwnPropertyDescriptor(t,e);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(i,n,r)}:function(i,t,e,n){n===void 0&&(n=e),i[n]=t[e]}),p=this&&this.__setModuleDefault||(Object.create?function(i,t){Object.defineProperty(i,"default",{enumerable:!0,value:t})}:function(i,t){i.default=t}),h=this&&this.__importStar||function(i){if(i&&i.__esModule)return i;var t={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&g(t,i,e);return p(t,i),t};Object.defineProperty(u,"__esModule",{value:!0}),u.WebGLContext=u.linearSearchLastTrue=void 0;const o=b(1670),c=h(b(7769)),f=b(9390);function s(i){let t=0;for(;tthis.isTimerResultAvailable(i)),this.getTimerResult(i)}async createAndWaitForFence(){const i=this.createFence(this.gl);return this.pollFence(i)}createFence(i){let t;const e=i,n=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return i.flush(),t=n===null?()=>!0:()=>{const r=e.clientWaitSync(n,0,0);return r===e.ALREADY_SIGNALED||r===e.CONDITION_SATISFIED},{query:n,isFencePassed:t}}async pollFence(i){return new Promise(t=>{this.addItemToPoll(()=>i.isFencePassed(),()=>t())})}pollItems(){const i=s(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=i;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(i+1)}async addItemToPoll(i,t){this.itemsToPoll.push({isDoneFn:i,resolveFn:t}),this.itemsToPoll.length>1||await(0,f.repeatedTry)(()=>(this.pollItems(),this.itemsToPoll.length===0))}}},1036:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ExecutionPlan=void 0;const g=b(6231);class p{constructor(o,c){this.op=o,this.node=c}}u.ExecutionPlan=class{constructor(h,o,c){this.graph=h,this.profiler=c,this.initialize(o)}initialize(h){this.profiler.event("session","ExecutionPlan.initialize",()=>{const o=this.graph.getNodes();if(o.length!==h.length)throw new Error("The size of nodes and OPs do not match.");this._ops=h.map((c,f)=>new p(c,o[f])),this.reset(),this._starter=[],this._ops.forEach((c,f)=>{let s=!0;for(const i of c.node.inputs)if(!this._values[i]&&this.graph.getInputIndices().indexOf(i)===-1){s=!1;break}s&&this._starter.push(f)})})}reset(){this._values=this.graph.getValues().map(h=>h.tensor)}async execute(h,o){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const c=h.createInferenceHandler(),f=this.graph.getInputIndices();if(o.length!==f.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${o.length} expected: ${f.length}`);o.forEach((r,a)=>{const l=f[a];this._values[l]=r});const s=this._starter.slice(0),i=this.graph.getValues(),t=this.graph.getNodes();let e=0;for(;ethis._values[v]);if(l.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${a.node}`);const d=l;g.Logger.verbose("ExecPlan",`Runing op:${a.node.name} (${d.map((v,_)=>`'${a.node.inputs[_]}': ${v.type}[${v.dims.join(",")}]`).join(", ")})`);const m=await this.profiler.event("node",a.node.name,async()=>a.op.impl(c,d,a.op.context));if(m.length!==a.node.outputs.length)throw new Error("the size of output does not match model definition.");m.forEach((v,_)=>{const T=a.node.outputs[_];if(this._values[T])throw new Error(`output [${T}] already has value: op:${a.node.name}`);this._values[T]=v});const y=new Set;m.forEach((v,_)=>{const T=a.node.outputs[_];for(const S of i[T].to){const A=t[S];let w=!0;for(const I of A.inputs)if(!this._values[I]){w=!1;break}w&&y.add(S)}}),s.push(...y)}const n=[];for(let r=0;r{Object.defineProperty(u,"__esModule",{value:!0}),u.Graph=void 0;const g=b(1446),p=b(7778),h=b(9395),o=b(9162),c=b(2517);var f=h.onnxruntime.experimental.fbs;u.Graph={from:(e,n)=>new t(e,n)};class s{constructor(n){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,n&&(this.type=c.ProtoUtil.tensorValueTypeFromProto(n.type.tensorType))}get from(){return this._from}get to(){return this._to}}class i{constructor(n,r){n instanceof g.onnx.NodeProto?(this.name=n.name,this.opType=n.opType,this.attributes=new p.Attribute(n.attribute)):n instanceof f.Node&&(this.name=r??n.name(),this.opType=n.opType(),this.attributes=new p.Attribute(c.ProtoUtil.tensorAttributesFromORTFormat(n))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class t{constructor(n,r){if(!n)throw new TypeError("graph is empty");this.buildGraph(n),this.transformGraph(r),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(n){if(n instanceof g.onnx.GraphProto)this.buildGraphFromOnnxFormat(n);else{if(!(n instanceof f.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(n)}}buildGraphFromOnnxFormat(n){const r=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const a=new Map;if(!n.input)throw new Error("missing information in graph: input");const l=[];for(const d of n.input){if(r.has(d.name))throw new Error(`duplicated input name: ${d.name}`);const m=this._allData.push(new s(d))-1;r.set(d.name,m),l.push(d.name)}if(!n.initializer)throw new Error("missing information in graph: initializer");for(const d of n.initializer){let m=r.get(d.name);if(m===void 0){const y=new s;y.type={shape:{dims:c.ProtoUtil.tensorDimsFromProto(d.dims)},tensorType:c.ProtoUtil.tensorDataTypeFromProto(d.dataType)},m=this._allData.push(y)-1,r.set(d.name,m)}this._allData[m]._from=-1,this._allData[m].tensor=o.Tensor.fromProto(d)}for(let d=0;d{this._allData[l]._to.forEach(d=>{n.add(d)})});const r=Array.from(n),a=new Array(this._nodes.length).fill("white");for(;r.length>0;){const l=r.pop();a[l]==="gray"?a[l]="black":(r.push(l),a[l]="gray",this._nodes[l].outputs.forEach(d=>{const m=this._allData[d];if(m.tensor!==void 0)throw new Error("node outputs should not be initialized");if(m._from!==l)throw new Error("from property of the Value object doesn't match index of Node being processed");m._to.forEach(y=>{if(a[y]==="gray")throw new Error("model graph is cyclic");a[y]==="white"&&r.push(y)})}))}}transformGraph(n){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),n&&n.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let n=0;for(let r=0;r0&&(this._nodes[r].inputs.forEach(a=>{const l=this._allData[a]._to.indexOf(r+n);l!==-1&&(this._allData[a]._to[l]=r)}),this._nodes[r].outputs.forEach(a=>{this._allData[a]._from&&this._allData[a]._from===r+n&&(this._allData[a]._from=r)})):(n++,this._nodes[r].outputs.forEach(a=>{this._allData[a]._from=-2}),this._nodes.splice(r,1),r--);n=0;for(let r=0;r0){let a=-1;this._allData[r].from!==void 0&&this._allData[r].from!==-1?(a=this._nodes[this._allData[r].from].outputs.indexOf(r+n),a!==-1&&(this._nodes[this._allData[r].from].outputs[a]=r)):(a=this._allInputIndices.indexOf(r+n),a!==-1&&(this._allInputIndices[a]=r)),this._allData[r].to.forEach(l=>{a=this._nodes[l].inputs.indexOf(r+n),a!==-1&&(this._nodes[l].inputs[a]=r)}),this._allData[r].to.length===0&&(a=this._allOutputIndices.indexOf(r+n),a!==-1&&(this._allOutputIndices[a]=r))}}else n++,this._allData.splice(r,1),r--}deleteNode(n){const r=this._nodes[n];if(r.outputs.length>1){for(let v=1;v0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}r.executeNode=!1;const a=r.inputs[0],l=r.outputs[0],d=this._allData[l].to,m=this._allData[a].to.indexOf(n);if(m===-1)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[a].to.splice(m,1),this._allData[l]._to=[];const y=this._allOutputIndices.indexOf(l);if(y!==-1&&(this._allOutputIndices[y]=a),d&&d.length>0)for(const v of d){const _=this._nodes[v].inputs.indexOf(l);if(_===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[v].inputs[_]=a,this._allData[a].to.push(v)}}removeAllDropoutNodes(){let n=0;for(const r of this._nodes){if(r.opType==="Dropout"){if(r.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(r.outputs.length!==1&&r.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(r.outputs.length===2&&this._allData[r.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(n)}n++}}removeAllIdentityNodes(){let n=0;for(const r of this._nodes)r.opType==="Identity"&&this.deleteNode(n),n++}isActivation(n){switch(n.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const n of this._nodes)if(n.opType==="Conv"){const r=this._allData[n.outputs[0]]._to;if(r.length===1&&this.isActivation(this._nodes[r[0]])){const a=this._nodes[r[0]];if(a.opType==="Clip")if(a.inputs.length===1)try{n.attributes.set("activation_params","floats",[a.attributes.getFloat("min"),a.attributes.getFloat("max")])}catch{n.attributes.set("activation_params","floats",[c.MIN_CLIP,c.MAX_CLIP])}else{if(!(a.inputs.length>=3&&this._allData[a.inputs[1]].tensor!==void 0&&this._allData[a.inputs[2]].tensor!==void 0))continue;n.attributes.set("activation_params","floats",[this._allData[a.inputs[1]].tensor.floatData[0],this._allData[a.inputs[2]].tensor.floatData[0]])}n.attributes.set("activation","string",a.opType),this.deleteNode(r[0])}}}}},6231:(D,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.now=u.Profiler=u.Logger=void 0;const b={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},g={none:new class{log(i,t,e){}},console:new class{log(i,t,e){console.log(`${this.color(i)} ${e?"\x1B[35m"+e+"\x1B[0m ":""}${t}`)}color(i){switch(i){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${i}`)}}}},p={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let h={"":p};function o(i,t,e,n){if(t===void 0)return r=i,{verbose:o.verbose.bind(null,r),info:o.info.bind(null,r),warning:o.warning.bind(null,r),error:o.error.bind(null,r),fatal:o.fatal.bind(null,r)};if(e===void 0)c(i,t);else if(typeof e=="number"&&n===void 0)c(i,t);else if(typeof e=="string"&&n===void 0)c(i,e,0,t);else{if(typeof e!="string"||typeof n!="number")throw new TypeError("input is valid");c(i,e,0,t)}var r}function c(i,t,e,n){const r=h[n||""]||h[""];b[i]{l.then(async y=>{r&&await r.end(),d(y)},async y=>{r&&await r.end(),m(y)})});if(!a&&r){const d=r.end();if(d&&typeof d.then=="function")return new Promise((m,y)=>{d.then(()=>{m(l)},v=>{y(v)})})}return l}begin(i,t,e){if(!this._started)throw new Error("profiler is not started yet");if(e===void 0){const n=(0,u.now)();return this.flush(n),new f(i,t,n,r=>this.endSync(r))}{const n=e.beginTimer();return new f(i,t,0,async r=>this.end(r),n,e)}}async end(i){const t=await i.checkTimer();this._timingEvents.length=this._flushBatchSize||i-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Model=void 0;const g=b(5686),p=b(1446),h=b(7070),o=b(9395),c=b(2517);var f=o.onnxruntime.experimental.fbs;u.Model=class{constructor(){}load(s,i,t){if(!t)try{return void this.loadFromOnnxFormat(s,i)}catch(e){if(t!==void 0)throw e}this.loadFromOrtFormat(s,i)}loadFromOnnxFormat(s,i){const t=p.onnx.ModelProto.decode(s);if(c.LongUtil.longToNumber(t.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=t.opsetImport.map(e=>({domain:e.domain,version:c.LongUtil.longToNumber(e.version)})),this._graph=h.Graph.from(t.graph,i)}loadFromOrtFormat(s,i){const t=new g.flatbuffers.ByteBuffer(s),e=f.InferenceSession.getRootAsInferenceSession(t).model();if(c.LongUtil.longToNumber(e.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let n=0;n{Object.defineProperty(u,"__esModule",{value:!0}),u.FLOAT_TYPES=u.INT_TYPES=u.NUMBER_TYPES=void 0,u.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],u.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],u.FLOAT_TYPES=["float32","float64"]},1047:(D,u)=>{function b(g,p){if(p.endsWith("+")){const h=Number.parseInt(p.substring(0,p.length-1),10);return!isNaN(h)&&h<=g}if(p.split("-").length===2){const h=p.split("-"),o=Number.parseInt(h[0],10),c=Number.parseInt(h[1],10);return!isNaN(o)&&!isNaN(c)&&o<=g&&g<=c}return Number.parseInt(p,10)===g}Object.defineProperty(u,"__esModule",{value:!0}),u.resolveOperator=void 0,u.resolveOperator=function(g,p,h){for(const o of h){const c=o[0],f=o[1],s=o[2],i=o[3],t=o[4];if(g.opType===c){for(const e of p)if((e.domain===f||e.domain==="ai.onnx"&&f==="")&&b(e.version,s))return{opImpl:i,opInit:t}}}throw new TypeError(`cannot resolve operator '${g.opType}' with opsets: ${p.map(o=>`${o.domain||"ai.onnx"} v${o.version}`).join(", ")}`)}},9395:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.onnxruntime=void 0;const g=b(5686);var p,h;p=u.onnxruntime||(u.onnxruntime={}),function(o){(function(c){c[c.UNDEFINED=0]="UNDEFINED",c[c.FLOAT=1]="FLOAT",c[c.INT=2]="INT",c[c.STRING=3]="STRING",c[c.TENSOR=4]="TENSOR",c[c.GRAPH=5]="GRAPH",c[c.FLOATS=6]="FLOATS",c[c.INTS=7]="INTS",c[c.STRINGS=8]="STRINGS",c[c.TENSORS=9]="TENSORS",c[c.GRAPHS=10]="GRAPHS",c[c.SPARSE_TENSOR=11]="SPARSE_TENSOR",c[c.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(o.AttributeType||(o.AttributeType={}))}((h=p.experimental||(p.experimental={})).fbs||(h.fbs={})),function(o){(function(c){(function(f){(function(s){s[s.UNKNOWN=0]="UNKNOWN",s[s.VALUE=1]="VALUE",s[s.PARAM=2]="PARAM"})(f.DimensionValueType||(f.DimensionValueType={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){(function(s){s[s.UNDEFINED=0]="UNDEFINED",s[s.FLOAT=1]="FLOAT",s[s.UINT8=2]="UINT8",s[s.INT8=3]="INT8",s[s.UINT16=4]="UINT16",s[s.INT16=5]="INT16",s[s.INT32=6]="INT32",s[s.INT64=7]="INT64",s[s.STRING=8]="STRING",s[s.BOOL=9]="BOOL",s[s.FLOAT16=10]="FLOAT16",s[s.DOUBLE=11]="DOUBLE",s[s.UINT32=12]="UINT32",s[s.UINT64=13]="UINT64",s[s.COMPLEX64=14]="COMPLEX64",s[s.COMPLEX128=15]="COMPLEX128",s[s.BFLOAT16=16]="BFLOAT16"})(f.TensorDataType||(f.TensorDataType={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){(function(s){s[s.Primitive=0]="Primitive",s[s.Fused=1]="Fused"})(f.NodeType||(f.NodeType={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){(function(s){s[s.NONE=0]="NONE",s[s.tensor_type=1]="tensor_type",s[s.sequence_type=2]="sequence_type",s[s.map_type=3]="map_type"})(f.TypeInfoValue||(f.TypeInfoValue={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}dim(t,e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new o.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(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 startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return s.startShape(t),s.addDim(t,e),s.endShape(t)}}f.Shape=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}value(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,n){return s.startDimension(t),s.addValue(t,e),s.addDenotation(t,n),s.endDimension(t)}}f.Dimension=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):o.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(t,e){t.addFieldInt8(0,e,o.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,n,r){return s.startDimensionValue(t),s.addDimType(t,e),s.addDimValue(t,n),s.addDimParam(t,r),s.endDimensionValue(t)}}f.DimensionValue=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(t,e){t.addFieldInt32(0,e,o.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,n){return s.startTensorTypeAndShape(t),s.addElemType(t,e),s.addShape(t,n),s.endTensorTypeAndShape(t)}}f.TensorTypeAndShape=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(t,e){t.addFieldInt32(0,e,o.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,n){return s.startMapType(t),s.addKeyType(t,e),s.addValueType(t,n),s.endMapType(t)}}f.MapType=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}elemType(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return s.startSequenceType(t),s.addElemType(t,e),s.endSequenceType(t)}}f.SequenceType=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(c.fbs||(c.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(f,s){return this.bb_pos=f,this.bb=s,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(f,s,i,t){return f.prep(4,12),f.writeInt32(t),f.writeInt32(i),f.writeInt32(s),f.offset()}}})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+n)+12*t,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(t,e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new o.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+n)+12*t,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,n,r){return s.startNodeEdge(t),s.addNodeIndex(t,e),s.addInputEdges(t,n),s.addOutputEdges(t,r),s.endNodeEdge(t)}}f.NodeEdge=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?(e||new o.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(t,e){t.addFieldInt32(6,e,o.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(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 startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(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 startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(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 startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(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 startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,n,r,a,l,d,m,y,v,_,T,S,A){return s.startNode(t),s.addName(t,e),s.addDocString(t,n),s.addDomain(t,r),s.addSinceVersion(t,a),s.addIndex(t,l),s.addOpType(t,d),s.addType(t,m),s.addExecutionProviderType(t,y),s.addInputs(t,v),s.addOutputs(t,_),s.addAttributes(t,T),s.addInputArgCounts(t,S),s.addImplicitInputs(t,A),s.endNode(t)}}f.Node=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new o.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,n,r){return s.startValueInfo(t),s.addName(t,e),s.addDocString(t,n),s.addType(t,r),s.endValueInfo(t)}}f.ValueInfo=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):o.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(t,e){t.addFieldInt8(1,e,o.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,n,r){return s.startTypeInfo(t),s.addDenotation(t,e),s.addValueType(t,n),s.addValue(t,r),s.endTypeInfo(t)}}f.TypeInfo=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,e,n){return s.startOperatorSetId(t),s.addDomain(t,e),s.addVersion(t,n),s.endOperatorSetId(t)}}f.OperatorSetId=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(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 startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(t,e){t.addFieldInt32(3,e,o.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(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 startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,n,r,a,l,d){return s.startTensor(t),s.addName(t,e),s.addDocString(t,n),s.addDims(t,r),s.addDataType(t,a),s.addRawData(t,l),s.addStringData(t,d),s.endTensor(t)}}f.Tensor=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}values(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}indices(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(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 startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,n,r){return s.startSparseTensor(t),s.addValues(t,e),s.addIndices(t,n),s.addDims(t,r),s.endSparseTensor(t)}}f.SparseTensor=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(t){let e=this.bb.__offset(this.bb_pos,16);return e?(t||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}g(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new o.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(t,e){let n=this.bb.__offset(this.bb_pos,26);return n?(e||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?(e||new o.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldInt32(2,e,o.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addFloat32(e[n]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(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 startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(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 startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(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 startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(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 startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,n,r,a,l,d,m,y,v,_,T,S,A){return s.startAttribute(t),s.addName(t,e),s.addDocString(t,n),s.addType(t,r),s.addF(t,a),s.addI(t,l),s.addS(t,d),s.addT(t,m),s.addG(t,y),s.addFloats(t,v),s.addInts(t,_),s.addStrings(t,T),s.addTensors(t,S),s.addGraphs(t,A),s.endAttribute(t)}}f.Attribute=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}initializers(t,e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(t,e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new o.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(t,e){let n=this.bb.__offset(this.bb_pos,12);return n?(e||new o.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(t,e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new o.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(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 startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(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 startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(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 startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(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 startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(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 startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(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 startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(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 startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,n,r,a,l,d,m,y){return s.startGraph(t),s.addInitializers(t,e),s.addNodeArgs(t,n),s.addNodes(t,r),s.addMaxNodeIndex(t,a),s.addNodeEdges(t,l),s.addInputs(t,d),s.addOutputs(t,m),s.addSparseInitializers(t,y),s.endGraph(t)}}f.Graph=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new o.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(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 startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,n,r,a,l,d,m,y,v){return s.startModel(t),s.addIrVersion(t,e),s.addOpsetImport(t,n),s.addProducerName(t,r),s.addProducerVersion(t,a),s.addDomain(t,l),s.addModelVersion(t,d),s.addDocString(t,m),s.addGraph(t,y),s.addGraphDocString(t,v),s.endModel(t)}}f.Model=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(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 startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,e,n){return s.startKernelCreateInfos(t),s.addNodeIndices(t,e),s.addKernelDefHashes(t,n),s.endKernelCreateInfos(t)}}f.KernelCreateInfos=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,n){return s.startSubGraphSessionState(t),s.addGraphId(t,e),s.addSessionState(t,n),s.endSubGraphSessionState(t)}}f.SubGraphSessionState=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}kernels(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}subGraphSessionStates(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(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 startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,n){return s.startSessionState(t),s.addKernels(t,e),s.addSubGraphSessionStates(t,n),s.endSessionState(t)}}f.SessionState=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new o.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,n,r){return s.startInferenceSession(t),s.addOrtVersion(t,e),s.addModel(t,n),s.addSessionState(t,r),s.endInferenceSession(t)}}f.InferenceSession=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={}))},7448:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.OnnxjsSessionHandler=void 0;const g=b(1670),p=b(9162);u.OnnxjsSessionHandler=class{constructor(h){this.session=h,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(h,o,c){const f=new Map;for(const t in h)if(Object.hasOwnProperty.call(h,t)){const e=h[t];f.set(t,new p.Tensor(e.dims,e.type,void 0,void 0,e.data))}const s=await this.session.run(f),i={};return s.forEach((t,e)=>{i[e]=new g.Tensor(t.type,t.data,t.dims)}),i}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Session=void 0;const g=b(7067),p=b(1296),h=b(7091),o=b(1036),c=b(6231),f=b(2644);u.Session=class{constructor(s={}){this._initialized=!1,this.backendHint=s.backendHint,this.profiler=c.Profiler.create(s.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(s,i,t){await this.profiler.event("session","Session.loadModel",async()=>{const e=await(0,h.resolveBackend)(this.backendHint);if(this.sessionHandler=e.createSessionHandler(this.context),this._model=new f.Model,typeof s=="string"){const n=s.endsWith(".ort");if(typeof fetch>"u"){const r=await(0,p.promisify)(g.readFile)(s);this.initialize(r,n)}else{const r=await fetch(s),a=await r.arrayBuffer();this.initialize(new Uint8Array(a),n)}}else if(ArrayBuffer.isView(s))this.initialize(s);else{const n=new Uint8Array(s,i||0,t||s.byteLength);this.initialize(n)}})}initialize(s,i){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const t=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(s,t,i),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new o.ExecutionPlan(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(s){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{const i=this.normalizeAndValidateInputs(s),t=await this._executionPlan.execute(this.sessionHandler,i);return this.createOutput(t)})}normalizeAndValidateInputs(s){const i=this._model.graph.getInputNames();if(Array.isArray(s)){if(s.length!==i.length)throw new Error(`incorrect input array length: expected ${i.length} but got ${s.length}`)}else{if(s.size!==i.length)throw new Error(`incorrect input map size: expected ${i.length} but got ${s.size}`);const t=new Array(s.size);let e=0;for(let n=0;ntypeof A=="string")))throw new TypeError("cache should be a string array");S&&(this.cache=new Array(T))}else{if(v!==void 0){const A=e(d);if(!(v instanceof A))throw new TypeError(`cache should be type ${A.name}`)}if(S){const A=new ArrayBuffer(T*function(w){switch(w){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${w}`)}}(d));this.cache=function(w,I){return new(e(I))(w)}(A,d)}}}static fromProto(l){if(!l)throw new Error("cannot construct Value from an empty tensor");const d=f.ProtoUtil.tensorDataTypeFromProto(l.dataType),m=f.ProtoUtil.tensorDimsFromProto(l.dims),y=new i(m,d);if(d==="string")l.stringData.forEach((v,_)=>{y.data[_]=(0,f.decodeUtf8String)(v)});else if(l.rawData&&typeof l.rawData.byteLength=="number"&&l.rawData.byteLength>0){const v=y.data,_=new DataView(l.rawData.buffer,l.rawData.byteOffset,l.rawData.byteLength),T=t(l.dataType),S=l.rawData.byteLength/T;if(l.rawData.byteLength%T!=0)throw new Error("invalid buffer length");if(v.length!==S)throw new Error("buffer length mismatch");for(let A=0;A0){const v=y.data,_=new DataView(l.rawDataArray().buffer,l.rawDataArray().byteOffset,l.rawDataLength()),T=t(l.dataType()),S=l.rawDataLength()/T;if(l.rawDataLength()%T!=0)throw new Error("invalid buffer length");if(v.length!==S)throw new Error("buffer length mismatch");for(let A=0;A1&&I>1)return;S[T-A]=Math.max(w,I)}return S}static index(d,m){const y=new Array(m.length);return s.fillIndex(d,m,y),y}static fillIndex(d,m,y){const v=d.length-m.length;for(let _=0;_=0;J--)w[J]=B%T[J],B=Math.floor(B/T[J]);W||(s.fillIndex(w,d.dims,I),j=d.get(I)),k||(s.fillIndex(w,m.dims,R),N=m.get(R)),A.set(w,y(j,N))}}return A}}static isValidBroadcast(d,m){const y=d.length,v=m.length;if(y>v)return!1;for(let _=1;_<=y;_++)if(d[y-_]!==1&&d[y-_]!==m[v-_])return!1;return!0}static getBroadcastDims(d,m){const y=d.length,v=[];for(let _=0;_1&&S===1&&v.unshift(T)}return v}}u.BroadcastUtil=s,u.arrayCopyHelper=function(l,d,m,y,v){if(y<0||y>=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+v>d.length)throw new Error("source indices to be copied are outside bounds");if(m+v>l.length)throw new Error("target array is too small to hold result");for(let _=0;_h.default.isLong(m)?m.toNumber():m)}static tensorValueTypeFromProto(d){return{tensorType:i.tensorDataTypeFromProto(d.elemType),shape:{dims:i.tensorDimsFromProto(d.shape.dim.map(m=>m.dimValue))}}}static tensorDimsFromORTFormat(d){const m=[];for(let y=0;yd.length)throw new Error(`invalid dimension of ${m} for sizeFromDimension as Tensor has ${d.length} dimensions.`);return e.getSizeFromDimensionRange(d,m,d.length)}static sizeToDimension(d,m){if(m<0||m>d.length)throw new Error(`invalid dimension of ${m} for sizeToDimension as Tensor has ${d.length} dimensions.`);return e.getSizeFromDimensionRange(d,0,m)}static getSizeFromDimensionRange(d,m,y){let v=1;for(let _=m;_=0;--v)y[v]=y[v+1]*d[v+1];return y}static transpose(d){return d.slice().reverse()}static indicesToOffset(d,m,y){y===void 0&&(y=d.length);let v=0;for(let _=0;_=m)throw new Error("unsupported axis for this operation.");return d<0?d+m:d}static normalizeAxes(d,m){return d.map(y=>this.normalizeAxis(y,m))}static incrementIndex(d,m,y){if(m.length===0||d.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(y===void 0)y=m.length;else if(y<=0||y>m.length)throw new Error("Incorrect axis to increment on");for(let v=y-1;v>=0&&(d[v]++,!(d[v]=d.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");v[A]=d[A]}else v[A]=m[A];T*=v[A]}}const S=e.size(d);if(_!==-1){if(S%T!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${d}] Output shape: [${m}]`);v[_]=S/T}else if(T!==S)throw new Error("reshapedDims and originalDims don't have matching sizes");return v}static sortBasedOnPerm(d,m){return m?m.map(y=>d[y]):d.slice().reverse()}static padShape(d,m){const y=d.length;return d.map((v,_)=>v+m[_]+m[_+y])}static areEqual(d,m){return d.length===m.length&&d.every((y,v)=>y===m[v])}static validateDimsAndCalcSize(d){if(d.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let m=1;for(const y of d){if(!Number.isInteger(y))throw new TypeError(`Invalid shape: ${y} is not an integer`);if(y<0||y>2147483647)throw new TypeError(`Invalid shape: length ${y} is not allowed`);m*=y}return m}static flattenShape(d,m){m<0&&(m+=d.length);const y=d.reduce((_,T)=>_*T,1),v=d.slice(m).reduce((_,T)=>_*T,1);return[y/v,v]}static squeezeShape(d,m){const y=new Array;m=e.normalizeAxes(m,d.length);for(let v=0;v=0;if(_&&d[v]!==1)throw new Error("squeeze an axis of size different than 1");(m.length===0&&d[v]>1||m.length>0&&!_)&&y.push(d[v])}return y}static unsqueezeShape(d,m){const y=new Array(d.length+m.length);y.fill(0);for(let _=0;_=y.length)throw new Error("'axes' has an out of range axis");if(y[T]!==0)throw new Error("'axes' has a duplicate axis");y[T]=1}let v=0;for(let _=0;_=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+v>d.length)throw new Error("source indices to be copied are outside bounds");if(m+v>l.length)throw new Error("target array is too small to hold result");for(let _=0;_=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+v>d.length)throw new Error("source indices to be copied are outside bounds");if(m+v>l.length)throw new Error("target array is too small to hold result");for(let T=0;T=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+v>d.length)throw new Error("source indices to be copied are outside bounds");if(m+v>l.length)throw new Error("target array is too small to hold result");for(let T=0;T=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+v>d.length)throw new Error("source indices to be copied are outside bounds");if(m+v>l.length)throw new Error("target array is too small to hold result");for(let _=0;_m.push(N));const S=r.calcReduceShape(T,m,!0),A=e.size(S),w=new c.Tensor(S,d.type),I=e.computeStrides(S),R=e.computeStrides(T),B=new Array(T.length);for(let j=0;j=m.length)return T(d[_]);const w=m[v],I=w>=y.length?1:e.size(y.slice(w+1));for(let R=0;R_!==0)}}u.ReduceUtil=r;class a{static adjustPoolAttributes(d,m,y,v,_,T){if(!d&&y.length!==m.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(d)for(let S=0;S=y.length?y.push(m[S+2]):y[S]=m[S+2];for(let S=0;S=y[S]||T[S+y.length]>=y[S])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(d,m,y,v,_,T){if(T){if(_.length!==2*(d.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(m.length!==d.length-2)throw new Error("length of strides should be the length of data dimensions");if(v.length!==d.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let S=0;S{Object.defineProperty(u,"__esModule",{value:!0}),u.iterateExtraOptions=void 0,u.iterateExtraOptions=(b,g,p,h)=>{if(typeof b=="object"&&b!==null){if(p.has(b))throw new Error("Circular reference in options");p.add(b)}Object.entries(b).forEach(([o,c])=>{const f=g?g+o:o;if(typeof c=="object")(0,u.iterateExtraOptions)(c,f+".",p,h);else if(typeof c=="string"||typeof c=="number")h(f,c.toString());else{if(typeof c!="boolean")throw new Error("Can't handle extra config type: "+typeof c);h(f,c?"1":"0")}})}},2157:function(D,u,b){var g,p=this&&this.__createBinding||(Object.create?function(I,R,B,j){j===void 0&&(j=B);var N=Object.getOwnPropertyDescriptor(R,B);N&&!("get"in N?!R.__esModule:N.writable||N.configurable)||(N={enumerable:!0,get:function(){return R[B]}}),Object.defineProperty(I,j,N)}:function(I,R,B,j){j===void 0&&(j=B),I[j]=R[B]}),h=this&&this.__setModuleDefault||(Object.create?function(I,R){Object.defineProperty(I,"default",{enumerable:!0,value:R})}:function(I,R){I.default=R}),o=this&&this.__importStar||function(I){if(I&&I.__esModule)return I;var R={};if(I!=null)for(var B in I)B!=="default"&&Object.prototype.hasOwnProperty.call(I,B)&&p(R,I,B);return h(R,I),R};Object.defineProperty(u,"__esModule",{value:!0}),u.endProfiling=u.run=u.releaseSession=u.createSession=u.createSessionFinalize=u.createSessionAllocate=u.initOrt=u.initWasm=void 0;const c=b(1670),f=o(b(349)),s=b(6361),i=()=>!!c.env.wasm.proxy&&typeof document<"u";let t,e,n,r=!1,a=!1,l=!1;const d=[],m=[],y=[],v=[],_=[],T=[],S=()=>{if(r||!a||l||!t)throw new Error("worker not ready")},A=I=>{switch(I.data.type){case"init-wasm":r=!1,I.data.err?(l=!0,e[1](I.data.err)):(a=!0,e[0]());break;case"init-ort":I.data.err?n[1](I.data.err):n[0]();break;case"create_allocate":I.data.err?d.shift()[1](I.data.err):d.shift()[0](I.data.out);break;case"create_finalize":I.data.err?m.shift()[1](I.data.err):m.shift()[0](I.data.out);break;case"create":I.data.err?y.shift()[1](I.data.err):y.shift()[0](I.data.out);break;case"release":I.data.err?v.shift()[1](I.data.err):v.shift()[0]();break;case"run":I.data.err?_.shift()[1](I.data.err):_.shift()[0](I.data.out);break;case"end-profiling":I.data.err?T.shift()[1](I.data.err):T.shift()[0]()}},w=typeof document<"u"?(g=document==null?void 0:document.currentScript)===null||g===void 0?void 0:g.src:void 0;u.initWasm=async()=>{if(i()){if(a)return;if(r)throw new Error("multiple calls to 'initWasm()' detected.");if(l)throw new Error("previous call to 'initWasm()' failed.");return r=!0,c.env.wasm.wasmPaths===void 0&&w&&w.indexOf("blob:")!==0&&(c.env.wasm.wasmPaths=w.substr(0,+w.lastIndexOf("/")+1)),new Promise((I,R)=>{t==null||t.terminate(),t=b(9710).Z(),t.onmessage=A,e=[I,R];const B={type:"init-wasm",in:c.env.wasm};t.postMessage(B)})}return(0,s.initializeWebAssembly)(c.env.wasm)},u.initOrt=async(I,R)=>{if(i())return S(),new Promise((B,j)=>{n=[B,j];const N={type:"init-ort",in:{numThreads:I,loggingLevel:R}};t.postMessage(N)});f.initOrt(I,R)},u.createSessionAllocate=async I=>i()?(S(),new Promise((R,B)=>{d.push([R,B]);const j={type:"create_allocate",in:{model:I}};t.postMessage(j,[I.buffer])})):f.createSessionAllocate(I),u.createSessionFinalize=async(I,R)=>i()?(S(),new Promise((B,j)=>{m.push([B,j]);const N={type:"create_finalize",in:{modeldata:I,options:R}};t.postMessage(N)})):f.createSessionFinalize(I,R),u.createSession=async(I,R)=>i()?(S(),new Promise((B,j)=>{y.push([B,j]);const N={type:"create",in:{model:I,options:R}};t.postMessage(N,[I.buffer])})):f.createSession(I,R),u.releaseSession=async I=>{if(i())return S(),new Promise((R,B)=>{v.push([R,B]);const j={type:"release",in:I};t.postMessage(j)});f.releaseSession(I)},u.run=async(I,R,B,j,N)=>i()?(S(),new Promise((W,k)=>{_.push([W,k]);const V={type:"run",in:{sessionId:I,inputIndices:R,inputs:B,outputIndices:j,options:N}};t.postMessage(V,f.extractTransferableBuffers(B))})):f.run(I,R,B,j,N),u.endProfiling=async I=>{if(i())return S(),new Promise((R,B)=>{T.push([R,B]);const j={type:"end-profiling",in:I};t.postMessage(j)});f.endProfiling(I)}},586:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.setRunOptions=void 0;const g=b(7967),p=b(4983),h=b(6361);u.setRunOptions=o=>{const c=(0,h.getInstance)();let f=0;const s=[],i=o||{};try{if((o==null?void 0:o.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof o.logSeverityLevel!="number"||!Number.isInteger(o.logSeverityLevel)||o.logSeverityLevel<0||o.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${o.logSeverityLevel}`);if((o==null?void 0:o.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof o.logVerbosityLevel!="number"||!Number.isInteger(o.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${o.logVerbosityLevel}`);(o==null?void 0:o.terminate)===void 0&&(i.terminate=!1);let t=0;if((o==null?void 0:o.tag)!==void 0&&(t=(0,p.allocWasmString)(o.tag,s)),f=c._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,t),f===0)throw new Error("Can't create run options");return(o==null?void 0:o.extra)!==void 0&&(0,g.iterateExtraOptions)(o.extra,"",new WeakSet,(e,n)=>{const r=(0,p.allocWasmString)(e,s),a=(0,p.allocWasmString)(n,s);if(c._OrtAddRunConfigEntry(f,r,a)!==0)throw new Error(`Can't set a run config entry: ${e} - ${n}`)}),[f,s]}catch(t){throw f!==0&&c._OrtReleaseRunOptions(f),s.forEach(c._free),t}}},2306:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.OnnxruntimeWebAssemblySessionHandler=void 0;const g=b(2806),p=b(1670),h=b(2850),o=b(2157);let c;u.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(f){const s=await fetch(f),i=await s.arrayBuffer();return(0,o.createSessionAllocate)(new Uint8Array(i))}async loadModel(f,s){if(c||(await(0,o.initOrt)(p.env.wasm.numThreads,(i=>{switch(i){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: ${i}`)}})(p.env.logLevel)),c=!0),typeof f=="string")if(typeof fetch>"u"){const i=await(0,h.promisify)(g.readFile)(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,o.createSession)(i,s)}else{const i=await this.createSessionAllocate(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,o.createSessionFinalize)(i,s)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,o.createSession)(f,s)}async dispose(){return(0,o.releaseSession)(this.sessionId)}async run(f,s,i){const t=[],e=[];Object.entries(f).forEach(l=>{const d=l[0],m=l[1],y=this.inputNames.indexOf(d);if(y===-1)throw new Error(`invalid input '${d}'`);t.push(m),e.push(y)});const n=[];Object.entries(s).forEach(l=>{const d=l[0],m=this.outputNames.indexOf(d);if(m===-1)throw new Error(`invalid output '${d}'`);n.push(m)});const r=await(0,o.run)(this.sessionId,e,t.map(l=>[l.type,l.dims,l.data]),n,i),a={};for(let l=0;l{Object.defineProperty(u,"__esModule",{value:!0}),u.setSessionOptions=void 0;const g=b(7967),p=b(4983),h=b(6361);u.setSessionOptions=o=>{const c=(0,h.getInstance)();let f=0;const s=[],i=o||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(i);try{(o==null?void 0:o.graphOptimizationLevel)===void 0&&(i.graphOptimizationLevel="all");const t=(r=>{switch(r){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${r}`)}})(i.graphOptimizationLevel);(o==null?void 0:o.enableCpuMemArena)===void 0&&(i.enableCpuMemArena=!0),(o==null?void 0:o.enableMemPattern)===void 0&&(i.enableMemPattern=!0),(o==null?void 0:o.executionMode)===void 0&&(i.executionMode="sequential");const e=(r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}})(i.executionMode);let n=0;if((o==null?void 0:o.logId)!==void 0&&(n=(0,p.allocWasmString)(o.logId,s)),(o==null?void 0:o.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof o.logSeverityLevel!="number"||!Number.isInteger(o.logSeverityLevel)||o.logSeverityLevel<0||o.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${o.logSeverityLevel}`);if((o==null?void 0:o.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof o.logVerbosityLevel!="number"||!Number.isInteger(o.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${o.logVerbosityLevel}`);if((o==null?void 0:o.enableProfiling)===void 0&&(i.enableProfiling=!1),f=c._OrtCreateSessionOptions(t,!!i.enableCpuMemArena,!!i.enableMemPattern,e,!!i.enableProfiling,0,n,i.logSeverityLevel,i.logVerbosityLevel),f===0)throw new Error("Can't create session options");return o!=null&&o.executionProviders&&((r,a,l)=>{for(const d of a){let m=typeof d=="string"?d:d.name;switch(m){case"xnnpack":m="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${m}`)}const y=(0,p.allocWasmString)(m,l);if((0,h.getInstance)()._OrtAppendExecutionProvider(r,y)!==0)throw new Error(`Can't append execution provider: ${m}`)}})(f,o.executionProviders,s),(o==null?void 0:o.extra)!==void 0&&(0,g.iterateExtraOptions)(o.extra,"",new WeakSet,(r,a)=>{const l=(0,p.allocWasmString)(r,s),d=(0,p.allocWasmString)(a,s);if(c._OrtAddSessionConfigEntry(f,l,d)!==0)throw new Error(`Can't set a session config entry: ${r} - ${a}`)}),[f,s]}catch(t){throw f!==0&&c._OrtReleaseSessionOptions(f),s.forEach(c._free),t}}},4983:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.allocWasmString=void 0;const g=b(6361);u.allocWasmString=(p,h)=>{const o=(0,g.getInstance)(),c=o.lengthBytesUTF8(p)+1,f=o._malloc(c);return o.stringToUTF8(p,f,c),h.push(f),f}},349:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.extractTransferableBuffers=u.endProfiling=u.run=u.releaseSession=u.createSession=u.createSessionFinalize=u.createSessionAllocate=u.initOrt=void 0;const g=b(586),p=b(4919),h=b(4983),o=b(6361);u.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(n!==0)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const c=new Map;u.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},u.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,a=0,l=[];try{if([a,l]=(0,p.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],a),r===0)throw new Error("Can't create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(a),l.forEach(n._free)}const d=n._OrtGetInputCount(r),m=n._OrtGetOutputCount(r),y=[],v=[],_=[],T=[];for(let S=0;S{const n=(0,u.createSessionAllocate)(t);return(0,u.createSessionFinalize)(n,e)},u.releaseSession=t=>{const e=(0,o.getInstance)(),n=c.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],l=n[2];a.forEach(e._OrtFree),l.forEach(e._OrtFree),e._OrtReleaseSession(r),c.delete(t)};const f=t=>{switch(t){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"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){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 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},i=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};u.run=(t,e,n,r,a)=>{const l=(0,o.getInstance)(),d=c.get(t);if(!d)throw new Error("invalid session id");const m=d[0],y=d[1],v=d[2],_=e.length,T=r.length;let S=0,A=[];const w=[],I=[];try{[S,A]=(0,g.setRunOptions)(a);for(let k=0;k<_;k++){const V=n[k][0],J=n[k][1],Y=n[k][2];let te,ne;if(Array.isArray(Y)){ne=4*Y.length,te=l._malloc(ne),I.push(te);let Oe=te/4;for(let le=0;lel.HEAP32[Oe++]=xe);const le=l._OrtCreateTensor(f(V),te,ne,Pe,J.length);if(le===0)throw new Error("Can't create a tensor");w.push(le)}finally{l.stackRestore(me)}}const R=l.stackSave(),B=l.stackAlloc(4*_),j=l.stackAlloc(4*_),N=l.stackAlloc(4*T),W=l.stackAlloc(4*T);try{let k=B/4,V=j/4,J=N/4,Y=W/4;for(let me=0;me<_;me++)l.HEAPU32[k++]=w[me],l.HEAPU32[V++]=y[e[me]];for(let me=0;mewe*je);if(xe=s(He),xe==="string"){const we=[];let je=_e/4;for(let Ue=0;Ue{const e=(0,o.getInstance)(),n=c.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(a===0)throw new Error("Can't get an profile file name");e._OrtFree(a)},u.extractTransferableBuffers=t=>{const e=[];for(const n of t){const r=n[2];!Array.isArray(r)&&r.buffer&&e.push(r.buffer)}return e}},6361:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(a,l,d,m){m===void 0&&(m=d);var y=Object.getOwnPropertyDescriptor(l,d);y&&!("get"in y?!l.__esModule:y.writable||y.configurable)||(y={enumerable:!0,get:function(){return l[d]}}),Object.defineProperty(a,m,y)}:function(a,l,d,m){m===void 0&&(m=d),a[m]=l[d]}),p=this&&this.__setModuleDefault||(Object.create?function(a,l){Object.defineProperty(a,"default",{enumerable:!0,value:l})}:function(a,l){a.default=l}),h=this&&this.__importStar||function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var d in a)d!=="default"&&Object.prototype.hasOwnProperty.call(a,d)&&g(l,a,d);return p(l,a),l},o=this&&this.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(u,"__esModule",{value:!0}),u.dispose=u.getInstance=u.initializeWebAssembly=void 0;const c=h(b(6449)),f=o(b(932)),s=b(3474);let i,t=!1,e=!1,n=!1;const r=(a,l)=>l?a?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":a?"ort-wasm-simd.wasm":"ort-wasm.wasm";u.initializeWebAssembly=async a=>{if(t)return Promise.resolve();if(e)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(n)throw new Error("previous call to 'initializeWebAssembly()' failed.");e=!0;const l=a.initTimeout,d=a.numThreads,m=a.simd,y=d>1&&(()=>{try{return typeof SharedArrayBuffer<"u"&&(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}})(),v=m&&(()=>{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}})(),_=typeof a.wasmPaths=="string"?a.wasmPaths:void 0,T=r(!1,y),S=r(v,y),A=typeof a.wasmPaths=="object"?a.wasmPaths[S]:void 0;let w=!1;const I=[];if(l>0&&I.push(new Promise(R=>{setTimeout(()=>{w=!0,R()},l)})),I.push(new Promise((R,B)=>{const j=y?s:f.default,N={locateFile:(W,k)=>y&&W.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([b(4154)],{type:"text/javascript"})):W===T?A??(_??k)+S:k+W};if(y)if(typeof Blob>"u")N.mainScriptUrlOrBlob=c.join("/","ort-wasm-threaded.js");else{const W=`var ortWasmThreaded=(function(){var _scriptDir;return ${j.toString()}})();`;N.mainScriptUrlOrBlob=new Blob([W],{type:"text/javascript"})}j(N).then(W=>{e=!1,t=!0,i=W,R()},W=>{e=!1,n=!0,B(W)})})),await Promise.race(I),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${l}ms`)},u.getInstance=()=>{if(t&&i)return i;throw new Error("WebAssembly is not initialized yet.")},u.dispose=()=>{var a;!t||e||n||(e=!0,(a=i.PThread)===null||a===void 0||a.terminateAllThreads(),i=void 0,e=!1,t=!1,n=!0)}},9710:(D,u,b)=>{b.d(u,{Z:()=>h});var g=b(477),p=b.n(g);function h(){return p()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){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"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){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 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(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(t){return!1}})(),o=a&&(()=>{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(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:D=>{D.exports=function(u,b,g,p){var h=self||window;try{try{var o;try{o=new h.Blob([u])}catch{(o=new(h.BlobBuilder||h.WebKitBlobBuilder||h.MozBlobBuilder||h.MSBlobBuilder)).append(u),o=o.getBlob()}var c=h.URL||h.webkitURL,f=c.createObjectURL(o),s=new h[b](f,g);return c.revokeObjectURL(f),s}catch{return new h[b]("data:application/javascript,".concat(encodeURIComponent(u)),g)}}catch{if(!p)throw Error("Inline worker is not supported");return new h[b](p,g)}}},4154:D=>{D.exports=`"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}}; -`},1670:D=>{D.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(D,u,b)=>{b.r(u),b.d(u,{flatbuffers:()=>g});var g={};g.Offset,g.Table,g.SIZEOF_SHORT=2,g.SIZEOF_INT=4,g.FILE_IDENTIFIER_LENGTH=4,g.SIZE_PREFIX_LENGTH=4,g.Encoding={UTF8_BYTES:1,UTF16_STRING:2},g.int32=new Int32Array(2),g.float32=new Float32Array(g.int32.buffer),g.float64=new Float64Array(g.int32.buffer),g.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,g.Long=function(p,h){this.low=0|p,this.high=0|h},g.Long.create=function(p,h){return p==0&&h==0?g.Long.ZERO:new g.Long(p,h)},g.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},g.Long.prototype.equals=function(p){return this.low==p.low&&this.high==p.high},g.Long.ZERO=new g.Long(0,0),g.Builder=function(p){if(p)h=p;else var h=1024;this.bb=g.ByteBuffer.allocate(h),this.space=h,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},g.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},g.Builder.prototype.forceDefaults=function(p){this.force_defaults=p},g.Builder.prototype.dataBuffer=function(){return this.bb},g.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},g.Builder.prototype.prep=function(p,h){p>this.minalign&&(this.minalign=p);for(var o=1+~(this.bb.capacity()-this.space+h)&p-1;this.space=0&&this.vtable[h]==0;h--);for(var o=h+1;h>=0;h--)this.addInt16(this.vtable[h]!=0?p-this.vtable[h]:0);this.addInt16(p-this.object_start);var c=(o+2)*g.SIZEOF_SHORT;this.addInt16(c);var f=0,s=this.space;e:for(h=0;h=0;s--)this.writeInt8(f.charCodeAt(s))}this.prep(this.minalign,g.SIZEOF_INT+c),this.addOffset(p),c&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},g.Builder.prototype.finishSizePrefixed=function(p,h){this.finish(p,h,!0)},g.Builder.prototype.requiredField=function(p,h){var o=this.bb.capacity()-p,c=o-this.bb.readInt32(o);if(this.bb.readInt16(c+h)==0)throw new Error("FlatBuffers: field "+h+" must be set")},g.Builder.prototype.startVector=function(p,h,o){this.notNested(),this.vector_num_elems=h,this.prep(g.SIZEOF_INT,p*h),this.prep(o,p*h)},g.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},g.Builder.prototype.createString=function(p){if(p instanceof Uint8Array)var h=p;else{h=[];for(var o=0;o=56320?f:(f<<10)+p.charCodeAt(o++)+-56613888)<128?h.push(c):(c<2048?h.push(c>>6&31|192):(c<65536?h.push(c>>12&15|224):h.push(c>>18&7|240,c>>12&63|128),h.push(c>>6&63|128)),h.push(63&c|128))}}this.addInt8(0),this.startVector(1,h.length,1),this.bb.setPosition(this.space-=h.length),o=0;for(var s=this.space,i=this.bb.bytes();o>24},g.ByteBuffer.prototype.readUint8=function(p){return this.bytes_[p]},g.ByteBuffer.prototype.readInt16=function(p){return this.readUint16(p)<<16>>16},g.ByteBuffer.prototype.readUint16=function(p){return this.bytes_[p]|this.bytes_[p+1]<<8},g.ByteBuffer.prototype.readInt32=function(p){return this.bytes_[p]|this.bytes_[p+1]<<8|this.bytes_[p+2]<<16|this.bytes_[p+3]<<24},g.ByteBuffer.prototype.readUint32=function(p){return this.readInt32(p)>>>0},g.ByteBuffer.prototype.readInt64=function(p){return new g.Long(this.readInt32(p),this.readInt32(p+4))},g.ByteBuffer.prototype.readUint64=function(p){return new g.Long(this.readUint32(p),this.readUint32(p+4))},g.ByteBuffer.prototype.readFloat32=function(p){return g.int32[0]=this.readInt32(p),g.float32[0]},g.ByteBuffer.prototype.readFloat64=function(p){return g.int32[g.isLittleEndian?0:1]=this.readInt32(p),g.int32[g.isLittleEndian?1:0]=this.readInt32(p+4),g.float64[0]},g.ByteBuffer.prototype.writeInt8=function(p,h){this.bytes_[p]=h},g.ByteBuffer.prototype.writeUint8=function(p,h){this.bytes_[p]=h},g.ByteBuffer.prototype.writeInt16=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8},g.ByteBuffer.prototype.writeUint16=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8},g.ByteBuffer.prototype.writeInt32=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8,this.bytes_[p+2]=h>>16,this.bytes_[p+3]=h>>24},g.ByteBuffer.prototype.writeUint32=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8,this.bytes_[p+2]=h>>16,this.bytes_[p+3]=h>>24},g.ByteBuffer.prototype.writeInt64=function(p,h){this.writeInt32(p,h.low),this.writeInt32(p+4,h.high)},g.ByteBuffer.prototype.writeUint64=function(p,h){this.writeUint32(p,h.low),this.writeUint32(p+4,h.high)},g.ByteBuffer.prototype.writeFloat32=function(p,h){g.float32[0]=h,this.writeInt32(p,g.int32[0])},g.ByteBuffer.prototype.writeFloat64=function(p,h){g.float64[0]=h,this.writeInt32(p,g.int32[g.isLittleEndian?0:1]),this.writeInt32(p+4,g.int32[g.isLittleEndian?1:0])},g.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&s)))}return c},g.ByteBuffer.prototype.__indirect=function(p){return p+this.readInt32(p)},g.ByteBuffer.prototype.__vector=function(p){return p+this.readInt32(p)+g.SIZEOF_INT},g.ByteBuffer.prototype.__vector_len=function(p){return this.readInt32(p+this.readInt32(p))},g.ByteBuffer.prototype.__has_identifier=function(p){if(p.length!=g.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+g.FILE_IDENTIFIER_LENGTH);for(var h=0;h{var u=D&&D.__esModule?()=>D.default:()=>D;return __webpack_require__.d(u,{a:u}),u},__webpack_require__.d=(D,u)=>{for(var b in u)__webpack_require__.o(u,b)&&!__webpack_require__.o(D,b)&&Object.defineProperty(D,b,{enumerable:!0,get:u[b]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(D,u)=>Object.prototype.hasOwnProperty.call(D,u),__webpack_require__.r=D=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(D,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(D,"__esModule",{value:!0})};var __webpack_exports__=__webpack_require__(6018);return __webpack_exports__})())}(ortWeb_min)),ortWeb_min.exports}var assetPath={},hasRequiredAssetPath;function requireAssetPath(){if(hasRequiredAssetPath)return assetPath;hasRequiredAssetPath=1,Object.defineProperty(assetPath,"__esModule",{value:!0}),assetPath.baseAssetPath=void 0;const u=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let b="/";return u&&(b=u.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),assetPath.baseAssetPath=b,assetPath}var defaultModelFetcher={},hasRequiredDefaultModelFetcher;function requireDefaultModelFetcher(){if(hasRequiredDefaultModelFetcher)return defaultModelFetcher;hasRequiredDefaultModelFetcher=1,Object.defineProperty(defaultModelFetcher,"__esModule",{value:!0}),defaultModelFetcher.defaultModelFetcher=void 0;const D=u=>fetch(u).then(b=>b.arrayBuffer());return defaultModelFetcher.defaultModelFetcher=D,defaultModelFetcher}var frameProcessor={},logging={},hasRequiredLogging;function requireLogging(){return hasRequiredLogging||(hasRequiredLogging=1,function(D){Object.defineProperty(D,"__esModule",{value:!0}),D.log=D.LOG_PREFIX=void 0,D.LOG_PREFIX="[VAD]";const u=["error","debug","warn"];function b(p){return(...h)=>{console[p](D.LOG_PREFIX,...h)}}const g=u.reduce((p,h)=>(p[h]=b(h),p),{});D.log=g}(logging)),logging}var messages={},hasRequiredMessages;function requireMessages(){if(hasRequiredMessages)return messages;hasRequiredMessages=1,Object.defineProperty(messages,"__esModule",{value:!0}),messages.Message=void 0;var D;return function(u){u.AudioFrame="AUDIO_FRAME",u.SpeechStart="SPEECH_START",u.VADMisfire="VAD_MISFIRE",u.SpeechEnd="SPEECH_END",u.SpeechStop="SPEECH_STOP"}(D||(messages.Message=D={})),messages}var hasRequiredFrameProcessor;function requireFrameProcessor(){if(hasRequiredFrameProcessor)return frameProcessor;hasRequiredFrameProcessor=1,Object.defineProperty(frameProcessor,"__esModule",{value:!0}),frameProcessor.FrameProcessor=frameProcessor.validateOptions=frameProcessor.defaultV5FrameProcessorOptions=frameProcessor.defaultLegacyFrameProcessorOptions=void 0;const D=requireLogging(),u=requireMessages(),b=[512,1024,1536];frameProcessor.defaultLegacyFrameProcessorOptions={positiveSpeechThreshold:.5,negativeSpeechThreshold:.5-.15,preSpeechPadFrames:1,redemptionFrames:8,frameSamples:1536,minSpeechFrames:3,submitUserSpeechOnPause:!1},frameProcessor.defaultV5FrameProcessorOptions={positiveSpeechThreshold:.5,negativeSpeechThreshold:.5-.15,preSpeechPadFrames:3,redemptionFrames:24,frameSamples:512,minSpeechFrames:9,submitUserSpeechOnPause:!1};function g(o){b.includes(o.frameSamples)||D.log.warn("You are using an unusual frame size"),(o.positiveSpeechThreshold<0||o.positiveSpeechThreshold>1)&&D.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(o.negativeSpeechThreshold<0||o.negativeSpeechThreshold>o.positiveSpeechThreshold)&&D.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),o.preSpeechPadFrames<0&&D.log.error("preSpeechPadFrames should be positive"),o.redemptionFrames<0&&D.log.error("redemptionFrames should be positive")}frameProcessor.validateOptions=g;const p=o=>{const c=o.reduce((s,i)=>(s.push(s.at(-1)+i.length),s),[0]),f=new Float32Array(c.at(-1));return o.forEach((s,i)=>{const t=c[i];f.set(s,t)}),f};class h{constructor(c,f,s){this.modelProcessFunc=c,this.modelResetFunc=f,this.options=s,this.speaking=!1,this.redemptionCounter=0,this.active=!1,this.reset=()=>{this.speaking=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0},this.pause=()=>(this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment():(this.reset(),{})),this.resume=()=>{this.active=!0},this.endSegment=()=>{const i=this.audioBuffer;this.audioBuffer=[];const t=this.speaking;this.reset();const e=i.reduce((n,r)=>n+ +r.isSpeech,0);if(t)if(e>=this.options.minSpeechFrames){const n=p(i.map(r=>r.frame));return{msg:u.Message.SpeechEnd,audio:n}}else return{msg:u.Message.VADMisfire};return{}},this.process=async i=>{if(!this.active)return{};const t=await this.modelProcessFunc(i);if(this.audioBuffer.push({frame:i,isSpeech:t.isSpeech>=this.options.positiveSpeechThreshold}),t.isSpeech>=this.options.positiveSpeechThreshold&&this.redemptionCounter&&(this.redemptionCounter=0),t.isSpeech>=this.options.positiveSpeechThreshold&&!this.speaking)return this.speaking=!0,{probs:t,msg:u.Message.SpeechStart,frame:i};if(t.isSpeech=this.options.redemptionFrames){this.redemptionCounter=0,this.speaking=!1;const e=this.audioBuffer;if(this.audioBuffer=[],e.reduce((r,a)=>r+ +a.isSpeech,0)>=this.options.minSpeechFrames){const r=p(e.map(a=>a.frame));return{probs:t,msg:u.Message.SpeechEnd,audio:r,frame:i}}else return{probs:t,msg:u.Message.VADMisfire,frame:i}}if(!this.speaking)for(;this.audioBuffer.length>this.options.preSpeechPadFrames;)this.audioBuffer.shift();return{probs:t,frame:i}},this.audioBuffer=[],this.reset()}}return frameProcessor.FrameProcessor=h,frameProcessor}var nonRealTimeVad={},models={},common={},hasRequiredCommon;function requireCommon(){return hasRequiredCommon||(hasRequiredCommon=1,Object.defineProperty(common,"__esModule",{value:!0})),common}var legacy={},hasRequiredLegacy;function requireLegacy(){if(hasRequiredLegacy)return legacy;hasRequiredLegacy=1;var D;Object.defineProperty(legacy,"__esModule",{value:!0}),legacy.SileroLegacy=void 0;const u=requireLogging();class b{constructor(p,h,o,c,f){this.ortInstance=p,this._session=h,this._h=o,this._c=c,this._sr=f,this.reset_state=()=>{const s=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",s,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",s,[2,1,64])},this.process=async s=>{var a;const t={input:new this.ortInstance.Tensor("float32",s,[1,s.length]),h:this._h,c:this._c,sr:this._sr},e=await this._session.run(t);this._h=e.hn,this._c=e.cn;const[n]=(a=e.output)==null?void 0:a.data;return{notSpeech:1-n,isSpeech:n}}}}return legacy.SileroLegacy=b,D=b,b.new=async(g,p)=>{u.log.debug("initializing vad");const h=await p(),o=await g.InferenceSession.create(h),c=new g.Tensor("int64",[16000n]),f=Array(2*64).fill(0),s=new g.Tensor("float32",f,[2,1,64]),i=new g.Tensor("float32",f,[2,1,64]);return u.log.debug("vad is initialized"),new D(g,o,s,i,c)},legacy}var v5={},hasRequiredV5;function requireV5(){if(hasRequiredV5)return v5;hasRequiredV5=1;var D;Object.defineProperty(v5,"__esModule",{value:!0}),v5.SileroV5=void 0;const u=requireLogging();function b(p){const h=Array(256).fill(0);return new p.Tensor("float32",h,[2,1,128])}class g{constructor(h,o,c,f){this._session=h,this._state=o,this._sr=c,this.ortInstance=f,this.reset_state=()=>{this._state=b(this.ortInstance)},this.process=async s=>{var a;const t={input:new this.ortInstance.Tensor("float32",s,[1,s.length]),state:this._state,sr:this._sr},e=await this._session.run(t);this._state=e.stateN;const[n]=(a=e.output)==null?void 0:a.data;return{notSpeech:1-n,isSpeech:n}}}}return v5.SileroV5=g,D=g,g.new=async(p,h)=>{u.log.debug("Loading VAD...");const o=await h(),c=await p.InferenceSession.create(o),f=new p.Tensor("int64",[16000n]),s=b(p);return u.log.debug("...finished loading VAD"),new D(c,s,f,p)},v5}var hasRequiredModels;function requireModels(){return hasRequiredModels||(hasRequiredModels=1,function(D){var u=models&&models.__createBinding||(Object.create?function(h,o,c,f){f===void 0&&(f=c);var s=Object.getOwnPropertyDescriptor(o,c);(!s||("get"in s?!o.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return o[c]}}),Object.defineProperty(h,f,s)}:function(h,o,c,f){f===void 0&&(f=c),h[f]=o[c]}),b=models&&models.__exportStar||function(h,o){for(var c in h)c!=="default"&&!Object.prototype.hasOwnProperty.call(o,c)&&u(o,h,c)};Object.defineProperty(D,"__esModule",{value:!0}),D.SileroV5=D.SileroLegacy=void 0,b(requireCommon(),D);var g=requireLegacy();Object.defineProperty(D,"SileroLegacy",{enumerable:!0,get:function(){return g.SileroLegacy}});var p=requireV5();Object.defineProperty(D,"SileroV5",{enumerable:!0,get:function(){return p.SileroV5}})}(models)),models}var resampler={},hasRequiredResampler;function requireResampler(){if(hasRequiredResampler)return resampler;hasRequiredResampler=1,Object.defineProperty(resampler,"__esModule",{value:!0}),resampler.Resampler=void 0;const D=requireLogging();class u{constructor(g){this.options=g,this.process=p=>{const h=[];for(const o of p)for(this.inputBuffer.push(o);this.hasEnoughDataForFrame();){const c=this.generateOutputFrame();h.push(c)}return h},this.stream=async function*(p){for(const h of p)for(this.inputBuffer.push(h);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()},g.nativeSampleRate<16e3&&D.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const g=new Float32Array(this.options.targetFrameSize);let p=0,h=0;for(;p{const i=await g.SileroLegacy.new(this.ort,this.modelFetcher);this.frameProcessor=new u.FrameProcessor(i.process,i.reset_state,{frameSamples:this.options.frameSamples,positiveSpeechThreshold:this.options.positiveSpeechThreshold,negativeSpeechThreshold:this.options.negativeSpeechThreshold,redemptionFrames:this.options.redemptionFrames,preSpeechPadFrames:this.options.preSpeechPadFrames,minSpeechFrames:this.options.minSpeechFrames,submitUserSpeechOnPause:this.options.submitUserSpeechOnPause}),this.frameProcessor.resume()},this.run=async function*(i,t){const e={nativeSampleRate:t,targetSampleRate:16e3,targetFrameSize:this.options.frameSamples},n=new p.Resampler(e);let r=0,a=0,l=0;for await(const y of n.stream(i)){const{msg:v,audio:_}=await this.frameProcessor.process(y);switch(v){case b.Message.SpeechStart:r=l*this.options.frameSamples/16;break;case b.Message.SpeechEnd:a=(l+1)*this.options.frameSamples/16,yield{audio:_,start:r,end:a};break}l++}const{msg:d,audio:m}=this.frameProcessor.endSegment();d==b.Message.SpeechEnd&&(yield{audio:m,start:r,end:l*this.options.frameSamples/16})},(0,u.validateOptions)(s)}}D.PlatformAgnosticNonRealTimeVAD=h}(nonRealTimeVad)),nonRealTimeVad}var utils={},hasRequiredUtils;function requireUtils(){if(hasRequiredUtils)return utils;hasRequiredUtils=1,Object.defineProperty(utils,"__esModule",{value:!0}),utils.audioFileToArray=utils.encodeWAV=utils.arrayBufferToBase64=utils.minFramesForTargetMS=void 0;function D(c,f,s=16e3){return Math.ceil(c*s/1e3/f)}utils.minFramesForTargetMS=D;function u(c){const f=new Uint8Array(c),s=f.byteLength,i=new Array(s);for(var t=0;t{s.addEventListener("loadend",r=>{const a=s.result;f.decodeAudioData(a,l=>{i=l,f.startRendering().then(d=>{console.log("Rendering completed successfully"),n()}).catch(d=>{console.error(`Rendering failed: ${d}`)})},l=>{console.log(`Error with decoding audio data: ${l}`)})}),s.readAsArrayBuffer(c)}),i===null)throw Error("some shit");let t=i,e=new Float32Array(t.length);for(let n=0;n({...d==="v5"?o.defaultV5FrameProcessorOptions:o.defaultLegacyFrameProcessorOptions,onFrameProcessed:y=>{},onVADMisfire:()=>{c.log.debug("VAD misfire")},onSpeechStart:()=>{c.log.debug("Detected speech start")},onSpeechEnd:()=>{c.log.debug("Detected speech end")},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.22/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/",stream:void 0,ortConfig:void 0,model:D.DEFAULT_MODEL,workletOptions:{}});D.getDefaultRealTimeVADOptions=r;class a{static async new(m={}){const y={...(0,D.getDefaultRealTimeVADOptions)(m.model??D.DEFAULT_MODEL),...m};(0,o.validateOptions)(y);let v;y.stream===void 0?v=await navigator.mediaDevices.getUserMedia({audio:{...y.additionalAudioConstraints,channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}):v=y.stream;const _=new AudioContext,T=new MediaStreamAudioSourceNode(_,{mediaStream:v}),S=await l.new(_,y);return S.receive(T),new a(y,_,v,S,T)}constructor(m,y,v,_,T,S=!1){this.options=m,this.audioContext=y,this.stream=v,this.audioNodeVAD=_,this.sourceNode=T,this.listening=S,this.pause=()=>{this.audioNodeVAD.pause(),this.listening=!1},this.start=()=>{this.audioNodeVAD.start(),this.listening=!0},this.destroy=()=>{this.listening&&this.pause(),this.options.stream===void 0&&this.stream.getTracks().forEach(A=>A.stop()),this.sourceNode.disconnect(),this.audioNodeVAD.destroy(),this.audioContext.close()}}}D.MicVAD=a;class l{static async new(m,y={}){const v={...(0,D.getDefaultRealTimeVADOptions)(y.model??D.DEFAULT_MODEL),...y};(0,o.validateOptions)(v),D.ort.env.wasm.wasmPaths=v.onnxWASMBasePath,v.ortConfig!==void 0&&v.ortConfig(D.ort);const _=v.model==="v5"?e:n,T=v.baseAssetPath+_,S=v.model==="v5"?s.SileroV5.new:s.SileroLegacy.new;let A;try{A=await S(D.ort,()=>(0,h.defaultModelFetcher)(T))}catch(R){throw console.error(`Encountered an error while loading model file ${T}`),R}const w=new o.FrameProcessor(A.process,A.reset_state,{frameSamples:v.frameSamples,positiveSpeechThreshold:v.positiveSpeechThreshold,negativeSpeechThreshold:v.negativeSpeechThreshold,redemptionFrames:v.redemptionFrames,preSpeechPadFrames:v.preSpeechPadFrames,minSpeechFrames:v.minSpeechFrames,submitUserSpeechOnPause:v.submitUserSpeechOnPause}),I=new l(m,v,w);return await I.setupAudioNode(),I}constructor(m,y,v){this.ctx=m,this.options=y,this.bufferIndex=0,this.pause=()=>{const _=this.frameProcessor.pause();this.handleFrameProcessorEvent(_)},this.start=()=>{this.frameProcessor.resume()},this.receive=_=>{_.connect(this.audioNode)},this.processFrame=async _=>{const T=await this.frameProcessor.process(_);this.handleFrameProcessorEvent(T)},this.handleFrameProcessorEvent=_=>{switch(_.probs!==void 0&&this.options.onFrameProcessed(_.probs,_.frame),_.msg){case f.Message.SpeechStart:this.options.onSpeechStart();break;case f.Message.VADMisfire:this.options.onVADMisfire();break;case f.Message.SpeechEnd:this.options.onSpeechEnd(_.audio);break}},this.destroy=()=>{var _;this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:f.Message.SpeechStop}),this.audioNode.disconnect(),(_=this.gainNode)==null||_.disconnect()},this.frameProcessor=v}async setupAudioNode(){if("audioWorklet"in this.ctx&&typeof AudioWorkletNode=="function")try{const _=this.options.baseAssetPath+t;await this.ctx.audioWorklet.addModule(_);const T=this.options.workletOptions??{};T.processorOptions={...T.processorOptions??{},frameSamples:this.options.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",T),this.audioNode.port.onmessage=async S=>{var A;switch((A=S.data)==null?void 0:A.message){case f.Message.AudioFrame:let w=S.data.data;w instanceof ArrayBuffer||(w=new ArrayBuffer(S.data.data.byteLength),new Uint8Array(w).set(new Uint8Array(S.data.data)));const I=new Float32Array(w);await this.processFrame(I);break}};return}catch(_){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",_)}this.resampler=new i.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.options.frameSamples??480});const y=4096;this.audioNode=this.ctx.createScriptProcessor(y,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let v=!1;this.audioNode.onaudioprocess=async _=>{if(!v){v=!0;try{const T=_.inputBuffer.getChannelData(0);if(_.outputBuffer.getChannelData(0).fill(0),this.resampler){const A=this.resampler.process(T);for(const w of A)await this.processFrame(w)}}catch(T){console.error("Error processing audio:",T)}finally{v=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}D.AudioNodeVAD=l}(realTimeVad)),realTimeVad}var hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(D){var u=dist&&dist.__createBinding||(Object.create?function(n,r,a,l){l===void 0&&(l=a);var d=Object.getOwnPropertyDescriptor(r,a);(!d||("get"in d?!r.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return r[a]}}),Object.defineProperty(n,l,d)}:function(n,r,a,l){l===void 0&&(l=a),n[l]=r[a]}),b=dist&&dist.__setModuleDefault||(Object.create?function(n,r){Object.defineProperty(n,"default",{enumerable:!0,value:r})}:function(n,r){n.default=r}),g=dist&&dist.__importStar||function(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var a in n)a!=="default"&&Object.prototype.hasOwnProperty.call(n,a)&&u(r,n,a);return b(r,n),r};Object.defineProperty(D,"__esModule",{value:!0}),D.NonRealTimeVAD=D.Message=D.FrameProcessor=D.getDefaultRealTimeVADOptions=D.MicVAD=D.DEFAULT_MODEL=D.AudioNodeVAD=D.utils=D.defaultNonRealTimeVADOptions=void 0;const p=g(requireOrtWeb_min()),h=requireAssetPath(),o=requireDefaultModelFetcher(),c=requireFrameProcessor();Object.defineProperty(D,"FrameProcessor",{enumerable:!0,get:function(){return c.FrameProcessor}});const f=requireMessages();Object.defineProperty(D,"Message",{enumerable:!0,get:function(){return f.Message}});const s=requireNonRealTimeVad(),i=requireUtils();D.defaultNonRealTimeVADOptions={modelURL:h.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:o.defaultModelFetcher};class t extends s.PlatformAgnosticNonRealTimeVAD{static async new(r={}){const{modelURL:a,modelFetcher:l}={...D.defaultNonRealTimeVADOptions,...r};return await this._new(()=>l(a),p,r)}}D.NonRealTimeVAD=t,D.utils={audioFileToArray:i.audioFileToArray,minFramesForTargetMS:i.minFramesForTargetMS,arrayBufferToBase64:i.arrayBufferToBase64,encodeWAV:i.encodeWAV};var e=requireRealTimeVad();Object.defineProperty(D,"AudioNodeVAD",{enumerable:!0,get:function(){return e.AudioNodeVAD}}),Object.defineProperty(D,"DEFAULT_MODEL",{enumerable:!0,get:function(){return e.DEFAULT_MODEL}}),Object.defineProperty(D,"MicVAD",{enumerable:!0,get:function(){return e.MicVAD}}),Object.defineProperty(D,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return e.getDefaultRealTimeVADOptions}})}(dist)),dist}var distExports=requireDist();export{distExports as d}; +${i}`);return n}deleteShader(i){this.gl.deleteShader(i)}bindTextureToUniform(i,t,e){const n=this.gl;n.activeTexture(n.TEXTURE0+t),this.checkError(),n.bindTexture(n.TEXTURE_2D,i),this.checkError(),n.uniform1i(e,t),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(o.env.debug){const i=this.gl,t=i.getError();let e="";switch(t){case i.NO_ERROR:return;case i.INVALID_ENUM:e="INVALID_ENUM";break;case i.INVALID_VALUE:e="INVALID_VALUE";break;case i.INVALID_OPERATION:e="INVALID_OPERATION";break;case i.INVALID_FRAMEBUFFER_OPERATION:e="INVALID_FRAMEBUFFER_OPERATION";break;case i.OUT_OF_MEMORY:e="OUT_OF_MEMORY";break;case i.CONTEXT_LOST_WEBGL:e="CONTEXT_LOST_WEBGL";break;default:e=`Unknown WebGL Error: ${t.toString(16)}`}throw new Error(e)}}deleteTexture(i){this.gl.deleteTexture(i)}deleteProgram(i){this.gl.deleteProgram(i)}getEncoder(i,t,e=0){if(this.version===2)return new c.RedFloat32DataEncoder(this.gl,t);switch(i){case"float":return e===1||this.isRenderFloat32Supported?new c.RGBAFloatDataEncoder(this.gl,t):new c.RGBAFloatDataEncoder(this.gl,t,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new c.Uint8DataEncoder(this.gl,t);default:throw new Error(`Invalid dataType: ${i}`)}}clearActiveTextures(){const i=this.gl;for(let t=0;tthis.isTimerResultAvailable(i)),this.getTimerResult(i)}async createAndWaitForFence(){const i=this.createFence(this.gl);return this.pollFence(i)}createFence(i){let t;const e=i,n=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return i.flush(),t=n===null?()=>!0:()=>{const r=e.clientWaitSync(n,0,0);return r===e.ALREADY_SIGNALED||r===e.CONDITION_SATISFIED},{query:n,isFencePassed:t}}async pollFence(i){return new Promise(t=>{this.addItemToPoll(()=>i.isFencePassed(),()=>t())})}pollItems(){const i=s(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=i;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(i+1)}async addItemToPoll(i,t){this.itemsToPoll.push({isDoneFn:i,resolveFn:t}),this.itemsToPoll.length>1||await(0,f.repeatedTry)(()=>(this.pollItems(),this.itemsToPoll.length===0))}}},1036:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ExecutionPlan=void 0;const g=b(6231);class p{constructor(o,c){this.op=o,this.node=c}}u.ExecutionPlan=class{constructor(h,o,c){this.graph=h,this.profiler=c,this.initialize(o)}initialize(h){this.profiler.event("session","ExecutionPlan.initialize",()=>{const o=this.graph.getNodes();if(o.length!==h.length)throw new Error("The size of nodes and OPs do not match.");this._ops=h.map((c,f)=>new p(c,o[f])),this.reset(),this._starter=[],this._ops.forEach((c,f)=>{let s=!0;for(const i of c.node.inputs)if(!this._values[i]&&this.graph.getInputIndices().indexOf(i)===-1){s=!1;break}s&&this._starter.push(f)})})}reset(){this._values=this.graph.getValues().map(h=>h.tensor)}async execute(h,o){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const c=h.createInferenceHandler(),f=this.graph.getInputIndices();if(o.length!==f.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${o.length} expected: ${f.length}`);o.forEach((r,a)=>{const l=f[a];this._values[l]=r});const s=this._starter.slice(0),i=this.graph.getValues(),t=this.graph.getNodes();let e=0;for(;ethis._values[_]);if(l.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${a.node}`);const d=l;g.Logger.verbose("ExecPlan",`Runing op:${a.node.name} (${d.map((_,v)=>`'${a.node.inputs[v]}': ${_.type}[${_.dims.join(",")}]`).join(", ")})`);const m=await this.profiler.event("node",a.node.name,async()=>a.op.impl(c,d,a.op.context));if(m.length!==a.node.outputs.length)throw new Error("the size of output does not match model definition.");m.forEach((_,v)=>{const T=a.node.outputs[v];if(this._values[T])throw new Error(`output [${T}] already has value: op:${a.node.name}`);this._values[T]=_});const y=new Set;m.forEach((_,v)=>{const T=a.node.outputs[v];for(const S of i[T].to){const O=t[S];let w=!0;for(const I of O.inputs)if(!this._values[I]){w=!1;break}w&&y.add(S)}}),s.push(...y)}const n=[];for(let r=0;r{Object.defineProperty(u,"__esModule",{value:!0}),u.Graph=void 0;const g=b(1446),p=b(7778),h=b(9395),o=b(9162),c=b(2517);var f=h.onnxruntime.experimental.fbs;u.Graph={from:(e,n)=>new t(e,n)};class s{constructor(n){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,n&&(this.type=c.ProtoUtil.tensorValueTypeFromProto(n.type.tensorType))}get from(){return this._from}get to(){return this._to}}class i{constructor(n,r){n instanceof g.onnx.NodeProto?(this.name=n.name,this.opType=n.opType,this.attributes=new p.Attribute(n.attribute)):n instanceof f.Node&&(this.name=r??n.name(),this.opType=n.opType(),this.attributes=new p.Attribute(c.ProtoUtil.tensorAttributesFromORTFormat(n))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class t{constructor(n,r){if(!n)throw new TypeError("graph is empty");this.buildGraph(n),this.transformGraph(r),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(n){if(n instanceof g.onnx.GraphProto)this.buildGraphFromOnnxFormat(n);else{if(!(n instanceof f.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(n)}}buildGraphFromOnnxFormat(n){const r=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const a=new Map;if(!n.input)throw new Error("missing information in graph: input");const l=[];for(const d of n.input){if(r.has(d.name))throw new Error(`duplicated input name: ${d.name}`);const m=this._allData.push(new s(d))-1;r.set(d.name,m),l.push(d.name)}if(!n.initializer)throw new Error("missing information in graph: initializer");for(const d of n.initializer){let m=r.get(d.name);if(m===void 0){const y=new s;y.type={shape:{dims:c.ProtoUtil.tensorDimsFromProto(d.dims)},tensorType:c.ProtoUtil.tensorDataTypeFromProto(d.dataType)},m=this._allData.push(y)-1,r.set(d.name,m)}this._allData[m]._from=-1,this._allData[m].tensor=o.Tensor.fromProto(d)}for(let d=0;d{this._allData[l]._to.forEach(d=>{n.add(d)})});const r=Array.from(n),a=new Array(this._nodes.length).fill("white");for(;r.length>0;){const l=r.pop();a[l]==="gray"?a[l]="black":(r.push(l),a[l]="gray",this._nodes[l].outputs.forEach(d=>{const m=this._allData[d];if(m.tensor!==void 0)throw new Error("node outputs should not be initialized");if(m._from!==l)throw new Error("from property of the Value object doesn't match index of Node being processed");m._to.forEach(y=>{if(a[y]==="gray")throw new Error("model graph is cyclic");a[y]==="white"&&r.push(y)})}))}}transformGraph(n){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),n&&n.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let n=0;for(let r=0;r0&&(this._nodes[r].inputs.forEach(a=>{const l=this._allData[a]._to.indexOf(r+n);l!==-1&&(this._allData[a]._to[l]=r)}),this._nodes[r].outputs.forEach(a=>{this._allData[a]._from&&this._allData[a]._from===r+n&&(this._allData[a]._from=r)})):(n++,this._nodes[r].outputs.forEach(a=>{this._allData[a]._from=-2}),this._nodes.splice(r,1),r--);n=0;for(let r=0;r0){let a=-1;this._allData[r].from!==void 0&&this._allData[r].from!==-1?(a=this._nodes[this._allData[r].from].outputs.indexOf(r+n),a!==-1&&(this._nodes[this._allData[r].from].outputs[a]=r)):(a=this._allInputIndices.indexOf(r+n),a!==-1&&(this._allInputIndices[a]=r)),this._allData[r].to.forEach(l=>{a=this._nodes[l].inputs.indexOf(r+n),a!==-1&&(this._nodes[l].inputs[a]=r)}),this._allData[r].to.length===0&&(a=this._allOutputIndices.indexOf(r+n),a!==-1&&(this._allOutputIndices[a]=r))}}else n++,this._allData.splice(r,1),r--}deleteNode(n){const r=this._nodes[n];if(r.outputs.length>1){for(let _=1;_0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}r.executeNode=!1;const a=r.inputs[0],l=r.outputs[0],d=this._allData[l].to,m=this._allData[a].to.indexOf(n);if(m===-1)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[a].to.splice(m,1),this._allData[l]._to=[];const y=this._allOutputIndices.indexOf(l);if(y!==-1&&(this._allOutputIndices[y]=a),d&&d.length>0)for(const _ of d){const v=this._nodes[_].inputs.indexOf(l);if(v===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[_].inputs[v]=a,this._allData[a].to.push(_)}}removeAllDropoutNodes(){let n=0;for(const r of this._nodes){if(r.opType==="Dropout"){if(r.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(r.outputs.length!==1&&r.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(r.outputs.length===2&&this._allData[r.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(n)}n++}}removeAllIdentityNodes(){let n=0;for(const r of this._nodes)r.opType==="Identity"&&this.deleteNode(n),n++}isActivation(n){switch(n.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const n of this._nodes)if(n.opType==="Conv"){const r=this._allData[n.outputs[0]]._to;if(r.length===1&&this.isActivation(this._nodes[r[0]])){const a=this._nodes[r[0]];if(a.opType==="Clip")if(a.inputs.length===1)try{n.attributes.set("activation_params","floats",[a.attributes.getFloat("min"),a.attributes.getFloat("max")])}catch{n.attributes.set("activation_params","floats",[c.MIN_CLIP,c.MAX_CLIP])}else{if(!(a.inputs.length>=3&&this._allData[a.inputs[1]].tensor!==void 0&&this._allData[a.inputs[2]].tensor!==void 0))continue;n.attributes.set("activation_params","floats",[this._allData[a.inputs[1]].tensor.floatData[0],this._allData[a.inputs[2]].tensor.floatData[0]])}n.attributes.set("activation","string",a.opType),this.deleteNode(r[0])}}}}},6231:(D,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.now=u.Profiler=u.Logger=void 0;const b={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},g={none:new class{log(i,t,e){}},console:new class{log(i,t,e){console.log(`${this.color(i)} ${e?"\x1B[35m"+e+"\x1B[0m ":""}${t}`)}color(i){switch(i){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${i}`)}}}},p={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let h={"":p};function o(i,t,e,n){if(t===void 0)return r=i,{verbose:o.verbose.bind(null,r),info:o.info.bind(null,r),warning:o.warning.bind(null,r),error:o.error.bind(null,r),fatal:o.fatal.bind(null,r)};if(e===void 0)c(i,t);else if(typeof e=="number"&&n===void 0)c(i,t);else if(typeof e=="string"&&n===void 0)c(i,e,0,t);else{if(typeof e!="string"||typeof n!="number")throw new TypeError("input is valid");c(i,e,0,t)}var r}function c(i,t,e,n){const r=h[n||""]||h[""];b[i]{l.then(async y=>{r&&await r.end(),d(y)},async y=>{r&&await r.end(),m(y)})});if(!a&&r){const d=r.end();if(d&&typeof d.then=="function")return new Promise((m,y)=>{d.then(()=>{m(l)},_=>{y(_)})})}return l}begin(i,t,e){if(!this._started)throw new Error("profiler is not started yet");if(e===void 0){const n=(0,u.now)();return this.flush(n),new f(i,t,n,r=>this.endSync(r))}{const n=e.beginTimer();return new f(i,t,0,async r=>this.end(r),n,e)}}async end(i){const t=await i.checkTimer();this._timingEvents.length=this._flushBatchSize||i-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Model=void 0;const g=b(5686),p=b(1446),h=b(7070),o=b(9395),c=b(2517);var f=o.onnxruntime.experimental.fbs;u.Model=class{constructor(){}load(s,i,t){if(!t)try{return void this.loadFromOnnxFormat(s,i)}catch(e){if(t!==void 0)throw e}this.loadFromOrtFormat(s,i)}loadFromOnnxFormat(s,i){const t=p.onnx.ModelProto.decode(s);if(c.LongUtil.longToNumber(t.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=t.opsetImport.map(e=>({domain:e.domain,version:c.LongUtil.longToNumber(e.version)})),this._graph=h.Graph.from(t.graph,i)}loadFromOrtFormat(s,i){const t=new g.flatbuffers.ByteBuffer(s),e=f.InferenceSession.getRootAsInferenceSession(t).model();if(c.LongUtil.longToNumber(e.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let n=0;n{Object.defineProperty(u,"__esModule",{value:!0}),u.FLOAT_TYPES=u.INT_TYPES=u.NUMBER_TYPES=void 0,u.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],u.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],u.FLOAT_TYPES=["float32","float64"]},1047:(D,u)=>{function b(g,p){if(p.endsWith("+")){const h=Number.parseInt(p.substring(0,p.length-1),10);return!isNaN(h)&&h<=g}if(p.split("-").length===2){const h=p.split("-"),o=Number.parseInt(h[0],10),c=Number.parseInt(h[1],10);return!isNaN(o)&&!isNaN(c)&&o<=g&&g<=c}return Number.parseInt(p,10)===g}Object.defineProperty(u,"__esModule",{value:!0}),u.resolveOperator=void 0,u.resolveOperator=function(g,p,h){for(const o of h){const c=o[0],f=o[1],s=o[2],i=o[3],t=o[4];if(g.opType===c){for(const e of p)if((e.domain===f||e.domain==="ai.onnx"&&f==="")&&b(e.version,s))return{opImpl:i,opInit:t}}}throw new TypeError(`cannot resolve operator '${g.opType}' with opsets: ${p.map(o=>`${o.domain||"ai.onnx"} v${o.version}`).join(", ")}`)}},9395:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.onnxruntime=void 0;const g=b(5686);var p,h;p=u.onnxruntime||(u.onnxruntime={}),function(o){(function(c){c[c.UNDEFINED=0]="UNDEFINED",c[c.FLOAT=1]="FLOAT",c[c.INT=2]="INT",c[c.STRING=3]="STRING",c[c.TENSOR=4]="TENSOR",c[c.GRAPH=5]="GRAPH",c[c.FLOATS=6]="FLOATS",c[c.INTS=7]="INTS",c[c.STRINGS=8]="STRINGS",c[c.TENSORS=9]="TENSORS",c[c.GRAPHS=10]="GRAPHS",c[c.SPARSE_TENSOR=11]="SPARSE_TENSOR",c[c.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(o.AttributeType||(o.AttributeType={}))}((h=p.experimental||(p.experimental={})).fbs||(h.fbs={})),function(o){(function(c){(function(f){(function(s){s[s.UNKNOWN=0]="UNKNOWN",s[s.VALUE=1]="VALUE",s[s.PARAM=2]="PARAM"})(f.DimensionValueType||(f.DimensionValueType={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){(function(s){s[s.UNDEFINED=0]="UNDEFINED",s[s.FLOAT=1]="FLOAT",s[s.UINT8=2]="UINT8",s[s.INT8=3]="INT8",s[s.UINT16=4]="UINT16",s[s.INT16=5]="INT16",s[s.INT32=6]="INT32",s[s.INT64=7]="INT64",s[s.STRING=8]="STRING",s[s.BOOL=9]="BOOL",s[s.FLOAT16=10]="FLOAT16",s[s.DOUBLE=11]="DOUBLE",s[s.UINT32=12]="UINT32",s[s.UINT64=13]="UINT64",s[s.COMPLEX64=14]="COMPLEX64",s[s.COMPLEX128=15]="COMPLEX128",s[s.BFLOAT16=16]="BFLOAT16"})(f.TensorDataType||(f.TensorDataType={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){(function(s){s[s.Primitive=0]="Primitive",s[s.Fused=1]="Fused"})(f.NodeType||(f.NodeType={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){(function(s){s[s.NONE=0]="NONE",s[s.tensor_type=1]="tensor_type",s[s.sequence_type=2]="sequence_type",s[s.map_type=3]="map_type"})(f.TypeInfoValue||(f.TypeInfoValue={}))})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}dim(t,e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new o.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(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 startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return s.startShape(t),s.addDim(t,e),s.endShape(t)}}f.Shape=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}value(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,n){return s.startDimension(t),s.addValue(t,e),s.addDenotation(t,n),s.endDimension(t)}}f.Dimension=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):o.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(t,e){t.addFieldInt8(0,e,o.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,n,r){return s.startDimensionValue(t),s.addDimType(t,e),s.addDimValue(t,n),s.addDimParam(t,r),s.endDimensionValue(t)}}f.DimensionValue=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(t,e){t.addFieldInt32(0,e,o.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,n){return s.startTensorTypeAndShape(t),s.addElemType(t,e),s.addShape(t,n),s.endTensorTypeAndShape(t)}}f.TensorTypeAndShape=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(t,e){t.addFieldInt32(0,e,o.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,n){return s.startMapType(t),s.addKeyType(t,e),s.addValueType(t,n),s.endMapType(t)}}f.MapType=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}elemType(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return s.startSequenceType(t),s.addElemType(t,e),s.endSequenceType(t)}}f.SequenceType=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(c.fbs||(c.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(f,s){return this.bb_pos=f,this.bb=s,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(f,s,i,t){return f.prep(4,12),f.writeInt32(t),f.writeInt32(i),f.writeInt32(s),f.offset()}}})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+n)+12*t,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(t,e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new o.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+n)+12*t,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,n,r){return s.startNodeEdge(t),s.addNodeIndex(t,e),s.addInputEdges(t,n),s.addOutputEdges(t,r),s.endNodeEdge(t)}}f.NodeEdge=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?(e||new o.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(t,e){t.addFieldInt32(6,e,o.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(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 startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(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 startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(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 startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(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 startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,n,r,a,l,d,m,y,_,v,T,S,O){return s.startNode(t),s.addName(t,e),s.addDocString(t,n),s.addDomain(t,r),s.addSinceVersion(t,a),s.addIndex(t,l),s.addOpType(t,d),s.addType(t,m),s.addExecutionProviderType(t,y),s.addInputs(t,_),s.addOutputs(t,v),s.addAttributes(t,T),s.addInputArgCounts(t,S),s.addImplicitInputs(t,O),s.endNode(t)}}f.Node=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new o.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,n,r){return s.startValueInfo(t),s.addName(t,e),s.addDocString(t,n),s.addType(t,r),s.endValueInfo(t)}}f.ValueInfo=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):o.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(t,e){t.addFieldInt8(1,e,o.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,n,r){return s.startTypeInfo(t),s.addDenotation(t,e),s.addValueType(t,n),s.addValue(t,r),s.endTypeInfo(t)}}f.TypeInfo=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,e,n){return s.startOperatorSetId(t),s.addDomain(t,e),s.addVersion(t,n),s.endOperatorSetId(t)}}f.OperatorSetId=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(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 startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(t,e){t.addFieldInt32(3,e,o.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(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 startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,n,r,a,l,d){return s.startTensor(t),s.addName(t,e),s.addDocString(t,n),s.addDims(t,r),s.addDataType(t,a),s.addRawData(t,l),s.addStringData(t,d),s.endTensor(t)}}f.Tensor=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}values(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}indices(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(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 startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,n,r){return s.startSparseTensor(t),s.addValues(t,e),s.addIndices(t,n),s.addDims(t,r),s.endSparseTensor(t)}}f.SparseTensor=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):o.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(t){let e=this.bb.__offset(this.bb_pos,16);return e?(t||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}g(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new o.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(t,e){let n=this.bb.__offset(this.bb_pos,26);return n?(e||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?(e||new o.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldInt32(2,e,o.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addFloat32(e[n]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(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 startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(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 startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(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 startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(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 startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,n,r,a,l,d,m,y,_,v,T,S,O){return s.startAttribute(t),s.addName(t,e),s.addDocString(t,n),s.addType(t,r),s.addF(t,a),s.addI(t,l),s.addS(t,d),s.addT(t,m),s.addG(t,y),s.addFloats(t,_),s.addInts(t,v),s.addStrings(t,T),s.addTensors(t,S),s.addGraphs(t,O),s.endAttribute(t)}}f.Attribute=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}initializers(t,e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new o.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(t,e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new o.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(t,e){let n=this.bb.__offset(this.bb_pos,12);return n?(e||new o.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(t,e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new o.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(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 startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(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 startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(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 startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(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 startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(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 startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(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 startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(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 startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,n,r,a,l,d,m,y){return s.startGraph(t),s.addInitializers(t,e),s.addNodeArgs(t,n),s.addNodes(t,r),s.addMaxNodeIndex(t,a),s.addNodeEdges(t,l),s.addInputs(t,d),s.addOutputs(t,m),s.addSparseInitializers(t,y),s.endGraph(t)}}f.Graph=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new o.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(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 startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,n,r,a,l,d,m,y,_){return s.startModel(t),s.addIrVersion(t,e),s.addOpsetImport(t,n),s.addProducerName(t,r),s.addProducerVersion(t,a),s.addDomain(t,l),s.addModelVersion(t,d),s.addDocString(t,m),s.addGraph(t,y),s.addGraphDocString(t,_),s.endModel(t)}}f.Model=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(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 startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,e,n){return s.startKernelCreateInfos(t),s.addNodeIndices(t,e),s.addKernelDefHashes(t,n),s.endKernelCreateInfos(t)}}f.KernelCreateInfos=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,n){return s.startSubGraphSessionState(t),s.addGraphId(t,e),s.addSessionState(t,n),s.endSubGraphSessionState(t)}}f.SubGraphSessionState=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}kernels(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new o.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}subGraphSessionStates(t,e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new o.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+n)+4*t),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(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 startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,n){return s.startSessionState(t),s.addKernels(t,e),s.addSubGraphSessionStates(t,n),s.endSessionState(t)}}f.SessionState=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={})),function(o){(function(c){(function(f){class s{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+g.flatbuffers.SIZE_PREFIX_LENGTH),(e||new s).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new o.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new o.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,n,r){return s.startInferenceSession(t),s.addOrtVersion(t,e),s.addModel(t,n),s.addSessionState(t,r),s.endInferenceSession(t)}}f.InferenceSession=s})(c.fbs||(c.fbs={}))})(o.experimental||(o.experimental={}))}(u.onnxruntime||(u.onnxruntime={}))},7448:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.OnnxjsSessionHandler=void 0;const g=b(1670),p=b(9162);u.OnnxjsSessionHandler=class{constructor(h){this.session=h,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(h,o,c){const f=new Map;for(const t in h)if(Object.hasOwnProperty.call(h,t)){const e=h[t];f.set(t,new p.Tensor(e.dims,e.type,void 0,void 0,e.data))}const s=await this.session.run(f),i={};return s.forEach((t,e)=>{i[e]=new g.Tensor(t.type,t.data,t.dims)}),i}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.Session=void 0;const g=b(7067),p=b(1296),h=b(7091),o=b(1036),c=b(6231),f=b(2644);u.Session=class{constructor(s={}){this._initialized=!1,this.backendHint=s.backendHint,this.profiler=c.Profiler.create(s.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(s,i,t){await this.profiler.event("session","Session.loadModel",async()=>{const e=await(0,h.resolveBackend)(this.backendHint);if(this.sessionHandler=e.createSessionHandler(this.context),this._model=new f.Model,typeof s=="string"){const n=s.endsWith(".ort");if(typeof fetch>"u"){const r=await(0,p.promisify)(g.readFile)(s);this.initialize(r,n)}else{const r=await fetch(s),a=await r.arrayBuffer();this.initialize(new Uint8Array(a),n)}}else if(ArrayBuffer.isView(s))this.initialize(s);else{const n=new Uint8Array(s,i||0,t||s.byteLength);this.initialize(n)}})}initialize(s,i){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const t=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(s,t,i),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new o.ExecutionPlan(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(s){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{const i=this.normalizeAndValidateInputs(s),t=await this._executionPlan.execute(this.sessionHandler,i);return this.createOutput(t)})}normalizeAndValidateInputs(s){const i=this._model.graph.getInputNames();if(Array.isArray(s)){if(s.length!==i.length)throw new Error(`incorrect input array length: expected ${i.length} but got ${s.length}`)}else{if(s.size!==i.length)throw new Error(`incorrect input map size: expected ${i.length} but got ${s.size}`);const t=new Array(s.size);let e=0;for(let n=0;ntypeof O=="string")))throw new TypeError("cache should be a string array");S&&(this.cache=new Array(T))}else{if(_!==void 0){const O=e(d);if(!(_ instanceof O))throw new TypeError(`cache should be type ${O.name}`)}if(S){const O=new ArrayBuffer(T*function(w){switch(w){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${w}`)}}(d));this.cache=function(w,I){return new(e(I))(w)}(O,d)}}}static fromProto(l){if(!l)throw new Error("cannot construct Value from an empty tensor");const d=f.ProtoUtil.tensorDataTypeFromProto(l.dataType),m=f.ProtoUtil.tensorDimsFromProto(l.dims),y=new i(m,d);if(d==="string")l.stringData.forEach((_,v)=>{y.data[v]=(0,f.decodeUtf8String)(_)});else if(l.rawData&&typeof l.rawData.byteLength=="number"&&l.rawData.byteLength>0){const _=y.data,v=new DataView(l.rawData.buffer,l.rawData.byteOffset,l.rawData.byteLength),T=t(l.dataType),S=l.rawData.byteLength/T;if(l.rawData.byteLength%T!=0)throw new Error("invalid buffer length");if(_.length!==S)throw new Error("buffer length mismatch");for(let O=0;O0){const _=y.data,v=new DataView(l.rawDataArray().buffer,l.rawDataArray().byteOffset,l.rawDataLength()),T=t(l.dataType()),S=l.rawDataLength()/T;if(l.rawDataLength()%T!=0)throw new Error("invalid buffer length");if(_.length!==S)throw new Error("buffer length mismatch");for(let O=0;O1&&I>1)return;S[T-O]=Math.max(w,I)}return S}static index(d,m){const y=new Array(m.length);return s.fillIndex(d,m,y),y}static fillIndex(d,m,y){const _=d.length-m.length;for(let v=0;v=0;J--)w[J]=B%T[J],B=Math.floor(B/T[J]);W||(s.fillIndex(w,d.dims,I),j=d.get(I)),k||(s.fillIndex(w,m.dims,R),N=m.get(R)),O.set(w,y(j,N))}}return O}}static isValidBroadcast(d,m){const y=d.length,_=m.length;if(y>_)return!1;for(let v=1;v<=y;v++)if(d[y-v]!==1&&d[y-v]!==m[_-v])return!1;return!0}static getBroadcastDims(d,m){const y=d.length,_=[];for(let v=0;v1&&S===1&&_.unshift(T)}return _}}u.BroadcastUtil=s,u.arrayCopyHelper=function(l,d,m,y,_){if(y<0||y>=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+_>d.length)throw new Error("source indices to be copied are outside bounds");if(m+_>l.length)throw new Error("target array is too small to hold result");for(let v=0;v<_;v++)l[m+v]=d[y+v]},u.GemmUtil=class{static getShapeOfGemmResult(l,d,m,y,_){if(l.length!==2||m.length!==2)throw new Error("shape need to be of size 2");let v,T,S;d?(v=l[1],T=l[0]):(v=l[0],T=l[1]);let O=-1;if(y?(S=m[0],O=1):(S=m[1],O=0),m[O]!==T)throw new Error("dimension mismatch");if(v<=0||S<=0||T<=0)throw new Error("invalid shape specified");if(_&&!s.isValidBroadcast(_,[v,S]))throw new Error("gemm: invalid bias shape for broadcast");return[v,S,T]}};class i{static tensorDataTypeFromProto(d){switch(d){case o.onnx.TensorProto.DataType.INT8:return"int8";case o.onnx.TensorProto.DataType.UINT8:return"uint8";case o.onnx.TensorProto.DataType.BOOL:return"bool";case o.onnx.TensorProto.DataType.INT16:return"int16";case o.onnx.TensorProto.DataType.UINT16:return"uint16";case o.onnx.TensorProto.DataType.INT32:return"int32";case o.onnx.TensorProto.DataType.UINT32:return"uint32";case o.onnx.TensorProto.DataType.FLOAT:return"float32";case o.onnx.TensorProto.DataType.DOUBLE:return"float64";case o.onnx.TensorProto.DataType.STRING:return"string";case o.onnx.TensorProto.DataType.INT64:return"int32";case o.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${o.onnx.TensorProto.DataType[d]}`)}}static tensorDataTypeStringToEnum(d){switch(d){case"int8":return o.onnx.TensorProto.DataType.INT8;case"uint8":return o.onnx.TensorProto.DataType.UINT8;case"bool":return o.onnx.TensorProto.DataType.BOOL;case"int16":return o.onnx.TensorProto.DataType.INT16;case"uint16":return o.onnx.TensorProto.DataType.UINT16;case"int32":return o.onnx.TensorProto.DataType.INT32;case"uint32":return o.onnx.TensorProto.DataType.UINT32;case"float32":return o.onnx.TensorProto.DataType.FLOAT;case"float64":return o.onnx.TensorProto.DataType.DOUBLE;case"string":return o.onnx.TensorProto.DataType.STRING;case"int64":return o.onnx.TensorProto.DataType.INT64;case"uint64":return o.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${d}`)}}static tensorDimsFromProto(d){return d.map(m=>h.default.isLong(m)?m.toNumber():m)}static tensorValueTypeFromProto(d){return{tensorType:i.tensorDataTypeFromProto(d.elemType),shape:{dims:i.tensorDimsFromProto(d.shape.dim.map(m=>m.dimValue))}}}static tensorDimsFromORTFormat(d){const m=[];for(let y=0;yd.length)throw new Error(`invalid dimension of ${m} for sizeFromDimension as Tensor has ${d.length} dimensions.`);return e.getSizeFromDimensionRange(d,m,d.length)}static sizeToDimension(d,m){if(m<0||m>d.length)throw new Error(`invalid dimension of ${m} for sizeToDimension as Tensor has ${d.length} dimensions.`);return e.getSizeFromDimensionRange(d,0,m)}static getSizeFromDimensionRange(d,m,y){let _=1;for(let v=m;v=0;--_)y[_]=y[_+1]*d[_+1];return y}static transpose(d){return d.slice().reverse()}static indicesToOffset(d,m,y){y===void 0&&(y=d.length);let _=0;for(let v=0;v=m)throw new Error("unsupported axis for this operation.");return d<0?d+m:d}static normalizeAxes(d,m){return d.map(y=>this.normalizeAxis(y,m))}static incrementIndex(d,m,y){if(m.length===0||d.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(y===void 0)y=m.length;else if(y<=0||y>m.length)throw new Error("Incorrect axis to increment on");for(let _=y-1;_>=0&&(d[_]++,!(d[_]=d.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");_[O]=d[O]}else _[O]=m[O];T*=_[O]}}const S=e.size(d);if(v!==-1){if(S%T!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${d}] Output shape: [${m}]`);_[v]=S/T}else if(T!==S)throw new Error("reshapedDims and originalDims don't have matching sizes");return _}static sortBasedOnPerm(d,m){return m?m.map(y=>d[y]):d.slice().reverse()}static padShape(d,m){const y=d.length;return d.map((_,v)=>_+m[v]+m[v+y])}static areEqual(d,m){return d.length===m.length&&d.every((y,_)=>y===m[_])}static validateDimsAndCalcSize(d){if(d.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let m=1;for(const y of d){if(!Number.isInteger(y))throw new TypeError(`Invalid shape: ${y} is not an integer`);if(y<0||y>2147483647)throw new TypeError(`Invalid shape: length ${y} is not allowed`);m*=y}return m}static flattenShape(d,m){m<0&&(m+=d.length);const y=d.reduce((v,T)=>v*T,1),_=d.slice(m).reduce((v,T)=>v*T,1);return[y/_,_]}static squeezeShape(d,m){const y=new Array;m=e.normalizeAxes(m,d.length);for(let _=0;_=0;if(v&&d[_]!==1)throw new Error("squeeze an axis of size different than 1");(m.length===0&&d[_]>1||m.length>0&&!v)&&y.push(d[_])}return y}static unsqueezeShape(d,m){const y=new Array(d.length+m.length);y.fill(0);for(let v=0;v=y.length)throw new Error("'axes' has an out of range axis");if(y[T]!==0)throw new Error("'axes' has a duplicate axis");y[T]=1}let _=0;for(let v=0;v=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+_>d.length)throw new Error("source indices to be copied are outside bounds");if(m+_>l.length)throw new Error("target array is too small to hold result");for(let v=0;v<_;v++)l[m+v]+=Math.pow(d[y+v],2)}static axpy(l,d,m,y,_,v){if(y<0||y>=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+_>d.length)throw new Error("source indices to be copied are outside bounds");if(m+_>l.length)throw new Error("target array is too small to hold result");for(let T=0;T<_;T++)l[m+T]+=v*d[y+T]}static powx(l,d,m,y,_,v){if(y<0||y>=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+_>d.length)throw new Error("source indices to be copied are outside bounds");if(m+_>l.length)throw new Error("target array is too small to hold result");for(let T=0;T<_;T++)l[m+T]=Math.pow(d[y+T],v)}static mul(l,d,m,y,_){if(y<0||y>=d.length)throw new Error("sourceIndex out of bounds");if(m<0||m>=l.length)throw new Error("targetIndex out of bounds");if(y+_>d.length)throw new Error("source indices to be copied are outside bounds");if(m+_>l.length)throw new Error("target array is too small to hold result");for(let v=0;v<_;v++)l[m+v]=d[y+v]*l[m+v]}};class n{static splitShape(d,m,y,_){if(y.length===0){if(!_)throw new Error("need to know number of outputs when the 'split' attribute is not specified");n.determineSplit(d[m],_,y)}const v=[],T=[0];for(let S=0;Sm.push(N));const S=r.calcReduceShape(T,m,!0),O=e.size(S),w=new c.Tensor(S,d.type),I=e.computeStrides(S),R=e.computeStrides(T),B=new Array(T.length);for(let j=0;j=m.length)return T(d[v]);const w=m[_],I=w>=y.length?1:e.size(y.slice(w+1));for(let R=0;Rv!==0)}}u.ReduceUtil=r;class a{static adjustPoolAttributes(d,m,y,_,v,T){if(!d&&y.length!==m.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(d)for(let S=0;S=y.length?y.push(m[S+2]):y[S]=m[S+2];for(let S=0;S=y[S]||T[S+y.length]>=y[S])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(d,m,y,_,v,T){if(T){if(v.length!==2*(d.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(m.length!==d.length-2)throw new Error("length of strides should be the length of data dimensions");if(_.length!==d.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let S=0;S{Object.defineProperty(u,"__esModule",{value:!0}),u.iterateExtraOptions=void 0,u.iterateExtraOptions=(b,g,p,h)=>{if(typeof b=="object"&&b!==null){if(p.has(b))throw new Error("Circular reference in options");p.add(b)}Object.entries(b).forEach(([o,c])=>{const f=g?g+o:o;if(typeof c=="object")(0,u.iterateExtraOptions)(c,f+".",p,h);else if(typeof c=="string"||typeof c=="number")h(f,c.toString());else{if(typeof c!="boolean")throw new Error("Can't handle extra config type: "+typeof c);h(f,c?"1":"0")}})}},2157:function(D,u,b){var g,p=this&&this.__createBinding||(Object.create?function(I,R,B,j){j===void 0&&(j=B);var N=Object.getOwnPropertyDescriptor(R,B);N&&!("get"in N?!R.__esModule:N.writable||N.configurable)||(N={enumerable:!0,get:function(){return R[B]}}),Object.defineProperty(I,j,N)}:function(I,R,B,j){j===void 0&&(j=B),I[j]=R[B]}),h=this&&this.__setModuleDefault||(Object.create?function(I,R){Object.defineProperty(I,"default",{enumerable:!0,value:R})}:function(I,R){I.default=R}),o=this&&this.__importStar||function(I){if(I&&I.__esModule)return I;var R={};if(I!=null)for(var B in I)B!=="default"&&Object.prototype.hasOwnProperty.call(I,B)&&p(R,I,B);return h(R,I),R};Object.defineProperty(u,"__esModule",{value:!0}),u.endProfiling=u.run=u.releaseSession=u.createSession=u.createSessionFinalize=u.createSessionAllocate=u.initOrt=u.initWasm=void 0;const c=b(1670),f=o(b(349)),s=b(6361),i=()=>!!c.env.wasm.proxy&&typeof document<"u";let t,e,n,r=!1,a=!1,l=!1;const d=[],m=[],y=[],_=[],v=[],T=[],S=()=>{if(r||!a||l||!t)throw new Error("worker not ready")},O=I=>{switch(I.data.type){case"init-wasm":r=!1,I.data.err?(l=!0,e[1](I.data.err)):(a=!0,e[0]());break;case"init-ort":I.data.err?n[1](I.data.err):n[0]();break;case"create_allocate":I.data.err?d.shift()[1](I.data.err):d.shift()[0](I.data.out);break;case"create_finalize":I.data.err?m.shift()[1](I.data.err):m.shift()[0](I.data.out);break;case"create":I.data.err?y.shift()[1](I.data.err):y.shift()[0](I.data.out);break;case"release":I.data.err?_.shift()[1](I.data.err):_.shift()[0]();break;case"run":I.data.err?v.shift()[1](I.data.err):v.shift()[0](I.data.out);break;case"end-profiling":I.data.err?T.shift()[1](I.data.err):T.shift()[0]()}},w=typeof document<"u"?(g=document==null?void 0:document.currentScript)===null||g===void 0?void 0:g.src:void 0;u.initWasm=async()=>{if(i()){if(a)return;if(r)throw new Error("multiple calls to 'initWasm()' detected.");if(l)throw new Error("previous call to 'initWasm()' failed.");return r=!0,c.env.wasm.wasmPaths===void 0&&w&&w.indexOf("blob:")!==0&&(c.env.wasm.wasmPaths=w.substr(0,+w.lastIndexOf("/")+1)),new Promise((I,R)=>{t==null||t.terminate(),t=b(9710).Z(),t.onmessage=O,e=[I,R];const B={type:"init-wasm",in:c.env.wasm};t.postMessage(B)})}return(0,s.initializeWebAssembly)(c.env.wasm)},u.initOrt=async(I,R)=>{if(i())return S(),new Promise((B,j)=>{n=[B,j];const N={type:"init-ort",in:{numThreads:I,loggingLevel:R}};t.postMessage(N)});f.initOrt(I,R)},u.createSessionAllocate=async I=>i()?(S(),new Promise((R,B)=>{d.push([R,B]);const j={type:"create_allocate",in:{model:I}};t.postMessage(j,[I.buffer])})):f.createSessionAllocate(I),u.createSessionFinalize=async(I,R)=>i()?(S(),new Promise((B,j)=>{m.push([B,j]);const N={type:"create_finalize",in:{modeldata:I,options:R}};t.postMessage(N)})):f.createSessionFinalize(I,R),u.createSession=async(I,R)=>i()?(S(),new Promise((B,j)=>{y.push([B,j]);const N={type:"create",in:{model:I,options:R}};t.postMessage(N,[I.buffer])})):f.createSession(I,R),u.releaseSession=async I=>{if(i())return S(),new Promise((R,B)=>{_.push([R,B]);const j={type:"release",in:I};t.postMessage(j)});f.releaseSession(I)},u.run=async(I,R,B,j,N)=>i()?(S(),new Promise((W,k)=>{v.push([W,k]);const V={type:"run",in:{sessionId:I,inputIndices:R,inputs:B,outputIndices:j,options:N}};t.postMessage(V,f.extractTransferableBuffers(B))})):f.run(I,R,B,j,N),u.endProfiling=async I=>{if(i())return S(),new Promise((R,B)=>{T.push([R,B]);const j={type:"end-profiling",in:I};t.postMessage(j)});f.endProfiling(I)}},586:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.setRunOptions=void 0;const g=b(7967),p=b(4983),h=b(6361);u.setRunOptions=o=>{const c=(0,h.getInstance)();let f=0;const s=[],i=o||{};try{if((o==null?void 0:o.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof o.logSeverityLevel!="number"||!Number.isInteger(o.logSeverityLevel)||o.logSeverityLevel<0||o.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${o.logSeverityLevel}`);if((o==null?void 0:o.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof o.logVerbosityLevel!="number"||!Number.isInteger(o.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${o.logVerbosityLevel}`);(o==null?void 0:o.terminate)===void 0&&(i.terminate=!1);let t=0;if((o==null?void 0:o.tag)!==void 0&&(t=(0,p.allocWasmString)(o.tag,s)),f=c._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,t),f===0)throw new Error("Can't create run options");return(o==null?void 0:o.extra)!==void 0&&(0,g.iterateExtraOptions)(o.extra,"",new WeakSet,(e,n)=>{const r=(0,p.allocWasmString)(e,s),a=(0,p.allocWasmString)(n,s);if(c._OrtAddRunConfigEntry(f,r,a)!==0)throw new Error(`Can't set a run config entry: ${e} - ${n}`)}),[f,s]}catch(t){throw f!==0&&c._OrtReleaseRunOptions(f),s.forEach(c._free),t}}},2306:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.OnnxruntimeWebAssemblySessionHandler=void 0;const g=b(2806),p=b(1670),h=b(2850),o=b(2157);let c;u.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(f){const s=await fetch(f),i=await s.arrayBuffer();return(0,o.createSessionAllocate)(new Uint8Array(i))}async loadModel(f,s){if(c||(await(0,o.initOrt)(p.env.wasm.numThreads,(i=>{switch(i){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: ${i}`)}})(p.env.logLevel)),c=!0),typeof f=="string")if(typeof fetch>"u"){const i=await(0,h.promisify)(g.readFile)(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,o.createSession)(i,s)}else{const i=await this.createSessionAllocate(f);[this.sessionId,this.inputNames,this.outputNames]=await(0,o.createSessionFinalize)(i,s)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,o.createSession)(f,s)}async dispose(){return(0,o.releaseSession)(this.sessionId)}async run(f,s,i){const t=[],e=[];Object.entries(f).forEach(l=>{const d=l[0],m=l[1],y=this.inputNames.indexOf(d);if(y===-1)throw new Error(`invalid input '${d}'`);t.push(m),e.push(y)});const n=[];Object.entries(s).forEach(l=>{const d=l[0],m=this.outputNames.indexOf(d);if(m===-1)throw new Error(`invalid output '${d}'`);n.push(m)});const r=await(0,o.run)(this.sessionId,e,t.map(l=>[l.type,l.dims,l.data]),n,i),a={};for(let l=0;l{Object.defineProperty(u,"__esModule",{value:!0}),u.setSessionOptions=void 0;const g=b(7967),p=b(4983),h=b(6361);u.setSessionOptions=o=>{const c=(0,h.getInstance)();let f=0;const s=[],i=o||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(i);try{(o==null?void 0:o.graphOptimizationLevel)===void 0&&(i.graphOptimizationLevel="all");const t=(r=>{switch(r){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${r}`)}})(i.graphOptimizationLevel);(o==null?void 0:o.enableCpuMemArena)===void 0&&(i.enableCpuMemArena=!0),(o==null?void 0:o.enableMemPattern)===void 0&&(i.enableMemPattern=!0),(o==null?void 0:o.executionMode)===void 0&&(i.executionMode="sequential");const e=(r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}})(i.executionMode);let n=0;if((o==null?void 0:o.logId)!==void 0&&(n=(0,p.allocWasmString)(o.logId,s)),(o==null?void 0:o.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof o.logSeverityLevel!="number"||!Number.isInteger(o.logSeverityLevel)||o.logSeverityLevel<0||o.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${o.logSeverityLevel}`);if((o==null?void 0:o.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof o.logVerbosityLevel!="number"||!Number.isInteger(o.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${o.logVerbosityLevel}`);if((o==null?void 0:o.enableProfiling)===void 0&&(i.enableProfiling=!1),f=c._OrtCreateSessionOptions(t,!!i.enableCpuMemArena,!!i.enableMemPattern,e,!!i.enableProfiling,0,n,i.logSeverityLevel,i.logVerbosityLevel),f===0)throw new Error("Can't create session options");return o!=null&&o.executionProviders&&((r,a,l)=>{for(const d of a){let m=typeof d=="string"?d:d.name;switch(m){case"xnnpack":m="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${m}`)}const y=(0,p.allocWasmString)(m,l);if((0,h.getInstance)()._OrtAppendExecutionProvider(r,y)!==0)throw new Error(`Can't append execution provider: ${m}`)}})(f,o.executionProviders,s),(o==null?void 0:o.extra)!==void 0&&(0,g.iterateExtraOptions)(o.extra,"",new WeakSet,(r,a)=>{const l=(0,p.allocWasmString)(r,s),d=(0,p.allocWasmString)(a,s);if(c._OrtAddSessionConfigEntry(f,l,d)!==0)throw new Error(`Can't set a session config entry: ${r} - ${a}`)}),[f,s]}catch(t){throw f!==0&&c._OrtReleaseSessionOptions(f),s.forEach(c._free),t}}},4983:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.allocWasmString=void 0;const g=b(6361);u.allocWasmString=(p,h)=>{const o=(0,g.getInstance)(),c=o.lengthBytesUTF8(p)+1,f=o._malloc(c);return o.stringToUTF8(p,f,c),h.push(f),f}},349:(D,u,b)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.extractTransferableBuffers=u.endProfiling=u.run=u.releaseSession=u.createSession=u.createSessionFinalize=u.createSessionAllocate=u.initOrt=void 0;const g=b(586),p=b(4919),h=b(4983),o=b(6361);u.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(n!==0)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const c=new Map;u.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},u.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,a=0,l=[];try{if([a,l]=(0,p.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],a),r===0)throw new Error("Can't create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(a),l.forEach(n._free)}const d=n._OrtGetInputCount(r),m=n._OrtGetOutputCount(r),y=[],_=[],v=[],T=[];for(let S=0;S{const n=(0,u.createSessionAllocate)(t);return(0,u.createSessionFinalize)(n,e)},u.releaseSession=t=>{const e=(0,o.getInstance)(),n=c.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],l=n[2];a.forEach(e._OrtFree),l.forEach(e._OrtFree),e._OrtReleaseSession(r),c.delete(t)};const f=t=>{switch(t){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"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){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 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},i=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};u.run=(t,e,n,r,a)=>{const l=(0,o.getInstance)(),d=c.get(t);if(!d)throw new Error("invalid session id");const m=d[0],y=d[1],_=d[2],v=e.length,T=r.length;let S=0,O=[];const w=[],I=[];try{[S,O]=(0,g.setRunOptions)(a);for(let k=0;kl.HEAP32[Oe++]=xe);const le=l._OrtCreateTensor(f(V),te,ne,Pe,J.length);if(le===0)throw new Error("Can't create a tensor");w.push(le)}finally{l.stackRestore(me)}}const R=l.stackSave(),B=l.stackAlloc(4*v),j=l.stackAlloc(4*v),N=l.stackAlloc(4*T),W=l.stackAlloc(4*T);try{let k=B/4,V=j/4,J=N/4,Y=W/4;for(let me=0;mewe*je);if(xe=s(He),xe==="string"){const we=[];let je=_e/4;for(let Ue=0;Ue{const e=(0,o.getInstance)(),n=c.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(a===0)throw new Error("Can't get an profile file name");e._OrtFree(a)},u.extractTransferableBuffers=t=>{const e=[];for(const n of t){const r=n[2];!Array.isArray(r)&&r.buffer&&e.push(r.buffer)}return e}},6361:function(D,u,b){var g=this&&this.__createBinding||(Object.create?function(a,l,d,m){m===void 0&&(m=d);var y=Object.getOwnPropertyDescriptor(l,d);y&&!("get"in y?!l.__esModule:y.writable||y.configurable)||(y={enumerable:!0,get:function(){return l[d]}}),Object.defineProperty(a,m,y)}:function(a,l,d,m){m===void 0&&(m=d),a[m]=l[d]}),p=this&&this.__setModuleDefault||(Object.create?function(a,l){Object.defineProperty(a,"default",{enumerable:!0,value:l})}:function(a,l){a.default=l}),h=this&&this.__importStar||function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var d in a)d!=="default"&&Object.prototype.hasOwnProperty.call(a,d)&&g(l,a,d);return p(l,a),l},o=this&&this.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(u,"__esModule",{value:!0}),u.dispose=u.getInstance=u.initializeWebAssembly=void 0;const c=h(b(6449)),f=o(b(932)),s=b(3474);let i,t=!1,e=!1,n=!1;const r=(a,l)=>l?a?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":a?"ort-wasm-simd.wasm":"ort-wasm.wasm";u.initializeWebAssembly=async a=>{if(t)return Promise.resolve();if(e)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(n)throw new Error("previous call to 'initializeWebAssembly()' failed.");e=!0;const l=a.initTimeout,d=a.numThreads,m=a.simd,y=d>1&&(()=>{try{return typeof SharedArrayBuffer<"u"&&(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}})(),_=m&&(()=>{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}})(),v=typeof a.wasmPaths=="string"?a.wasmPaths:void 0,T=r(!1,y),S=r(_,y),O=typeof a.wasmPaths=="object"?a.wasmPaths[S]:void 0;let w=!1;const I=[];if(l>0&&I.push(new Promise(R=>{setTimeout(()=>{w=!0,R()},l)})),I.push(new Promise((R,B)=>{const j=y?s:f.default,N={locateFile:(W,k)=>y&&W.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([b(4154)],{type:"text/javascript"})):W===T?O??(v??k)+S:k+W};if(y)if(typeof Blob>"u")N.mainScriptUrlOrBlob=c.join("/","ort-wasm-threaded.js");else{const W=`var ortWasmThreaded=(function(){var _scriptDir;return ${j.toString()}})();`;N.mainScriptUrlOrBlob=new Blob([W],{type:"text/javascript"})}j(N).then(W=>{e=!1,t=!0,i=W,R()},W=>{e=!1,n=!0,B(W)})})),await Promise.race(I),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${l}ms`)},u.getInstance=()=>{if(t&&i)return i;throw new Error("WebAssembly is not initialized yet.")},u.dispose=()=>{var a;!t||e||n||(e=!0,(a=i.PThread)===null||a===void 0||a.terminateAllThreads(),i=void 0,e=!1,t=!1,n=!0)}},9710:(D,u,b)=>{b.d(u,{Z:()=>h});var g=b(477),p=b.n(g);function h(){return p()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){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"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){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 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(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(t){return!1}})(),o=a&&(()=>{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(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:D=>{D.exports=function(u,b,g,p){var h=self||window;try{try{var o;try{o=new h.Blob([u])}catch{(o=new(h.BlobBuilder||h.WebKitBlobBuilder||h.MozBlobBuilder||h.MSBlobBuilder)).append(u),o=o.getBlob()}var c=h.URL||h.webkitURL,f=c.createObjectURL(o),s=new h[b](f,g);return c.revokeObjectURL(f),s}catch{return new h[b]("data:application/javascript,".concat(encodeURIComponent(u)),g)}}catch{if(!p)throw Error("Inline worker is not supported");return new h[b](p,g)}}},4154:D=>{D.exports=`"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}}; +`},1670:D=>{D.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(D,u,b)=>{b.r(u),b.d(u,{flatbuffers:()=>g});var g={};g.Offset,g.Table,g.SIZEOF_SHORT=2,g.SIZEOF_INT=4,g.FILE_IDENTIFIER_LENGTH=4,g.SIZE_PREFIX_LENGTH=4,g.Encoding={UTF8_BYTES:1,UTF16_STRING:2},g.int32=new Int32Array(2),g.float32=new Float32Array(g.int32.buffer),g.float64=new Float64Array(g.int32.buffer),g.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,g.Long=function(p,h){this.low=0|p,this.high=0|h},g.Long.create=function(p,h){return p==0&&h==0?g.Long.ZERO:new g.Long(p,h)},g.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},g.Long.prototype.equals=function(p){return this.low==p.low&&this.high==p.high},g.Long.ZERO=new g.Long(0,0),g.Builder=function(p){if(p)h=p;else var h=1024;this.bb=g.ByteBuffer.allocate(h),this.space=h,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},g.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},g.Builder.prototype.forceDefaults=function(p){this.force_defaults=p},g.Builder.prototype.dataBuffer=function(){return this.bb},g.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},g.Builder.prototype.prep=function(p,h){p>this.minalign&&(this.minalign=p);for(var o=1+~(this.bb.capacity()-this.space+h)&p-1;this.space=0&&this.vtable[h]==0;h--);for(var o=h+1;h>=0;h--)this.addInt16(this.vtable[h]!=0?p-this.vtable[h]:0);this.addInt16(p-this.object_start);var c=(o+2)*g.SIZEOF_SHORT;this.addInt16(c);var f=0,s=this.space;e:for(h=0;h=0;s--)this.writeInt8(f.charCodeAt(s))}this.prep(this.minalign,g.SIZEOF_INT+c),this.addOffset(p),c&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},g.Builder.prototype.finishSizePrefixed=function(p,h){this.finish(p,h,!0)},g.Builder.prototype.requiredField=function(p,h){var o=this.bb.capacity()-p,c=o-this.bb.readInt32(o);if(this.bb.readInt16(c+h)==0)throw new Error("FlatBuffers: field "+h+" must be set")},g.Builder.prototype.startVector=function(p,h,o){this.notNested(),this.vector_num_elems=h,this.prep(g.SIZEOF_INT,p*h),this.prep(o,p*h)},g.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},g.Builder.prototype.createString=function(p){if(p instanceof Uint8Array)var h=p;else{h=[];for(var o=0;o=56320?f:(f<<10)+p.charCodeAt(o++)+-56613888)<128?h.push(c):(c<2048?h.push(c>>6&31|192):(c<65536?h.push(c>>12&15|224):h.push(c>>18&7|240,c>>12&63|128),h.push(c>>6&63|128)),h.push(63&c|128))}}this.addInt8(0),this.startVector(1,h.length,1),this.bb.setPosition(this.space-=h.length),o=0;for(var s=this.space,i=this.bb.bytes();o>24},g.ByteBuffer.prototype.readUint8=function(p){return this.bytes_[p]},g.ByteBuffer.prototype.readInt16=function(p){return this.readUint16(p)<<16>>16},g.ByteBuffer.prototype.readUint16=function(p){return this.bytes_[p]|this.bytes_[p+1]<<8},g.ByteBuffer.prototype.readInt32=function(p){return this.bytes_[p]|this.bytes_[p+1]<<8|this.bytes_[p+2]<<16|this.bytes_[p+3]<<24},g.ByteBuffer.prototype.readUint32=function(p){return this.readInt32(p)>>>0},g.ByteBuffer.prototype.readInt64=function(p){return new g.Long(this.readInt32(p),this.readInt32(p+4))},g.ByteBuffer.prototype.readUint64=function(p){return new g.Long(this.readUint32(p),this.readUint32(p+4))},g.ByteBuffer.prototype.readFloat32=function(p){return g.int32[0]=this.readInt32(p),g.float32[0]},g.ByteBuffer.prototype.readFloat64=function(p){return g.int32[g.isLittleEndian?0:1]=this.readInt32(p),g.int32[g.isLittleEndian?1:0]=this.readInt32(p+4),g.float64[0]},g.ByteBuffer.prototype.writeInt8=function(p,h){this.bytes_[p]=h},g.ByteBuffer.prototype.writeUint8=function(p,h){this.bytes_[p]=h},g.ByteBuffer.prototype.writeInt16=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8},g.ByteBuffer.prototype.writeUint16=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8},g.ByteBuffer.prototype.writeInt32=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8,this.bytes_[p+2]=h>>16,this.bytes_[p+3]=h>>24},g.ByteBuffer.prototype.writeUint32=function(p,h){this.bytes_[p]=h,this.bytes_[p+1]=h>>8,this.bytes_[p+2]=h>>16,this.bytes_[p+3]=h>>24},g.ByteBuffer.prototype.writeInt64=function(p,h){this.writeInt32(p,h.low),this.writeInt32(p+4,h.high)},g.ByteBuffer.prototype.writeUint64=function(p,h){this.writeUint32(p,h.low),this.writeUint32(p+4,h.high)},g.ByteBuffer.prototype.writeFloat32=function(p,h){g.float32[0]=h,this.writeInt32(p,g.int32[0])},g.ByteBuffer.prototype.writeFloat64=function(p,h){g.float64[0]=h,this.writeInt32(p,g.int32[g.isLittleEndian?0:1]),this.writeInt32(p+4,g.int32[g.isLittleEndian?1:0])},g.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&s)))}return c},g.ByteBuffer.prototype.__indirect=function(p){return p+this.readInt32(p)},g.ByteBuffer.prototype.__vector=function(p){return p+this.readInt32(p)+g.SIZEOF_INT},g.ByteBuffer.prototype.__vector_len=function(p){return this.readInt32(p+this.readInt32(p))},g.ByteBuffer.prototype.__has_identifier=function(p){if(p.length!=g.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+g.FILE_IDENTIFIER_LENGTH);for(var h=0;h{var u=D&&D.__esModule?()=>D.default:()=>D;return __webpack_require__.d(u,{a:u}),u},__webpack_require__.d=(D,u)=>{for(var b in u)__webpack_require__.o(u,b)&&!__webpack_require__.o(D,b)&&Object.defineProperty(D,b,{enumerable:!0,get:u[b]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(D,u)=>Object.prototype.hasOwnProperty.call(D,u),__webpack_require__.r=D=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(D,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(D,"__esModule",{value:!0})};var __webpack_exports__=__webpack_require__(6018);return __webpack_exports__})())}(ortWeb_min)),ortWeb_min.exports}var models={},common={},hasRequiredCommon;function requireCommon(){return hasRequiredCommon||(hasRequiredCommon=1,Object.defineProperty(common,"__esModule",{value:!0})),common}var legacy={},hasRequiredLegacy;function requireLegacy(){if(hasRequiredLegacy)return legacy;hasRequiredLegacy=1;var D;Object.defineProperty(legacy,"__esModule",{value:!0}),legacy.SileroLegacy=void 0;const u=requireLogging();class b{constructor(p,h,o,c,f){this.ortInstance=p,this._session=h,this._h=o,this._c=c,this._sr=f,this.reset_state=()=>{const s=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",s,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",s,[2,1,64])},this.process=async s=>{var a;const t={input:new this.ortInstance.Tensor("float32",s,[1,s.length]),h:this._h,c:this._c,sr:this._sr},e=await this._session.run(t);this._h=e.hn,this._c=e.cn;const[n]=(a=e.output)==null?void 0:a.data;return{notSpeech:1-n,isSpeech:n}}}}return legacy.SileroLegacy=b,D=b,b.new=async(g,p)=>{u.log.debug("initializing vad");const h=await p(),o=await g.InferenceSession.create(h),c=new g.Tensor("int64",[16000n]),f=Array(2*64).fill(0),s=new g.Tensor("float32",f,[2,1,64]),i=new g.Tensor("float32",f,[2,1,64]);return u.log.debug("vad is initialized"),new D(g,o,s,i,c)},legacy}var v5={},hasRequiredV5;function requireV5(){if(hasRequiredV5)return v5;hasRequiredV5=1;var D;Object.defineProperty(v5,"__esModule",{value:!0}),v5.SileroV5=void 0;const u=requireLogging();function b(p){const h=Array(256).fill(0);return new p.Tensor("float32",h,[2,1,128])}class g{constructor(h,o,c,f){this._session=h,this._state=o,this._sr=c,this.ortInstance=f,this.reset_state=()=>{this._state=b(this.ortInstance)},this.process=async s=>{var a;const t={input:new this.ortInstance.Tensor("float32",s,[1,s.length]),state:this._state,sr:this._sr},e=await this._session.run(t);this._state=e.stateN;const[n]=(a=e.output)==null?void 0:a.data;return{notSpeech:1-n,isSpeech:n}}}}return v5.SileroV5=g,D=g,g.new=async(p,h)=>{u.log.debug("Loading VAD...");const o=await h(),c=await p.InferenceSession.create(o),f=new p.Tensor("int64",[16000n]),s=b(p);return u.log.debug("...finished loading VAD"),new D(c,s,f,p)},v5}var hasRequiredModels;function requireModels(){return hasRequiredModels||(hasRequiredModels=1,function(D){var u=models&&models.__createBinding||(Object.create?function(h,o,c,f){f===void 0&&(f=c);var s=Object.getOwnPropertyDescriptor(o,c);(!s||("get"in s?!o.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return o[c]}}),Object.defineProperty(h,f,s)}:function(h,o,c,f){f===void 0&&(f=c),h[f]=o[c]}),b=models&&models.__exportStar||function(h,o){for(var c in h)c!=="default"&&!Object.prototype.hasOwnProperty.call(o,c)&&u(o,h,c)};Object.defineProperty(D,"__esModule",{value:!0}),D.SileroV5=D.SileroLegacy=void 0,b(requireCommon(),D);var g=requireLegacy();Object.defineProperty(D,"SileroLegacy",{enumerable:!0,get:function(){return g.SileroLegacy}});var p=requireV5();Object.defineProperty(D,"SileroV5",{enumerable:!0,get:function(){return p.SileroV5}})}(models)),models}var resampler={},hasRequiredResampler;function requireResampler(){if(hasRequiredResampler)return resampler;hasRequiredResampler=1,Object.defineProperty(resampler,"__esModule",{value:!0}),resampler.Resampler=void 0;const D=requireLogging();class u{constructor(g){this.options=g,this.process=p=>{const h=[];for(const o of p)for(this.inputBuffer.push(o);this.hasEnoughDataForFrame();){const c=this.generateOutputFrame();h.push(c)}return h},g.nativeSampleRate<16e3&&D.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(g){for(const p of g)for(this.inputBuffer.push(p);this.hasEnoughDataForFrame();)yield this.generateOutputFrame()}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const g=new Float32Array(this.options.targetFrameSize);let p=0,h=0;for(;pr.modelFetcher(r.modelURL),l=await s.SileroLegacy.new(p,a),d=new c.FrameProcessor(l.process,l.reset_state,{frameSamples:r.frameSamples,positiveSpeechThreshold:r.positiveSpeechThreshold,negativeSpeechThreshold:r.negativeSpeechThreshold,redemptionFrames:r.redemptionFrames,preSpeechPadFrames:r.preSpeechPadFrames,minSpeechFrames:r.minSpeechFrames,submitUserSpeechOnPause:r.submitUserSpeechOnPause});return d.resume(),new this(a,p,r,d)}constructor(n,r,a,l){this.modelFetcher=n,this.ort=r,this.options=a,this.frameProcessor=l}async*run(n,r){const a={nativeSampleRate:r,targetSampleRate:16e3,targetFrameSize:this.options.frameSamples},l=new i.Resampler(a);let d=0,m=0,y=0,_=[];for await(const S of l.stream(n)){await this.frameProcessor.process(S,O=>{_.push(O)});for(const O of _)switch(O.msg){case f.Message.SpeechStart:d=y*this.options.frameSamples/16;break;case f.Message.SpeechEnd:m=(y+1)*this.options.frameSamples/16,yield{audio:O.audio,start:d,end:m};break}y++}const{msg:v,audio:T}=this.frameProcessor.endSegment(S=>{_.push(S)});for(const S of _)switch(S.msg){case f.Message.SpeechEnd:yield{audio:S.audio,start:d,end:y*this.options.frameSamples/16}}}}D.NonRealTimeVAD=t}(nonRealTimeVad)),nonRealTimeVad}var utils={},hasRequiredUtils;function requireUtils(){if(hasRequiredUtils)return utils;hasRequiredUtils=1,Object.defineProperty(utils,"__esModule",{value:!0}),utils.audioFileToArray=utils.encodeWAV=utils.arrayBufferToBase64=utils.minFramesForTargetMS=void 0;function D(c,f,s=16e3){return Math.ceil(c*s/1e3/f)}utils.minFramesForTargetMS=D;function u(c){const f=new Uint8Array(c),s=f.byteLength,i=new Array(s);for(var t=0;t{s.addEventListener("loadend",r=>{const a=s.result;f.decodeAudioData(a,l=>{i=l,f.startRendering().then(d=>{console.log("Rendering completed successfully"),n()}).catch(d=>{console.error(`Rendering failed: ${d}`)})},l=>{console.log(`Error with decoding audio data: ${l}`)})}),s.readAsArrayBuffer(c)}),i===null)throw Error("some shit");let t=i,e=new Float32Array(t.length);for(let n=0;n({...d==="v5"?o.defaultV5FrameProcessorOptions:o.defaultLegacyFrameProcessorOptions,onFrameProcessed:(y,_)=>{},onVADMisfire:()=>{c.log.debug("VAD misfire")},onSpeechStart:()=>{c.log.debug("Detected speech start")},onSpeechEnd:()=>{c.log.debug("Detected speech end")},onSpeechRealStart:()=>{c.log.debug("Detected real speech start")},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@latest/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/",stream:void 0,ortConfig:void 0,model:d,workletOptions:{}});D.getDefaultRealTimeVADOptions=r;class a{static async new(m={}){const y={...(0,D.getDefaultRealTimeVADOptions)(m.model??D.DEFAULT_MODEL),...m};(0,o.validateOptions)(y);let _;y.stream===void 0?_=await navigator.mediaDevices.getUserMedia({audio:{...y.additionalAudioConstraints,channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}):_=y.stream;const v=new AudioContext,T=new MediaStreamAudioSourceNode(v,{mediaStream:_}),S=await l.new(v,y);return S.receive(T),new a(y,v,_,S,T)}constructor(m,y,_,v,T,S=!1){this.options=m,this.audioContext=y,this.stream=_,this.audioNodeVAD=v,this.sourceNode=T,this.listening=S,this.pause=()=>{this.audioNodeVAD.pause(),this.listening=!1},this.start=()=>{this.audioNodeVAD.start(),this.listening=!0},this.destroy=()=>{this.listening&&this.pause(),this.options.stream===void 0&&this.stream.getTracks().forEach(O=>O.stop()),this.sourceNode.disconnect(),this.audioNodeVAD.destroy(),this.audioContext.close()},this.setOptions=O=>{this.audioNodeVAD.setFrameProcessorOptions(O)}}}D.MicVAD=a;class l{static async new(m,y={}){const _={...(0,D.getDefaultRealTimeVADOptions)(y.model??D.DEFAULT_MODEL),...y};(0,o.validateOptions)(_),D.ort.env.wasm.wasmPaths=_.onnxWASMBasePath,_.ortConfig!==void 0&&_.ortConfig(D.ort);const v=_.model==="v5"?e:n,T=_.baseAssetPath+v,S=_.model==="v5"?s.SileroV5.new:s.SileroLegacy.new;let O;try{O=await S(D.ort,()=>(0,h.defaultModelFetcher)(T))}catch(R){throw console.error(`Encountered an error while loading model file ${T}`),R}const w=new o.FrameProcessor(O.process,O.reset_state,{frameSamples:_.frameSamples,positiveSpeechThreshold:_.positiveSpeechThreshold,negativeSpeechThreshold:_.negativeSpeechThreshold,redemptionFrames:_.redemptionFrames,preSpeechPadFrames:_.preSpeechPadFrames,minSpeechFrames:_.minSpeechFrames,submitUserSpeechOnPause:_.submitUserSpeechOnPause}),I=new l(m,_,w);return await I.setupAudioNode(),I}constructor(m,y,_){this.ctx=m,this.options=y,this.bufferIndex=0,this.pause=()=>{this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.start=()=>{this.frameProcessor.resume()},this.receive=v=>{v.connect(this.audioNode)},this.processFrame=async v=>{await this.frameProcessor.process(v,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=v=>{switch(v.msg){case f.Message.FrameProcessed:this.options.onFrameProcessed(v.probs,v.frame);break;case f.Message.SpeechStart:this.options.onSpeechStart();break;case f.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case f.Message.VADMisfire:this.options.onVADMisfire();break;case f.Message.SpeechEnd:this.options.onSpeechEnd(v.audio);break}},this.destroy=()=>{var v;this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:f.Message.SpeechStop}),this.audioNode.disconnect(),(v=this.gainNode)==null||v.disconnect()},this.setFrameProcessorOptions=v=>{this.frameProcessor.options={...this.frameProcessor.options,...v}},this.frameProcessor=_}async setupAudioNode(){if("audioWorklet"in this.ctx&&typeof AudioWorkletNode=="function")try{const v=this.options.baseAssetPath+t;await this.ctx.audioWorklet.addModule(v);const T=this.options.workletOptions??{};T.processorOptions={...T.processorOptions??{},frameSamples:this.options.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",T),this.audioNode.port.onmessage=async S=>{var O;switch((O=S.data)==null?void 0:O.message){case f.Message.AudioFrame:let w=S.data.data;w instanceof ArrayBuffer||(w=new ArrayBuffer(S.data.data.byteLength),new Uint8Array(w).set(new Uint8Array(S.data.data)));const I=new Float32Array(w);await this.processFrame(I);break}};return}catch(v){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",v)}this.resampler=new i.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.options.frameSamples??480});const y=4096;this.audioNode=this.ctx.createScriptProcessor(y,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let _=!1;this.audioNode.onaudioprocess=async v=>{if(!_){_=!0;try{const T=v.inputBuffer.getChannelData(0);if(v.outputBuffer.getChannelData(0).fill(0),this.resampler){const O=this.resampler.process(T);for(const w of O)await this.processFrame(w)}}catch(T){console.error("Error processing audio:",T)}finally{_=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}D.AudioNodeVAD=l}(realTimeVad)),realTimeVad}var hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(D){Object.defineProperty(D,"__esModule",{value:!0}),D.getDefaultRealTimeVADOptions=D.MicVAD=D.DEFAULT_MODEL=D.AudioNodeVAD=D.utils=D.NonRealTimeVAD=D.Message=D.FrameProcessor=D.defaultModelFetcher=D.baseAssetPath=void 0;var u=requireAssetPath();Object.defineProperty(D,"baseAssetPath",{enumerable:!0,get:function(){return u.baseAssetPath}});var b=requireDefaultModelFetcher();Object.defineProperty(D,"defaultModelFetcher",{enumerable:!0,get:function(){return b.defaultModelFetcher}});var g=requireFrameProcessor();Object.defineProperty(D,"FrameProcessor",{enumerable:!0,get:function(){return g.FrameProcessor}});var p=requireMessages();Object.defineProperty(D,"Message",{enumerable:!0,get:function(){return p.Message}});var h=requireNonRealTimeVad();Object.defineProperty(D,"NonRealTimeVAD",{enumerable:!0,get:function(){return h.NonRealTimeVAD}});const o=requireUtils();D.utils={audioFileToArray:o.audioFileToArray,minFramesForTargetMS:o.minFramesForTargetMS,arrayBufferToBase64:o.arrayBufferToBase64,encodeWAV:o.encodeWAV};var c=requireRealTimeVad();Object.defineProperty(D,"AudioNodeVAD",{enumerable:!0,get:function(){return c.AudioNodeVAD}}),Object.defineProperty(D,"DEFAULT_MODEL",{enumerable:!0,get:function(){return c.DEFAULT_MODEL}}),Object.defineProperty(D,"MicVAD",{enumerable:!0,get:function(){return c.MicVAD}}),Object.defineProperty(D,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return c.getDefaultRealTimeVADOptions}})}(dist)),dist}var distExports=requireDist();export{distExports as d}; diff --git a/assets/index-MYV-cYy6.js b/assets/index-DCkir7nL.js similarity index 75% rename from assets/index-MYV-cYy6.js rename to assets/index-DCkir7nL.js index f19606027cee0ab19ce71a6780d2f67f37ffb62a..264ccd76d1ea314d611bf54c8432a53ec944f3fc 100644 --- a/assets/index-MYV-cYy6.js +++ b/assets/index-DCkir7nL.js @@ -1 +1 @@ -import{_ as Z}from"./IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js";import{l as G,J as P}from"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{_ as K,a as W}from"./Model.vue_vue_type_script_setup_true_lang-Dx1Lxvvu.js";import{d as E,G as D,c as f,o as s,b as t,f as q,g as H,bE as Q,s as X,r as $,v as Y,bF as ee,i as l,A,j as te,w as c,e as u,x as O,y as oe,k as b,t as N,F as U,l as V,at as ne,_ as ie,bG as ae,K as le}from"./index-BQKiy4UR.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import"./mcp-DQCTu0C2.js";import{a as z,b as se}from"./mini_xsschema-P_8cZcRg.js";import"./three-vrm-animation.module-DtlqIxay.js";import{V as re}from"./browser-CkchkNbv.js";import{_ as I,a as de}from"./ColorPalette.vue_vue_type_script_setup_true_lang-CuLfdqu0.js";import{u as ce}from"./useIconAnimation-ITs7Jlod.js";import{b as B}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./index-D1N6XcGk.js";const ue=["disabled"],h=E({__name:"Live2DModelControlButton",emits:["click"],setup(j){const m=D();return(r,n)=>(s(),f("button",{disabled:t(m).loadingLive2dModel,bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",transition:"all ease-in-out duration-250",rounded:"",onClick:n[0]||(n[0]=p=>r.$emit("click"))},[q(r.$slots,"default")],8,ue))}}),me={flex:"~ col gap-4"},fe={flex:"","items-center":"","gap-2":""},pe=["disabled","placeholder"],ve={"font-medium":""},_e={flex:"","gap-2":""},ge=["onUpdate:modelValue"],be=["href","download"],he=E({__name:"Live2DSettings",props:{palette:null},emits:["extractColorsFromModel"],setup(j){const{t:m}=H(),r=Q({accept:"application/zip"}),n=D(),{live2dModelFile:p,live2dMotionMap:v,live2dLoadSource:y,loadingLive2dModel:k,availableLive2dMotions:L,live2dModelUrl:M}=X(n),_=$(M.value);r.onChange(o=>{o&&o.length>0&&(v.value={},p.value=o[0],y.value="file",k.value=!0)}),Y(()=>n.loadingLive2dModel,o=>{o||y.value==="file"&&L.value.forEach(e=>{e.motionName in z?v.value[e.fileName]=e.motionName:v.value[e.fileName]=se})});async function g(o,e){if(!Object.keys(e).length)return o;const a=await new P().loadAsync(o),d=Object.keys(a.files).find(F=>F.endsWith("model3.json"));if(!d)throw new Error("model3.json not found");const J=await a.file(d).async("string"),R=JSON.parse(J),C={};Object.entries(e).forEach(([F,S])=>{if(C[S]){C[S].push({File:F});return}C[S]=[{File:F}]}),R.FileReferences.Motions=C,a.file(d,JSON.stringify(R,null,2));const T=await a.generateAsync({type:"blob"});return new File([T],o.name,{type:o.type,lastModified:o.lastModified})}async function w(){const o=await G.getItem("live2dModel");if(!o)return;const e=await g(o,v.value);p.value=e,y.value="file",k.value=!0}const x=ee(p);return(o,e)=>(s(),f("div",me,[l(t(I),{title:"settings.live2d.change-model.title",icon:"i-solar:magic-stick-3-bold-duotone","inner-class":"text-sm"},{default:c(()=>[u("div",fe,[O(u("input",{"onUpdate:modelValue":e[0]||(e[0]=i=>_.value=i),disabled:t(n).loadingLive2dModel,class:"form-control flex-1",border:"neutral-300 dark:neutral-800 solid 1 focus:neutral-400 dark:focus:neutral-600",transition:"border duration-250 ease-in-out",placeholder:t(m)("settings.live2d.change-model.from-url-placeholder")},null,8,pe),[[oe,_.value]]),l(h,{class:"form-control",onClick:e[1]||(e[1]=i=>M.value=_.value)},{default:c(()=>[b(N(t(m)("settings.live2d.change-model.from-url")),1)]),_:1})]),l(h,{class:"form-control place-self-end",onClick:e[2]||(e[2]=i=>t(r).open())},{default:c(()=>[b(N(t(m)("settings.live2d.change-model.from-file"))+"... ",1)]),_:1}),l(h,{class:"form-control",onClick:e[3]||(e[3]=i=>o.$emit("extractColorsFromModel"))},{default:c(()=>e[4]||(e[4]=[b(" Extract colors from model ")])),_:1}),l(de,{colors:j.palette.map(i=>({hex:i,name:i}))},null,8,["colors"])]),_:1}),t(n).live2dLoadSource==="file"?(s(),A(t(I),{key:0,title:"settings.live2d.edit-motion-map.title",icon:"i-solar:face-scan-circle-bold-duotone"},{default:c(()=>{var i;return[(s(!0),f(U,null,V(t(n).availableLive2dMotions,a=>(s(),f("div",{key:a.fileName,flex:"","items-center":"","justify-between":"","text-sm":""},[u("span",ve,N(a.fileName),1),u("div",_e,[O(u("select",{"onUpdate:modelValue":d=>t(n).live2dMotionMap[a.fileName]=d},[(s(!0),f(U,null,V(Object.keys(t(z)),d=>(s(),f("option",{key:d},N(d),1))),128))],8,ge),[[ne,t(n).live2dMotionMap[a.fileName]]]),l(h,{class:"form-control",onClick:d=>t(n).live2dCurrentMotion={group:a.motionName,index:a.motionIndex}},{default:c(()=>e[5]||(e[5]=[b(" Play ")])),_:2},1032,["onClick"])])]))),128)),l(h,{onClick:w},{default:c(()=>e[6]||(e[6]=[b(" Save and patch ")])),_:1}),u("a",{"mt-2":"",block:"",href:t(x),download:`${((i=t(n).live2dModelFile)==null?void 0:i.name)||"live2d"}-motion-edited.zip`},[l(h,{"w-full":""},{default:c(()=>e[7]||(e[7]=[b("Export")])),_:1})],8,be)]}),_:1})):te("",!0)]))}}),ye=ie(he,[["__scopeId","data-v-b2e16668"]]),xe={flex:""},ke={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:15},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},Me=E({__name:"index",setup(j){const m=$(),r=$(),{width:n,height:p}=ae(m),v=$([]);async function y(){if(!r.value)return;const _=await r.value.captureFrame();if(!_){console.error("No frame captured");return}const g=URL.createObjectURL(_);try{const x=await new re(g).getPalette();v.value=Object.values(x).map(o=>o==null?void 0:o.hex).filter(o=>typeof o=="string")}finally{URL.revokeObjectURL(g)}}const{iconAnimationStarted:k,showIconAnimation:L,animationIcon:M}=ce("i-solar:people-nearby-bold-duotone");return(_,g)=>{const w=Z,x=le("motion");return s(),f(U,null,[u("div",xe,[u("div",{ref_key:"live2dContainerRef",ref:m,w:"50%",h:"80vh"},[l(t(W),{ref_key:"live2dCanvasRef",ref:r,width:t(n),height:t(p)},{default:c(({app:o})=>[l(t(K),{app:o,"mouth-open-size":0,width:t(n),height:t(p),paused:!1},null,8,["app","width","height"])]),_:1},8,["width","height"])],512),l(ye,{w:"50%",h:"80vh",palette:v.value,onExtractColorsFromModel:y},null,8,["palette"])]),t(L)?(s(),A(w,{key:0,"z-index":-1,icon:t(M),"icon-size":12,duration:1e3,started:t(k),"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"])):O((s(),f("div",ke,g[0]||(g[0]=[u("div",{text:"60","i-solar:people-nearby-bold-duotone":""},null,-1)]))),[[x]])],64)}}});typeof B=="function"&&B(Me);export{Me as default}; +import{_ as Z}from"./IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js";import{l as P,J as G}from"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{_ as K,a as W}from"./Model.vue_vue_type_script_setup_true_lang-PK96Pm-_.js";import{d as E,G as D,c as f,o as s,b as t,f as q,g as H,b7 as Q,s as X,r as F,v as Y,b8 as ee,i as l,A,j as te,w as c,e as u,x as O,y as oe,k as b,t as $,F as U,l as V,av as ne,_ as ie,b9 as ae,K as le}from"./index-CQudhZin.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import"./mcp-C9U4MroK.js";import{a as z,b as se}from"./mini_xsschema-P_8cZcRg.js";import"./three-vrm-animation.module-Dklr5eVx.js";import{V as re}from"./browser-CkchkNbv.js";import{_ as I,a as de}from"./ColorPalette.vue_vue_type_script_setup_true_lang-1nqX-kcz.js";import{u as ce}from"./useIconAnimation-BCxWQrf7.js";import{b as B}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./index-CAP_srMr.js";const ue=["disabled"],h=E({__name:"Live2DModelControlButton",emits:["click"],setup(j){const m=D();return(r,n)=>(s(),f("button",{disabled:t(m).loadingLive2dModel,bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",transition:"all ease-in-out duration-250",rounded:"",onClick:n[0]||(n[0]=p=>r.$emit("click"))},[q(r.$slots,"default")],8,ue))}}),me={flex:"~ col gap-4"},fe={flex:"","items-center":"","gap-2":""},pe=["disabled","placeholder"],ve={"font-medium":""},_e={flex:"","gap-2":""},ge=["onUpdate:modelValue"],be=["href","download"],he=E({__name:"Live2DSettings",props:{palette:null},emits:["extractColorsFromModel"],setup(j){const{t:m}=H(),r=Q({accept:"application/zip"}),n=D(),{live2dModelFile:p,live2dMotionMap:v,live2dLoadSource:y,loadingLive2dModel:k,availableLive2dMotions:L,live2dModelUrl:M}=X(n),_=F(M.value);r.onChange(o=>{o&&o.length>0&&(v.value={},p.value=o[0],y.value="file",k.value=!0)}),Y(()=>n.loadingLive2dModel,o=>{o||y.value==="file"&&L.value.forEach(e=>{e.motionName in z?v.value[e.fileName]=e.motionName:v.value[e.fileName]=se})});async function g(o,e){if(!Object.keys(e).length)return o;const a=await new G().loadAsync(o),d=Object.keys(a.files).find(N=>N.endsWith("model3.json"));if(!d)throw new Error("model3.json not found");const J=await a.file(d).async("string"),R=JSON.parse(J),C={};Object.entries(e).forEach(([N,S])=>{if(C[S]){C[S].push({File:N});return}C[S]=[{File:N}]}),R.FileReferences.Motions=C,a.file(d,JSON.stringify(R,null,2));const T=await a.generateAsync({type:"blob"});return new File([T],o.name,{type:o.type,lastModified:o.lastModified})}async function w(){const o=await P.getItem("live2dModel");if(!o)return;const e=await g(o,v.value);p.value=e,y.value="file",k.value=!0}const x=ee(p);return(o,e)=>(s(),f("div",me,[l(t(I),{title:"settings.live2d.change-model.title",icon:"i-solar:magic-stick-3-bold-duotone","inner-class":"text-sm"},{default:c(()=>[u("div",fe,[O(u("input",{"onUpdate:modelValue":e[0]||(e[0]=i=>_.value=i),disabled:t(n).loadingLive2dModel,class:"form-control flex-1",border:"neutral-300 dark:neutral-800 solid 1 focus:neutral-400 dark:focus:neutral-600",transition:"border duration-250 ease-in-out",placeholder:t(m)("settings.live2d.change-model.from-url-placeholder")},null,8,pe),[[oe,_.value]]),l(h,{class:"form-control",onClick:e[1]||(e[1]=i=>M.value=_.value)},{default:c(()=>[b($(t(m)("settings.live2d.change-model.from-url")),1)]),_:1})]),l(h,{class:"form-control place-self-end",onClick:e[2]||(e[2]=i=>t(r).open())},{default:c(()=>[b($(t(m)("settings.live2d.change-model.from-file"))+"... ",1)]),_:1}),l(h,{class:"form-control",onClick:e[3]||(e[3]=i=>o.$emit("extractColorsFromModel"))},{default:c(()=>e[4]||(e[4]=[b(" Extract colors from model ")])),_:1}),l(de,{colors:j.palette.map(i=>({hex:i,name:i}))},null,8,["colors"])]),_:1}),t(n).live2dLoadSource==="file"?(s(),A(t(I),{key:0,title:"settings.live2d.edit-motion-map.title",icon:"i-solar:face-scan-circle-bold-duotone"},{default:c(()=>{var i;return[(s(!0),f(U,null,V(t(n).availableLive2dMotions,a=>(s(),f("div",{key:a.fileName,flex:"","items-center":"","justify-between":"","text-sm":""},[u("span",ve,$(a.fileName),1),u("div",_e,[O(u("select",{"onUpdate:modelValue":d=>t(n).live2dMotionMap[a.fileName]=d},[(s(!0),f(U,null,V(Object.keys(t(z)),d=>(s(),f("option",{key:d},$(d),1))),128))],8,ge),[[ne,t(n).live2dMotionMap[a.fileName]]]),l(h,{class:"form-control",onClick:d=>t(n).live2dCurrentMotion={group:a.motionName,index:a.motionIndex}},{default:c(()=>e[5]||(e[5]=[b(" Play ")])),_:2},1032,["onClick"])])]))),128)),l(h,{onClick:w},{default:c(()=>e[6]||(e[6]=[b(" Save and patch ")])),_:1}),u("a",{"mt-2":"",block:"",href:t(x),download:`${((i=t(n).live2dModelFile)==null?void 0:i.name)||"live2d"}-motion-edited.zip`},[l(h,{"w-full":""},{default:c(()=>e[7]||(e[7]=[b("Export")])),_:1})],8,be)]}),_:1})):te("",!0)]))}}),ye=ie(he,[["__scopeId","data-v-b2e16668"]]),xe={flex:""},ke={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:15},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},Me=E({__name:"index",setup(j){const m=F(),r=F(),{width:n,height:p}=ae(m),v=F([]);async function y(){if(!r.value)return;const _=await r.value.captureFrame();if(!_){console.error("No frame captured");return}const g=URL.createObjectURL(_);try{const x=await new re(g).getPalette();v.value=Object.values(x).map(o=>o==null?void 0:o.hex).filter(o=>typeof o=="string")}finally{URL.revokeObjectURL(g)}}const{iconAnimationStarted:k,showIconAnimation:L,animationIcon:M}=ce("i-solar:people-nearby-bold-duotone");return(_,g)=>{const w=Z,x=le("motion");return s(),f(U,null,[u("div",xe,[u("div",{ref_key:"live2dContainerRef",ref:m,w:"50%",h:"80vh"},[l(t(W),{ref_key:"live2dCanvasRef",ref:r,width:t(n),height:t(p)},{default:c(({app:o})=>[l(t(K),{app:o,"mouth-open-size":0,width:t(n),height:t(p),paused:!1},null,8,["app","width","height"])]),_:1},8,["width","height"])],512),l(ye,{w:"50%",h:"80vh",palette:v.value,onExtractColorsFromModel:y},null,8,["palette"])]),t(L)?(s(),A(w,{key:0,"z-index":-1,icon:t(M),"icon-size":12,duration:1e3,started:t(k),"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"])):O((s(),f("div",ke,g[0]||(g[0]=[u("div",{text:"60","i-solar:people-nearby-bold-duotone":""},null,-1)]))),[[x]])],64)}}});typeof B=="function"&&B(Me);export{Me as default}; diff --git a/assets/index-DANZbU0h.js b/assets/index-DhNz88Xj.js similarity index 75% rename from assets/index-DANZbU0h.js rename to assets/index-DhNz88Xj.js index 2088d3743606ccbd5e2ed1304e803fe31b0915db..6138c0d5014e8d8ddfff6904856a782440cc2f0c 100644 --- a/assets/index-DANZbU0h.js +++ b/assets/index-DhNz88Xj.js @@ -1 +1 @@ -import{_ as g}from"./IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as k,s as v,K as b,c as e,o,e as c,A as s,x as l,F as m,l as I,b as i}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as h}from"./providers-kjOpfeNb.js";import{I as z}from"./IconStatusItem-DqA2VeX5.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{u as A}from"./useIconAnimation-ITs7Jlod.js";import{b as d}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";const B={grid:"~ cols-2 gap-4"},S={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:20},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},w=k({__name:"index",setup(D){const u=h(),{allProvidersMetadata:p}=v(u),{iconAnimationStarted:f,showIconAnimation:_,animationIcon:y}=A("i-solar:box-minimalistic-bold-duotone");return(C,n)=>{const x=g,r=b("motion");return o(),e(m,null,[c("div",B,[(o(!0),e(m,null,I(i(p),(t,a)=>l((o(),s(i(z),{key:t.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+a*10,delay:a*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))]),i(_)?(o(),s(x,{key:0,"z-index":-1,icon:i(y),"icon-size":12,duration:1e3,started:i(f),"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"])):l((o(),e("div",S,n[0]||(n[0]=[c("div",{text:"60","i-solar:box-minimalistic-bold-duotone":""},null,-1)]))),[[r]])],64)}}});typeof d=="function"&&d(w);export{w as default}; +import{_ as g}from"./IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as k,s as v,K as b,c as e,o,e as c,A as s,x as l,F as m,l as I,b as i}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as h}from"./providers-Y3Mr8_DF.js";import{I as z}from"./IconStatusItem-CzuT67Cw.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{u as A}from"./useIconAnimation-BCxWQrf7.js";import{b as d}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";const B={grid:"~ cols-2 gap-4"},S={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:20},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},w=k({__name:"index",setup(D){const u=h(),{allProvidersMetadata:p}=v(u),{iconAnimationStarted:f,showIconAnimation:_,animationIcon:y}=A("i-solar:box-minimalistic-bold-duotone");return(C,n)=>{const x=g,r=b("motion");return o(),e(m,null,[c("div",B,[(o(!0),e(m,null,I(i(p),(t,a)=>l((o(),s(i(z),{key:t.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+a*10,delay:a*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))]),i(_)?(o(),s(x,{key:0,"z-index":-1,icon:i(y),"icon-size":12,duration:1e3,started:i(f),"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"])):l((o(),e("div",S,n[0]||(n[0]=[c("div",{text:"60","i-solar:box-minimalistic-bold-duotone":""},null,-1)]))),[[r]])],64)}}});typeof d=="function"&&d(w);export{w as default}; diff --git a/assets/index-C6zTw43n.js b/assets/index-DnVVffQQ.js similarity index 84% rename from assets/index-C6zTw43n.js rename to assets/index-DnVVffQQ.js index 058c7af1ab1f55210223b8dc45d1c84327f8ad0b..0419ecae33296f5251ff5fb877e5535e320aa414 100644 --- a/assets/index-C6zTw43n.js +++ b/assets/index-DnVVffQQ.js @@ -1 +1 @@ -import{_ as d}from"./IconAnimation.vue_vue_type_script_setup_true_lang-CIBirOSE.js";import{u}from"./useIconAnimation-ITs7Jlod.js";import{d as p,K as f,c as n,o as e,e as i,A as _,x as v,b as o,F as x}from"./index-BQKiy4UR.js";import{b as r}from"./route-block-B_A1xBdJ.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";const k={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:20},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},y=p({__name:"index",setup(b){const{iconAnimationStarted:a,showIconAnimation:s,animationIcon:c}=u("i-solar:armchair-2-bold-duotone");return(h,t)=>{const l=d,m=f("motion");return e(),n(x,null,[t[1]||(t[1]=i("div",null," Scene ",-1)),o(s)?(e(),_(l,{key:0,"z-index":-1,icon:o(c),"icon-size":12,duration:1e3,started:o(a),"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"])):v((e(),n("div",k,t[0]||(t[0]=[i("div",{text:"60","i-solar:armchair-2-bold-duotone":""},null,-1)]))),[[m]])],64)}}});typeof r=="function"&&r(y);export{y as default}; +import{_ as d}from"./IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js";import{u}from"./useIconAnimation-BCxWQrf7.js";import{d as p,K as f,c as n,o as e,e as i,A as _,x as v,b as o,F as x}from"./index-CQudhZin.js";import{b as r}from"./route-block-B_A1xBdJ.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";const k={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:20},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},y=p({__name:"index",setup(b){const{iconAnimationStarted:a,showIconAnimation:s,animationIcon:c}=u("i-solar:armchair-2-bold-duotone");return(h,t)=>{const l=d,m=f("motion");return e(),n(x,null,[t[1]||(t[1]=i("div",null," Scene ",-1)),o(s)?(e(),_(l,{key:0,"z-index":-1,icon:o(c),"icon-size":12,duration:1e3,started:o(a),"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"])):v((e(),n("div",k,t[0]||(t[0]=[i("div",{text:"60","i-solar:armchair-2-bold-duotone":""},null,-1)]))),[[m]])],64)}}});typeof r=="function"&&r(y);export{y as default}; diff --git a/assets/index-BJf3Tezf.js b/assets/index-Ep8bbMjW.js similarity index 79% rename from assets/index-BJf3Tezf.js rename to assets/index-Ep8bbMjW.js index ba59bce81cbe6dcc62cb5c0831ded5207af23f88..738c2eb09ec5776e4e6082b832dc997865fdd052 100644 --- a/assets/index-BJf3Tezf.js +++ b/assets/index-Ep8bbMjW.js @@ -1 +1 @@ -import{d as i,K as n,x as r,o as a,c as s,e as c}from"./index-BQKiy4UR.js";import{b as t}from"./route-block-B_A1xBdJ.js";const l={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:15},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},d=i({__name:"index",setup(m){return(p,e)=>{const o=n("motion");return r((a(),s("div",l,e[0]||(e[0]=[c("div",{text:"60","i-solar:leaf-bold-duotone":""},null,-1)]))),[[o]])}}});typeof t=="function"&&t(d);export{d as default}; +import{d as i,K as n,x as r,o as a,c as s,e as c}from"./index-CQudhZin.js";import{b as t}from"./route-block-B_A1xBdJ.js";const l={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:15},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},d=i({__name:"index",setup(m){return(p,e)=>{const o=n("motion");return r((a(),s("div",l,e[0]||(e[0]=[c("div",{text:"60","i-solar:leaf-bold-duotone":""},null,-1)]))),[[o]])}}});typeof t=="function"&&t(d);export{d as default}; diff --git a/assets/index-BOS-VO_F.js b/assets/index-Lt-e6-Iy.js similarity index 99% rename from assets/index-BOS-VO_F.js rename to assets/index-Lt-e6-Iy.js index b505ec98618d4ee7cefbad7218dd40413f8fa752..f2221e23918c1e95759bd250c52fa55ba78951fc 100644 --- a/assets/index-BOS-VO_F.js +++ b/assets/index-Lt-e6-Iy.js @@ -1,4 +1,4 @@ -import{Z as s,a as x}from"./mcp-DQCTu0C2.js";import"./index-BQKiy4UR.js";const M=Symbol("Let zodToJsonSchema decide on which parser to use"),P={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},D=t=>typeof t=="string"?{...P,name:t}:{...P,...t},T=t=>{const e=D(t),a=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,r])=>[r._def,{def:r._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function _(t,e,a,n){n!=null&&n.errorMessages&&a&&(t.errorMessage={...t.errorMessage,[e]:a})}function l(t,e,a,n,r){t[e]=a,_(t,e,n,r)}function N(){return{}}function $(t,e){var n,r,i;const a={type:"array"};return(n=t.type)!=null&&n._def&&((i=(r=t.type)==null?void 0:r._def)==null?void 0:i.typeName)!==s.ZodAny&&(a.items=c(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&l(a,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&l(a,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(l(a,"minItems",t.exactLength.value,t.exactLength.message,e),l(a,"maxItems",t.exactLength.value,t.exactLength.message,e)),a}function w(t,e){const a={type:"integer",format:"int64"};if(!t.checks)return a;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?l(a,"minimum",n.value,n.message,e):l(a,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(a.exclusiveMinimum=!0),l(a,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?l(a,"maximum",n.value,n.message,e):l(a,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(a.exclusiveMaximum=!0),l(a,"maximum",n.value,n.message,e));break;case"multipleOf":l(a,"multipleOf",n.value,n.message,e);break}return a}function z(){return{type:"boolean"}}function Z(t,e){return c(t.type._def,e)}const L=(t,e)=>c(t.innerType._def,e);function S(t,e,a){const n=a??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,i)=>S(t,e,r))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return F(t,e)}}const F=(t,e)=>{const a={type:"integer",format:"unix-time"};if(e.target==="openApi3")return a;for(const n of t.checks)switch(n.kind){case"min":l(a,"minimum",n.value,n.message,e);break;case"max":l(a,"maximum",n.value,n.message,e);break}return a};function I(t,e){return{...c(t.innerType._def,e),default:t.defaultValue()}}function E(t,e){return e.effectStrategy==="input"?c(t.schema._def,e):{}}function R(t){return{type:"string",enum:Array.from(t.values)}}const C=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function U(t,e){const a=[c(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),c(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return a.forEach(i=>{if(C(i))r.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let o=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:m,...p}=i;o=p}else n=void 0;r.push(o)}}),r.length?{allOf:r,...n}:void 0}function B(t,e){const a=typeof t.value;return a!=="bigint"&&a!=="number"&&a!=="boolean"&&a!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:a==="bigint"?"integer":a,enum:[t.value]}:{type:a==="bigint"?"integer":a,const:t.value}}let b;const f={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(b===void 0&&(b=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),b),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function O(t,e){const a={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":l(a,"minLength",typeof a.minLength=="number"?Math.max(a.minLength,n.value):n.value,n.message,e);break;case"max":l(a,"maxLength",typeof a.maxLength=="number"?Math.min(a.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":y(a,"email",n.message,e);break;case"format:idn-email":y(a,"idn-email",n.message,e);break;case"pattern:zod":d(a,f.email,n.message,e);break}break;case"url":y(a,"uri",n.message,e);break;case"uuid":y(a,"uuid",n.message,e);break;case"regex":d(a,n.regex,n.message,e);break;case"cuid":d(a,f.cuid,n.message,e);break;case"cuid2":d(a,f.cuid2,n.message,e);break;case"startsWith":d(a,RegExp(`^${v(n.value,e)}`),n.message,e);break;case"endsWith":d(a,RegExp(`${v(n.value,e)}$`),n.message,e);break;case"datetime":y(a,"date-time",n.message,e);break;case"date":y(a,"date",n.message,e);break;case"time":y(a,"time",n.message,e);break;case"duration":y(a,"duration",n.message,e);break;case"length":l(a,"minLength",typeof a.minLength=="number"?Math.max(a.minLength,n.value):n.value,n.message,e),l(a,"maxLength",typeof a.maxLength=="number"?Math.min(a.maxLength,n.value):n.value,n.message,e);break;case"includes":{d(a,RegExp(v(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&y(a,"ipv4",n.message,e),n.version!=="v4"&&y(a,"ipv6",n.message,e);break}case"base64url":d(a,f.base64url,n.message,e);break;case"jwt":d(a,f.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&d(a,f.ipv4Cidr,n.message,e),n.version!=="v4"&&d(a,f.ipv6Cidr,n.message,e);break}case"emoji":d(a,f.emoji(),n.message,e);break;case"ulid":{d(a,f.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{y(a,"binary",n.message,e);break}case"contentEncoding:base64":{l(a,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{d(a,f.base64,n.message,e);break}}break}case"nanoid":d(a,f.nanoid,n.message,e)}return a}function v(t,e){return e.patternStrategy==="escape"?q(t):t}const V=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function q(t){let e="";for(let a=0;ai.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...a&&n.errorMessages&&{errorMessage:{format:a}}})):l(t,"format",e,a,n)}function d(t,e,a,n){var r;t.pattern||(r=t.allOf)!=null&&r.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:k(e,n),...a&&n.errorMessages&&{errorMessage:{pattern:a}}})):l(t,"pattern",k(e,n),a,n)}function k(t,e){var p;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let r="",i=!1,o=!1,m=!1;for(let u=0;utypeof t=="string"?{...P,name:t}:{...P,...t},T=t=>{const e=D(t),a=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:a,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,r])=>[r._def,{def:r._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function _(t,e,a,n){n!=null&&n.errorMessages&&a&&(t.errorMessage={...t.errorMessage,[e]:a})}function l(t,e,a,n,r){t[e]=a,_(t,e,n,r)}function N(){return{}}function $(t,e){var n,r,i;const a={type:"array"};return(n=t.type)!=null&&n._def&&((i=(r=t.type)==null?void 0:r._def)==null?void 0:i.typeName)!==s.ZodAny&&(a.items=c(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&l(a,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&l(a,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(l(a,"minItems",t.exactLength.value,t.exactLength.message,e),l(a,"maxItems",t.exactLength.value,t.exactLength.message,e)),a}function w(t,e){const a={type:"integer",format:"int64"};if(!t.checks)return a;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?l(a,"minimum",n.value,n.message,e):l(a,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(a.exclusiveMinimum=!0),l(a,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?l(a,"maximum",n.value,n.message,e):l(a,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(a.exclusiveMaximum=!0),l(a,"maximum",n.value,n.message,e));break;case"multipleOf":l(a,"multipleOf",n.value,n.message,e);break}return a}function z(){return{type:"boolean"}}function Z(t,e){return c(t.type._def,e)}const L=(t,e)=>c(t.innerType._def,e);function S(t,e,a){const n=a??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((r,i)=>S(t,e,r))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return F(t,e)}}const F=(t,e)=>{const a={type:"integer",format:"unix-time"};if(e.target==="openApi3")return a;for(const n of t.checks)switch(n.kind){case"min":l(a,"minimum",n.value,n.message,e);break;case"max":l(a,"maximum",n.value,n.message,e);break}return a};function I(t,e){return{...c(t.innerType._def,e),default:t.defaultValue()}}function E(t,e){return e.effectStrategy==="input"?c(t.schema._def,e):{}}function R(t){return{type:"string",enum:Array.from(t.values)}}const C=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function U(t,e){const a=[c(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),c(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return a.forEach(i=>{if(C(i))r.push(...i.allOf),i.unevaluatedProperties===void 0&&(n=void 0);else{let o=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:m,...p}=i;o=p}else n=void 0;r.push(o)}}),r.length?{allOf:r,...n}:void 0}function B(t,e){const a=typeof t.value;return a!=="bigint"&&a!=="number"&&a!=="boolean"&&a!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:a==="bigint"?"integer":a,enum:[t.value]}:{type:a==="bigint"?"integer":a,const:t.value}}let b;const f={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(b===void 0&&(b=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),b),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function O(t,e){const a={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":l(a,"minLength",typeof a.minLength=="number"?Math.max(a.minLength,n.value):n.value,n.message,e);break;case"max":l(a,"maxLength",typeof a.maxLength=="number"?Math.min(a.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":y(a,"email",n.message,e);break;case"format:idn-email":y(a,"idn-email",n.message,e);break;case"pattern:zod":d(a,f.email,n.message,e);break}break;case"url":y(a,"uri",n.message,e);break;case"uuid":y(a,"uuid",n.message,e);break;case"regex":d(a,n.regex,n.message,e);break;case"cuid":d(a,f.cuid,n.message,e);break;case"cuid2":d(a,f.cuid2,n.message,e);break;case"startsWith":d(a,RegExp(`^${v(n.value,e)}`),n.message,e);break;case"endsWith":d(a,RegExp(`${v(n.value,e)}$`),n.message,e);break;case"datetime":y(a,"date-time",n.message,e);break;case"date":y(a,"date",n.message,e);break;case"time":y(a,"time",n.message,e);break;case"duration":y(a,"duration",n.message,e);break;case"length":l(a,"minLength",typeof a.minLength=="number"?Math.max(a.minLength,n.value):n.value,n.message,e),l(a,"maxLength",typeof a.maxLength=="number"?Math.min(a.maxLength,n.value):n.value,n.message,e);break;case"includes":{d(a,RegExp(v(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&y(a,"ipv4",n.message,e),n.version!=="v4"&&y(a,"ipv6",n.message,e);break}case"base64url":d(a,f.base64url,n.message,e);break;case"jwt":d(a,f.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&d(a,f.ipv4Cidr,n.message,e),n.version!=="v4"&&d(a,f.ipv6Cidr,n.message,e);break}case"emoji":d(a,f.emoji(),n.message,e);break;case"ulid":{d(a,f.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{y(a,"binary",n.message,e);break}case"contentEncoding:base64":{l(a,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{d(a,f.base64,n.message,e);break}}break}case"nanoid":d(a,f.nanoid,n.message,e)}return a}function v(t,e){return e.patternStrategy==="escape"?q(t):t}const V=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function q(t){let e="";for(let a=0;ai.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...a&&n.errorMessages&&{errorMessage:{format:a}}})):l(t,"format",e,a,n)}function d(t,e,a,n){var r;t.pattern||(r=t.allOf)!=null&&r.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:k(e,n),...a&&n.errorMessages&&{errorMessage:{pattern:a}}})):l(t,"pattern",k(e,n),a,n)}function k(t,e){var p;if(!e.applyRegexFlags||!t.flags)return t.source;const a={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=a.i?t.source.toLowerCase():t.source;let r="",i=!1,o=!1,m=!1;for(let u=0;u[{id:"consciousness",name:e("settings.pages.modules.consciousness.title"),description:e("settings.pages.modules.consciousness.description"),icon:"i-solar:ghost-bold-duotone",to:"/settings/modules/consciousness",configured:!1},{id:"speech",name:e("settings.pages.modules.speech.title"),description:e("settings.pages.modules.speech.description"),icon:"i-solar:user-speak-rounded-bold-duotone",to:"/settings/modules/speech",configured:!1},{id:"hearing",name:e("settings.pages.modules.hearing.title"),description:e("settings.pages.modules.hearing.description"),icon:"i-solar:microphone-3-bold-duotone",to:"",configured:!1},{id:"vision",name:e("settings.pages.modules.vision.title"),description:e("settings.pages.modules.vision.description"),icon:"i-solar:eye-closed-bold-duotone",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-solar:bookmark-bold-duotone",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-solar:book-bookmark-bold-duotone",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:u,showIconAnimation:f,animationIcon:y}=z("i-solar:layers-bold-duotone");return(D,n)=>{const r=k("motion");return i(),t(l,null,[c("div",A,[(i(!0),t(l,null,x(p.value,(o,a)=>m((i(),d(s(_),{key:o.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+a*10,delay:a*50,title:o.name,description:o.description,icon:o.icon,"icon-color":o.iconColor,"icon-image":o.iconImage,to:o.to,configured:o.configured},null,8,["duration","delay","title","description","icon","icon-color","icon-image","to","configured"])),[[r]])),128))]),s(f)?(i(),d(I,{key:0,icon:s(y),"icon-size":12,duration:1e3,started:s(u),"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((i(),t("div",B,n[0]||(n[0]=[c("div",{text:"60","i-solar:layers-bold-duotone":""},null,-1)]))),[[r]])],64)}}});typeof g=="function"&&g(w);export{w as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as h,g as v,h as b,K as k,c as t,o as i,e as c,A as d,x as m,F as l,l as x,b as s}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{I as _}from"./IconStatusItem-CzuT67Cw.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as I}from"./IconAnimation.vue_vue_type_script_setup_true_lang-DU0M2CKl.js";import{u as z}from"./useIconAnimation-BCxWQrf7.js";import{b as g}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";const A={grid:"~ cols-1 sm:cols-2 gap-4"},B={key:1,text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,y:20},enter:{scale:1,opacity:1,y:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},w=h({__name:"index",setup(C){const{t:e}=v(),p=b(()=>[{id:"consciousness",name:e("settings.pages.modules.consciousness.title"),description:e("settings.pages.modules.consciousness.description"),icon:"i-solar:ghost-bold-duotone",to:"/settings/modules/consciousness",configured:!1},{id:"speech",name:e("settings.pages.modules.speech.title"),description:e("settings.pages.modules.speech.description"),icon:"i-solar:user-speak-rounded-bold-duotone",to:"/settings/modules/speech",configured:!1},{id:"hearing",name:e("settings.pages.modules.hearing.title"),description:e("settings.pages.modules.hearing.description"),icon:"i-solar:microphone-3-bold-duotone",to:"",configured:!1},{id:"vision",name:e("settings.pages.modules.vision.title"),description:e("settings.pages.modules.vision.description"),icon:"i-solar:eye-closed-bold-duotone",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-solar:bookmark-bold-duotone",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-solar:book-bookmark-bold-duotone",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:u,showIconAnimation:f,animationIcon:y}=z("i-solar:layers-bold-duotone");return(D,n)=>{const r=k("motion");return i(),t(l,null,[c("div",A,[(i(!0),t(l,null,x(p.value,(o,a)=>m((i(),d(s(_),{key:o.id,initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+a*10,delay:a*50,title:o.name,description:o.description,icon:o.icon,"icon-color":o.iconColor,"icon-image":o.iconImage,to:o.to,configured:o.configured},null,8,["duration","delay","title","description","icon","icon-color","icon-image","to","configured"])),[[r]])),128))]),s(f)?(i(),d(I,{key:0,icon:s(y),"icon-size":12,duration:1e3,started:s(u),"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((i(),t("div",B,n[0]||(n[0]=[c("div",{text:"60","i-solar:layers-bold-duotone":""},null,-1)]))),[[r]])],64)}}});typeof g=="function"&&g(w);export{w as default}; diff --git a/assets/index-CYwgNiYZ.js b/assets/index-fbmB4MjP.js similarity index 86% rename from assets/index-CYwgNiYZ.js rename to assets/index-fbmB4MjP.js index 9b988acc86d553733fc29b25cf182dcb9ba83f8a..28c355ff02b40ced723a16d386afd4dd95603b98 100644 --- a/assets/index-CYwgNiYZ.js +++ b/assets/index-fbmB4MjP.js @@ -1 +1 @@ -import{d as A,m as _,u as F,c as r,o,x as a,e,i as c,bu as V,k as h,j as U,t as u,w as g,n as x,T as j,G as H,bt as M,g as O,r as N,v as P,K as z,A as b,Q as R,b as i,at as I,y as L,F as k,l as G,_ as K}from"./index-BQKiy4UR.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as C,a as Q}from"./ColorPalette.vue_vue_type_script_setup_true_lang-CuLfdqu0.js";import{b as D}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./index-D1N6XcGk.js";const q={class:"w-full flex cursor-pointer items-center justify-between rounded-lg px-4 py-3 text-sm outline-none transition-all duration-250 ease-in-out",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},J=["aria-checked"],W={key:0,text:"sm neutral-500"},B=A({__name:"CheckBar",props:_({text:null,iconOn:null,iconOff:null,description:null},{modelValue:{type:Boolean},modelModifiers:{}}),emits:["update:modelValue"],setup(p){const n=F(p,"modelValue");return(y,m)=>(o(),r("label",q,[a(e("input",{"onUpdate:modelValue":m[0]||(m[0]=v=>n.value=v),"aria-checked":n.value,type:"checkbox",hidden:""},null,8,J),[[V,n.value]]),e("div",null,[h(u(y.$t(p.text))+" ",1),p.description?(o(),r("div",W,u(y.$t(p.description)),1)):U("",!0)]),c(j,{name:"slide-away",mode:"out-in"},{default:g(()=>[n.value?(o(),r("div",{key:0,class:x(p.iconOn),transition:"all ease-in-out duration-250"},null,2)):(o(),r("div",{key:1,class:x(p.iconOff),transition:"all ease-in-out duration-250"},null,2))]),_:1})]))}}),X=[[],["#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"]],Y={class:"w-full flex items-center justify-between rounded-lg px-4 py-3 text-sm outline-none transition-all duration-250 ease-in-out",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+3*10,delay:3*50,transition:"all ease-in-out duration-250"},Z={value:"en-US"},ee={value:"zh-CN"},te={flex:"","items-center":"","justify-between":"",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+5*10,delay:5*50,transition:"all ease-in-out duration-250"},ie={"text-lg":"","font-semibold":""},ne={relative:"",flex:"","cursor-pointer":"","items-center":"","gap-2":""},ae=["disabled"],oe={class:"color-bar",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+7*10,delay:7*50,transition:"all ease-in-out duration-250"},se={"text-white":"",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+8*10,delay:8*50,transition:"all ease-in-out duration-250"},le={class:"color-bar transparency-grid",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+9*10,delay:9*50,transition:"all ease-in-out duration-250"},re=["duration","delay"],de={"font-medium":""},ue={text:"sm neutral-500"},pe={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[65dvh]","right--15":"","z--1":"",initial:{scale:.9,opacity:0,rotate:30},enter:{scale:1,opacity:1,rotate:0},duration:250,flex:"","items-center":"","justify-center":""},w=A({__name:"index",setup(p){const n=H(),y=M(),{t:m}=O(),v=N(!1);return P(()=>[n.usePageSpecificTransitions,n.disableTransitions],()=>{v.value=!0}),(d,t)=>{const s=z("motion");return o(),r(k,null,[a((o(),b(i(C),{title:i(m)("settings.sections.section.general.title"),icon:"i-solar:filters-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+1*10,delay:1*50,transition:"all ease-in-out duration-250"},{default:g(()=>[a(c(B,{modelValue:i(y),"onUpdate:modelValue":t[0]||(t[0]=l=>R(y)?y.value=l:null),initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+2*10,delay:2*50,"icon-on":"i-solar:moon-stars-bold-duotone","icon-off":"i-solar:sun-fog-bold-duotone",text:"settings.theme",transition:"all ease-in-out duration-250"},null,8,["modelValue"]),[[s]]),a((o(),r("div",Y,[h(u(d.$t("settings.language.title"))+" ",1),a(e("select",{"onUpdate:modelValue":t[1]||(t[1]=l=>i(n).language=l),transition:"all ease-in-out duration-250","cursor-pointer":"","bg-transparent":"","text-right":"","outline-none":""},[e("option",Z,u(d.$t("settings.language.english")),1),e("option",ee,u(d.$t("settings.language.chinese")),1)],512),[[I,i(n).language]])])),[[s]])]),_:1},8,["title"])),[[s]]),a((o(),b(i(C),{title:i(m)("settings.pages.themes.sections.section.custom-color.title"),icon:"i-solar:pallete-2-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+4*10,delay:4*50,transition:"all ease-in-out duration-250"},{default:g(()=>[a((o(),r("div",te,[e("span",ie,u(d.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.label")),1),e("label",ne,[a(e("input",{"onUpdate:modelValue":t[2]||(t[2]=l=>i(n).themeColorsHueDynamic=l),type:"checkbox",class:"peer sr-only"},null,512),[[V,i(n).themeColorsHueDynamic]]),t[6]||(t[6]=e("div",{class:"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 peer-checked:bg-primary-500 after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white"},null,-1)),h(" "+u(d.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.rgb-on.title")),1)])])),[[s]]),a(e("input",{"onUpdate:modelValue":t[3]||(t[3]=l=>i(n).themeColorsHue=l),initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+6*10,delay:6*50,transition:"all ease-in-out duration-250",type:"range",min:"0",max:"360",step:"0.01",class:x(["theme-hue-slider",i(n).themeColorsHueDynamic?"opacity-25 cursor-not-allowed":"cursor-pointer"]),disabled:i(n).themeColorsHueDynamic},null,10,ae),[[L,i(n).themeColorsHue],[s]]),a((o(),r("div",oe,[t[8]||(t[8]=e("span",{"bg-primary-50":""},"50",-1)),t[9]||(t[9]=e("span",{"bg-primary-100":""},"100",-1)),t[10]||(t[10]=e("span",{"bg-primary-200":""},"200",-1)),t[11]||(t[11]=e("span",{"bg-primary-300":""},"300",-1)),t[12]||(t[12]=e("span",{"bg-primary-400":""},"400",-1)),t[13]||(t[13]=e("span",{"bg-primary-500":""},"500",-1)),a((o(),r("div",se,t[7]||(t[7]=[e("span",{"bg-primary-600":""},"600",-1),e("span",{"bg-primary-700":""},"700",-1),e("span",{"bg-primary-800":""},"800",-1),e("span",{"bg-primary-900":""},"900",-1),e("span",{"bg-primary-950":""},"950",-1)]))),[[s]])])),[[s]]),a((o(),r("div",le,t[14]||(t[14]=[e("span",{bg:"primary-500/5"},"500/5",-1),e("span",{bg:"primary-500/10"},"500/10",-1),e("span",{bg:"primary-500/20"},"500/20",-1),e("span",{bg:"primary-500/30"},"500/30",-1),e("span",{bg:"primary-500/40"},"500/40",-1),e("span",{bg:"primary-500/50"},"500/50",-1),e("span",{bg:"primary-500/60"},"500/60",-1),e("span",{bg:"primary-500/70"},"500/70",-1),e("span",{bg:"primary-500/80"},"500/80",-1),e("span",{bg:"primary-500/90"},"500/90",-1),e("span",{bg:"primary-500"},"500",-1)]))),[[s]])]),_:1},8,["title"])),[[s]]),a((o(),b(i(C),{title:"settings.pages.themes.sections.section.theme-presets.title",icon:"i-solar:magic-stick-2-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+10*10,delay:10*50,transition:"all ease-in-out duration-250"},{default:g(()=>[(o(!0),r(k,null,G(d.$tm("settings.pages.themes.sections.section.theme-presets.presets"),({title:l,description:$,colors:T},f)=>a((o(),r("div",{key:f,class:"w-full flex items-center justify-between rounded-lg px-4 py-3 outline-none transition-all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+11*10+f*10,delay:11*50+f*50,transition:"all ease-in-out duration-250"},[e("div",null,[e("span",de,u(d.$rt(l)),1),e("div",ue,u(d.$rt($)),1)]),c(Q,{colors:T.map((E,S)=>({hex:i(X)[f][S],name:d.$rt(E)}))},null,8,["colors"])],8,re)),[[s]])),128))]),_:1})),[[s]]),a((o(),b(i(C),{title:"settings.pages.themes.sections.section.developer.title",icon:"i-solar:code-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+18*10,delay:18*50,transition:"all ease-in-out duration-250"},{default:g(()=>[a(c(B,{modelValue:i(n).disableTransitions,"onUpdate:modelValue":t[4]||(t[4]=l=>i(n).disableTransitions=l),"icon-on":"i-solar:people-nearby-bold-duotone","icon-off":"i-solar:running-2-line-duotone",text:"settings.animations.stage-transitions.title",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+19*10,delay:19*50,transition:"all ease-in-out duration-250"},null,8,["modelValue"]),[[s]]),a(c(B,{modelValue:i(n).usePageSpecificTransitions,"onUpdate:modelValue":t[5]||(t[5]=l=>i(n).usePageSpecificTransitions=l),disabled:i(n).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",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+20*10,delay:20*50,transition:"all ease-in-out duration-250"},null,8,["modelValue","disabled"]),[[s]])]),_:1})),[[s]]),a((o(),r("div",pe,t[15]||(t[15]=[e("div",{text:"60","i-solar:filters-bold-duotone":""},null,-1)]))),[[s]])],64)}}});typeof D=="function"&&D(w);const De=K(w,[["__scopeId","data-v-aa1dd799"]]);export{De as default}; +import{d as A,m as _,u as F,c as r,o,x as a,e,i as c,aZ as V,k as h,j as U,t as u,w as g,n as x,T as j,G as H,aY as M,g as O,r as N,v as P,K as z,A as b,Q as R,b as i,av as I,y as L,F as k,l as G,_ as K}from"./index-CQudhZin.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as C,a as Q}from"./ColorPalette.vue_vue_type_script_setup_true_lang-1nqX-kcz.js";import{b as D}from"./route-block-B_A1xBdJ.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./index-CAP_srMr.js";const Y={class:"w-full flex cursor-pointer items-center justify-between rounded-lg px-4 py-3 text-sm outline-none transition-all duration-250 ease-in-out",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700"},Z=["aria-checked"],q={key:0,text:"sm neutral-500"},B=A({__name:"CheckBar",props:_({text:null,iconOn:null,iconOff:null,description:null},{modelValue:{type:Boolean},modelModifiers:{}}),emits:["update:modelValue"],setup(p){const n=F(p,"modelValue");return(y,m)=>(o(),r("label",Y,[a(e("input",{"onUpdate:modelValue":m[0]||(m[0]=v=>n.value=v),"aria-checked":n.value,type:"checkbox",hidden:""},null,8,Z),[[V,n.value]]),e("div",null,[h(u(y.$t(p.text))+" ",1),p.description?(o(),r("div",q,u(y.$t(p.description)),1)):U("",!0)]),c(j,{name:"slide-away",mode:"out-in"},{default:g(()=>[n.value?(o(),r("div",{key:0,class:x(p.iconOn),transition:"all ease-in-out duration-250"},null,2)):(o(),r("div",{key:1,class:x(p.iconOff),transition:"all ease-in-out duration-250"},null,2))]),_:1})]))}}),J=[[],["#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"]],W={class:"w-full flex items-center justify-between rounded-lg px-4 py-3 text-sm outline-none transition-all duration-250 ease-in-out",bg:"neutral-50 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+3*10,delay:3*50,transition:"all ease-in-out duration-250"},X={value:"en-US"},ee={value:"zh-CN"},te={flex:"","items-center":"","justify-between":"",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+5*10,delay:5*50,transition:"all ease-in-out duration-250"},ie={"text-lg":"","font-semibold":""},ne={relative:"",flex:"","cursor-pointer":"","items-center":"","gap-2":""},ae=["disabled"],oe={class:"color-bar",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+7*10,delay:7*50,transition:"all ease-in-out duration-250"},se={"text-white":"",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+8*10,delay:8*50,transition:"all ease-in-out duration-250"},le={class:"color-bar transparency-grid",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+9*10,delay:9*50,transition:"all ease-in-out duration-250"},re=["duration","delay"],de={"font-medium":""},ue={text:"sm neutral-500"},pe={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[65dvh]","right--15":"","z--1":"",initial:{scale:.9,opacity:0,rotate:30},enter:{scale:1,opacity:1,rotate:0},duration:250,flex:"","items-center":"","justify-center":""},w=A({__name:"index",setup(p){const n=H(),y=M(),{t:m}=O(),v=N(!1);return P(()=>[n.usePageSpecificTransitions,n.disableTransitions],()=>{v.value=!0}),(d,t)=>{const s=z("motion");return o(),r(k,null,[a((o(),b(i(C),{title:i(m)("settings.sections.section.general.title"),icon:"i-solar:filters-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+1*10,delay:1*50,transition:"all ease-in-out duration-250"},{default:g(()=>[a(c(B,{modelValue:i(y),"onUpdate:modelValue":t[0]||(t[0]=l=>R(y)?y.value=l:null),initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+2*10,delay:2*50,"icon-on":"i-solar:moon-stars-bold-duotone","icon-off":"i-solar:sun-fog-bold-duotone",text:"settings.theme",transition:"all ease-in-out duration-250"},null,8,["modelValue"]),[[s]]),a((o(),r("div",W,[h(u(d.$t("settings.language.title"))+" ",1),a(e("select",{"onUpdate:modelValue":t[1]||(t[1]=l=>i(n).language=l),transition:"all ease-in-out duration-250","cursor-pointer":"","bg-transparent":"","text-right":"","outline-none":""},[e("option",X,u(d.$t("settings.language.english")),1),e("option",ee,u(d.$t("settings.language.chinese")),1)],512),[[I,i(n).language]])])),[[s]])]),_:1},8,["title"])),[[s]]),a((o(),b(i(C),{title:i(m)("settings.pages.themes.sections.section.custom-color.title"),icon:"i-solar:pallete-2-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+4*10,delay:4*50,transition:"all ease-in-out duration-250"},{default:g(()=>[a((o(),r("div",te,[e("span",ie,u(d.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.label")),1),e("label",ne,[a(e("input",{"onUpdate:modelValue":t[2]||(t[2]=l=>i(n).themeColorsHueDynamic=l),type:"checkbox",class:"peer sr-only"},null,512),[[V,i(n).themeColorsHueDynamic]]),t[6]||(t[6]=e("div",{class:"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 peer-checked:bg-primary-500 after:transition-all after:content-[''] peer-checked:after:translate-x-full peer-checked:after:border-white"},null,-1)),h(" "+u(d.$t("settings.pages.themes.sections.section.custom-color.fields.field.primary-color.rgb-on.title")),1)])])),[[s]]),a(e("input",{"onUpdate:modelValue":t[3]||(t[3]=l=>i(n).themeColorsHue=l),initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+6*10,delay:6*50,transition:"all ease-in-out duration-250",type:"range",min:"0",max:"360",step:"0.01",class:x(["theme-hue-slider",i(n).themeColorsHueDynamic?"opacity-25 cursor-not-allowed":"cursor-pointer"]),disabled:i(n).themeColorsHueDynamic},null,10,ae),[[L,i(n).themeColorsHue],[s]]),a((o(),r("div",oe,[t[8]||(t[8]=e("span",{"bg-primary-50":""},"50",-1)),t[9]||(t[9]=e("span",{"bg-primary-100":""},"100",-1)),t[10]||(t[10]=e("span",{"bg-primary-200":""},"200",-1)),t[11]||(t[11]=e("span",{"bg-primary-300":""},"300",-1)),t[12]||(t[12]=e("span",{"bg-primary-400":""},"400",-1)),t[13]||(t[13]=e("span",{"bg-primary-500":""},"500",-1)),a((o(),r("div",se,t[7]||(t[7]=[e("span",{"bg-primary-600":""},"600",-1),e("span",{"bg-primary-700":""},"700",-1),e("span",{"bg-primary-800":""},"800",-1),e("span",{"bg-primary-900":""},"900",-1),e("span",{"bg-primary-950":""},"950",-1)]))),[[s]])])),[[s]]),a((o(),r("div",le,t[14]||(t[14]=[e("span",{bg:"primary-500/5"},"500/5",-1),e("span",{bg:"primary-500/10"},"500/10",-1),e("span",{bg:"primary-500/20"},"500/20",-1),e("span",{bg:"primary-500/30"},"500/30",-1),e("span",{bg:"primary-500/40"},"500/40",-1),e("span",{bg:"primary-500/50"},"500/50",-1),e("span",{bg:"primary-500/60"},"500/60",-1),e("span",{bg:"primary-500/70"},"500/70",-1),e("span",{bg:"primary-500/80"},"500/80",-1),e("span",{bg:"primary-500/90"},"500/90",-1),e("span",{bg:"primary-500"},"500",-1)]))),[[s]])]),_:1},8,["title"])),[[s]]),a((o(),b(i(C),{title:"settings.pages.themes.sections.section.theme-presets.title",icon:"i-solar:magic-stick-2-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+10*10,delay:10*50,transition:"all ease-in-out duration-250"},{default:g(()=>[(o(!0),r(k,null,G(d.$tm("settings.pages.themes.sections.section.theme-presets.presets"),({title:l,description:$,colors:T},f)=>a((o(),r("div",{key:f,class:"w-full flex items-center justify-between rounded-lg px-4 py-3 outline-none transition-all duration-250 ease-in-out",bg:"neutral-100 dark:neutral-800",hover:"bg-neutral-200 dark:bg-neutral-700",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+11*10+f*10,delay:11*50+f*50,transition:"all ease-in-out duration-250"},[e("div",null,[e("span",de,u(d.$rt(l)),1),e("div",ue,u(d.$rt($)),1)]),c(Q,{colors:T.map((E,S)=>({hex:i(J)[f][S],name:d.$rt(E)}))},null,8,["colors"])],8,re)),[[s]])),128))]),_:1})),[[s]]),a((o(),b(i(C),{title:"settings.pages.themes.sections.section.developer.title",icon:"i-solar:code-bold-duotone",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+18*10,delay:18*50,transition:"all ease-in-out duration-250"},{default:g(()=>[a(c(B,{modelValue:i(n).disableTransitions,"onUpdate:modelValue":t[4]||(t[4]=l=>i(n).disableTransitions=l),"icon-on":"i-solar:people-nearby-bold-duotone","icon-off":"i-solar:running-2-line-duotone",text:"settings.animations.stage-transitions.title",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+19*10,delay:19*50,transition:"all ease-in-out duration-250"},null,8,["modelValue"]),[[s]]),a(c(B,{modelValue:i(n).usePageSpecificTransitions,"onUpdate:modelValue":t[5]||(t[5]=l=>i(n).usePageSpecificTransitions=l),disabled:i(n).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",initial:{opacity:0,y:10},enter:{opacity:1,y:0},duration:250+20*10,delay:20*50,transition:"all ease-in-out duration-250"},null,8,["modelValue","disabled"]),[[s]])]),_:1})),[[s]]),a((o(),r("div",pe,t[15]||(t[15]=[e("div",{text:"60","i-solar:filters-bold-duotone":""},null,-1)]))),[[s]])],64)}}});typeof D=="function"&&D(w);const De=K(w,[["__scopeId","data-v-aa1dd799"]]);export{De as default}; diff --git a/assets/mcp-C9U4MroK.js b/assets/mcp-C9U4MroK.js new file mode 100644 index 0000000000000000000000000000000000000000..bc9964d552bc56a617881f4b77ed6531e60ac4bf --- /dev/null +++ b/assets/mcp-C9U4MroK.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/effect-AvyXEvwH-DHZdf01Y.js","assets/index-CQudhZin.js","assets/index-C-ktGyiB.css","assets/valibot-BI4iQMg3-DivldWga.js","assets/zod-CxRm5Gac-CPS76V3O.js"])))=>i.map(i=>d[i]); +import{L as ge}from"./index-CQudhZin.js";async function Se(r,e={},t){return window.__TAURI_INTERNALS__.invoke(r,e,t)}async function Nt(r,e){await Se("plugin:mcp|connect_server",{command:r,args:e})}async function Rt(){await Se("plugin:mcp|disconnect_server")}async function jt(){return await Se("plugin:mcp|list_tools")}async function It(r,e){return await Se("plugin:mcp|call_tool",{name:r,args:e})}const ar=async(r,e)=>{try{return await r}catch{throw new Error(`xsschema: Missing dependencies "${e}".`)}},Mt=async r=>{switch(r){case"arktype":return ge(()=>import("./arktype-C-GObzDh-1xlRyYUo.js"),[]).then(async({getToJsonSchemaFn:e})=>e());case"effect":return ge(()=>import("./effect-AvyXEvwH-DHZdf01Y.js"),__vite__mapDeps([0,1,2])).then(async({getToJsonSchemaFn:e})=>e());case"valibot":return ge(()=>import("./valibot-BI4iQMg3-DivldWga.js"),__vite__mapDeps([3,1,2])).then(async({getToJsonSchemaFn:e})=>e());case"zod":return ge(()=>import("./zod-CxRm5Gac-CPS76V3O.js"),__vite__mapDeps([4,1,2])).then(async({getToJsonSchemaFn:e})=>e());default:throw new Error(`xsschema: Unsupported schema vendor "${r}"`)}},Pe=async r=>Mt(r["~standard"].vendor).then(async e=>e(r)),xe=async r=>({execute:r.execute,function:{description:r.description,name:r.name,parameters:await Pe(r.parameters),returns:r.returns?await Pe(r.returns):void 0,strict:r.strict},type:"function"});var g;(function(r){r.assertEqual=n=>n;function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(g||(g={}));var be;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(be||(be={}));const f=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}},c=g.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Le=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class Z extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,l=0;for(;lt.message){const t={},s=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Z.create=r=>new Z(r);const W=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r)}return{message:t}};let De=W;function ze(r){De=r}function le(){return De}const fe=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const l=s.filter(d=>!!d).slice().reverse();for(const d of l)o=d(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Ue=[];function u(r,e){const t=le(),s=fe({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===W?void 0:W].filter(n=>!!n)});r.common.issues.push(s)}class k{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return _;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return k.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const _=Object.freeze({status:"aborted"}),F=r=>({status:"dirty",value:r}),w=r=>({status:"valid",value:r}),ke=r=>r.status==="aborted",we=r=>r.status==="dirty",D=r=>r.status==="valid",H=r=>typeof Promise<"u"&&r instanceof Promise;function Te(r,e,t,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Fe(r,e,t,s,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(h||(h={}));var de,ue;class R{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $e=(r,e)=>{if(D(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Z(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{var l,d;const{message:p}=r;return i.code==="invalid_enum_value"?{message:p??o.defaultError}:typeof o.data>"u"?{message:(l=p??s)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(d=p??t)!==null&&d!==void 0?d:o.defaultError}},description:n}}class y{get description(){return this._def.description}_getType(e){return N(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new k,ctx:{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(H(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;const n={common:{issues:[],async:(s=t==null?void 0:t.async)!==null&&s!==void 0?s:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},a=this._parseSync({data:e,path:n.path,parent:n});return $e(n,a)}"~validate"(e){var t,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:n});return D(a)?{value:a.value}:{issues:n.common.issues}}catch(a){!((s=(t=a==null?void 0:a.message)===null||t===void 0?void 0:t.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>D(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(H(n)?n:Promise.resolve(n));return $e(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:c.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new S({schema:this,typeName:m.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return O.create(this,this._def)}nullable(){return V.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return E.create(this)}promise(){return J.create(this,this._def)}or(e){return K.create([this,e],this._def)}and(e){return ee.create(this,e,this._def)}transform(e){return new S({...v(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ae({...v(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new Ce({typeName:m.ZodBranded,type:this,...v(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ie({...v(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ce.create(this,e)}readonly(){return oe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Pt=/^c[^\s-]{8,}$/i,$t=/^[0-9a-z]+$/,Vt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Lt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Dt=/^[a-z0-9_-]{21}$/i,zt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ut=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ft=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oe;const Wt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Yt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ht=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Be="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Qt=new RegExp(`^${Be}$`);function We(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Xt(r){return new RegExp(`^${We(r)}$`)}function Ne(r){let e=`${Be}T${We(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Kt(r,e){return!!((e==="v4"||!e)&&Wt.test(r)||(e==="v6"||!e)&&Jt.test(r))}function er(r,e){if(!zt.test(r))return!1;try{const[t]=r.split("."),s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function tr(r,e){return!!((e==="v4"||!e)&&qt.test(r)||(e==="v6"||!e)&&Yt.test(r))}class C extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:f.string,received:a.parsedType}),_}const s=new k;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.lengtha.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.lengthe.test(n),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new C({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(s=e==null?void 0:e.local)!==null&&s!==void 0?s:!1,...h.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...h.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...h.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new C({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new C({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new C({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new C({checks:[],typeName:m.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...v(r)})};function rr(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=parseInt(r.toFixed(n).replace(".","")),i=parseInt(e.toFixed(n).replace(".",""));return a%i/Math.pow(10,n)}class M extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:f.number,received:a.parsedType}),_}let s;const n=new k;for(const a of this._def.checks)a.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:c.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?rr(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:c.not_finite,message:a.message}),n.dirty()):g.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new M({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new M({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.valuenew M({checks:[],typeName:m.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...v(r)});class P extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s;const n=new k;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):g.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return u(t,{code:c.invalid_type,expected:f.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new P({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new P({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new P({checks:[],typeName:m.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...v(r)})};class G extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.boolean,received:s.parsedType}),_}return w(e.data)}}G.create=r=>new G({typeName:m.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...v(r)});class z extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:f.date,received:a.parsedType}),_}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_date}),_}const s=new k;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:c.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):g.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew z({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:m.ZodDate,...v(r)});class he extends y{_parse(e){if(this._getType(e)!==f.symbol){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.symbol,received:s.parsedType}),_}return w(e.data)}}he.create=r=>new he({typeName:m.ZodSymbol,...v(r)});class Q extends y{_parse(e){if(this._getType(e)!==f.undefined){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.undefined,received:s.parsedType}),_}return w(e.data)}}Q.create=r=>new Q({typeName:m.ZodUndefined,...v(r)});class X extends y{_parse(e){if(this._getType(e)!==f.null){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.null,received:s.parsedType}),_}return w(e.data)}}X.create=r=>new X({typeName:m.ZodNull,...v(r)});class q extends y{constructor(){super(...arguments),this._any=!0}_parse(e){return w(e.data)}}q.create=r=>new q({typeName:m.ZodAny,...v(r)});class L extends y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return w(e.data)}}L.create=r=>new L({typeName:m.ZodUnknown,...v(r)});class j extends y{_parse(e){const t=this._getOrReturnCtx(e);return u(t,{code:c.invalid_type,expected:f.never,received:t.parsedType}),_}}j.create=r=>new j({typeName:m.ZodNever,...v(r)});class pe extends y{_parse(e){if(this._getType(e)!==f.undefined){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.void,received:s.parsedType}),_}return w(e.data)}}pe.create=r=>new pe({typeName:m.ZodVoid,...v(r)});class E extends y{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return u(t,{code:c.invalid_type,expected:f.array,received:t.parsedType}),_;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.lengthn.maxLength.value&&(u(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new R(t,i,t.path,o)))).then(i=>k.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new R(t,i,t.path,o)));return k.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new E({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new E({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new E({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}}E.create=(r,e)=>new E({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...v(e)});function Y(r){if(r instanceof x){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=O.create(Y(s))}return new x({...r._def,shape:()=>e})}else return r instanceof E?new E({...r._def,type:Y(r.element)}):r instanceof O?O.create(Y(r.unwrap())):r instanceof V?V.create(Y(r.unwrap())):r instanceof A?A.create(r.items.map(e=>Y(e))):r}class x extends y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=g.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==f.object){const d=this._getOrReturnCtx(e);return u(d,{code:c.invalid_type,expected:f.object,received:d.parsedType}),_}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof j&&this._def.unknownKeys==="strip"))for(const d in n.data)i.includes(d)||o.push(d);const l=[];for(const d of i){const p=a[d],T=n.data[d];l.push({key:{status:"valid",value:d},value:p._parse(new R(n,T,n.path,d)),alwaysSet:d in n.data})}if(this._def.catchall instanceof j){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of o)l.push({key:{status:"valid",value:p},value:{status:"valid",value:n.data[p]}});else if(d==="strict")o.length>0&&(u(n,{code:c.unrecognized_keys,keys:o}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of o){const T=n.data[p];l.push({key:{status:"valid",value:p},value:d._parse(new R(n,T,n.path,p)),alwaysSet:p in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of l){const T=await p.key,ve=await p.value;d.push({key:T,value:ve,alwaysSet:p.alwaysSet})}return d}).then(d=>k.mergeObjectSync(s,d)):k.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new x({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var n,a,i,o;const l=(i=(a=(n=this._def).errorMap)===null||a===void 0?void 0:a.call(n,t,s).message)!==null&&i!==void 0?i:s.defaultError;return t.code==="unrecognized_keys"?{message:(o=h.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new x({...this._def,unknownKeys:"strip"})}passthrough(){return new x({...this._def,unknownKeys:"passthrough"})}extend(e){return new x({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new x({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new x({...this._def,catchall:e})}pick(e){const t={};return g.objectKeys(e).forEach(s=>{e[s]&&this.shape[s]&&(t[s]=this.shape[s])}),new x({...this._def,shape:()=>t})}omit(e){const t={};return g.objectKeys(this.shape).forEach(s=>{e[s]||(t[s]=this.shape[s])}),new x({...this._def,shape:()=>t})}deepPartial(){return Y(this)}partial(e){const t={};return g.objectKeys(this.shape).forEach(s=>{const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}),new x({...this._def,shape:()=>t})}required(e){const t={};return g.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof O;)a=a._def.innerType;t[s]=a}}),new x({...this._def,shape:()=>t})}keyof(){return qe(g.objectKeys(this.shape))}}x.create=(r,e)=>new x({shape:()=>r,unknownKeys:"strip",catchall:j.create(),typeName:m.ZodObject,...v(e)});x.strictCreate=(r,e)=>new x({shape:()=>r,unknownKeys:"strict",catchall:j.create(),typeName:m.ZodObject,...v(e)});x.lazycreate=(r,e)=>new x({shape:r,unknownKeys:"strip",catchall:j.create(),typeName:m.ZodObject,...v(e)});class K extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new Z(o.ctx.common.issues));return u(t,{code:c.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const l of s){const d={...t,common:{...t.common,issues:[]},parent:null},p=l._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new Z(l));return u(t,{code:c.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}}K.create=(r,e)=>new K({options:r,typeName:m.ZodUnion,...v(e)});const I=r=>r instanceof re?I(r.schema):r instanceof S?I(r.innerType()):r instanceof se?[r.value]:r instanceof $?r.options:r instanceof ne?g.objectValues(r.enum):r instanceof ae?I(r._def.innerType):r instanceof Q?[void 0]:r instanceof X?[null]:r instanceof O?[void 0,...I(r.unwrap())]:r instanceof V?[null,...I(r.unwrap())]:r instanceof Ce||r instanceof oe?I(r.unwrap()):r instanceof ie?I(r._def.innerType):[];class ye extends y{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return u(t,{code:c.invalid_type,expected:f.object,received:t.parsedType}),_;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=I(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new ye({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...v(s)})}}function Ae(r,e){const t=N(r),s=N(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&s===f.object){const n=g.objectKeys(e),a=g.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const l=Ae(r[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(t===f.array&&s===f.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a{if(ke(a)||ke(i))return _;const o=Ae(a.value,i.value);return o.valid?((we(a)||we(i))&&t.dirty(),{status:t.value,value:o.data}):(u(s,{code:c.invalid_intersection_types}),_)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}ee.create=(r,e,t)=>new ee({left:r,right:e,typeName:m.ZodIntersection,...v(t)});class A extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return u(s,{code:c.invalid_type,expected:f.array,received:s.parsedType}),_;if(s.data.lengththis._def.items.length&&(u(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new R(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>k.mergeArray(t,i)):k.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new A({...this._def,rest:e})}}A.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new A({items:r,typeName:m.ZodTuple,rest:null,...v(e)})};class te extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return u(s,{code:c.invalid_type,expected:f.object,received:s.parsedType}),_;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in s.data)n.push({key:a._parse(new R(s,o,s.path,o)),value:i._parse(new R(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?k.mergeObjectAsync(t,n):k.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof y?new te({keyType:e,valueType:t,typeName:m.ZodRecord,...v(s)}):new te({keyType:C.create(),valueType:e,typeName:m.ZodRecord,...v(t)})}}class me extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return u(s,{code:c.invalid_type,expected:f.map,received:s.parsedType}),_;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,l],d)=>({key:n._parse(new R(s,o,s.path,[d,"key"])),value:a._parse(new R(s,l,s.path,[d,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const d=await l.key,p=await l.value;if(d.status==="aborted"||p.status==="aborted")return _;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(d.value,p.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of i){const d=l.key,p=l.value;if(d.status==="aborted"||p.status==="aborted")return _;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(d.value,p.value)}return{status:t.value,value:o}}}}me.create=(r,e,t)=>new me({valueType:e,keyType:r,typeName:m.ZodMap,...v(t)});class U extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return u(s,{code:c.invalid_type,expected:f.set,received:s.parsedType}),_;const n=this._def;n.minSize!==null&&s.data.sizen.maxSize.value&&(u(s,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(l){const d=new Set;for(const p of l){if(p.status==="aborted")return _;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const o=[...s.data.values()].map((l,d)=>a._parse(new R(s,l,s.path,d)));return s.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new U({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new U({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}U.create=(r,e)=>new U({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...v(e)});class B extends y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return u(t,{code:c.invalid_type,expected:f.function,received:t.parsedType}),_;function s(o,l){return fe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),W].filter(d=>!!d),issueData:{code:c.invalid_arguments,argumentsError:l}})}function n(o,l){return fe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),W].filter(d=>!!d),issueData:{code:c.invalid_return_type,returnTypeError:l}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof J){const o=this;return w(async function(...l){const d=new Z([]),p=await o._def.args.parseAsync(l,a).catch(Ee=>{throw d.addIssue(s(l,Ee)),d}),T=await Reflect.apply(i,this,p);return await o._def.returns._def.type.parseAsync(T,a).catch(Ee=>{throw d.addIssue(n(T,Ee)),d})})}else{const o=this;return w(function(...l){const d=o._def.args.safeParse(l,a);if(!d.success)throw new Z([s(l,d.error)]);const p=Reflect.apply(i,this,d.data),T=o._def.returns.safeParse(p,a);if(!T.success)throw new Z([n(p,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new B({...this._def,args:A.create(e).rest(L.create())})}returns(e){return new B({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new B({args:e||A.create([]).rest(L.create()),returns:t||L.create(),typeName:m.ZodFunction,...v(s)})}}class re extends y{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}re.create=(r,e)=>new re({getter:r,typeName:m.ZodLazy,...v(e)});class se extends y{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}}se.create=(r,e)=>new se({value:r,typeName:m.ZodLiteral,...v(e)});function qe(r,e){return new $({values:r,typeName:m.ZodEnum,...v(e)})}class $ extends y{constructor(){super(...arguments),de.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{expected:g.joinValues(s),received:t.parsedType,code:c.invalid_type}),_}if(Te(this,de)||Fe(this,de,new Set(this._def.values)),!Te(this,de).has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{received:t.data,code:c.invalid_enum_value,options:s}),_}return w(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return $.create(e,{...this._def,...t})}exclude(e,t=this._def){return $.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}de=new WeakMap;$.create=qe;class ne extends y{constructor(){super(...arguments),ue.set(this,void 0)}_parse(e){const t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){const n=g.objectValues(t);return u(s,{expected:g.joinValues(n),received:s.parsedType,code:c.invalid_type}),_}if(Te(this,ue)||Fe(this,ue,new Set(g.getValidEnumValues(this._def.values))),!Te(this,ue).has(e.data)){const n=g.objectValues(t);return u(s,{received:s.data,code:c.invalid_enum_value,options:n}),_}return w(e.data)}get enum(){return this._def.values}}ue=new WeakMap;ne.create=(r,e)=>new ne({values:r,typeName:m.ZodNativeEnum,...v(e)});class J extends y{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return u(t,{code:c.invalid_type,expected:f.promise,received:t.parsedType}),_;const s=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return w(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}J.create=(r,e)=>new J({type:r,typeName:m.ZodPromise,...v(e)});class S extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{u(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;const l=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?F(l.value):l});{if(t.value==="aborted")return _;const o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?_:o.status==="dirty"||t.value==="dirty"?F(o.value):o}}if(n.type==="refinement"){const i=o=>{const l=n.refinement(o,a);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!D(i))return i;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>D(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):i);g.assertNever(n)}}S.create=(r,e,t)=>new S({schema:r,typeName:m.ZodEffects,effect:e,...v(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...v(t)});class O extends y{_parse(e){return this._getType(e)===f.undefined?w(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}O.create=(r,e)=>new O({innerType:r,typeName:m.ZodOptional,...v(e)});class V extends y{_parse(e){return this._getType(e)===f.null?w(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}V.create=(r,e)=>new V({innerType:r,typeName:m.ZodNullable,...v(e)});class ae extends y{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ae.create=(r,e)=>new ae({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});class ie extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return H(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Z(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Z(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ie.create=(r,e)=>new ie({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});class _e extends y{_parse(e){if(this._getType(e)!==f.nan){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.nan,received:s.parsedType}),_}return{status:"valid",value:e.data}}}_e.create=r=>new _e({typeName:m.ZodNaN,...v(r)});const Je=Symbol("zod_brand");class Ce extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class ce extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),F(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?_:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new ce({in:e,out:t,typeName:m.ZodPipeline})}}class oe extends y{_parse(e){const t=this._def.innerType._parse(e),s=n=>(D(n)&&(n.value=Object.freeze(n.value)),n);return H(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}oe.create=(r,e)=>new oe({innerType:r,typeName:m.ZodReadonly,...v(e)});function Ve(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Re(r,e={},t){return r?q.create().superRefine((s,n)=>{var a,i;const o=r(s);if(o instanceof Promise)return o.then(l=>{var d,p;if(!l){const T=Ve(e,s),ve=(p=(d=T.fatal)!==null&&d!==void 0?d:t)!==null&&p!==void 0?p:!0;n.addIssue({code:"custom",...T,fatal:ve})}});if(!o){const l=Ve(e,s),d=(i=(a=l.fatal)!==null&&a!==void 0?a:t)!==null&&i!==void 0?i:!0;n.addIssue({code:"custom",...l,fatal:d})}}):q.create()}const Ye={object:x.lazycreate};var m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(m||(m={}));const He=(r,e={message:`Input not instance of ${r.name}`})=>Re(t=>t instanceof r,e),je=C.create,Ie=M.create,Ge=_e.create,Qe=P.create,Me=G.create,Xe=z.create,Ke=he.create,et=Q.create,tt=X.create,rt=q.create,st=L.create,nt=j.create,at=pe.create,it=E.create,ot=x.create,ct=x.strictCreate,dt=K.create,ut=ye.create,lt=ee.create,ft=A.create,ht=te.create,pt=me.create,mt=U.create,_t=B.create,yt=re.create,vt=se.create,gt=$.create,xt=ne.create,bt=J.create,Ze=S.create,kt=O.create,wt=V.create,Tt=S.createWithPreprocess,Zt=ce.create,St=()=>je().optional(),Ct=()=>Ie().optional(),Et=()=>Me().optional(),Ot={string:r=>C.create({...r,coerce:!0}),number:r=>M.create({...r,coerce:!0}),boolean:r=>G.create({...r,coerce:!0}),bigint:r=>P.create({...r,coerce:!0}),date:r=>z.create({...r,coerce:!0})},At=_;var b=Object.freeze({__proto__:null,defaultErrorMap:W,setErrorMap:ze,getErrorMap:le,makeIssue:fe,EMPTY_PATH:Ue,addIssueToContext:u,ParseStatus:k,INVALID:_,DIRTY:F,OK:w,isAborted:ke,isDirty:we,isValid:D,isAsync:H,get util(){return g},get objectUtil(){return be},ZodParsedType:f,getParsedType:N,ZodType:y,datetimeRegex:Ne,ZodString:C,ZodNumber:M,ZodBigInt:P,ZodBoolean:G,ZodDate:z,ZodSymbol:he,ZodUndefined:Q,ZodNull:X,ZodAny:q,ZodUnknown:L,ZodNever:j,ZodVoid:pe,ZodArray:E,ZodObject:x,ZodUnion:K,ZodDiscriminatedUnion:ye,ZodIntersection:ee,ZodTuple:A,ZodRecord:te,ZodMap:me,ZodSet:U,ZodFunction:B,ZodLazy:re,ZodLiteral:se,ZodEnum:$,ZodNativeEnum:ne,ZodPromise:J,ZodEffects:S,ZodTransformer:S,ZodOptional:O,ZodNullable:V,ZodDefault:ae,ZodCatch:ie,ZodNaN:_e,BRAND:Je,ZodBranded:Ce,ZodPipeline:ce,ZodReadonly:oe,custom:Re,Schema:y,ZodSchema:y,late:Ye,get ZodFirstPartyTypeKind(){return m},coerce:Ot,any:rt,array:it,bigint:Qe,boolean:Me,date:Xe,discriminatedUnion:ut,effect:Ze,enum:gt,function:_t,instanceof:He,intersection:lt,lazy:yt,literal:vt,map:pt,nan:Ge,nativeEnum:xt,never:nt,null:tt,nullable:wt,number:Ie,object:ot,oboolean:Et,onumber:Ct,optional:kt,ostring:St,pipeline:Zt,preprocess:Tt,promise:bt,record:ht,set:mt,strictObject:ct,string:je,symbol:Ke,transformer:Ze,tuple:ft,undefined:et,union:dt,unknown:st,void:at,NEVER:At,ZodIssueCode:c,quotelessJson:Le,ZodError:Z});const ir=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Je,DIRTY:F,EMPTY_PATH:Ue,INVALID:_,NEVER:At,OK:w,ParseStatus:k,Schema:y,ZodAny:q,ZodArray:E,ZodBigInt:P,ZodBoolean:G,ZodBranded:Ce,ZodCatch:ie,ZodDate:z,ZodDefault:ae,ZodDiscriminatedUnion:ye,ZodEffects:S,ZodEnum:$,ZodError:Z,get ZodFirstPartyTypeKind(){return m},ZodFunction:B,ZodIntersection:ee,ZodIssueCode:c,ZodLazy:re,ZodLiteral:se,ZodMap:me,ZodNaN:_e,ZodNativeEnum:ne,ZodNever:j,ZodNull:X,ZodNullable:V,ZodNumber:M,ZodObject:x,ZodOptional:O,ZodParsedType:f,ZodPipeline:ce,ZodPromise:J,ZodReadonly:oe,ZodRecord:te,ZodSchema:y,ZodSet:U,ZodString:C,ZodSymbol:he,ZodTransformer:S,ZodTuple:A,ZodType:y,ZodUndefined:Q,ZodUnion:K,ZodUnknown:L,ZodVoid:pe,addIssueToContext:u,any:rt,array:it,bigint:Qe,boolean:Me,coerce:Ot,custom:Re,date:Xe,datetimeRegex:Ne,default:b,defaultErrorMap:W,discriminatedUnion:ut,effect:Ze,enum:gt,function:_t,getErrorMap:le,getParsedType:N,instanceof:He,intersection:lt,isAborted:ke,isAsync:H,isDirty:we,isValid:D,late:Ye,lazy:yt,literal:vt,makeIssue:fe,map:pt,nan:Ge,nativeEnum:xt,never:nt,null:tt,nullable:wt,number:Ie,object:ot,get objectUtil(){return be},oboolean:Et,onumber:Ct,optional:kt,ostring:St,pipeline:Zt,preprocess:Tt,promise:bt,quotelessJson:Le,record:ht,set:mt,setErrorMap:ze,strictObject:ct,string:je,symbol:Ke,transformer:Ze,tuple:ft,undefined:et,union:dt,unknown:st,get util(){return g},void:at,z:b},Symbol.toStringTag,{value:"Module"})),sr=[xe({name:"mcp_list_tools",description:"List all tools available on the MCP server",execute:async(r,e)=>await jt(),parameters:b.object({}),returns:b.object({})}),xe({name:"mcp_connect_server",description:"Connect to the MCP server",execute:async({command:r,args:e})=>(await Nt(r,e),"success"),parameters:b.object({command:b.string().describe("The command to connect to the MCP server"),args:b.array(b.string()).describe("The arguments to pass to the MCP server")}),returns:b.string().describe('If "success", the connection to the MCP server is successful. Otherwise, the connection fails.')}),xe({name:"mcp_disconnect_server",description:"Disconnect from the MCP server",execute:async()=>(await Rt(),"success"),parameters:b.object({}),returns:b.string().describe('If "success", the connection to the MCP server is successful. Otherwise, the connection fails.')}),xe({name:"mcp_call_tool",description:"Call a tool on the MCP server",execute:async({name:r,parameters:e})=>{const t=Object.fromEntries(e.map(({name:n,value:a})=>[n,a]));return await It(r,t)},parameters:b.object({name:b.string().describe("The name of the tool to call"),parameters:b.array(b.object({name:b.string().describe("The name of the parameter"),value:b.any().describe("The value of the parameter")})).describe("The parameters to pass to the tool")}),returns:b.object({content:b.array(b.object({type:b.string().describe("The type of the content"),text:b.string().describe("The text of the content")})).describe("The content of the tool call result"),isError:b.boolean().describe("Whether the tool call is an error")}).describe("The result of the tool call")})],or=async()=>Promise.all(sr);export{m as Z,O as a,ir as i,or as m,ar as t}; diff --git a/assets/mcp-DQCTu0C2.js b/assets/mcp-DQCTu0C2.js deleted file mode 100644 index e928693d644b351b137beb06343639c43cdefd37..0000000000000000000000000000000000000000 --- a/assets/mcp-DQCTu0C2.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/effect-AvyXEvwH-DIOBmVdI.js","assets/index-BQKiy4UR.js","assets/index-C-ktGyiB.css","assets/valibot-BI4iQMg3-C6wv93uD.js","assets/zod-CxRm5Gac-D7xrOp6Y.js"])))=>i.map(i=>d[i]); -import{L as ge}from"./index-BQKiy4UR.js";async function Se(r,e={},t){return window.__TAURI_INTERNALS__.invoke(r,e,t)}async function Nt(r,e){await Se("plugin:mcp|connect_server",{command:r,args:e})}async function Rt(){await Se("plugin:mcp|disconnect_server")}async function jt(){return await Se("plugin:mcp|list_tools")}async function It(r,e){return await Se("plugin:mcp|call_tool",{name:r,args:e})}const ar=async(r,e)=>{try{return await r}catch{throw new Error(`xsschema: Missing dependencies "${e}".`)}},Mt=async r=>{switch(r){case"arktype":return ge(()=>import("./arktype-C-GObzDh-1xlRyYUo.js"),[]).then(async({getToJsonSchemaFn:e})=>e());case"effect":return ge(()=>import("./effect-AvyXEvwH-DIOBmVdI.js"),__vite__mapDeps([0,1,2])).then(async({getToJsonSchemaFn:e})=>e());case"valibot":return ge(()=>import("./valibot-BI4iQMg3-C6wv93uD.js"),__vite__mapDeps([3,1,2])).then(async({getToJsonSchemaFn:e})=>e());case"zod":return ge(()=>import("./zod-CxRm5Gac-D7xrOp6Y.js"),__vite__mapDeps([4,1,2])).then(async({getToJsonSchemaFn:e})=>e());default:throw new Error(`xsschema: Unsupported schema vendor "${r}"`)}},Pe=async r=>Mt(r["~standard"].vendor).then(async e=>e(r)),xe=async r=>({execute:r.execute,function:{description:r.description,name:r.name,parameters:await Pe(r.parameters),returns:r.returns?await Pe(r.returns):void 0,strict:r.strict},type:"function"});var g;(function(r){r.assertEqual=n=>n;function e(n){}r.assertIs=e;function t(n){throw new Error}r.assertNever=t,r.arrayToEnum=n=>{const a={};for(const i of n)a[i]=i;return a},r.getValidEnumValues=n=>{const a=r.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),i={};for(const o of a)i[o]=n[o];return r.objectValues(i)},r.objectValues=n=>r.objectKeys(n).map(function(a){return n[a]}),r.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const a=[];for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&a.push(i);return a},r.find=(n,a)=>{for(const i of n)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function s(n,a=" | "){return n.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=s,r.jsonStringifyReplacer=(n,a)=>typeof a=="bigint"?a.toString():a})(g||(g={}));var be;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(be||(be={}));const f=g.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),N=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}},c=g.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Le=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:");class Z extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},s={_errors:[]},n=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(n);else if(i.code==="invalid_return_type")n(i.returnTypeError);else if(i.code==="invalid_arguments")n(i.argumentsError);else if(i.path.length===0)s._errors.push(t(i));else{let o=s,l=0;for(;lt.message){const t={},s=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):s.push(e(n));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}Z.create=r=>new Z(r);const W=(r,e)=>{let t;switch(r.code){case c.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case c.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,g.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:t=`Unrecognized key(s) in object: ${g.joinValues(r.keys,", ")}`;break;case c.invalid_union:t="Invalid input";break;case c.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${g.joinValues(r.options)}`;break;case c.invalid_enum_value:t=`Invalid enum value. Expected ${g.joinValues(r.options)}, received '${r.received}'`;break;case c.invalid_arguments:t="Invalid function arguments";break;case c.invalid_return_type:t="Invalid function return type";break;case c.invalid_date:t="Invalid date";break;case c.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:g.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case c.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case c.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case c.custom:t="Invalid input";break;case c.invalid_intersection_types:t="Intersection results could not be merged";break;case c.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case c.not_finite:t="Number must be finite";break;default:t=e.defaultError,g.assertNever(r)}return{message:t}};let De=W;function ze(r){De=r}function le(){return De}const fe=r=>{const{data:e,path:t,errorMaps:s,issueData:n}=r,a=[...t,...n.path||[]],i={...n,path:a};if(n.message!==void 0)return{...n,path:a,message:n.message};let o="";const l=s.filter(d=>!!d).slice().reverse();for(const d of l)o=d(i,{data:e,defaultError:o}).message;return{...n,path:a,message:o}},Ue=[];function u(r,e){const t=le(),s=fe({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===W?void 0:W].filter(n=>!!n)});r.common.issues.push(s)}class k{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const n of t){if(n.status==="aborted")return _;n.status==="dirty"&&e.dirty(),s.push(n.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const n of t){const a=await n.key,i=await n.value;s.push({key:a,value:i})}return k.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const n of t){const{key:a,value:i}=n;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||n.alwaysSet)&&(s[a.value]=i.value)}return{status:e.value,value:s}}}const _=Object.freeze({status:"aborted"}),F=r=>({status:"dirty",value:r}),w=r=>({status:"valid",value:r}),ke=r=>r.status==="aborted",we=r=>r.status==="dirty",D=r=>r.status==="valid",H=r=>typeof Promise<"u"&&r instanceof Promise;function Te(r,e,t,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(r)}function Fe(r,e,t,s,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(h||(h={}));var de,ue;class R{constructor(e,t,s,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $e=(r,e)=>{if(D(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Z(r.common.issues);return this._error=t,this._error}}};function v(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:n}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(i,o)=>{var l,d;const{message:p}=r;return i.code==="invalid_enum_value"?{message:p??o.defaultError}:typeof o.data>"u"?{message:(l=p??s)!==null&&l!==void 0?l:o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:(d=p??t)!==null&&d!==void 0?d:o.defaultError}},description:n}}class y{get description(){return this._def.description}_getType(e){return N(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new k,ctx:{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(H(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){var s;const n={common:{issues:[],async:(s=t==null?void 0:t.async)!==null&&s!==void 0?s:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},a=this._parseSync({data:e,path:n.path,parent:n});return $e(n,a)}"~validate"(e){var t,s;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};if(!this["~standard"].async)try{const a=this._parseSync({data:e,path:[],parent:n});return D(a)?{value:a.value}:{issues:n.common.issues}}catch(a){!((s=(t=a==null?void 0:a.message)===null||t===void 0?void 0:t.toLowerCase())===null||s===void 0)&&s.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>D(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},n=this._parse({data:e,path:s.path,parent:s}),a=await(H(n)?n:Promise.resolve(n));return $e(s,a)}refine(e,t){const s=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,a)=>{const i=e(n),o=()=>a.addIssue({code:c.custom,...s(n)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((s,n)=>e(s)?!0:(n.addIssue(typeof t=="function"?t(s,n):t),!1))}_refinement(e){return new S({schema:this,typeName:m.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return O.create(this,this._def)}nullable(){return V.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return E.create(this)}promise(){return J.create(this,this._def)}or(e){return Q.create([this,e],this._def)}and(e){return ee.create(this,e,this._def)}transform(e){return new S({...v(this._def),schema:this,typeName:m.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new ae({...v(this._def),innerType:this,defaultValue:t,typeName:m.ZodDefault})}brand(){return new Ce({typeName:m.ZodBranded,type:this,...v(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new ie({...v(this._def),innerType:this,catchValue:t,typeName:m.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ce.create(this,e)}readonly(){return oe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Pt=/^c[^\s-]{8,}$/i,$t=/^[0-9a-z]+$/,Vt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Lt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Dt=/^[a-z0-9_-]{21}$/i,zt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ut=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ft=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Oe;const Wt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Jt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Yt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ht=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Be="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Xt=new RegExp(`^${Be}$`);function We(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Kt(r){return new RegExp(`^${We(r)}$`)}function Ne(r){let e=`${Be}T${We(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Qt(r,e){return!!((e==="v4"||!e)&&Wt.test(r)||(e==="v6"||!e)&&Jt.test(r))}function er(r,e){if(!zt.test(r))return!1;try{const[t]=r.split("."),s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(s));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function tr(r,e){return!!((e==="v4"||!e)&&qt.test(r)||(e==="v6"||!e)&&Yt.test(r))}class C extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:f.string,received:a.parsedType}),_}const s=new k;let n;for(const a of this._def.checks)if(a.kind==="min")e.data.lengtha.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:c.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),s.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.lengthe.test(n),{validation:t,code:c.invalid_string,...h.errToObj(s)})}_addCheck(e){return new C({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){var t,s;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(s=e==null?void 0:e.local)!==null&&s!==void 0?s:!1,...h.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...h.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...h.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new C({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new C({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new C({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new C({checks:[],typeName:m.ZodString,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...v(r)})};function rr(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,n=t>s?t:s,a=parseInt(r.toFixed(n).replace(".","")),i=parseInt(e.toFixed(n).replace(".",""));return a%i/Math.pow(10,n)}class M extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:f.number,received:a.parsedType}),_}let s;const n=new k;for(const a of this._def.checks)a.kind==="int"?g.isInteger(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:c.invalid_type,expected:"integer",received:"float",message:a.message}),n.dirty()):a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),n.dirty()):a.kind==="multipleOf"?rr(e.data,a.value)!==0&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(s=this._getOrReturnCtx(e,s),u(s,{code:c.not_finite,message:a.message}),n.dirty()):g.assertNever(a);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new M({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new M({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&g.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.valuenew M({checks:[],typeName:m.ZodNumber,coerce:(r==null?void 0:r.coerce)||!1,...v(r)});class P extends y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let s;const n=new k;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.dataa.value:e.data>=a.value)&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),n.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(s=this._getOrReturnCtx(e,s),u(s,{code:c.not_multiple_of,multipleOf:a.value,message:a.message}),n.dirty()):g.assertNever(a);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return u(t,{code:c.invalid_type,expected:f.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,s,n){return new P({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:h.toString(n)}]})}_addCheck(e){return new P({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new P({checks:[],typeName:m.ZodBigInt,coerce:(e=r==null?void 0:r.coerce)!==null&&e!==void 0?e:!1,...v(r)})};class G extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.boolean,received:s.parsedType}),_}return w(e.data)}}G.create=r=>new G({typeName:m.ZodBoolean,coerce:(r==null?void 0:r.coerce)||!1,...v(r)});class z extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_type,expected:f.date,received:a.parsedType}),_}if(isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return u(a,{code:c.invalid_date}),_}const s=new k;let n;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()a.value&&(n=this._getOrReturnCtx(e,n),u(n,{code:c.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),s.dirty()):g.assertNever(a);return{status:s.value,value:new Date(e.data.getTime())}}_addCheck(e){return new z({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew z({checks:[],coerce:(r==null?void 0:r.coerce)||!1,typeName:m.ZodDate,...v(r)});class he extends y{_parse(e){if(this._getType(e)!==f.symbol){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.symbol,received:s.parsedType}),_}return w(e.data)}}he.create=r=>new he({typeName:m.ZodSymbol,...v(r)});class X extends y{_parse(e){if(this._getType(e)!==f.undefined){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.undefined,received:s.parsedType}),_}return w(e.data)}}X.create=r=>new X({typeName:m.ZodUndefined,...v(r)});class K extends y{_parse(e){if(this._getType(e)!==f.null){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.null,received:s.parsedType}),_}return w(e.data)}}K.create=r=>new K({typeName:m.ZodNull,...v(r)});class q extends y{constructor(){super(...arguments),this._any=!0}_parse(e){return w(e.data)}}q.create=r=>new q({typeName:m.ZodAny,...v(r)});class L extends y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return w(e.data)}}L.create=r=>new L({typeName:m.ZodUnknown,...v(r)});class j extends y{_parse(e){const t=this._getOrReturnCtx(e);return u(t,{code:c.invalid_type,expected:f.never,received:t.parsedType}),_}}j.create=r=>new j({typeName:m.ZodNever,...v(r)});class pe extends y{_parse(e){if(this._getType(e)!==f.undefined){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.void,received:s.parsedType}),_}return w(e.data)}}pe.create=r=>new pe({typeName:m.ZodVoid,...v(r)});class E extends y{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),n=this._def;if(t.parsedType!==f.array)return u(t,{code:c.invalid_type,expected:f.array,received:t.parsedType}),_;if(n.exactLength!==null){const i=t.data.length>n.exactLength.value,o=t.data.lengthn.maxLength.value&&(u(t,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>n.type._parseAsync(new R(t,i,t.path,o)))).then(i=>k.mergeArray(s,i));const a=[...t.data].map((i,o)=>n.type._parseSync(new R(t,i,t.path,o)));return k.mergeArray(s,a)}get element(){return this._def.type}min(e,t){return new E({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new E({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new E({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}}E.create=(r,e)=>new E({type:r,minLength:null,maxLength:null,exactLength:null,typeName:m.ZodArray,...v(e)});function Y(r){if(r instanceof x){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=O.create(Y(s))}return new x({...r._def,shape:()=>e})}else return r instanceof E?new E({...r._def,type:Y(r.element)}):r instanceof O?O.create(Y(r.unwrap())):r instanceof V?V.create(Y(r.unwrap())):r instanceof A?A.create(r.items.map(e=>Y(e))):r}class x extends y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=g.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==f.object){const d=this._getOrReturnCtx(e);return u(d,{code:c.invalid_type,expected:f.object,received:d.parsedType}),_}const{status:s,ctx:n}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof j&&this._def.unknownKeys==="strip"))for(const d in n.data)i.includes(d)||o.push(d);const l=[];for(const d of i){const p=a[d],T=n.data[d];l.push({key:{status:"valid",value:d},value:p._parse(new R(n,T,n.path,d)),alwaysSet:d in n.data})}if(this._def.catchall instanceof j){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of o)l.push({key:{status:"valid",value:p},value:{status:"valid",value:n.data[p]}});else if(d==="strict")o.length>0&&(u(n,{code:c.unrecognized_keys,keys:o}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of o){const T=n.data[p];l.push({key:{status:"valid",value:p},value:d._parse(new R(n,T,n.path,p)),alwaysSet:p in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of l){const T=await p.key,ve=await p.value;d.push({key:T,value:ve,alwaysSet:p.alwaysSet})}return d}).then(d=>k.mergeObjectSync(s,d)):k.mergeObjectSync(s,l)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new x({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{var n,a,i,o;const l=(i=(a=(n=this._def).errorMap)===null||a===void 0?void 0:a.call(n,t,s).message)!==null&&i!==void 0?i:s.defaultError;return t.code==="unrecognized_keys"?{message:(o=h.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new x({...this._def,unknownKeys:"strip"})}passthrough(){return new x({...this._def,unknownKeys:"passthrough"})}extend(e){return new x({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new x({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:m.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new x({...this._def,catchall:e})}pick(e){const t={};return g.objectKeys(e).forEach(s=>{e[s]&&this.shape[s]&&(t[s]=this.shape[s])}),new x({...this._def,shape:()=>t})}omit(e){const t={};return g.objectKeys(this.shape).forEach(s=>{e[s]||(t[s]=this.shape[s])}),new x({...this._def,shape:()=>t})}deepPartial(){return Y(this)}partial(e){const t={};return g.objectKeys(this.shape).forEach(s=>{const n=this.shape[s];e&&!e[s]?t[s]=n:t[s]=n.optional()}),new x({...this._def,shape:()=>t})}required(e){const t={};return g.objectKeys(this.shape).forEach(s=>{if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof O;)a=a._def.innerType;t[s]=a}}),new x({...this._def,shape:()=>t})}keyof(){return qe(g.objectKeys(this.shape))}}x.create=(r,e)=>new x({shape:()=>r,unknownKeys:"strip",catchall:j.create(),typeName:m.ZodObject,...v(e)});x.strictCreate=(r,e)=>new x({shape:()=>r,unknownKeys:"strict",catchall:j.create(),typeName:m.ZodObject,...v(e)});x.lazycreate=(r,e)=>new x({shape:r,unknownKeys:"strip",catchall:j.create(),typeName:m.ZodObject,...v(e)});class Q extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function n(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new Z(o.ctx.common.issues));return u(t,{code:c.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(s.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(n);{let a;const i=[];for(const l of s){const d={...t,common:{...t.common,issues:[]},parent:null},p=l._parseSync({data:t.data,path:t.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!a&&(a={result:p,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(l=>new Z(l));return u(t,{code:c.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}}Q.create=(r,e)=>new Q({options:r,typeName:m.ZodUnion,...v(e)});const I=r=>r instanceof re?I(r.schema):r instanceof S?I(r.innerType()):r instanceof se?[r.value]:r instanceof $?r.options:r instanceof ne?g.objectValues(r.enum):r instanceof ae?I(r._def.innerType):r instanceof X?[void 0]:r instanceof K?[null]:r instanceof O?[void 0,...I(r.unwrap())]:r instanceof V?[null,...I(r.unwrap())]:r instanceof Ce||r instanceof oe?I(r.unwrap()):r instanceof ie?I(r._def.innerType):[];class ye extends y{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return u(t,{code:c.invalid_type,expected:f.object,received:t.parsedType}),_;const s=this.discriminator,n=t.data[s],a=this.optionsMap.get(n);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const n=new Map;for(const a of t){const i=I(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of i){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,a)}}return new ye({typeName:m.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...v(s)})}}function Ae(r,e){const t=N(r),s=N(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&s===f.object){const n=g.objectKeys(e),a=g.objectKeys(r).filter(o=>n.indexOf(o)!==-1),i={...r,...e};for(const o of a){const l=Ae(r[o],e[o]);if(!l.valid)return{valid:!1};i[o]=l.data}return{valid:!0,data:i}}else if(t===f.array&&s===f.array){if(r.length!==e.length)return{valid:!1};const n=[];for(let a=0;a{if(ke(a)||ke(i))return _;const o=Ae(a.value,i.value);return o.valid?((we(a)||we(i))&&t.dirty(),{status:t.value,value:o.data}):(u(s,{code:c.invalid_intersection_types}),_)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([a,i])=>n(a,i)):n(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}ee.create=(r,e,t)=>new ee({left:r,right:e,typeName:m.ZodIntersection,...v(t)});class A extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.array)return u(s,{code:c.invalid_type,expected:f.array,received:s.parsedType}),_;if(s.data.lengththis._def.items.length&&(u(s,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((i,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new R(s,i,s.path,o)):null}).filter(i=>!!i);return s.common.async?Promise.all(a).then(i=>k.mergeArray(t,i)):k.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new A({...this._def,rest:e})}}A.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new A({items:r,typeName:m.ZodTuple,rest:null,...v(e)})};class te extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.object)return u(s,{code:c.invalid_type,expected:f.object,received:s.parsedType}),_;const n=[],a=this._def.keyType,i=this._def.valueType;for(const o in s.data)n.push({key:a._parse(new R(s,o,s.path,o)),value:i._parse(new R(s,s.data[o],s.path,o)),alwaysSet:o in s.data});return s.common.async?k.mergeObjectAsync(t,n):k.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof y?new te({keyType:e,valueType:t,typeName:m.ZodRecord,...v(s)}):new te({keyType:C.create(),valueType:e,typeName:m.ZodRecord,...v(t)})}}class me extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.map)return u(s,{code:c.invalid_type,expected:f.map,received:s.parsedType}),_;const n=this._def.keyType,a=this._def.valueType,i=[...s.data.entries()].map(([o,l],d)=>({key:n._parse(new R(s,o,s.path,[d,"key"])),value:a._parse(new R(s,l,s.path,[d,"value"]))}));if(s.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of i){const d=await l.key,p=await l.value;if(d.status==="aborted"||p.status==="aborted")return _;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(d.value,p.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of i){const d=l.key,p=l.value;if(d.status==="aborted"||p.status==="aborted")return _;(d.status==="dirty"||p.status==="dirty")&&t.dirty(),o.set(d.value,p.value)}return{status:t.value,value:o}}}}me.create=(r,e,t)=>new me({valueType:e,keyType:r,typeName:m.ZodMap,...v(t)});class U extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==f.set)return u(s,{code:c.invalid_type,expected:f.set,received:s.parsedType}),_;const n=this._def;n.minSize!==null&&s.data.sizen.maxSize.value&&(u(s,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const a=this._def.valueType;function i(l){const d=new Set;for(const p of l){if(p.status==="aborted")return _;p.status==="dirty"&&t.dirty(),d.add(p.value)}return{status:t.value,value:d}}const o=[...s.data.values()].map((l,d)=>a._parse(new R(s,l,s.path,d)));return s.common.async?Promise.all(o).then(l=>i(l)):i(o)}min(e,t){return new U({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new U({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}U.create=(r,e)=>new U({valueType:r,minSize:null,maxSize:null,typeName:m.ZodSet,...v(e)});class B extends y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return u(t,{code:c.invalid_type,expected:f.function,received:t.parsedType}),_;function s(o,l){return fe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),W].filter(d=>!!d),issueData:{code:c.invalid_arguments,argumentsError:l}})}function n(o,l){return fe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,le(),W].filter(d=>!!d),issueData:{code:c.invalid_return_type,returnTypeError:l}})}const a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof J){const o=this;return w(async function(...l){const d=new Z([]),p=await o._def.args.parseAsync(l,a).catch(Ee=>{throw d.addIssue(s(l,Ee)),d}),T=await Reflect.apply(i,this,p);return await o._def.returns._def.type.parseAsync(T,a).catch(Ee=>{throw d.addIssue(n(T,Ee)),d})})}else{const o=this;return w(function(...l){const d=o._def.args.safeParse(l,a);if(!d.success)throw new Z([s(l,d.error)]);const p=Reflect.apply(i,this,d.data),T=o._def.returns.safeParse(p,a);if(!T.success)throw new Z([n(p,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new B({...this._def,args:A.create(e).rest(L.create())})}returns(e){return new B({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new B({args:e||A.create([]).rest(L.create()),returns:t||L.create(),typeName:m.ZodFunction,...v(s)})}}class re extends y{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}re.create=(r,e)=>new re({getter:r,typeName:m.ZodLazy,...v(e)});class se extends y{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:c.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}}se.create=(r,e)=>new se({value:r,typeName:m.ZodLiteral,...v(e)});function qe(r,e){return new $({values:r,typeName:m.ZodEnum,...v(e)})}class $ extends y{constructor(){super(...arguments),de.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{expected:g.joinValues(s),received:t.parsedType,code:c.invalid_type}),_}if(Te(this,de)||Fe(this,de,new Set(this._def.values)),!Te(this,de).has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return u(t,{received:t.data,code:c.invalid_enum_value,options:s}),_}return w(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return $.create(e,{...this._def,...t})}exclude(e,t=this._def){return $.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}de=new WeakMap;$.create=qe;class ne extends y{constructor(){super(...arguments),ue.set(this,void 0)}_parse(e){const t=g.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==f.string&&s.parsedType!==f.number){const n=g.objectValues(t);return u(s,{expected:g.joinValues(n),received:s.parsedType,code:c.invalid_type}),_}if(Te(this,ue)||Fe(this,ue,new Set(g.getValidEnumValues(this._def.values))),!Te(this,ue).has(e.data)){const n=g.objectValues(t);return u(s,{received:s.data,code:c.invalid_enum_value,options:n}),_}return w(e.data)}get enum(){return this._def.values}}ue=new WeakMap;ne.create=(r,e)=>new ne({values:r,typeName:m.ZodNativeEnum,...v(e)});class J extends y{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return u(t,{code:c.invalid_type,expected:f.promise,received:t.parsedType}),_;const s=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return w(s.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}J.create=(r,e)=>new J({type:r,typeName:m.ZodPromise,...v(e)});class S extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===m.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),n=this._def.effect||null,a={addIssue:i=>{u(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(a.addIssue=a.addIssue.bind(a),n.type==="preprocess"){const i=n.transform(s.data,a);if(s.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;const l=await this._def.schema._parseAsync({data:o,path:s.path,parent:s});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?F(l.value):l});{if(t.value==="aborted")return _;const o=this._def.schema._parseSync({data:i,path:s.path,parent:s});return o.status==="aborted"?_:o.status==="dirty"||t.value==="dirty"?F(o.value):o}}if(n.type==="refinement"){const i=o=>{const l=n.refinement(o,a);if(s.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(s.common.async===!1){const o=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!D(i))return i;const o=n.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>D(i)?Promise.resolve(n.transform(i.value,a)).then(o=>({status:t.value,value:o})):i);g.assertNever(n)}}S.create=(r,e,t)=>new S({schema:r,typeName:m.ZodEffects,effect:e,...v(t)});S.createWithPreprocess=(r,e,t)=>new S({schema:e,effect:{type:"preprocess",transform:r},typeName:m.ZodEffects,...v(t)});class O extends y{_parse(e){return this._getType(e)===f.undefined?w(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}O.create=(r,e)=>new O({innerType:r,typeName:m.ZodOptional,...v(e)});class V extends y{_parse(e){return this._getType(e)===f.null?w(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}V.create=(r,e)=>new V({innerType:r,typeName:m.ZodNullable,...v(e)});class ae extends y{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===f.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ae.create=(r,e)=>new ae({innerType:r,typeName:m.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});class ie extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return H(n)?n.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Z(s.common.issues)},input:s.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Z(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}ie.create=(r,e)=>new ie({innerType:r,typeName:m.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});class _e extends y{_parse(e){if(this._getType(e)!==f.nan){const s=this._getOrReturnCtx(e);return u(s,{code:c.invalid_type,expected:f.nan,received:s.parsedType}),_}return{status:"valid",value:e.data}}}_e.create=r=>new _e({typeName:m.ZodNaN,...v(r)});const Je=Symbol("zod_brand");class Ce extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class ce extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),F(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const n=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?_:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:s.path,parent:s})}}static create(e,t){return new ce({in:e,out:t,typeName:m.ZodPipeline})}}class oe extends y{_parse(e){const t=this._def.innerType._parse(e),s=n=>(D(n)&&(n.value=Object.freeze(n.value)),n);return H(t)?t.then(n=>s(n)):s(t)}unwrap(){return this._def.innerType}}oe.create=(r,e)=>new oe({innerType:r,typeName:m.ZodReadonly,...v(e)});function Ve(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Re(r,e={},t){return r?q.create().superRefine((s,n)=>{var a,i;const o=r(s);if(o instanceof Promise)return o.then(l=>{var d,p;if(!l){const T=Ve(e,s),ve=(p=(d=T.fatal)!==null&&d!==void 0?d:t)!==null&&p!==void 0?p:!0;n.addIssue({code:"custom",...T,fatal:ve})}});if(!o){const l=Ve(e,s),d=(i=(a=l.fatal)!==null&&a!==void 0?a:t)!==null&&i!==void 0?i:!0;n.addIssue({code:"custom",...l,fatal:d})}}):q.create()}const Ye={object:x.lazycreate};var m;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(m||(m={}));const He=(r,e={message:`Input not instance of ${r.name}`})=>Re(t=>t instanceof r,e),je=C.create,Ie=M.create,Ge=_e.create,Xe=P.create,Me=G.create,Ke=z.create,Qe=he.create,et=X.create,tt=K.create,rt=q.create,st=L.create,nt=j.create,at=pe.create,it=E.create,ot=x.create,ct=x.strictCreate,dt=Q.create,ut=ye.create,lt=ee.create,ft=A.create,ht=te.create,pt=me.create,mt=U.create,_t=B.create,yt=re.create,vt=se.create,gt=$.create,xt=ne.create,bt=J.create,Ze=S.create,kt=O.create,wt=V.create,Tt=S.createWithPreprocess,Zt=ce.create,St=()=>je().optional(),Ct=()=>Ie().optional(),Et=()=>Me().optional(),Ot={string:r=>C.create({...r,coerce:!0}),number:r=>M.create({...r,coerce:!0}),boolean:r=>G.create({...r,coerce:!0}),bigint:r=>P.create({...r,coerce:!0}),date:r=>z.create({...r,coerce:!0})},At=_;var b=Object.freeze({__proto__:null,defaultErrorMap:W,setErrorMap:ze,getErrorMap:le,makeIssue:fe,EMPTY_PATH:Ue,addIssueToContext:u,ParseStatus:k,INVALID:_,DIRTY:F,OK:w,isAborted:ke,isDirty:we,isValid:D,isAsync:H,get util(){return g},get objectUtil(){return be},ZodParsedType:f,getParsedType:N,ZodType:y,datetimeRegex:Ne,ZodString:C,ZodNumber:M,ZodBigInt:P,ZodBoolean:G,ZodDate:z,ZodSymbol:he,ZodUndefined:X,ZodNull:K,ZodAny:q,ZodUnknown:L,ZodNever:j,ZodVoid:pe,ZodArray:E,ZodObject:x,ZodUnion:Q,ZodDiscriminatedUnion:ye,ZodIntersection:ee,ZodTuple:A,ZodRecord:te,ZodMap:me,ZodSet:U,ZodFunction:B,ZodLazy:re,ZodLiteral:se,ZodEnum:$,ZodNativeEnum:ne,ZodPromise:J,ZodEffects:S,ZodTransformer:S,ZodOptional:O,ZodNullable:V,ZodDefault:ae,ZodCatch:ie,ZodNaN:_e,BRAND:Je,ZodBranded:Ce,ZodPipeline:ce,ZodReadonly:oe,custom:Re,Schema:y,ZodSchema:y,late:Ye,get ZodFirstPartyTypeKind(){return m},coerce:Ot,any:rt,array:it,bigint:Xe,boolean:Me,date:Ke,discriminatedUnion:ut,effect:Ze,enum:gt,function:_t,instanceof:He,intersection:lt,lazy:yt,literal:vt,map:pt,nan:Ge,nativeEnum:xt,never:nt,null:tt,nullable:wt,number:Ie,object:ot,oboolean:Et,onumber:Ct,optional:kt,ostring:St,pipeline:Zt,preprocess:Tt,promise:bt,record:ht,set:mt,strictObject:ct,string:je,symbol:Qe,transformer:Ze,tuple:ft,undefined:et,union:dt,unknown:st,void:at,NEVER:At,ZodIssueCode:c,quotelessJson:Le,ZodError:Z});const ir=Object.freeze(Object.defineProperty({__proto__:null,BRAND:Je,DIRTY:F,EMPTY_PATH:Ue,INVALID:_,NEVER:At,OK:w,ParseStatus:k,Schema:y,ZodAny:q,ZodArray:E,ZodBigInt:P,ZodBoolean:G,ZodBranded:Ce,ZodCatch:ie,ZodDate:z,ZodDefault:ae,ZodDiscriminatedUnion:ye,ZodEffects:S,ZodEnum:$,ZodError:Z,get ZodFirstPartyTypeKind(){return m},ZodFunction:B,ZodIntersection:ee,ZodIssueCode:c,ZodLazy:re,ZodLiteral:se,ZodMap:me,ZodNaN:_e,ZodNativeEnum:ne,ZodNever:j,ZodNull:K,ZodNullable:V,ZodNumber:M,ZodObject:x,ZodOptional:O,ZodParsedType:f,ZodPipeline:ce,ZodPromise:J,ZodReadonly:oe,ZodRecord:te,ZodSchema:y,ZodSet:U,ZodString:C,ZodSymbol:he,ZodTransformer:S,ZodTuple:A,ZodType:y,ZodUndefined:X,ZodUnion:Q,ZodUnknown:L,ZodVoid:pe,addIssueToContext:u,any:rt,array:it,bigint:Xe,boolean:Me,coerce:Ot,custom:Re,date:Ke,datetimeRegex:Ne,default:b,defaultErrorMap:W,discriminatedUnion:ut,effect:Ze,enum:gt,function:_t,getErrorMap:le,getParsedType:N,instanceof:He,intersection:lt,isAborted:ke,isAsync:H,isDirty:we,isValid:D,late:Ye,lazy:yt,literal:vt,makeIssue:fe,map:pt,nan:Ge,nativeEnum:xt,never:nt,null:tt,nullable:wt,number:Ie,object:ot,get objectUtil(){return be},oboolean:Et,onumber:Ct,optional:kt,ostring:St,pipeline:Zt,preprocess:Tt,promise:bt,quotelessJson:Le,record:ht,set:mt,setErrorMap:ze,strictObject:ct,string:je,symbol:Qe,transformer:Ze,tuple:ft,undefined:et,union:dt,unknown:st,get util(){return g},void:at,z:b},Symbol.toStringTag,{value:"Module"})),sr=[xe({name:"mcp_list_tools",description:"List all tools available on the MCP server",execute:async(r,e)=>await jt(),parameters:b.object({}),returns:b.object({})}),xe({name:"mcp_connect_server",description:"Connect to the MCP server",execute:async({command:r,args:e})=>(await Nt(r,e),"success"),parameters:b.object({command:b.string().describe("The command to connect to the MCP server"),args:b.array(b.string()).describe("The arguments to pass to the MCP server")}),returns:b.string().describe('If "success", the connection to the MCP server is successful. Otherwise, the connection fails.')}),xe({name:"mcp_disconnect_server",description:"Disconnect from the MCP server",execute:async()=>(await Rt(),"success"),parameters:b.object({}),returns:b.string().describe('If "success", the connection to the MCP server is successful. Otherwise, the connection fails.')}),xe({name:"mcp_call_tool",description:"Call a tool on the MCP server",execute:async({name:r,parameters:e})=>{const t=Object.fromEntries(e.map(({name:n,value:a})=>[n,a]));return await It(r,t)},parameters:b.object({name:b.string().describe("The name of the tool to call"),parameters:b.array(b.object({name:b.string().describe("The name of the parameter"),value:b.any().describe("The value of the parameter")})).describe("The parameters to pass to the tool")}),returns:b.object({content:b.array(b.object({type:b.string().describe("The type of the content"),text:b.string().describe("The text of the content")})).describe("The content of the tool call result"),isError:b.boolean().describe("Whether the tool call is an error")}).describe("The result of the tool call")})],or=async()=>Promise.all(sr);export{m as Z,O as a,ir as i,or as m,ar as t}; diff --git a/assets/memory-long-term-CRoA5-PX.js b/assets/memory-long-term-B-ZAjue9.js similarity index 71% rename from assets/memory-long-term-CRoA5-PX.js rename to assets/memory-long-term-B-ZAjue9.js index 893abc48094efa85e963881e581c3bee7e16b8c7..acb5d6aca7a256d65e92f1309ef85e53ff94343d 100644 --- a/assets/memory-long-term-CRoA5-PX.js +++ b/assets/memory-long-term-B-ZAjue9.js @@ -1 +1 @@ -import{d as o,c as t,o as n}from"./index-BQKiy4UR.js";import{b as e}from"./route-block-B_A1xBdJ.js";const r=o({__name:"memory-long-term",setup(c){return(m,a)=>(n(),t("div"))}});typeof e=="function"&&e(r);export{r as default}; +import{d as o,c as t,o as n}from"./index-CQudhZin.js";import{b as e}from"./route-block-B_A1xBdJ.js";const r=o({__name:"memory-long-term",setup(c){return(m,a)=>(n(),t("div"))}});typeof e=="function"&&e(r);export{r as default}; diff --git a/assets/memory-short-term-ivGgMFGG.js b/assets/memory-short-term-BPGQesh6.js similarity index 71% rename from assets/memory-short-term-ivGgMFGG.js rename to assets/memory-short-term-BPGQesh6.js index adfcb59e20e8eb91126c7a3872b63f4d264cbda5..77c7ce7b92dd67b162f667fad13f8123058412cc 100644 --- a/assets/memory-short-term-ivGgMFGG.js +++ b/assets/memory-short-term-BPGQesh6.js @@ -1 +1 @@ -import{d as o,c as t,o as r}from"./index-BQKiy4UR.js";import{b as e}from"./route-block-B_A1xBdJ.js";const n=o({__name:"memory-short-term",setup(c){return(m,a)=>(r(),t("div"))}});typeof e=="function"&&e(n);export{n as default}; +import{d as o,c as t,o as r}from"./index-CQudhZin.js";import{b as e}from"./route-block-B_A1xBdJ.js";const n=o({__name:"memory-short-term",setup(c){return(m,a)=>(r(),t("div"))}});typeof e=="function"&&e(n);export{n as default}; diff --git a/assets/messages-CUrOjMW7.js b/assets/messages-CNwMKqXh.js similarity index 68% rename from assets/messages-CUrOjMW7.js rename to assets/messages-CNwMKqXh.js index 172223ac9be8feee0926837d265dec3863f16825..2d7736993f2095b7b34a99f7e372c46f79595958 100644 --- a/assets/messages-CUrOjMW7.js +++ b/assets/messages-CNwMKqXh.js @@ -1 +1 @@ -import{u as c}from"./queue-DNS07_tB.js";import{b as g,l as _}from"./queues-C9_pVSeq.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as v}from"./Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js";import{d as b,r as a,c as l,o as r,e,i as x,b as k,t as p,F as h,l as w}from"./index-BQKiy4UR.js";import"./mini_xsschema-P_8cZcRg.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";const S={flex:"","flex-col":"","gap-2":"","p-2":""},V={flex:"","flex-row":"","gap-2":""},y={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},M={"w-full":"",flex:"","flex-row":"","gap-4":""},Q={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},L=b({__name:"messages",setup(B){const s=a(""),u=a([]),o=a(!1),m=c({handlers:[async i=>{u.value.push(i.data)}]}),d=g(m);async function f(){o.value=!0,d.add(s.value),d.add(_),s.value="",o.value=!1}return(i,t)=>(r(),l("div",S,[e("div",V,[x(k(v),{modelValue:s.value,"onUpdate:modelValue":t[0]||(t[0]=n=>s.value=n),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:f},null,8,["modelValue"]),e("button",y,p(o.value?"Processing...":"Send"),1)]),e("div",M,[e("div",Q,[t[1]||(t[1]=e("h3",{"font-semibold":""}," TTS Message ",-1)),(r(!0),l(h,null,w(u.value,n=>(r(),l("div",{key:n},[e("div",null,p(n),1)]))),128))])])]))}});export{L as default}; +import{u as c}from"./queue-3c99Yq5f.js";import{b as g,l as _}from"./queues-B-17ADgG.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as v}from"./Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js";import{d as b,r as a,c as l,o as r,e,i as x,b as k,t as p,F as h,l as w}from"./index-CQudhZin.js";import"./mini_xsschema-P_8cZcRg.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";const S={flex:"","flex-col":"","gap-2":"","p-2":""},V={flex:"","flex-row":"","gap-2":""},y={"rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-4":""},M={"w-full":"",flex:"","flex-row":"","gap-4":""},Q={"w-full":"","rounded-lg":"",bg:"neutral-100 dark:neutral-700","p-2":""},L=b({__name:"messages",setup(B){const s=a(""),u=a([]),o=a(!1),m=c({handlers:[async i=>{u.value.push(i.data)}]}),d=g(m);async function f(){o.value=!0,d.add(s.value),d.add(_),s.value="",o.value=!1}return(i,t)=>(r(),l("div",S,[e("div",V,[x(k(v),{modelValue:s.value,"onUpdate:modelValue":t[0]||(t[0]=n=>s.value=n),placeholder:"Message",p:"2",bg:"neutral-100 dark:neutral-700","w-full":"","rounded-lg":"","outline-none":"",onSubmit:f},null,8,["modelValue"]),e("button",y,p(o.value?"Processing...":"Send"),1)]),e("div",M,[e("div",Q,[t[1]||(t[1]=e("h3",{"font-semibold":""}," TTS Message ",-1)),(r(!0),l(h,null,w(u.value,n=>(r(),l("div",{key:n},[e("div",null,p(n),1)]))),128))])])]))}});export{L as default}; diff --git a/assets/microsoft-speech-Bg9KcYTS.js b/assets/microsoft-speech-B1rDo1CL.js similarity index 69% rename from assets/microsoft-speech-Bg9KcYTS.js rename to assets/microsoft-speech-B1rDo1CL.js index 8e43c332fb3ea69257d03d83c70605cbc873cd63..77259424211c0f08cdc68f4f0f2feda28faae0b0 100644 --- a/assets/microsoft-speech-Bg9KcYTS.js +++ b/assets/microsoft-speech-B1rDo1CL.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as B,g as F,s as M,r as v,h as g,H,v as K,A as N,o as T,w as b,i as n,b as o,e as q}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as z}from"./providers-kjOpfeNb.js";import{u as A}from"./speech-Db_L6FBm.js";import{_ as E}from"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import{_ as h}from"./FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as G,a as R}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js";import{b as k}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";const j={flex:"~ col gap-4"},t="microsoft-speech",C="v1",D=B({__name:"microsoft-speech",setup(I){const{t:r}=F(),P={pitch:0,speed:1,volume:0},a=A(),p=z(),{providers:l}=M(p),m=v(0),V=v(1),_=v(0),d=g({get:()=>{var s;return((s=l.value[t])==null?void 0:s.region)||"eastasia"},set:s=>{l.value[t]||(l.value[t]={region:"eastasia"}),l.value[t].region=s}}),y=g(()=>{var s;return!!((s=l.value[t])!=null&&s.apiKey)}),w=g(()=>a.availableVoices[t]||[]);H(async()=>{await a.loadVoicesForProvider(t)}),K([y,d],async()=>{await a.loadVoicesForProvider(t)});async function U(s,i,e){const c=p.getProviderInstance(t);if(!c)throw new Error("Failed to initialize speech provider");const u=p.getProviderConfig(t),x=u.model||C,S={...u,region:d.value,disableSsml:!e};if(!e&&i){const $=w.value.find(f=>f.id===i);if($){const f=a.generateSSML(s,$,{...u,pitch:m.value});return await a.speech(c,x,f,i,S)}}return await a.speech(c,x,s,i,S)}return(s,i)=>(T(),N(o(R),{"provider-id":t,"default-model":C,"additional-settings":P},{"basic-settings":b(()=>[n(o(E),{modelValue:d.value,"onUpdate:modelValue":i[0]||(i[0]=e=>d.value=e),label:o(r)("settings.pages.providers.provider.microsoft-speech.fields.field.region.label"),description:o(r)("settings.pages.providers.provider.microsoft-speech.fields.field.region.description"),placeholder:"eastasia",required:"",type:"text"},null,8,["modelValue","label","description"])]),"voice-settings":b(()=>[q("div",j,[n(o(h),{modelValue:m.value,"onUpdate:modelValue":i[1]||(i[1]=e=>m.value=e),label:o(r)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":e=>`${e}%`},null,8,["modelValue","label","description","format-value"]),n(o(h),{modelValue:V.value,"onUpdate:modelValue":i[2]||(i[2]=e=>V.value=e),label:o(r)("settings.pages.providers.provider.common.fields.field.speed.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"]),n(o(h),{modelValue:_.value,"onUpdate:modelValue":i[3]||(i[3]=e=>_.value=e),label:o(r)("settings.pages.providers.provider.common.fields.field.volume.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":e=>`${e}%`},null,8,["modelValue","label","description","format-value"])])]),playground:b(()=>[n(o(G),{"available-voices":w.value,"generate-speech":U,"api-key-configured":y.value,"default-text":"Hello! This is a test of the Microsoft Speech synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof k=="function"&&k(D);export{D as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as B,g as F,s as M,r as v,h as g,H,v as K,A as N,o as T,w as b,i as n,b as o,e as q}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as z}from"./providers-Y3Mr8_DF.js";import{u as A}from"./speech-nVAae-rt.js";import{_ as E}from"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import{_ as h}from"./FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as G,a as R}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js";import{b as k}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";const j={flex:"~ col gap-4"},t="microsoft-speech",C="v1",D=B({__name:"microsoft-speech",setup(I){const{t:r}=F(),P={pitch:0,speed:1,volume:0},a=A(),p=z(),{providers:l}=M(p),m=v(0),V=v(1),_=v(0),d=g({get:()=>{var s;return((s=l.value[t])==null?void 0:s.region)||"eastasia"},set:s=>{l.value[t]||(l.value[t]={region:"eastasia"}),l.value[t].region=s}}),y=g(()=>{var s;return!!((s=l.value[t])!=null&&s.apiKey)}),w=g(()=>a.availableVoices[t]||[]);H(async()=>{await a.loadVoicesForProvider(t)}),K([y,d],async()=>{await a.loadVoicesForProvider(t)});async function U(s,i,e){const c=p.getProviderInstance(t);if(!c)throw new Error("Failed to initialize speech provider");const u=p.getProviderConfig(t),x=u.model||C,S={...u,region:d.value,disableSsml:!e};if(!e&&i){const $=w.value.find(f=>f.id===i);if($){const f=a.generateSSML(s,$,{...u,pitch:m.value});return await a.speech(c,x,f,i,S)}}return await a.speech(c,x,s,i,S)}return(s,i)=>(T(),N(o(R),{"provider-id":t,"default-model":C,"additional-settings":P},{"basic-settings":b(()=>[n(o(E),{modelValue:d.value,"onUpdate:modelValue":i[0]||(i[0]=e=>d.value=e),label:o(r)("settings.pages.providers.provider.microsoft-speech.fields.field.region.label"),description:o(r)("settings.pages.providers.provider.microsoft-speech.fields.field.region.description"),placeholder:"eastasia",required:"",type:"text"},null,8,["modelValue","label","description"])]),"voice-settings":b(()=>[q("div",j,[n(o(h),{modelValue:m.value,"onUpdate:modelValue":i[1]||(i[1]=e=>m.value=e),label:o(r)("settings.pages.providers.provider.common.fields.field.pitch.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.pitch.description"),min:-100,max:100,step:1,"format-value":e=>`${e}%`},null,8,["modelValue","label","description","format-value"]),n(o(h),{modelValue:V.value,"onUpdate:modelValue":i[2]||(i[2]=e=>V.value=e),label:o(r)("settings.pages.providers.provider.common.fields.field.speed.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"]),n(o(h),{modelValue:_.value,"onUpdate:modelValue":i[3]||(i[3]=e=>_.value=e),label:o(r)("settings.pages.providers.provider.common.fields.field.volume.label"),description:o(r)("settings.pages.providers.provider.common.fields.field.volume.description"),min:-100,max:100,step:1,"format-value":e=>`${e}%`},null,8,["modelValue","label","description","format-value"])])]),playground:b(()=>[n(o(G),{"available-voices":w.value,"generate-speech":U,"api-key-configured":y.value,"default-text":"Hello! This is a test of the Microsoft Speech synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof k=="function"&&k(D);export{D as default}; diff --git a/assets/mistral-ai-BaBOYsbt.js b/assets/mistral-ai-CCjWqN_I.js similarity index 66% rename from assets/mistral-ai-BaBOYsbt.js rename to assets/mistral-ai-CCjWqN_I.js index ed5243fb05196c220be976cab2a5541f3d81ec04..369302ff9e0807d495754496a8d2f0c3e3717645 100644 --- a/assets/mistral-ai-BaBOYsbt.js +++ b/assets/mistral-ai-CCjWqN_I.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as V,g as k,S as y,s as $,h as c,H as K,v as h,A as S,o as w,w as p,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const a="mistral-ai",B=V({__name:"mistral-ai",setup(I){const{t:u}=k(),b=y(),d=x(),{providers:o}=$(d),n=c(()=>d.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}}),s=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}});K(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),h([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var v,f;return w(),S(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(b).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:p(()=>{var m;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=U=>r.value=U),"provider-name":(m=n.value)==null?void 0:m.localizedName,placeholder:"mis-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=m=>s.value=m),placeholder:"https://api.mistral.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as V,g as k,S as y,s as $,h as c,H as K,v as h,A as S,o as w,w as p,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const a="mistral-ai",B=V({__name:"mistral-ai",setup(I){const{t:u}=k(),b=y(),d=x(),{providers:o}=$(d),n=c(()=>d.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}}),s=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}});K(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),h([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var v,f;return w(),S(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(b).back()},{default:p(()=>[l(t(N),null,{default:p(()=>[l(t(P),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:p(()=>{var m;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=U=>r.value=U),"provider-name":(m=n.value)==null?void 0:m.localizedName,placeholder:"mis-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=m=>s.value=m),placeholder:"https://api.mistral.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; diff --git a/assets/moonshot-ai-CpWLI90H.js b/assets/moonshot-ai-Og7KMbxi.js similarity index 66% rename from assets/moonshot-ai-CpWLI90H.js rename to assets/moonshot-ai-Og7KMbxi.js index 3b38cd90de14acf29023c30600f0779c19bb313f..fb6d7a70eb0aa101a2a9ef5eb1f5ff518c695b93 100644 --- a/assets/moonshot-ai-CpWLI90H.js +++ b/assets/moonshot-ai-Og7KMbxi.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as U,g as V,S as k,s as y,h as v,H as $,v as K,A as S,o as w,w as p,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const o="moonshot-ai",C=U({__name:"moonshot-ai",setup(I){const{t:u}=V(),b=k(),d=x(),{providers:a}=y(d),n=v(()=>d.getProviderMetadata(o)),s=v({get:()=>{var e;return((e=a.value[o])==null?void 0:e.apiKey)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].apiKey=e}}),r=v({get:()=>{var e;return((e=a.value[o])==null?void 0:e.baseUrl)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].baseUrl=e}});$(()=>{var e,i;d.initializeProvider(o),s.value=((e=a.value[o])==null?void 0:e.apiKey)||"",r.value=((i=a.value[o])==null?void 0:i.baseUrl)||""}),K([s,r],()=>{a.value[o]={...a.value[o],apiKey:s.value,baseUrl:r.value||""}});function g(){var e;a.value[o]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return w(),S(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:p(()=>[l(t(P),null,{default:p(()=>[l(t(R),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:p(()=>{var m;return[l(t(N),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=h=>s.value=h),"provider-name":(m=n.value)==null?void 0:m.localizedName,placeholder:"ms-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=m=>r.value=m),placeholder:"https://api.moonshot.cn/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as U,g as V,S as k,s as y,h as v,H as $,v as K,A as S,o as w,w as p,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const o="moonshot-ai",C=U({__name:"moonshot-ai",setup(I){const{t:u}=V(),b=k(),d=x(),{providers:a}=y(d),n=v(()=>d.getProviderMetadata(o)),s=v({get:()=>{var e;return((e=a.value[o])==null?void 0:e.apiKey)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].apiKey=e}}),r=v({get:()=>{var e;return((e=a.value[o])==null?void 0:e.baseUrl)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].baseUrl=e}});$(()=>{var e,i;d.initializeProvider(o),s.value=((e=a.value[o])==null?void 0:e.apiKey)||"",r.value=((i=a.value[o])==null?void 0:i.baseUrl)||""}),K([s,r],()=>{a.value[o]={...a.value[o],apiKey:s.value,baseUrl:r.value||""}});function g(){var e;a.value[o]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return w(),S(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:p(()=>[l(t(P),null,{default:p(()=>[l(t(R),{title:t(u)("settings.pages.providers.common.section.basic.title"),description:t(u)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:p(()=>{var m;return[l(t(N),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=h=>s.value=h),"provider-name":(m=n.value)==null?void 0:m.localizedName,placeholder:"ms-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(u)("settings.pages.providers.common.section.advanced.title")},{default:p(()=>[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=m=>r.value=m),placeholder:"https://api.moonshot.cn/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; diff --git a/assets/novita-ai-pNiSEK4a.js b/assets/novita-ai-BiraQuur.js similarity index 66% rename from assets/novita-ai-pNiSEK4a.js rename to assets/novita-ai-BiraQuur.js index 05a2b3aafcbaaa5979766a03e85064ac8e1afb9f..c4415a7cbb4901fa277336b240829892cecdadbd 100644 --- a/assets/novita-ai-pNiSEK4a.js +++ b/assets/novita-ai-BiraQuur.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as V,g as k,S as y,s as $,h as v,H as K,v as h,A as S,o as w,w as u,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const a="novita-ai",B=V({__name:"novita-ai",setup(I){const{t:m}=k(),b=y(),d=x(),{providers:o}=$(d),n=v(()=>d.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}});K(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),h([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return w(),S(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(b).back()},{default:u(()=>[l(t(N),null,{default:u(()=>[l(t(P),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=U=>r.value=U),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"nvt-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.novita.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as V,g as k,S as y,s as $,h as v,H as K,v as h,A as S,o as w,w as u,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const a="novita-ai",B=V({__name:"novita-ai",setup(I){const{t:m}=k(),b=y(),d=x(),{providers:o}=$(d),n=v(()=>d.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}});K(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),h([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return w(),S(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(b).back()},{default:u(()=>[l(t(N),null,{default:u(()=>[l(t(P),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(M),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=U=>r.value=U),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"nvt-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.novita.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; diff --git a/assets/ollama-lxq_i-rm.js b/assets/ollama-Bin1uANJ.js similarity index 81% rename from assets/ollama-lxq_i-rm.js rename to assets/ollama-Bin1uANJ.js index ff8c8f000eea9d139671c1df84de4d505e377ff0..e0414fb0861e8a4a8a45934ba77f9adb326f5813 100644 --- a/assets/ollama-lxq_i-rm.js +++ b/assets/ollama-Bin1uANJ.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as K,m as x,u as U,c as g,o as f,i as m,r as w,v as B,K as S,e as _,x as O,k as R,j as z,t as $,F as D,l as F,g as I,S as A,s as T,h as M,H as j,av as E,A as H,w as V,b as o}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as L}from"./providers-kjOpfeNb.js";import{_ as q}from"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{a as G,_ as J}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as Q,a as W}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as X}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as C}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";const Y={flex:"~ gap-2"},Z=K({__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 a=v,s=U(v,"propertyKey"),u=U(v,"propertyValue");return(r,t)=>(f(),g("div",Y,[m(q,{modelValue:s.value,"onUpdate:modelValue":t[0]||(t[0]=i=>s.value=i),placeholder:a.keyPlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"]),m(q,{modelValue:u.value,"onUpdate:modelValue":t[1]||(t[1]=i=>u.value=i),placeholder:a.valuePlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"])]))}}),ee={"max-w-full":""},le={flex:"~ col gap-2"},te={class:"flex items-center gap-1 text-sm font-medium"},oe={key:0,class:"text-red-500"},ae={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},re={flex:"~ col gap-2"},se=["onClick"],ie=K({__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:a}){const s=v,u=a,r=U(v,"modelValue"),t=w(""),i=w("");return B([t,i],()=>{u("add",t.value,i.value)}),(P,p)=>{const b=S("auto-animate");return f(),g("div",ee,[_("label",le,[_("div",null,[_("div",te,[R($(s.label)+" ",1),s.required!==!1?(f(),g("span",oe,"*")):z("",!0)]),_("div",ae,$(s.description),1)]),O((f(),g("div",re,[(f(!0),g(D,null,F(r.value,(y,l)=>(f(),g("div",{key:l,"w-full":"",flex:"","items-center":"","gap-2":""},[m(Z,{"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,se)]))),128))])),[[b]])])])}}}),d="ollama",ne=K({__name:"ollama",setup(v){const{t:a}=I(),s=A(),u=L(),{providers:r}=T(u),t=M(()=>u.getProviderMetadata(d)),i=M({get:()=>{var l,e,n;return((l=r.value[d])==null?void 0:l.baseUrl)||((n=(e=t.value)==null?void 0:e.defaultOptions)==null?void 0:n.baseUrl)||""},set:l=>{r.value[d]||(r.value[d]={}),r.value[d].baseUrl=l}});j(()=>{var l,e,n,h;u.initializeProvider(d),i.value=((l=r.value[d])==null?void 0:l.baseUrl)||((n=(e=t.value)==null?void 0:e.defaultOptions)==null?void 0:n.baseUrl)||"",(h=r.value[d])!=null&&h.headers||(r.value[d].headers={})});function P(){var l;r.value[d]={...(l=t.value)==null?void 0:l.defaultOptions}}const p=E([{key:"",value:""}]);function b(l,e,n){l&&l.push({key:e,value:n})}function y(l,e){e&&(e.length===1?(e[0].key="",e[0].value=""):e.splice(l,1))}return B(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 n,h;return f(),H(o(X),{"provider-name":(n=t.value)==null?void 0:n.localizedName,"provider-icon":(h=t.value)==null?void 0:h.icon,"on-back":()=>o(s).back()},{default:V(()=>[m(o(Q),null,{default:V(()=>[m(o(W),{title:o(a)("settings.pages.providers.common.section.basic.title"),description:o(a)("settings.pages.providers.common.section.basic.description"),"on-reset":P},{default:V(()=>{var c,k;return[m(o(G),{modelValue:i.value,"onUpdate:modelValue":e[0]||(e[0]=N=>i.value=N),placeholder:((k=(c=t.value)==null?void 0:c.defaultOptions)==null?void 0:k.baseUrl)||"",required:""},null,8,["modelValue","placeholder"])]}),_:1},8,["title","description"]),m(o(J),{title:o(a)("settings.pages.providers.common.section.advanced.title")},{default:V(()=>[m(o(ie),{modelValue:p,"onUpdate:modelValue":e[1]||(e[1]=c=>p=c),label:o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.label"),description:o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.description"),"key-placeholder":o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.key.placeholder"),"value-placeholder":o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.value.placeholder"),onAdd:e[2]||(e[2]=(c,k)=>b(p,c,k)),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"])}}});typeof C=="function"&&C(ne);export{ne as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as K,m as x,u as U,c as g,o as f,i as m,r as w,v as B,K as S,e as _,x as O,k as R,j as z,t as $,F as D,l as F,g as I,S as T,s as A,h as M,H as j,aT as E,A as H,w as V,b as o}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as L}from"./providers-Y3Mr8_DF.js";import{_ as q}from"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{a as G,_ as J}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as Q,a as W}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as X}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as C}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";const Y={flex:"~ gap-2"},Z=K({__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 a=v,s=U(v,"propertyKey"),u=U(v,"propertyValue");return(r,t)=>(f(),g("div",Y,[m(q,{modelValue:s.value,"onUpdate:modelValue":t[0]||(t[0]=i=>s.value=i),placeholder:a.keyPlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"]),m(q,{modelValue:u.value,"onUpdate:modelValue":t[1]||(t[1]=i=>u.value=i),placeholder:a.valuePlaceholder,class:"w-1/2"},null,8,["modelValue","placeholder"])]))}}),ee={"max-w-full":""},le={flex:"~ col gap-2"},te={class:"flex items-center gap-1 text-sm font-medium"},oe={key:0,class:"text-red-500"},ae={class:"text-xs text-neutral-500 dark:text-neutral-400","text-nowrap":""},re={flex:"~ col gap-2"},se=["onClick"],ie=K({__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:a}){const s=v,u=a,r=U(v,"modelValue"),t=w(""),i=w("");return B([t,i],()=>{u("add",t.value,i.value)}),(P,p)=>{const b=S("auto-animate");return f(),g("div",ee,[_("label",le,[_("div",null,[_("div",te,[R($(s.label)+" ",1),s.required!==!1?(f(),g("span",oe,"*")):z("",!0)]),_("div",ae,$(s.description),1)]),O((f(),g("div",re,[(f(!0),g(D,null,F(r.value,(y,l)=>(f(),g("div",{key:l,"w-full":"",flex:"","items-center":"","gap-2":""},[m(Z,{"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,se)]))),128))])),[[b]])])])}}}),d="ollama",ne=K({__name:"ollama",setup(v){const{t:a}=I(),s=T(),u=L(),{providers:r}=A(u),t=M(()=>u.getProviderMetadata(d)),i=M({get:()=>{var l,e,n;return((l=r.value[d])==null?void 0:l.baseUrl)||((n=(e=t.value)==null?void 0:e.defaultOptions)==null?void 0:n.baseUrl)||""},set:l=>{r.value[d]||(r.value[d]={}),r.value[d].baseUrl=l}});j(()=>{var l,e,n,h;u.initializeProvider(d),i.value=((l=r.value[d])==null?void 0:l.baseUrl)||((n=(e=t.value)==null?void 0:e.defaultOptions)==null?void 0:n.baseUrl)||"",(h=r.value[d])!=null&&h.headers||(r.value[d].headers={})});function P(){var l;r.value[d]={...(l=t.value)==null?void 0:l.defaultOptions}}const p=E([{key:"",value:""}]);function b(l,e,n){l&&l.push({key:e,value:n})}function y(l,e){e&&(e.length===1?(e[0].key="",e[0].value=""):e.splice(l,1))}return B(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 n,h;return f(),H(o(X),{"provider-name":(n=t.value)==null?void 0:n.localizedName,"provider-icon":(h=t.value)==null?void 0:h.icon,"on-back":()=>o(s).back()},{default:V(()=>[m(o(Q),null,{default:V(()=>[m(o(W),{title:o(a)("settings.pages.providers.common.section.basic.title"),description:o(a)("settings.pages.providers.common.section.basic.description"),"on-reset":P},{default:V(()=>{var c,k;return[m(o(G),{modelValue:i.value,"onUpdate:modelValue":e[0]||(e[0]=N=>i.value=N),placeholder:((k=(c=t.value)==null?void 0:c.defaultOptions)==null?void 0:k.baseUrl)||"",required:""},null,8,["modelValue","placeholder"])]}),_:1},8,["title","description"]),m(o(J),{title:o(a)("settings.pages.providers.common.section.advanced.title")},{default:V(()=>[m(o(ie),{modelValue:p,"onUpdate:modelValue":e[1]||(e[1]=c=>p=c),label:o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.label"),description:o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.description"),"key-placeholder":o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.key.placeholder"),"value-placeholder":o(a)("settings.pages.providers.common.section.advanced.fields.field.headers.value.placeholder"),onAdd:e[2]||(e[2]=(c,k)=>b(p,c,k)),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"])}}});typeof C=="function"&&C(ne);export{ne as default}; diff --git a/assets/openai-DQmuApR5.js b/assets/openai-BPj3vm_3.js similarity index 68% rename from assets/openai-DQmuApR5.js rename to assets/openai-BPj3vm_3.js index e980767e33f0fc7a6c3cdb1563434260afc7e645..a72107ae0cabc8165bdc4682afd1621079e9cfff 100644 --- a/assets/openai-DQmuApR5.js +++ b/assets/openai-BPj3vm_3.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as U,g as k,S as V,s as y,h as v,H as $,v as K,A as I,o as S,w as n,i as p,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as w}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as x,a as A}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as N,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as z}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const e="openai",B=U({__name:"openai",setup(C){const{t:m}=k(),b=V(),c=w(),{providers:a}=y(c),u=v(()=>c.getProviderMetadata(e)),s=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}});$(()=>{var o,i;a.value[e]||(a.value[e]={baseUrl:"https://api.openai.com/v1/"}),s.value=((o=a.value[e])==null?void 0:o.apiKey)||"",r.value=((i=a.value[e])==null?void 0:i.baseUrl)||"https://api.openai.com/v1/"}),K([s,r],()=>{a.value[e]={...a.value[e],apiKey:s.value,baseUrl:r.value||"https://api.openai.com/v1/"}});function g(){a.value[e]={baseUrl:"https://api.openai.com/v1/"}}return(o,i)=>{var d,f;return S(),I(t(z),{"provider-name":((d=u.value)==null?void 0:d.localizedName)||"OpenAI","provider-icon":(f=u.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:n(()=>[p(t(N),null,{default:n(()=>[p(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:n(()=>{var l;return[p(t(M),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=h=>s.value=h),"provider-name":((l=u.value)==null?void 0:l.localizedName)||"OpenAI",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),p(t(x),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:n(()=>[p(t(A),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=l=>r.value=l),placeholder:"https://api.openai.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as U,g as k,S as V,s as y,h as v,H as $,v as K,A as I,o as S,w as n,i as p,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as w}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as x,a as A}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as N,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as z}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const e="openai",B=U({__name:"openai",setup(C){const{t:m}=k(),b=V(),c=w(),{providers:a}=y(c),u=v(()=>c.getProviderMetadata(e)),s=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}});$(()=>{var o,i;a.value[e]||(a.value[e]={baseUrl:"https://api.openai.com/v1/"}),s.value=((o=a.value[e])==null?void 0:o.apiKey)||"",r.value=((i=a.value[e])==null?void 0:i.baseUrl)||"https://api.openai.com/v1/"}),K([s,r],()=>{a.value[e]={...a.value[e],apiKey:s.value,baseUrl:r.value||"https://api.openai.com/v1/"}});function g(){a.value[e]={baseUrl:"https://api.openai.com/v1/"}}return(o,i)=>{var d,f;return S(),I(t(z),{"provider-name":((d=u.value)==null?void 0:d.localizedName)||"OpenAI","provider-icon":(f=u.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:n(()=>[p(t(N),null,{default:n(()=>[p(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:n(()=>{var l;return[p(t(M),{modelValue:s.value,"onUpdate:modelValue":i[0]||(i[0]=h=>s.value=h),"provider-name":((l=u.value)==null?void 0:l.localizedName)||"OpenAI",placeholder:"sk-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),p(t(x),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:n(()=>[p(t(A),{modelValue:r.value,"onUpdate:modelValue":i[1]||(i[1]=l=>r.value=l),placeholder:"https://api.openai.com/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; diff --git a/assets/openrouter-ai-DJMkew1w.js b/assets/openrouter-ai-WP7_lFby.js similarity index 68% rename from assets/openrouter-ai-DJMkew1w.js rename to assets/openrouter-ai-WP7_lFby.js index fa2cf0b7b2b6d4f7ad3d49a2802db4af57cfe26e..e292d41f8069082b2c5e5b8cfe30fe54505a6b8a 100644 --- a/assets/openrouter-ai-DJMkew1w.js +++ b/assets/openrouter-ai-WP7_lFby.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as V,g as y,S as $,s as K,h as _,H as O,v as h,A as S,o as w,w as v,i as d,b as r}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const a="openrouter-ai",C=V({__name:"openrouter-ai",setup(I){const{t:c}=y(),g=$(),f=x(),{providers:o}=K(f),i=_(()=>f.getProviderMetadata(a)),l=_({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,s;return((e=o.value[a])==null?void 0:e.baseUrl)||((s=(t=i.value)==null?void 0:t.defaultOptions)==null?void 0:s.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});O(()=>{var e,t,s,u;f.initializeProvider(a),l.value=((e=o.value[a])==null?void 0:e.apiKey)||"",n.value=((t=o.value[a])==null?void 0:t.baseUrl)||((u=(s=i.value)==null?void 0:s.defaultOptions)==null?void 0:u.baseUrl)||""}),h([l,n],()=>{var e,t;o.value[a]={...o.value[a],apiKey:l.value,baseUrl:n.value||((t=(e=i.value)==null?void 0:e.defaultOptions)==null?void 0:t.baseUrl)||""}});function U(){var e;o.value[a]={...(e=i.value)==null?void 0:e.defaultOptions}}return(e,t)=>{var s,u;return w(),S(r(B),{"provider-name":(s=i.value)==null?void 0:s.localizedName,"provider-icon":(u=i.value)==null?void 0:u.icon,"on-back":()=>r(g).back()},{default:v(()=>[d(r(P),null,{default:v(()=>[d(r(R),{title:r(c)("settings.pages.providers.common.section.basic.title"),description:r(c)("settings.pages.providers.common.section.basic.description"),"on-reset":U},{default:v(()=>{var p;return[d(r(N),{modelValue:l.value,"onUpdate:modelValue":t[0]||(t[0]=m=>l.value=m),"provider-name":(p=i.value)==null?void 0:p.localizedName,placeholder:"sk-or-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),d(r(z),{title:r(c)("settings.pages.providers.common.section.advanced.title")},{default:v(()=>{var p,m;return[d(r(M),{modelValue:n.value,"onUpdate:modelValue":t[1]||(t[1]=k=>n.value=k),placeholder:((m=(p=i.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"])}}});typeof b=="function"&&b(C);export{C as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as V,g as y,S as $,s as K,h as _,H as O,v as h,A as S,o as w,w as v,i as d,b as r}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as x}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const a="openrouter-ai",C=V({__name:"openrouter-ai",setup(I){const{t:c}=y(),g=$(),f=x(),{providers:o}=K(f),i=_(()=>f.getProviderMetadata(a)),l=_({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,s;return((e=o.value[a])==null?void 0:e.baseUrl)||((s=(t=i.value)==null?void 0:t.defaultOptions)==null?void 0:s.baseUrl)||""},set:e=>{o.value[a]||(o.value[a]={}),o.value[a].baseUrl=e}});O(()=>{var e,t,s,u;f.initializeProvider(a),l.value=((e=o.value[a])==null?void 0:e.apiKey)||"",n.value=((t=o.value[a])==null?void 0:t.baseUrl)||((u=(s=i.value)==null?void 0:s.defaultOptions)==null?void 0:u.baseUrl)||""}),h([l,n],()=>{var e,t;o.value[a]={...o.value[a],apiKey:l.value,baseUrl:n.value||((t=(e=i.value)==null?void 0:e.defaultOptions)==null?void 0:t.baseUrl)||""}});function U(){var e;o.value[a]={...(e=i.value)==null?void 0:e.defaultOptions}}return(e,t)=>{var s,u;return w(),S(r(B),{"provider-name":(s=i.value)==null?void 0:s.localizedName,"provider-icon":(u=i.value)==null?void 0:u.icon,"on-back":()=>r(g).back()},{default:v(()=>[d(r(P),null,{default:v(()=>[d(r(R),{title:r(c)("settings.pages.providers.common.section.basic.title"),description:r(c)("settings.pages.providers.common.section.basic.description"),"on-reset":U},{default:v(()=>{var p;return[d(r(N),{modelValue:l.value,"onUpdate:modelValue":t[0]||(t[0]=m=>l.value=m),"provider-name":(p=i.value)==null?void 0:p.localizedName,placeholder:"sk-or-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),d(r(z),{title:r(c)("settings.pages.providers.common.section.advanced.title")},{default:v(()=>{var p,m;return[d(r(M),{modelValue:n.value,"onUpdate:modelValue":t[1]||(t[1]=k=>n.value=k),placeholder:((m=(p=i.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"])}}});typeof b=="function"&&b(C);export{C as default}; diff --git a/assets/providers-Y3Mr8_DF.js b/assets/providers-Y3Mr8_DF.js new file mode 100644 index 0000000000000000000000000000000000000000..02e2dd2d3d356c67d21ac3acd41172c1f5e0572a --- /dev/null +++ b/assets/providers-Y3Mr8_DF.js @@ -0,0 +1 @@ +import{p as oe,q as le,g as de,r as q,v as ce,h as w}from"./index-CQudhZin.js";import{r as Z,a as R,e as ee,o as k}from"./index-LHmcipjy.js";const b=async a=>(a.fetch??globalThis.fetch)(Z("models",a.baseURL),{headers:R(a.headers,a.apiKey),signal:a.abortSignal}).then(ee).then(({data:i})=>i),_=a=>({chat:i=>Object.assign(a,{model:i})}),K=a=>({embed:i=>Object.assign(a,{model:i})}),pe=a=>({image:i=>Object.assign(a,{model:i})}),f=a=>({model:()=>a}),ue=a=>({speech:i=>Object.assign(a,{model:i})}),ge=a=>({transcription:i=>Object.assign(a,{model:i})}),m=(a,i)=>({metadata:{id:a,...i}}),p=(...a)=>Object.assign(a[0],...a.slice(1)),me=(a,i="https://api.anthropic.com/v1/")=>p(m("anthropic"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),L=(a,i="https://api.deepseek.com/")=>p(m("deepseek"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),G=(a,i="https://api.fireworks.ai/inference/v1/")=>p(m("fireworks"),_({apiKey:a,baseURL:i}),K({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),$=(a,i="https://generativelanguage.googleapis.com/v1beta/openai/")=>p(m("google-generative-ai"),_({apiKey:a,baseURL:i}),K({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),D=(a,i="https://api.mistral.ai/v1/")=>p(m("mistral"),_({apiKey:a,baseURL:i}),K({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),V=(a,i="https://api.moonshot.cn/v1/")=>p(m("moonshot"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),N=(a,i="https://api.novita.ai/v3/openai/")=>p(m("novita"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),S=(a,i="https://api.openai.com/v1/")=>p(m("openai"),_({apiKey:a,baseURL:i}),K({apiKey:a,baseURL:i}),pe({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i}),ue({apiKey:a,baseURL:i}),ge({apiKey:a,baseURL:i})),ve=(a,i="")=>p(m("openrouter"),{chat:(d,o)=>{const h={apiKey:a,baseURL:i,model:d};return{...o?(({extraHeaders:n,models:v,provider:g})=>{n!=null&&(h.headers??(h.headers={}),Object.assign(h.headers,n));let c;return g!=null&&(c=k(g)),k({models:v,provider:c})})(o):{},...h}}},f({apiKey:a,baseURL:i})),_e=(a,i="https://api.perplexity.ai/")=>p(m("perplexity"),_({apiKey:a,baseURL:i})),W=(a,i="https://api.together.xyz/v1/")=>p(m("together-ai"),_({apiKey:a,baseURL:i}),K({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i,fetch:async(...d)=>globalThis.fetch(...d).then(async o=>o.json()).then(o=>Response.json({data:o,object:"list"}))})),he=(a,i)=>{const d=`https://api.cloudflare.com/client/v4/accounts/${i}/ai/v1/`;return p(m("workers-ai"),_({apiKey:a,baseURL:d}),K({apiKey:a,baseURL:d}))},H=(a,i="https://api.x.ai/v1/")=>p(m("xai"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),A=(a="http://localhost:11434/v1/")=>p(m("ollama"),_({baseURL:a}),K({baseURL:a}),f({baseURL:a}));var J=(a,i="http://localhost:5933/v1/")=>{const d=({applyTextNormalization:t,languageCode:n,nextRequestIds:v,nextText:g,previousRequestIds:c,previousText:y,pronunciationDictionaryLocators:x,seed:M,voiceSettings:C})=>({extraBody:k({applyTextNormalization:t,languageCode:n,nextRequestIds:v,nextText:g,previousRequestIds:c,previousText:y,pronunciationDictionaryLocators:x?x.map(B=>k(B)):void 0,seed:M,voiceSettings:k(C??{similarityBoost:.75,stability:.5})})});return p({speech:(t,n)=>({...n?d(n):{},apiKey:a,baseURL:i,model:`elevenlabs/${t}`})},{voice:t=>(i.endsWith("v1/")?i=i.slice(0,-3):i.endsWith("v1")&&(i=i.slice(0,-2)),{query:"provider=elevenlabs",...t?d(t):{},apiKey:a,baseURL:i})})},X=(a,i="http://localhost:5933/v1/")=>{const d=t=>{const{deploymentId:n,region:v,sampleRate:g}=t,c={deploymentId:n,region:v,sampleRate:g};return"disableSsml"in t?c.disableSsml=t.disableSsml:"lang"in t&&(c.lang=t.lang,c.gender=t.gender,c.voice=t.voice),{extraBody:k(c)}};return p({speech:(t,n)=>({...n?d(n):{},apiKey:a,baseURL:i,model:`microsoft/${t}`})},{voice:t=>(i.endsWith("v1/")?i=i.slice(0,-3):i.endsWith("v1")&&(i=i.slice(0,-2)),{query:`region=${t==null?void 0:t.region}&provider=microsoft`,...t?d(t):{},apiKey:a,baseURL:i})})},Q=(a,i="http://localhost:5933/v1/")=>{const d=t=>{var v,g;const n={app:{appid:(v=t.app)==null?void 0:v.appId,token:a}};return typeof t.app<"u"&&(n.app={...t.app,appid:(g=t.app)==null?void 0:g.appId,token:a}),typeof t.user<"u"&&(n.user=t.user),typeof t.audio<"u"&&(n.audio=t.audio),{extraBody:k(n)}};return p({speech:(t,n)=>({...n?d(n):{},apiKey:a,baseURL:i,model:`volcengine/${t}`})},{voice:t=>(i.endsWith("v1/")?i=i.slice(0,-3):i.endsWith("v1")&&(i=i.slice(0,-2)),{query:"provider=volcengine",...t?d(t):{},apiKey:a,baseURL:i})})},Y=(a,i="http://localhost:5933/v1/")=>{const d=t=>{const{sampleRate:n,volume:v,rate:g,pitch:c}=t,y={sampleRate:n,volume:v,rate:g,pitch:c};return Object.keys(y).forEach(x=>y[x]===void 0&&delete y[x]),{extraBody:k(y)}};return p({speech:(t,n)=>({...n?d(n):{},apiKey:a,baseURL:i,model:`alibaba/${t}`})},{voice:t=>{let n=i;return n.endsWith("v1/")?n=n.slice(0,-3):n.endsWith("v1")&&(n=n.slice(0,-2)),{query:"provider=alibaba",...t?d(t):{},apiKey:a,baseURL:n}}})},E=async a=>(a.fetch??globalThis.fetch)(Z(a.query?`api/voices?${a.query}`:"api/voices",a.baseURL),{headers:R({...a.headers},a.apiKey),method:"GET",signal:a.abortSignal}).then(ee).then(({voices:i})=>i);const fe=[{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=oe("providers",()=>{const a=le("settings/credentials/providers",{}),{t:i}=de();async function d(e){try{const r=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e.apiKey.trim()}`,"Content-Type":"application/json"}});if(!r.ok)throw new Error(`Failed to fetch OpenRouter models: ${r.statusText}`);return(await r.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(r){throw console.error("Error fetching OpenRouter models:",r),r}}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=>ve(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>d(e)},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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/v1/"},createProvider:e=>A(e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...A(e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"ollama",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.baseUrl}},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",createProvider:e=>A(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}]},validators:{validateProviderConfig:e=>!!e.baseUrl}},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=>S(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...S(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"openai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},anthropic:{id:"anthropic",nameKey:"settings.pages.providers.provider.anthropic.title",name:"Anthropic",descriptionKey:"settings.pages.providers.provider.anthropic.description",description:"anthropic.com",icon:"i-lobe-icons:anthropic",defaultOptions:{baseUrl:"https://api.anthropic.com/v1/"},createProvider:e=>me(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"claude-3-7-sonnet-20250219",name:"Claude 3.7 Sonnet",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-5-sonnet-20241022",name:"Claude 3.5 Sonnet (New)",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-5-sonnet-20240620",name:"Claude 3.5 Sonnet (Old)",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-haiku-20240307",name:"Claude 3 Haiku",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-opus-20240229",name:"Claude 3 Opus",provider:"anthropic",description:"",contextLength:0,deprecated:!1}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"google-generative-ai":{id:"google-generative-ai",nameKey:"settings.pages.providers.provider.google-generative-ai.title",name:"Google Gemini",descriptionKey:"settings.pages.providers.provider.google-generative-ai.description",description:"ai.google.dev",icon:"i-lobe-icons:gemini",defaultOptions:{baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai/"},createProvider:e=>$(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...$(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"google-generative-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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=>H(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...H(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"xai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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",createProvider:e=>L(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...L(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"deepseek",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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()=>fe.map(e=>({id:e.model_id,name:e.name,provider:"elevenlabs",description:e.description,contextLength:0,deprecated:!1})),listVoices:async e=>{const r=J(e.apiKey.trim(),e.baseUrl.trim()),l=await E({...r.voice()}),s=l.findIndex(P=>P.name.includes("Aria")),u=l.findIndex(P=>P.name.includes("Bill")),j=s!==-1?s:0,I=u!==-1?u:l.length-1,F=Math.min(j,I),z=Math.max(j,I);return[...l.slice(0,F),...l.slice(z+1),...l.slice(F,z+1)].map(P=>({id:P.id,name:P.name,provider:"elevenlabs",previewURL:P.preview_audio_url,languages:P.languages}))}},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>X(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 r=X(e.apiKey.trim(),e.baseUrl.trim());return(await E({...r.voice({region:e.region})})).map(s=>{var u;return{id:s.id,name:s.name,provider:"microsoft-speech",previewURL:s.preview_audio_url,languages:s.languages,gender:(u=s.labels)==null?void 0:u.gender}})}},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"alibaba-cloud-model-studio":{id:"alibaba-cloud-model-studio",nameKey:"settings.pages.providers.provider.alibaba-cloud-model-studio.title",name:"Alibaba Cloud Model Studio",descriptionKey:"settings.pages.providers.provider.alibaba-cloud-model-studio.description",description:"bailian.console.aliyun.com",iconColor:"i-lobe-icons:alibabacloud",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>Y(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listVoices:async e=>{const r=Y(e.apiKey.trim(),e.baseUrl.trim());return(await E({...r.voice()})).map(s=>{var u;return{id:s.id,name:s.name,provider:"alibaba-cloud-model-studio",previewURL:s.preview_audio_url,languages:s.languages,gender:(u=s.labels)==null?void 0:u.gender}})},listModels:async()=>[{id:"cozyvoice-v1",name:"CozyVoice",provider:"alibaba-cloud-model-studio",description:"",contextLength:0,deprecated:!1},{id:"cozyvoice-v2",name:"CozyVoice (New)",provider:"alibaba-cloud-model-studio",description:"",contextLength:0,deprecated:!1}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},volcengine:{id:"volcengine",nameKey:"settings.pages.providers.provider.volcengine.title",name:"settings.pages.providers.provider.volcengine.title",descriptionKey:"settings.pages.providers.provider.volcengine.description",description:"volcengine.com",iconColor:"i-lobe-icons:volcengine",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>Q(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listVoices:async e=>{const r=Q(e.apiKey.trim(),e.baseUrl.trim());return(await E({...r.voice()})).map(s=>{var u;return{id:s.id,name:s.name,provider:"volcano-engine",previewURL:s.preview_audio_url,languages:s.languages,gender:(u=s.labels)==null?void 0:u.gender}})},listModels:async()=>[{id:"v1",name:"v1",provider:"volcano-engine",description:"",contextLength:0,deprecated:!1}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl&&!!e.app&&!!e.app.appId}},"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",createProvider:e=>W(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...W(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"together-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",createProvider:e=>N(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...N(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"novita-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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=>G(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...G(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"fireworks-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"featherless-ai":{id:"featherless-ai",nameKey:"settings.pages.providers.provider.featherless.title",name:"Featherless.ai",descriptionKey:"settings.pages.providers.provider.featherless.description",description:"featherless.ai",icon:"i-lobe-icons:featherless-ai",defaultOptions:{baseUrl:"https://api.featherless.ai/v1/"},createProvider:e=>S(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...S(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"featherless-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",createProvider:e=>he(e.apiKey.trim(),e.accountId),capabilities:{listModels:async()=>[]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.accountId}},"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=>_e(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}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",createProvider:e=>D(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...D(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"mistral-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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=>V(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...V(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"moonshot-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}}};async function h(e){const r=a.value[e];if(!r)return!1;const l=o[e];return l?await l.validators.validateProviderConfig(r):!1}const t=q({});function n(e){var r;if(!a.value[e]){const l=o[e];a.value[e]={baseUrl:((r=l.defaultOptions)==null?void 0:r.baseUrl)||""}}}Object.keys(o).forEach(n);async function v(){await Promise.all(Object.keys(o).map(async e=>{t.value[e]=await h(e)}))}v(),ce(a,v,{deep:!0});const g=w(()=>Object.keys(o).filter(e=>t.value[e])),c=q({}),y=q({}),x=q({});async function M(e){const r=a.value[e];if(!r)return[];const l=o[e];if(!l)return[];y.value[e]=!0,x.value[e]=null;try{const s=l.capabilities.listModels?await l.capabilities.listModels(r):[];return c.value[e]=s.map(u=>({id:u.id,name:u.name,description:u.description,contextLength:u.contextLength,deprecated:u.deprecated,provider:e})),c.value[e]}catch(s){return console.error(`Error fetching models for ${e}:`,s),x.value[e]=s instanceof Error?s.message:"Unknown error",[]}finally{y.value[e]=!1}}function C(e){return c.value[e]||[]}const B=w(()=>{const e=[];for(const r of g.value)e.push(...c.value[r]||[]);return e});async function ae(){for(const e of g.value)o[e].capabilities.listModels&&await M(e)}function T(e){const r=o[e];if(!r)throw new Error(`Provider metadata for ${e} not found`);return{...r,localizedName:i(r.nameKey,r.name),localizedDescription:i(r.descriptionKey,r.description)}}const ie=w(()=>Object.values(o).map(e=>({...e,localizedName:i(e.nameKey,e.name),localizedDescription:i(e.descriptionKey,e.description),configured:t.value[e.id]||!1})));function O(e){const r=a.value[e];if(!r)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(r)}catch(s){throw console.error(`Error creating provider instance for ${e}:`,s),s}}const U=w(()=>g.value.map(e=>T(e))),re=w(()=>U.value.filter(e=>{const r=O(e.id);return"chat"in r&&typeof r.chat=="function"})),te=w(()=>U.value.filter(e=>{const r=O(e.id);return"transcription"in r&&typeof r.transcription=="function"})),ne=w(()=>U.value.filter(e=>{const r=O(e.id);return"speech"in r&&typeof r.speech=="function"}));function se(e){return a.value[e]}return{providers:a,getProviderConfig:se,availableProviders:g,configuredProviders:t,providerMetadata:o,getProviderMetadata:T,allProvidersMetadata:ie,initializeProvider:n,validateProvider:h,availableModels:c,isLoadingModels:y,modelLoadError:x,fetchModelsForProvider:M,getModelsForProvider:C,allAvailableModels:B,loadModelsForConfiguredProviders:ae,getProviderInstance:O,availableProvidersMetadata:U,availableTextGenerationsProvidersMetadata:re,availableAudioSpeechProvidersMetadata:ne,availableAudioTranscriptionProvidersMetadata:te}});export{b as l,Pe as u}; diff --git a/assets/providers-kjOpfeNb.js b/assets/providers-kjOpfeNb.js deleted file mode 100644 index c77e41a72317b83da6cb4deba9e949be3d36ae87..0000000000000000000000000000000000000000 --- a/assets/providers-kjOpfeNb.js +++ /dev/null @@ -1 +0,0 @@ -var le=Object.defineProperty;var de=(a,i,n)=>i in a?le(a,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):a[i]=n;var G=(a,i,n)=>de(a,typeof i!="symbol"?i+"":i,n);import{p as ce,q as pe,g as ue,r as U,v as ge,h as k}from"./index-BQKiy4UR.js";import{r as me,a as ve,e as _e,o as N}from"./index-LHmcipjy.js";const b=async a=>(a.fetch??globalThis.fetch)(me("models",a.baseURL),{headers:ve(a.headers,a.apiKey),signal:a.abortSignal}).then(_e).then(({data:i})=>i),_=a=>({chat:i=>Object.assign(a,{model:i})}),w=a=>({embed:i=>Object.assign(a,{model:i})}),f=a=>({model:()=>a}),he=a=>({speech:i=>Object.assign(a,{model:i})}),fe=a=>({transcription:i=>Object.assign(a,{model:i})}),g=(a,i)=>({metadata:{id:a,...i}}),m=(...a)=>Object.assign(a[0],...a.slice(1)),be=(a,i="https://api.anthropic.com/v1/")=>m(g("anthropic"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),D=(a,i="https://api.deepseek.com/")=>m(g("deepseek"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),V=(a,i="https://api.fireworks.ai/inference/v1/")=>m(g("fireworks"),_({apiKey:a,baseURL:i}),w({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),W=(a,i="https://generativelanguage.googleapis.com/v1beta/openai/")=>m(g("google-generative-ai"),_({apiKey:a,baseURL:i}),w({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),H=(a,i="https://api.mistral.ai/v1/")=>m(g("mistral"),_({apiKey:a,baseURL:i}),w({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),J=(a,i="https://api.moonshot.cn/v1/")=>m(g("moonshot"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),X=(a,i="https://api.novita.ai/v3/openai/")=>m(g("novita"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),q=(a,i="https://api.openai.com/v1/")=>m(g("openai"),_({apiKey:a,baseURL:i}),w({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i}),he({apiKey:a,baseURL:i}),fe({apiKey:a,baseURL:i})),ye=(a,i="")=>m(g("openrouter"),{chat:(n,l)=>{const h={apiKey:a,baseURL:i,model:n};return{...l?(({extraHeaders:s,models:v,provider:u})=>{s!=null&&(h.headers??(h.headers={}),Object.assign(h.headers,s));let c;return u!=null&&(c=N(u)),N({models:v,provider:c})})(l):{},...h}}},f({apiKey:a,baseURL:i})),xe=(a,i="https://api.perplexity.ai/")=>m(g("perplexity"),_({apiKey:a,baseURL:i})),Z=(a,i="https://api.together.xyz/v1/")=>m(g("together-ai"),_({apiKey:a,baseURL:i}),w({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i,fetch:async(...n)=>globalThis.fetch(...n).then(async l=>l.json()).then(l=>Response.json({data:l,object:"list"}))})),Pe=(a,i)=>{const n=`https://api.cloudflare.com/client/v4/accounts/${i}/ai/v1/`;return m(g("workers-ai"),_({apiKey:a,baseURL:n}),w({apiKey:a,baseURL:n}))},Q=(a,i="https://api.x.ai/v1/")=>m(g("xai"),_({apiKey:a,baseURL:i}),f({apiKey:a,baseURL:i})),T=(a="http://localhost:11434/v1/")=>m(g("ollama"),_({baseURL:a}),w({baseURL:a}),f({baseURL:a})),A=(...a)=>Object.assign(a[0],...a.slice(1));class j extends Error{constructor(n,l){super(n);G(this,"response");this.name="XSAIError",this.response=l}}const ke=a=>a.replace(/[A-Z]/g,i=>`_${i.toLowerCase()}`),K=a=>Object.fromEntries(Object.entries(a).map(([i,n])=>[ke(i),n])),we=a=>Object.fromEntries(Object.entries(a).filter(([,i])=>i!==void 0)),Ke=(a,i)=>we({Authorization:i!==void 0?`Bearer ${i}`:void 0,...a}),Me=(a,i)=>{const n=i.toString();return new URL(a,n.endsWith("/")?n:`${n}/`)},Ce=async a=>{if(!a.ok)throw new j(`Remote sent ${a.status} response: ${await a.text()}`,a);if(!a.body)throw new j("Response body is empty from remote server",a);if(!(a.body instanceof ReadableStream))throw new j(`Expected Response body to be a ReadableStream, but got ${String(a.body)}; Content Type is ${a.headers.get("Content-Type")}`,a);return a},Oe=async a=>Ce(a).then(async i=>{const n=await i.text();try{return JSON.parse(n)}catch{throw new Error(`Failed to parse response, response body: ${n}`)}});var Y=(a,i="http://localhost:5933/v1/")=>{const n=({applyTextNormalization:t,languageCode:s,nextRequestIds:v,nextText:u,previousRequestIds:c,previousText:y,pronunciationDictionaryLocators:x,seed:M,voiceSettings:C})=>({extraBody:K({applyTextNormalization:t,languageCode:s,nextRequestIds:v,nextText:u,previousRequestIds:c,previousText:y,pronunciationDictionaryLocators:x?x.map(B=>K(B)):void 0,seed:M,voiceSettings:K(C??{similarityBoost:.75,stability:.5})})});return A({speech:(t,s)=>({...s?n(s):{},apiKey:a,baseURL:i,model:`elevenlabs/${t}`})},{voice:t=>(i.endsWith("v1/")?i=i.slice(0,-3):i.endsWith("v1")&&(i=i.slice(0,-2)),{query:"provider=elevenlabs",...t?n(t):{},apiKey:a,baseURL:i})})},R=(a,i="http://localhost:5933/v1/")=>{const n=t=>{const{deploymentId:s,region:v,sampleRate:u}=t,c={deploymentId:s,region:v,sampleRate:u};return"disableSsml"in t?c.disableSsml=t.disableSsml:"lang"in t&&(c.lang=t.lang,c.gender=t.gender,c.voice=t.voice),{extraBody:K(c)}};return A({speech:(t,s)=>({...s?n(s):{},apiKey:a,baseURL:i,model:`microsoft/${t}`})},{voice:t=>(i.endsWith("v1/")?i=i.slice(0,-3):i.endsWith("v1")&&(i=i.slice(0,-2)),{query:`region=${t==null?void 0:t.region}&provider=microsoft`,...t?n(t):{},apiKey:a,baseURL:i})})},ee=(a,i="http://localhost:5933/v1/")=>{const n=t=>{var v,u;const s={app:{appid:(v=t.app)==null?void 0:v.appId,token:a}};return typeof t.app<"u"&&(s.app={...t.app,appid:(u=t.app)==null?void 0:u.appId,token:a}),typeof t.user<"u"&&(s.user=t.user),typeof t.audio<"u"&&(s.audio=t.audio),{extraBody:K(s)}};return A({speech:(t,s)=>({...s?n(s):{},apiKey:a,baseURL:i,model:`volcengine/${t}`})},{voice:t=>(i.endsWith("v1/")?i=i.slice(0,-3):i.endsWith("v1")&&(i=i.slice(0,-2)),{query:"provider=volcengine",...t?n(t):{},apiKey:a,baseURL:i})})},ae=(a,i="http://localhost:5933/v1/")=>{const n=t=>{const{sampleRate:s,volume:v,rate:u,pitch:c}=t,y={sampleRate:s,volume:v,rate:u,pitch:c};return Object.keys(y).forEach(x=>y[x]===void 0&&delete y[x]),{extraBody:K(y)}};return A({speech:(t,s)=>({...s?n(s):{},apiKey:a,baseURL:i,model:`alibaba/${t}`})},{voice:t=>{let s=i;return s.endsWith("v1/")?s=s.slice(0,-3):s.endsWith("v1")&&(s=s.slice(0,-2)),{query:"provider=alibaba",...t?n(t):{},apiKey:a,baseURL:s}}})},E=async a=>(a.fetch??globalThis.fetch)(Me(a.query?`api/voices?${a.query}`:"api/voices",a.baseURL),{headers:Ke({...a.headers},a.apiKey),method:"GET",signal:a.abortSignal}).then(Oe).then(({voices:i})=>i);const Se=[{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"}],Be=ce("providers",()=>{const a=pe("settings/credentials/providers",{}),{t:i}=ue();async function n(e){try{const r=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e.apiKey.trim()}`,"Content-Type":"application/json"}});if(!r.ok)throw new Error(`Failed to fetch OpenRouter models: ${r.statusText}`);return(await r.json()).data.map(o=>({id:o.id,name:o.name||o.id,provider:"openrouter-ai",description:o.description||"",contextLength:o.context_length,deprecated:!1}))}catch(r){throw console.error("Error fetching OpenRouter models:",r),r}}const l={"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=>ye(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>n(e)},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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/v1/"},createProvider:e=>T(e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...T(e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"ollama",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.baseUrl}},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",createProvider:e=>T(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}]},validators:{validateProviderConfig:e=>!!e.baseUrl}},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=>q(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...q(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"openai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},anthropic:{id:"anthropic",nameKey:"settings.pages.providers.provider.anthropic.title",name:"Anthropic",descriptionKey:"settings.pages.providers.provider.anthropic.description",description:"anthropic.com",icon:"i-lobe-icons:anthropic",defaultOptions:{baseUrl:"https://api.anthropic.com/v1/"},createProvider:e=>be(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async()=>[{id:"claude-3-7-sonnet-20250219",name:"Claude 3.7 Sonnet",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-5-sonnet-20241022",name:"Claude 3.5 Sonnet (New)",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-5-haiku-20241022",name:"Claude 3.5 Haiku",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-5-sonnet-20240620",name:"Claude 3.5 Sonnet (Old)",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-haiku-20240307",name:"Claude 3 Haiku",provider:"anthropic",description:"",contextLength:0,deprecated:!1},{id:"claude-3-opus-20240229",name:"Claude 3 Opus",provider:"anthropic",description:"",contextLength:0,deprecated:!1}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"google-generative-ai":{id:"google-generative-ai",nameKey:"settings.pages.providers.provider.google-generative-ai.title",name:"Google Gemini",descriptionKey:"settings.pages.providers.provider.google-generative-ai.description",description:"ai.google.dev",icon:"i-lobe-icons:gemini",defaultOptions:{baseUrl:"https://generativelanguage.googleapis.com/v1beta/openai/"},createProvider:e=>W(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...W(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"google-generative-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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=>Q(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...Q(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"xai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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",createProvider:e=>D(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...D(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"deepseek",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},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=>Y(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async()=>Se.map(e=>({id:e.model_id,name:e.name,provider:"elevenlabs",description:e.description,contextLength:0,deprecated:!1})),listVoices:async e=>{const r=Y(e.apiKey.trim(),e.baseUrl.trim()),d=await E({...r.voice()}),o=d.findIndex(P=>P.name.includes("Aria")),p=d.findIndex(P=>P.name.includes("Bill")),I=o!==-1?o:0,F=p!==-1?p:d.length-1,z=Math.min(I,F),L=Math.max(I,F);return[...d.slice(0,z),...d.slice(L+1),...d.slice(z,L+1)].map(P=>({id:P.id,name:P.name,provider:"elevenlabs",previewURL:P.preview_audio_url,languages:P.languages}))}},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>R(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 r=R(e.apiKey.trim(),e.baseUrl.trim());return(await E({...r.voice({region:e.region})})).map(o=>{var p;return{id:o.id,name:o.name,provider:"microsoft-speech",previewURL:o.preview_audio_url,languages:o.languages,gender:(p=o.labels)==null?void 0:p.gender}})}},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"alibaba-cloud-model-studio":{id:"alibaba-cloud-model-studio",nameKey:"settings.pages.providers.provider.alibaba-cloud-model-studio.title",name:"Alibaba Cloud Model Studio",descriptionKey:"settings.pages.providers.provider.alibaba-cloud-model-studio.description",description:"bailian.console.aliyun.com",iconColor:"i-lobe-icons:alibabacloud",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>ae(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listVoices:async e=>{const r=ae(e.apiKey.trim(),e.baseUrl.trim());return(await E({...r.voice()})).map(o=>{var p;return{id:o.id,name:o.name,provider:"alibaba-cloud-model-studio",previewURL:o.preview_audio_url,languages:o.languages,gender:(p=o.labels)==null?void 0:p.gender}})},listModels:async()=>[{id:"cozyvoice-v1",name:"CozyVoice",provider:"alibaba-cloud-model-studio",description:"",contextLength:0,deprecated:!1},{id:"cozyvoice-v2",name:"CozyVoice (New)",provider:"alibaba-cloud-model-studio",description:"",contextLength:0,deprecated:!1}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},volcengine:{id:"volcengine",nameKey:"settings.pages.providers.provider.volcengine.title",name:"settings.pages.providers.provider.volcengine.title",descriptionKey:"settings.pages.providers.provider.volcengine.description",description:"volcengine.com",iconColor:"i-lobe-icons:volcengine",defaultOptions:{baseUrl:"https://unspeech.hyp3r.link/v1/"},createProvider:e=>ee(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listVoices:async e=>{const r=ee(e.apiKey.trim(),e.baseUrl.trim());return(await E({...r.voice()})).map(o=>{var p;return{id:o.id,name:o.name,provider:"volcano-engine",previewURL:o.preview_audio_url,languages:o.languages,gender:(p=o.labels)==null?void 0:p.gender}})},listModels:async()=>[{id:"v1",name:"v1",provider:"volcano-engine",description:"",contextLength:0,deprecated:!1}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl&&!!e.app&&!!e.app.appId}},"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",createProvider:e=>Z(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...Z(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"together-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",createProvider:e=>X(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...X(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"novita-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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=>V(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...V(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"fireworks-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"featherless-ai":{id:"featherless-ai",nameKey:"settings.pages.providers.provider.featherless.title",name:"Featherless.ai",descriptionKey:"settings.pages.providers.provider.featherless.description",description:"featherless.ai",icon:"i-lobe-icons:featherless-ai",defaultOptions:{baseUrl:"https://api.featherless.ai/v1/"},createProvider:e=>q(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...q(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"featherless-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",createProvider:e=>Pe(e.apiKey.trim(),e.accountId),capabilities:{listModels:async()=>[]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.accountId}},"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=>xe(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}]},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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",createProvider:e=>H(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...H(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"mistral-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}},"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=>J(e.apiKey.trim(),e.baseUrl.trim()),capabilities:{listModels:async e=>(await b({...J(e.apiKey.trim(),e.baseUrl.trim()).model()})).map(r=>({id:r.id,name:r.id,provider:"moonshot-ai",description:"",contextLength:0,deprecated:!1}))},validators:{validateProviderConfig:e=>!!e.apiKey&&!!e.baseUrl}}};async function h(e){const r=a.value[e];if(!r)return!1;const d=l[e];return d?await d.validators.validateProviderConfig(r):!1}const t=U({});function s(e){var r;if(!a.value[e]){const d=l[e];a.value[e]={baseUrl:((r=d.defaultOptions)==null?void 0:r.baseUrl)||""}}}Object.keys(l).forEach(s);async function v(){await Promise.all(Object.keys(l).map(async e=>{t.value[e]=await h(e)}))}v(),ge(a,v,{deep:!0});const u=k(()=>Object.keys(l).filter(e=>t.value[e])),c=U({}),y=U({}),x=U({});async function M(e){const r=a.value[e];if(!r)return[];const d=l[e];if(!d)return[];y.value[e]=!0,x.value[e]=null;try{const o=d.capabilities.listModels?await d.capabilities.listModels(r):[];return c.value[e]=o.map(p=>({id:p.id,name:p.name,description:p.description,contextLength:p.contextLength,deprecated:p.deprecated,provider:e})),c.value[e]}catch(o){return console.error(`Error fetching models for ${e}:`,o),x.value[e]=o instanceof Error?o.message:"Unknown error",[]}finally{y.value[e]=!1}}function C(e){return c.value[e]||[]}const B=k(()=>{const e=[];for(const r of u.value)e.push(...c.value[r]||[]);return e});async function ie(){for(const e of u.value)l[e].capabilities.listModels&&await M(e)}function $(e){const r=l[e];if(!r)throw new Error(`Provider metadata for ${e} not found`);return{...r,localizedName:i(r.nameKey,r.name),localizedDescription:i(r.descriptionKey,r.description)}}const re=k(()=>Object.values(l).map(e=>({...e,localizedName:i(e.nameKey,e.name),localizedDescription:i(e.descriptionKey,e.description),configured:t.value[e.id]||!1})));function O(e){const r=a.value[e];if(!r)throw new Error(`Provider credentials for ${e} not found`);const d=l[e];if(!d)throw new Error(`Provider metadata for ${e} not found`);try{return d.createProvider(r)}catch(o){throw console.error(`Error creating provider instance for ${e}:`,o),o}}const S=k(()=>u.value.map(e=>$(e))),te=k(()=>S.value.filter(e=>{const r=O(e.id);return"chat"in r&&typeof r.chat=="function"})),ne=k(()=>S.value.filter(e=>{const r=O(e.id);return"transcription"in r&&typeof r.transcription=="function"})),se=k(()=>S.value.filter(e=>{const r=O(e.id);return"speech"in r&&typeof r.speech=="function"}));function oe(e){return a.value[e]}return{providers:a,getProviderConfig:oe,availableProviders:u,configuredProviders:t,providerMetadata:l,getProviderMetadata:$,allProvidersMetadata:re,initializeProvider:s,validateProvider:h,availableModels:c,isLoadingModels:y,modelLoadError:x,fetchModelsForProvider:M,getModelsForProvider:C,allAvailableModels:B,loadModelsForConfiguredProviders:ie,getProviderInstance:O,availableProvidersMetadata:S,availableTextGenerationsProvidersMetadata:te,availableAudioSpeechProvidersMetadata:se,availableAudioTranscriptionProvidersMetadata:ne}});export{b as l,Be as u}; diff --git a/assets/queue-DNS07_tB.js b/assets/queue-3c99Yq5f.js similarity index 91% rename from assets/queue-DNS07_tB.js rename to assets/queue-3c99Yq5f.js index 991cdc0b509699352b718643e2d87aef773266a8..4d7d1e347af4a85f3c99baddd5d7f11d73e80654 100644 --- a/assets/queue-DNS07_tB.js +++ b/assets/queue-3c99Yq5f.js @@ -1 +1 @@ -import{r as l}from"./index-BQKiy4UR.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 E(){const n=t.value.shift();if(n)return r("pick",n),n}async function u(){if(a.value)return;const n=E();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{r as l}from"./index-CQudhZin.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 E(){const n=t.value.shift();if(n)return r("pick",n),n}async function u(){if(a.value)return;const n=E();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/queue-DC7HdGzc.js b/assets/queue-C9PyLN3M.js similarity index 90% rename from assets/queue-DC7HdGzc.js rename to assets/queue-C9PyLN3M.js index 774d1d431f6d4e52685109c219790b5ca7399f35..7b47645a1d3a820cc803869eae4d1f3f0b59d20e 100644 --- a/assets/queue-DC7HdGzc.js +++ b/assets/queue-C9PyLN3M.js @@ -1 +1 @@ -import{u as o}from"./queue-DNS07_tB.js";import{d as v,r as h,H as k,c as w,o as g,e as I}from"./index-BQKiy4UR.js";const Q=v({__name:"queue",setup(H){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 k(()=>{m()}),(e,a)=>(g(),w("div",null,a[0]||(a[0]=[I("div",null,null,-1)])))}});export{Q as default}; +import{u as o}from"./queue-3c99Yq5f.js";import{d as v,r as h,H as k,c as w,o as g,e as I}from"./index-CQudhZin.js";const Q=v({__name:"queue",setup(H){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 k(()=>{m()}),(e,a)=>(g(),w("div",null,a[0]||(a[0]=[I("div",null,null,-1)])))}});export{Q as default}; diff --git a/assets/queues-C9_pVSeq.js b/assets/queues-B-17ADgG.js similarity index 94% rename from assets/queues-C9_pVSeq.js rename to assets/queues-B-17ADgG.js index 210cb2c29ec26351bcd082546fc01147027bbb62..018c9bd29909678bbbbc1f6ea956589fe1f6beed 100644 --- a/assets/queues-C9_pVSeq.js +++ b/assets/queues-B-17ADgG.js @@ -1 +1 @@ -import{E as i}from"./mini_xsschema-P_8cZcRg.js";import{u as s}from"./queue-DNS07_tB.js";import{r as d}from"./index-BQKiy4UR.js";const l="<|llm_inference_end|>";function y(o){function t(e){for(const n of i)if(e.includes(n))return{ok:!0,emotion:n};return{ok:!1,emotion:""}}return s({handlers:[async e=>{if(i.includes(e.data)){e.emit("emotion",e.data),await o.add(e.data);return}{const{ok:n,emotion:a}=t(e.data);n&&(e.emit("emotion",a),await o.add(a))}}]})}function k(){function o(e){if(!/<\|DELAY:\d+\|>/i.test(e))return{ok:!1,delay:0};const n=/<\|DELAY:(\d+)\|>/i.exec(e),a=n==null?void 0:n[1];if(!a)return{ok:!1,delay:0};const r=Number.parseFloat(a);return r<=0||Number.isNaN(r)?{ok:!0,delay:0}:{ok:!0,delay:r}}function t(e){return new Promise(n=>setTimeout(n,e))}return s({handlers:[async e=>{const{ok:n,delay:a}=o(e.data);n&&(e.emit("delay",a),await t(a*1e3))}]})}function p(o){const t=d("");return s({handlers:[async e=>{if(e.data===l){const a=t.value.trim();a&&await o.add(a),t.value="";return}const n=/[.?!]/;for(t.value+=e.data;t.value;){const a=n.exec(t.value);if(!a||typeof a.index>"u")break;const r=t.value.slice(0,a.index+1),u=t.value.slice(a.index+1);await o.add(r),t.value=u}}]})}export{y as a,p as b,l,k as u}; +import{E as i}from"./mini_xsschema-P_8cZcRg.js";import{u as s}from"./queue-3c99Yq5f.js";import{r as d}from"./index-CQudhZin.js";const l="<|llm_inference_end|>";function y(o){function t(e){for(const n of i)if(e.includes(n))return{ok:!0,emotion:n};return{ok:!1,emotion:""}}return s({handlers:[async e=>{if(i.includes(e.data)){e.emit("emotion",e.data),await o.add(e.data);return}{const{ok:n,emotion:a}=t(e.data);n&&(e.emit("emotion",a),await o.add(a))}}]})}function k(){function o(e){if(!/<\|DELAY:\d+\|>/i.test(e))return{ok:!1,delay:0};const n=/<\|DELAY:(\d+)\|>/i.exec(e),a=n==null?void 0:n[1];if(!a)return{ok:!1,delay:0};const r=Number.parseFloat(a);return r<=0||Number.isNaN(r)?{ok:!0,delay:0}:{ok:!0,delay:r}}function t(e){return new Promise(n=>setTimeout(n,e))}return s({handlers:[async e=>{const{ok:n,delay:a}=o(e.data);n&&(e.emit("delay",a),await t(a*1e3))}]})}function p(o){const t=d("");return s({handlers:[async e=>{if(e.data===l){const a=t.value.trim();a&&await o.add(a),t.value="";return}const n=/[.?!]/;for(t.value+=e.data;t.value;){const a=n.exec(t.value);if(!a||typeof a.index>"u")break;const r=t.value.slice(0,a.index+1),u=t.value.slice(a.index+1);await o.add(r),t.value=u}}]})}export{y as a,p as b,l,k as u}; diff --git a/assets/settings-DmZvPNPX.js b/assets/settings-DmZvPNPX.js deleted file mode 100644 index a68954ad561b88f863a84c4cd09f4e63fa621e06..0000000000000000000000000000000000000000 --- a/assets/settings-DmZvPNPX.js +++ /dev/null @@ -1 +0,0 @@ -var it=Object.defineProperty;var rt=(t,s,e)=>s in t?it(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e;var m=(t,s,e)=>rt(t,typeof s!="symbol"?s+"":s,e);import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{av as L,v as h,b as A,r as b,h as k,aw as nt,ax as ot,ay as y,az as q,aA as at,aB as P,aC as R,aD as u,aE as $,aF as O,aG as j,aH as v,aI as ut,aJ as lt,aK as ct,aL as U,aM as ft,aN as pt,aO as dt,aP as mt,aQ as gt,aR as bt,aS as ht,aT as yt,aU as vt,aV as xt,aW as Tt,aX as At,aY as Ot,aZ as wt,a_ as St,a$ as kt,b0 as Et,b1 as jt,d as G,H as Pt,I as Vt,c as M,e as S,S as Ct,j as Nt,t as W,o as D,b2 as J,g as Rt,s as Mt,i as V,R as Dt}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as zt}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{H as Lt}from"./HeaderLink-CnrAQmsl.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";const T={};class Ft{constructor(){m(this,"subscriptions",new Set)}add(s){return this.subscriptions.add(s),()=>this.subscriptions.delete(s)}notify(s,e,r){if(this.subscriptions.size)for(const i of this.subscriptions)i(s,e,r)}clear(){this.subscriptions.clear()}}function X(t){return!Number.isNaN(Number.parseFloat(t))}class Ht{constructor(s){m(this,"current");m(this,"prev");m(this,"timeDelta",0);m(this,"lastUpdated",0);m(this,"updateSubscribers",new Ft);m(this,"stopAnimation");m(this,"canTrackVelocity",!1);m(this,"updateAndNotify",s=>{this.prev=this.current,this.current=s;const{delta:e,timestamp:r}=ct();this.lastUpdated!==r&&(this.timeDelta=e,this.lastUpdated=r),U.postRender(this.scheduleVelocityCheck),this.updateSubscribers.notify(this.current)});m(this,"scheduleVelocityCheck",()=>U.postRender(this.velocityCheck));m(this,"velocityCheck",({timestamp:s})=>{this.canTrackVelocity||(this.canTrackVelocity=X(this.current)),s!==this.lastUpdated&&(this.prev=this.current)});this.prev=this.current=s,this.canTrackVelocity=X(this.current)}onChange(s){return this.updateSubscribers.add(s)}clearListeners(){this.updateSubscribers.clear()}set(s){this.updateAndNotify(s)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){return this.canTrackVelocity?ft(Number.parseFloat(this.current)-Number.parseFloat(this.prev),this.timeDelta):0}start(s){return this.stop(),new Promise(e=>{const{stop:r}=s(e);this.stopAnimation=r}).then(()=>this.clearAnimation())}stop(){this.stopAnimation&&this.stopAnimation(),this.clearAnimation()}isAnimating(){return!!this.stopAnimation}clearAnimation(){this.stopAnimation=null}destroy(){this.updateSubscribers.clear(),this.stop()}}function Bt(t){return new Ht(t)}const{isArray:$t}=Array;function Ut(){const t=b({}),s=r=>{const i=n=>{t.value[n]&&(t.value[n].stop(),t.value[n].destroy(),delete t.value[n])};r?$t(r)?r.forEach(i):i(r):Object.keys(t.value).forEach(i)},e=(r,i,n)=>{if(t.value[r])return t.value[r];const o=Bt(i);return o.onChange(a=>n[r]=a),t.value[r]=o,o};return Et(s),{motionValues:t,get:e,stop:s}}function Wt(t){return Array.isArray(t)}function w(){return{type:"spring",stiffness:500,damping:25,restDelta:.5,restSpeed:10}}function C(t){return{type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restDelta:.01,restSpeed:10}}function Xt(t){return{type:"spring",stiffness:550,damping:t===0?100:30,restDelta:.01,restSpeed:10}}function N(){return{type:"keyframes",ease:"linear",duration:300}}function Yt(t){return{type:"keyframes",duration:800,values:t}}const Y={default:Xt,x:w,y:w,z:w,rotate:w,rotateX:w,rotateY:w,rotateZ:w,scaleX:C,scaleY:C,scale:C,backgroundColor:N,color:N,opacity:N};function Q(t,s){let e;return Wt(s)?e=Yt:e=Y[t]||Y.default,{to:s,...e(s)}}const I={...at,transform:Math.round},_={color:v,backgroundColor:v,outlineColor:v,fill:v,stroke:v,borderColor:v,borderTopColor:v,borderRightColor:v,borderBottomColor:v,borderLeftColor:v,borderWidth:u,borderTopWidth:u,borderRightWidth:u,borderBottomWidth:u,borderLeftWidth:u,borderRadius:u,radius:u,borderTopLeftRadius:u,borderTopRightRadius:u,borderBottomRightRadius:u,borderBottomLeftRadius:u,width:u,maxWidth:u,height:u,maxHeight:u,size:u,top:u,right:u,bottom:u,left:u,padding:u,paddingTop:u,paddingRight:u,paddingBottom:u,paddingLeft:u,margin:u,marginTop:u,marginRight:u,marginBottom:u,marginLeft:u,rotate:O,rotateX:O,rotateY:O,rotateZ:O,scale:j,scaleX:j,scaleY:j,scaleZ:j,skew:O,skewX:O,skewY:O,distance:u,translateX:u,translateY:u,translateZ:u,x:u,y:u,z:u,perspective:u,transformPerspective:u,opacity:P,originX:$,originY:$,originZ:u,zIndex:I,filter:R,WebkitFilter:R,fillOpacity:P,strokeOpacity:P,numOctaves:I},F=t=>_[t];function z(t,s){return s&&typeof t=="number"&&s.transform?s.transform(t):t}function It(t,s){let e=F(t);return e!==R&&(e=q),e.getAnimatableNone?e.getAnimatableNone(s):void 0}const Zt={linear:kt,easeIn:St,easeInOut:wt,easeOut:Ot,circIn:At,circInOut:Tt,circOut:xt,backIn:vt,backInOut:yt,backOut:ht,anticipate:bt,bounceIn:gt,bounceInOut:mt,bounceOut:dt};function Z(t){if(Array.isArray(t)){const[s,e,r,i]=t;return pt(s,e,r,i)}else if(typeof t=="string")return Zt[t];return t}function Kt(t){return Array.isArray(t)&&typeof t[0]!="number"}function K(t,s){return t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&q.test(s)&&!s.startsWith("url("))}function qt(t){return Array.isArray(t.to)&&t.to[0]===null&&(t.to=[...t.to],t.to[0]=t.from),t}function Gt({ease:t,times:s,delay:e,...r}){const i={...r};return s&&(i.offset=s),t&&(i.ease=Kt(t)?t.map(Z):Z(t)),e&&(i.elapsed=-e),i}function Jt(t,s,e){return Array.isArray(s.to)&&(t.duration||(t.duration=800)),qt(s),Qt(t)||(t={...t,...Q(e,s.to)}),{...s,...Gt(t)}}function Qt({delay:t,repeat:s,repeatType:e,repeatDelay:r,from:i,...n}){return!!Object.keys(n).length}function _t(t,s){return t[s]||t.default||t}function te(t,s,e,r,i){const n=_t(r,t);let o=n.from===null||n.from===void 0?s.get():n.from;const a=K(t,e);o==="none"&&a&&typeof e=="string"&&(o=It(t,e));const f=K(t,o);function p(c){const d={from:o,to:e,velocity:r.velocity?r.velocity:s.getVelocity(),onUpdate:x=>s.set(x)};return n.type==="inertia"||n.type==="decay"?ut({...d,...n}):lt({...Jt(n,d,t),onUpdate:x=>{d.onUpdate(x),n.onUpdate&&n.onUpdate(x)},onComplete:()=>{i&&i(),c&&c()}})}function l(c){return s.set(e),i&&i(),c&&c(),{stop:()=>{}}}return!f||!a||n.type===!1?l:p}function ee(){const{motionValues:t,stop:s,get:e}=Ut();return{motionValues:t,stop:s,push:(i,n,o,a={},f)=>{const p=o[i],l=e(i,p,o);if(a&&a.immediate){l.set(n);return}const c=te(i,l,n,a,f);l.start(c)}}}function se(t,s={},{motionValues:e,push:r,stop:i}=ee()){const n=A(s),o=b(!1);h(e,c=>{o.value=Object.values(c).filter(d=>d.isAnimating()).length>0},{immediate:!0,deep:!0});const a=c=>{if(!n||!n[c])throw new Error(`The variant ${c} does not exist.`);return n[c]},f=c=>{typeof c=="string"&&(c=a(c));const d=Object.entries(c).map(([g,E])=>{if(g!=="transition")return new Promise(st=>r(g,E,t,c.transition||Q(g,c[g]),st))}).filter(Boolean);async function x(){var g,E;await Promise.all(d),(E=(g=c.transition)==null?void 0:g.onComplete)==null||E.call(g)}return Promise.all([x()])};return{isAnimating:o,apply:f,set:c=>{const d=nt(c)?c:a(c);Object.entries(d).forEach(([x,g])=>{x!=="transition"&&r(x,g,t,{immediate:!0})})},leave:async c=>{let d;if(n&&(n.leave&&(d=n.leave),!n.leave&&n.initial&&(d=n.initial)),!d){c();return}await f(d),c()},stop:i}}const H=typeof window<"u",ie=()=>H&&(window.onpointerdown===null||(T==null?void 0:T.TEST)),re=()=>H&&(window.ontouchstart===null||(T==null?void 0:T.TEST)),ne=()=>H&&(window.onmousedown===null||(T==null?void 0:T.TEST));function oe({target:t,state:s,variants:e,apply:r}){const i=A(e),n=b(!1),o=b(!1),a=b(!1),f=k(()=>{let l=[...Object.keys(s.value||{})];return i&&(i.hovered&&(l=[...l,...Object.keys(i.hovered)]),i.tapped&&(l=[...l,...Object.keys(i.tapped)]),i.focused&&(l=[...l,...Object.keys(i.focused)])),l}),p=k(()=>{const l={};Object.assign(l,s.value),n.value&&i.hovered&&Object.assign(l,i.hovered),o.value&&i.tapped&&Object.assign(l,i.tapped),a.value&&i.focused&&Object.assign(l,i.focused);for(const c in l)f.value.includes(c)||delete l[c];return l});i.hovered&&(y(t,"mouseenter",()=>n.value=!0),y(t,"mouseleave",()=>{n.value=!1,o.value=!1})),i.tapped&&(ne()&&(y(t,"mousedown",()=>o.value=!0),y(t,"mouseup",()=>o.value=!1)),ie()&&(y(t,"pointerdown",()=>o.value=!0),y(t,"pointerup",()=>o.value=!1)),re()&&(y(t,"touchstart",()=>o.value=!0),y(t,"touchend",()=>o.value=!1))),i.focused&&(y(t,"focus",()=>a.value=!0),y(t,"blur",()=>a.value=!1)),h([n,o,a],()=>{r(p.value)})}function ae({set:t,target:s,variants:e,variant:r}){const i=A(e);h(()=>s,()=>{i&&(i.initial&&(t("initial"),r.value="initial"),i.enter&&(r.value="enter"))},{immediate:!0,flush:"pre"})}function ue({state:t,apply:s}){h(t,e=>{e&&s(e)},{immediate:!0})}function le({target:t,variants:s,variant:e}){const r=A(s);r&&(r.visible||r.visibleOnce)&&ot(t,([{isIntersecting:i}])=>{r.visible?i?e.value="visible":e.value="initial":r.visibleOnce&&(i&&e.value!=="visibleOnce"?e.value="visibleOnce":e.value||(e.value="initial"))})}function ce(t,s={syncVariants:!0,lifeCycleHooks:!0,visibilityHooks:!0,eventListeners:!0}){s.lifeCycleHooks&&ae(t),s.syncVariants&&ue(t),s.visibilityHooks&&le(t),s.eventListeners&&oe(t)}function fe(t={}){const s=L({...t}),e=b({});return h(s,()=>{const r={};for(const[i,n]of Object.entries(s)){const o=F(i),a=z(n,o);r[i]=a}e.value=r},{immediate:!0,deep:!0}),{state:s,style:e}}function B(t,s){h(()=>jt(t),e=>{e&&s(e)},{immediate:!0})}const pe={x:"translateX",y:"translateY",z:"translateZ"};function de(t={},s=!0){const e=L({...t}),r=b("");return h(e,i=>{let n="",o=!1;if(s&&(i.x||i.y||i.z)){const a=[i.x||0,i.y||0,i.z||0].map(f=>z(f,u)).join(",");n+=`translate3d(${a}) `,o=!0}for(const[a,f]of Object.entries(i)){if(s&&(a==="x"||a==="y"||a==="z"))continue;const p=F(a),l=z(f,p);n+=`${pe[a]||a}(${l}) `}s&&!o&&(n+="translateZ(0px) "),r.value=n.trim()},{immediate:!0,deep:!0}),{state:e,transform:r}}const me=["","X","Y","Z"],ge=["perspective","translate","scale","rotate","skew"],tt=["transformPerspective","x","y","z"];ge.forEach(t=>{me.forEach(s=>{const e=t+s;tt.push(e)})});const be=new Set(tt);function et(t){return be.has(t)}const he=new Set(["originX","originY","originZ"]);function ye(t){return he.has(t)}function ve(t,s){let e,r;const{state:i,style:n}=fe();return B(t,o=>{r=o;for(const a of Object.keys(_))o.style[a]===null||o.style[a]===""||et(a)||ye(a)||(i[a]=o.style[a]);e&&Object.entries(e).forEach(([a,f])=>o.style[a]=f),s&&s(i)}),h(n,o=>{if(!r){e=o;return}for(const a in o)r.style[a]=o[a]},{immediate:!0}),{style:i}}function xe(t){const s=t.trim().split(/\) |\)/);if(s.length===1)return{};const e=r=>r.endsWith("px")||r.endsWith("deg")?Number.parseFloat(r):Number.isNaN(Number(r))?Number(r):r;return s.reduce((r,i)=>{if(!i)return r;const[n,o]=i.split("("),f=o.split(",").map(l=>e(l.endsWith(")")?l.replace(")",""):l.trim())),p=f.length===1?f[0]:f;return{...r,[n]:p}},{})}function Te(t,s){Object.entries(xe(s)).forEach(([e,r])=>{const i=["x","y","z"];if(e==="translate3d"){if(r===0){i.forEach(n=>t[n]=0);return}r.forEach((n,o)=>t[i[o]]=n);return}if(r=Number.parseFloat(`${r}`),e==="translateX"){t.x=r;return}if(e==="translateY"){t.y=r;return}if(e==="translateZ"){t.z=r;return}t[e]=r})}function Ae(t,s){let e,r;const{state:i,transform:n}=de();return B(t,o=>{r=o,o.style.transform&&Te(i,o.style.transform),e&&(o.style.transform=e),s&&s(i)}),h(n,o=>{if(!r){e=o;return}r.style.transform=o},{immediate:!0}),{transform:i}}function Oe(t){return Object.entries(t)}function we(t,s){const e=L({}),r=o=>Object.entries(o).forEach(([a,f])=>e[a]=f),{style:i}=ve(t,r),{transform:n}=Ae(t,r);return h(e,o=>{Oe(o).forEach(([a,f])=>{const p=et(a)?n:i;p[a]&&p[a]===f||(p[a]=f)})},{immediate:!0,deep:!0}),B(t,()=>s),{motionProperties:e,style:i,transform:n}}function Se(t={}){const s=A(t),e=b();return{state:k(()=>{if(e.value)return s[e.value]}),variant:e}}function ke(t,s={},e){const{motionProperties:r}=we(t),{variant:i,state:n}=Se(s),o=se(r,s),a={target:t,variant:i,variants:s,state:n,motionProperties:r,...o};return ce(a,e),a}const Ee={relative:""},je={key:0,absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},Pe={text:"neutral-300 dark:neutral-500","text-nowrap":""},Ve={"text-nowrap":"","text-3xl":"","font-semibold":""},Ce=G({__name:"PageHeader",props:{title:null,subtitle:null},setup(t){const s=t,e=Ct(),r=J(),i=b(),n=b(s.title),o=b(s.subtitle),{apply:a}=ke(i,{initial:{opacity:0,x:10,transition:{duration:250}},enter:{opacity:1,x:0,transition:{duration:250}},leave:{opacity:0,x:-5,transition:{duration:100}}});return Pt(async()=>{await a("initial"),await a("enter")}),Vt(async()=>{await a("leave")}),h([()=>s.title,()=>s.subtitle,r],async()=>{await a("leave"),n.value=s.title,o.value=s.subtitle,await a("initial"),await a("enter")}),(f,p)=>(D(),M("div",{ref_key:"pageHeaderRef",ref:i,style:{top:"env(safe-area-inset-top, 0px)",right:"env(safe-area-inset-right, 0px)",left:"env(safe-area-inset-left, 0px)"},sticky:"","inset-x-0":"","top-0":"","z-99":"","w-full":"","pb-6":"","pt-10":"",flex:"~ row items-center gap-2",bg:"$bg-color"},[S("button",{onClick:p[0]||(p[0]=l=>A(e).back())},p[1]||(p[1]=[S("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),S("h1",Ee,[o.value?(D(),M("div",je,[S("span",Pe,W(o.value),1)])):Nt("",!0),S("div",Ve,W(n.value),1)])],512))}}),Ne={style:{paddingBottom:"env(safe-area-inset-bottom, 0px)",paddingTop:"env(safe-area-inset-top, 0px)",paddingRight:"env(safe-area-inset-right, 0px)",paddingLeft:"env(safe-area-inset-left, 0px)"}},Re={class:"px-0 py-1 md:px-3 md:py-3","w-full":"","gap-2":"",bg:"$bg-color"},Me={class:"px-3 py-2 md:px-5 md:py-5",flex:"~ col","mx-auto":"","max-w-screen-xl":""},Ie=G({__name:"settings",setup(t){const s=J(),{t:e}=Rt(),r=zt(),{allProvidersMetadata:i}=Mt(r),n=k(()=>{const a={"/settings/airi-card":{subtitle:e("settings.title"),title:e("settings.pages.card.title")},"/settings/appearance":{subtitle:e("settings.title"),title:e("settings.pages.themes.title")},"/settings/memory":{subtitle:e("settings.title"),title:e("settings.pages.memory.title")},"/settings/models":{subtitle:e("settings.title"),title:e("settings.pages.models.title")},"/settings/modules":{subtitle:e("settings.title"),title:e("settings.pages.modules.title")},"/settings/modules/consciousness":{subtitle:e("settings.title"),title:e("settings.pages.modules.consciousness.title")},"/settings/modules/speech":{subtitle:e("settings.title"),title:e("settings.pages.modules.speech.title")},"/settings/modules/hearing":{subtitle:e("settings.title"),title:e("settings.pages.modules.hearing.title")},"/settings/modules/memory-short-term":{subtitle:e("settings.title"),title:e("settings.pages.modules.memory-short-term.title")},"/settings/modules/memory-long-term":{subtitle:e("settings.title"),title:e("settings.pages.modules.memory-long-term.title")},"/settings/modules/messaging-discord":{subtitle:e("settings.title"),title:e("settings.pages.modules.messaging-discord.title")},"/settings/modules/x":{subtitle:e("settings.title"),title:e("settings.pages.modules.x.title")},"/settings/modules/gaming-minecraft":{subtitle:e("settings.title"),title:e("settings.pages.modules.gaming-minecraft.title")},"/settings/modules/gaming-factorio":{subtitle:e("settings.title"),title:e("settings.pages.modules.gaming-factorio.title")},"/settings/providers":{subtitle:e("settings.title"),title:e("settings.pages.providers.title")},"/settings/scene":{subtitle:e("settings.title"),title:e("settings.pages.scene.title")},"/settings":{title:e("settings.title")}};for(const f of i.value)a[`/settings/providers/${f.id}`]={subtitle:e("settings.title"),title:e(f.nameKey)};return a}),o=k(()=>n.value[s.path]);return(a,f)=>{var p,l;return D(),M("div",Ne,[S("div",Re,[V(Lt)]),S("div",Me,[V(A(Ce),{title:(p=o.value)==null?void 0:p.title,subtitle:(l=o.value)==null?void 0:l.subtitle},null,8,["title","subtitle"]),V(A(Dt))])])}}});export{Ie as default}; diff --git a/assets/settings-IVO3Yq5k.js b/assets/settings-IVO3Yq5k.js new file mode 100644 index 0000000000000000000000000000000000000000..3802fbaacb7e873b64a072c79acefc695997023b --- /dev/null +++ b/assets/settings-IVO3Yq5k.js @@ -0,0 +1 @@ +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as y,r as p,U as h,H as w,I as k,v as H,c as m,e as a,b as c,S as R,j as $,t as v,o as f,V as _,g as M,s as V,h as x,i as d,R as B}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as S}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{H as C}from"./HeaderLink-DVu0ldr4.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";const N={relative:""},P={key:0,absolute:"","left-0":"","top-0":"","translate-y":"[-80%]"},I={text:"neutral-300 dark:neutral-500","text-nowrap":""},L={"text-nowrap":"","text-3xl":"","font-semibold":""},T=y({__name:"PageHeader",props:{title:null,subtitle:null},setup(b){const s=b,t=R(),g=_(),l=p(),o=p(s.title),n=p(s.subtitle),{apply:e}=h(l,{initial:{opacity:0,x:10,transition:{duration:250}},enter:{opacity:1,x:0,transition:{duration:250}},leave:{opacity:0,x:-5,transition:{duration:100}}});return w(async()=>{await e("initial"),await e("enter")}),k(async()=>{await e("leave")}),H([()=>s.title,()=>s.subtitle,g],async()=>{await e("leave"),o.value=s.title,n.value=s.subtitle,await e("initial"),await e("enter")}),(r,i)=>(f(),m("div",{ref_key:"pageHeaderRef",ref:l,style:{top:"env(safe-area-inset-top, 0px)",right:"env(safe-area-inset-right, 0px)",left:"env(safe-area-inset-left, 0px)"},sticky:"","inset-x-0":"","top-0":"","z-99":"","w-full":"","pb-6":"","pt-10":"",flex:"~ row items-center gap-2",bg:"$bg-color"},[a("button",{onClick:i[0]||(i[0]=u=>c(t).back())},i[1]||(i[1]=[a("div",{"i-solar:alt-arrow-left-line-duotone":"","text-2xl":""},null,-1)])),a("h1",N,[n.value?(f(),m("div",P,[a("span",I,v(n.value),1)])):$("",!0),a("div",L,v(o.value),1)])],512))}}),U={style:{paddingBottom:"env(safe-area-inset-bottom, 0px)",paddingTop:"env(safe-area-inset-top, 0px)",paddingRight:"env(safe-area-inset-right, 0px)",paddingLeft:"env(safe-area-inset-left, 0px)"}},j={class:"px-0 py-1 md:px-3 md:py-3","w-full":"","gap-2":"",bg:"$bg-color"},z={class:"px-3 py-2 md:px-5 md:py-5",flex:"~ col","mx-auto":"","max-w-screen-xl":""},W=y({__name:"settings",setup(b){const s=_(),{t}=M(),g=S(),{allProvidersMetadata:l}=V(g),o=x(()=>{const e={"/settings/airi-card":{subtitle:t("settings.title"),title:t("settings.pages.card.title")},"/settings/appearance":{subtitle:t("settings.title"),title:t("settings.pages.themes.title")},"/settings/memory":{subtitle:t("settings.title"),title:t("settings.pages.memory.title")},"/settings/models":{subtitle:t("settings.title"),title:t("settings.pages.models.title")},"/settings/modules":{subtitle:t("settings.title"),title:t("settings.pages.modules.title")},"/settings/modules/consciousness":{subtitle:t("settings.title"),title:t("settings.pages.modules.consciousness.title")},"/settings/modules/speech":{subtitle:t("settings.title"),title:t("settings.pages.modules.speech.title")},"/settings/modules/hearing":{subtitle:t("settings.title"),title:t("settings.pages.modules.hearing.title")},"/settings/modules/memory-short-term":{subtitle:t("settings.title"),title:t("settings.pages.modules.memory-short-term.title")},"/settings/modules/memory-long-term":{subtitle:t("settings.title"),title:t("settings.pages.modules.memory-long-term.title")},"/settings/modules/messaging-discord":{subtitle:t("settings.title"),title:t("settings.pages.modules.messaging-discord.title")},"/settings/modules/x":{subtitle:t("settings.title"),title:t("settings.pages.modules.x.title")},"/settings/modules/gaming-minecraft":{subtitle:t("settings.title"),title:t("settings.pages.modules.gaming-minecraft.title")},"/settings/modules/gaming-factorio":{subtitle:t("settings.title"),title:t("settings.pages.modules.gaming-factorio.title")},"/settings/providers":{subtitle:t("settings.title"),title:t("settings.pages.providers.title")},"/settings/scene":{subtitle:t("settings.title"),title:t("settings.pages.scene.title")},"/settings":{title:t("settings.title")}};for(const r of l.value)e[`/settings/providers/${r.id}`]={subtitle:t("settings.title"),title:t(r.nameKey)};return e}),n=x(()=>o.value[s.path]);return(e,r)=>{var i,u;return f(),m("div",U,[a("div",j,[d(C)]),a("div",z,[d(c(T),{title:(i=n.value)==null?void 0:i.title,subtitle:(u=n.value)==null?void 0:u.subtitle},null,8,["title","subtitle"]),d(c(B))])])}}});export{W as default}; diff --git a/assets/speech-BJorZHUt.js b/assets/speech-Cqx5-wPK.js similarity index 96% rename from assets/speech-BJorZHUt.js rename to assets/speech-Cqx5-wPK.js index 12cae33db4ad6603193dc946bc3e03df68ff82a9..6e437c7a3bfe3521cfaaef5c7a672c3b32dc45e1 100644 --- a/assets/speech-BJorZHUt.js +++ b/assets/speech-Cqx5-wPK.js @@ -1 +1 @@ -import{d as j,r as V,H as ae,v as X,f as re,c as u,o as i,F as H,l as Y,e,z as ve,n as $,m as W,u as K,x as Q,bH as me,j as P,t as y,i as S,b as t,w as I,_ as Z,h as pe,bo as fe,y as ne,A as J,g as ge,s as te,I as xe,K as he,P as be,Q as F,at as ye}from"./index-BQKiy4UR.js";import{_ as se,a as le,b as ke}from"./FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as we}from"./providers-kjOpfeNb.js";import{u as _e,g as Se}from"./speech-Db_L6FBm.js";import{_ as Ve}from"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as Me}from"./Textarea.vue_vue_type_script_setup_true_lang-DVC_B13e.js";import{R as Ce,a as $e}from"./RadioCardSimple-DdnP6Fc5.js";import{_ as Pe}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import{_ as Ue}from"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import{b as oe}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-BYlTp0xC.js";const Le=j({__name:"AudioSpectrum",props:{stream:null,bars:{default:32},minFreq:{default:60},maxFreq:{default:4e3}},setup(l){const o=l,g=V(Array.from({length:o.bars}).fill(0));ae(()=>{m()}),X(()=>o.stream,()=>{m()});function m(){if(!o.stream)return;const c=new(window.AudioContext||window.webkitAudioContext),f=c.createMediaStreamSource(o.stream),v=c.createAnalyser();v.fftSize=2048,f.connect(v);const h=v.frequencyBinCount,M=new Uint8Array(h),p=c.sampleRate/v.fftSize,k=Math.floor(o.minFreq/p),U=Math.floor(o.maxFreq/p),q=U-k,R=Math.floor(q/o.bars),T=()=>{try{requestAnimationFrame(T),v.getByteFrequencyData(M);const A=Array.from({length:o.bars}).fill(0);for(let z=0;zre(c.$slots,"default",{frequencies:g.value})}}),qe={"h-full":"",flex:"","items-center":"","gap-1":""},Ae=5,Re=j({__name:"AudioSpectrumVisualizer",props:{frequencies:null,barsClass:null},setup(l){const o=l;function g(c,f){return .1+(1-.1)*(c/f)}function m(c,f){const v=g(f,o.frequencies.length);return Math.min(100,Math.max(10,c*100*Ae*v))}return(c,f)=>(i(),u("div",qe,[(i(!0),u(H,null,Y(l.frequencies,(v,h)=>(i(),u("div",{key:h,"h-full":"",flex:"","flex-1":"","items-end":""},[e("div",{transition:"all 100 ease-in-out","mx-auto":"","my-0":"","w-full":"","rounded-full":"",class:$(l.barsClass),style:ve({height:`${m(v,h)}%`})},null,6)]))),128))]))}}),Ee={class:"p-3"},Te={class:"flex items-start"},ze=["checked","name","value"],Be={class:"relative mr-3 mt-0.5 flex-shrink-0"},Fe={key:0,class:"i-solar:pause-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},Ie={key:1,class:"i-solar:play-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},Ne={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"},De={class:"flex items-center"},Oe={key:0,class:"mt-1 flex flex-wrap gap-1"},Qe={key:1,class:"mt-3"},He={relative:""},Ge={key:0,class:"h-16 px-3 pb-2"},Je=j({__name:"VoiceCard",props:W({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:W(["togglePlayback"],["update:voice-id","update:custom-voice-name"]),setup(l,{emit:o}){const g=l,m=o,c=K(l,"voice-id"),f=K(l,"custom-voice-name");function v(b){return b.previewURL||b.preview_audio_url}function h(b){var k,U,q;const p=[];if((k=b.labels)!=null&&k.gender&&p.push(b.labels.gender),(U=b.labels)!=null&&U.age&&p.push(b.labels.age),(q=b.labels)!=null&&q.accent&&p.push(b.labels.accent),b.languages&&b.languages.length>0){const R=b.languages.map(T=>T.name).join(", ");p.push(R)}return p}function M(){m("togglePlayback",g.voice)}return(b,p)=>(i(),u("label",{border:"2px solid",class:$(["scroll-snap-align-start form_voice-card relative flex flex-col overflow-hidden rounded-xl",[c.value===g.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===g.voice.id?"form_voice-card-active":""]]),transition:"all duration-200 ease-in-out"},[e("div",Ee,[e("div",Te,[Q(e("input",{"onUpdate:modelValue":p[0]||(p[0]=k=>c.value=k),checked:c.value===g.voice.id,type:"radio",name:l.name,value:g.voice.id,class:"absolute cursor-pointer opacity-0"},null,8,ze),[[me,c.value]]),e("div",Be,[e("div",{class:$(["size-5 border-2 rounded-full transition-colors duration-200",[c.value===g.voice.id?"border-primary-500 dark:border-primary-400":"border-neutral-300 dark:border-neutral-600"]])},[e("div",{class:$(["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===g.voice.id?"opacity-100 bg-primary-500 dark:bg-primary-400":"opacity-0"]])},null,2)],2)]),v(l.voice)?(i(),u("button",{key:0,absolute:"","right-0":"",top:"0","z-3":"",class:$(["translate-x-[-50%] translate-y-[50%]",[l.currentlyPlayingId===l.voice.id?"text-white dark:text-white":""]]),onClick:M},[l.currentlyPlayingId===l.voice.id?(i(),u("div",Fe)):(i(),u("div",Ie))],2)):(i(),u("div",Ne," No preview available ")),e("div",je,[e("div",De,[e("span",{class:$(["line-clamp-1 font-medium",[c.value===l.voice.id?"text-neutral-700 dark:text-neutral-300":"text-neutral-700 dark:text-neutral-400"]])},y(l.voice.name),3)]),h(l.voice).length>0?(i(),u("div",Oe,[(i(!0),u(H,null,Y(h(l.voice),(k,U)=>(i(),u("span",{key:U,class:$(["inline-flex items-center rounded-md px-1.5 py-0.5 text-xs",[c.value===l.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"]])},y(k),3))),128))])):P("",!0),l.voice.customizable&&c.value===l.voice.id?(i(),u("div",Qe,[S(t(Ue),{modelValue:f.value,"onUpdate:modelValue":p[1]||(p[1]=k=>f.value=k),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:l.customInputPlaceholder},null,8,["modelValue","placeholder"])])):P("",!0),l.voice.description?(i(),u("div",{key:2,class:$(["line-clamp-2 mt-1 text-xs",[c.value===l.voice.id?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]])},y(l.voice.description),3)):P("",!0)])])]),e("div",He,[S(t(Pe),null,{default:I(()=>[l.showVisualizer&&l.currentlyPlayingId===l.voice.id&&l.audioStream?(i(),u("div",Ge,[S(t(Le),{stream:l.audioStream,bars:24,"min-freq":60,"max-freq":4e3},{default:I(({frequencies:k})=>[S(t(Re),{frequencies:k,"bars-class":c.value===l.voice.id?"bg-primary-500 dark:bg-primary-400":"bg-neutral-400 dark:bg-neutral-600"},null,8,["frequencies","bars-class"])]),_:1},8,["stream"])])):P("",!0)]),_:1})])],2))}}),Ke=Z(Je,[["__scopeId","data-v-a5ae8da9"]]),Ye={class:"voice-preview-player"},We={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},Xe=["placeholder"],Ze={class:"mt-4 space-y-2"},et={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},tt={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"},st={class:"flex flex-col"},lt={class:"font-medium"},ot={class:"text-sm text-amber-600 dark:text-amber-400"},at={class:"relative"},rt=j({__name:"VoiceCardManySelect",props:W({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(l){const o=l,g=V(!1),m=V(),c=V(new Map),f=V(new Map),v=V(new Map),h=V(new Map),M=V(null);function b(){return M.value||(M.value=new(window.AudioContext||window.webkitAudioContext)),M.value}const p=K(l,"search-query"),k=K(l,"voice-id"),U=pe(()=>{if(!p.value)return o.voices;const a=p.value.toLowerCase();return o.voices.filter(r=>{const n=r.name.toLowerCase().includes(a),x=r.description&&r.description.toLowerCase().includes(a),w=r.tags&&r.tags.some(_=>_.toLowerCase().includes(a)),L=r.labels&&Object.values(r.labels).some(_=>typeof _=="string"&&_.toLowerCase().includes(a)),C=r.languages&&r.languages.some(_=>_.name.toLowerCase().includes(a)||_.code.toLowerCase().includes(a));return n||x||w||L||C})});function q(a){return a.previewURL||a.preview_audio_url}function R(a){const r=q(a);if(!r)return null;if(c.value.has(a.id))return c.value.get(a.id)||null;const n=new Audio(r);return n.crossOrigin="anonymous",n.preload="auto",n.addEventListener("ended",()=>{if(m.value===a.id){m.value=void 0;const x=f.value.get(a.id);x&&(x.getTracks().forEach(w=>w.stop()),f.value.delete(a.id))}}),c.value.set(a.id,n),n}function T(a,r){try{if(f.value.has(r))return f.value.get(r)||null;const n=b();if(h.value.has(r)){const C=h.value.get(r),_=n.createMediaStreamDestination();C.connect(_);const D=_.stream;return f.value.set(r,D),D}const x=n.createMediaElementSource(a);h.value.set(r,x),x.connect(n.destination);const w=n.createMediaStreamDestination();x.connect(w);const L=w.stream;return f.value.set(r,L),L}catch(n){return console.error("Failed to create audio stream for visualizer:",n),null}}function A(a){try{if(!q(a))return;const n=R(a);if(!n)return;if(m.value===a.id){n.pause(),m.value=void 0;const x=f.value.get(a.id);x&&(x.getTracks().forEach(w=>w.stop()),f.value.delete(a.id));return}if(m.value){const x=c.value.get(m.value);x&&x.pause();const w=f.value.get(m.value);w&&(w.getTracks().forEach(L=>L.stop()),f.value.delete(m.value))}o.showVisualizer&&!f.value.has(a.id)&&T(n,a.id),n.currentTime=0,n.play().catch(x=>{console.error("Failed to play audio:",x)}),m.value=a.id}catch(r){console.error(r),m.value=void 0}}function z(){c.value.forEach(a=>{a.pause(),a.src=""}),c.value.clear(),f.value.forEach(a=>{a.getTracks().forEach(r=>r.stop())}),f.value.clear(),v.value.forEach(a=>{a.state!=="closed"&&a.close()}),v.value.clear(),h.value.clear(),m.value=void 0}X(p,()=>{if(m.value){const a=c.value.get(m.value);a&&a.pause();const r=f.value.get(m.value);r&&(r.getTracks().forEach(n=>n.stop()),f.value.delete(m.value)),m.value=void 0}}),fe(z);const B=V("");return(a,r)=>(i(),u("div",Ye,[l.searchable?(i(),u("div",We,[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)),Q(e("input",{"onUpdate:modelValue":r[0]||(r[0]=n=>p.value=n),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:l.searchPlaceholder},null,8,Xe),[[ne,p.value]])])):P("",!0),e("div",Ze,[p.value?(i(),u("div",et,y(l.searchResultsText.replace("{count}",U.value.length.toString()).replace("{total}",l.voices.length.toString())),1)):P("",!0),p.value&&U.value.length===0?(i(),u("div",tt,[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",st,[e("span",lt,y(l.searchNoResultsTitle),1),e("span",ot,y(l.searchNoResultsDescription.replace("{query}",p.value)),1)])])):P("",!0),e("div",at,[e("div",{class:$(["grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto scrollbar-none",[g.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"}},[(i(!0),u(H,null,Y(U.value,n=>(i(),J(Ke,{key:n.id,"voice-id":k.value,"onUpdate:voiceId":r[1]||(r[1]=x=>k.value=x),"custom-voice-name":B.value,"onUpdate:customVoiceName":r[2]||(r[2]=x=>B.value=x),name:"voice",voice:n,"currently-playing-id":m.value,"custom-input-placeholder":l.customInputPlaceholder,"show-visualizer":l.showVisualizer,"audio-stream":f.value.get(n.id),onTogglePlayback:A},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:$([g.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:$([g.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]=n=>g.value=!g.value)},[e("span",null,y(g.value?l.collapseButtonText:l.expandButtonText),1),e("div",{class:$([g.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),nt=Z(rt,[["__scopeId","data-v-4dd3b9e2"]]),it=j({__name:"Skeleton",props:{animation:{default:"pulse"}},setup(l){const o=l;return(g,m)=>(i(),u("div",{class:$(["skeleton",o.animation!=="none"?`skeleton-${o.animation}`:""]),bg:"neutral-200 dark:neutral-800",overflow:"hidden"},[re(g.$slots,"default",{},void 0,!0)],2))}}),O=Z(it,[["__scopeId","data-v-f404da2a"]]),ut={flex:"~ col md:row gap-6"},dt={bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4",class:"w-full md:w-[40%]"},ct={flex:"~ col gap-4"},vt={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},mt={text:"neutral-400 dark:neutral-500"},pt={"max-w-full":""},ft={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},gt={key:1},xt={key:0},ht={flex:"~ col gap-4"},bt={class:"text-lg md:text-2xl"},yt={text:"neutral-400 dark:neutral-400"},kt={key:0,class:"flex items-center justify-center py-4"},wt={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"},_t={class:"flex flex-col"},St={class:"font-medium"},Vt={class:"text-sm text-red-600 dark:text-red-400"},Mt={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"},Ct={class:"flex flex-col"},$t={class:"font-medium"},Pt={class:"text-sm text-amber-600 dark:text-amber-400"},Ut={key:0},Lt={flex:"~ col gap-4"},qt={key:0},At={class:"flex flex-col gap-4"},Rt={flex:"~ row gap-4"},Et={key:1,class:"space-y-6"},Tt={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"},zt={class:"flex flex-col"},Bt={class:"text-sm text-red-600 dark:text-red-400"},Ft={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"},It={flex:"~ col gap-4"},Nt={key:4,class:"mt-2 space-y-6"},jt={key:0},Dt={flex:"~ col gap-4"},Ot={flex:"~ col gap-6",class:"w-full md:w-[60%]"},Qt={"w-full":"","rounded-xl":""},Ht={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},Gt={class:"inline-flex items-center gap-4"},Jt={flex:"~ col gap-4"},Kt={flex:"~ row","gap-4":""},Yt=["disabled"],Wt={flex:"~ row","items-center":"","gap-2":""},Xt=["src"],Zt={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},es=j({__name:"speech",setup(l){const{t:o}=ge(),g=we(),m=_e(),{availableProviders:c,availableAudioSpeechProvidersMetadata:f}=te(g),{activeSpeechProvider:v,activeSpeechModel:h,activeSpeechVoice:M,activeSpeechVoiceId:b,pitch:p,isLoadingSpeechProviderVoices:k,supportsModelListing:U,providerModels:q,isLoadingActiveProviderModels:R,activeProviderModelError:T,modelSearchQuery:A,speechProviderError:z,ssmlEnabled:B,availableVoices:a}=te(m),r=V(""),n=V(!1),x=V("Hello, my name is AI Assistant"),w=V(""),L=V(!1),C=V(""),_=V(null),D=V("");ae(async()=>{await g.loadModelsForConfiguredProviders(),await m.loadVoicesForProvider(v.value)}),X(v,async()=>{await g.loadModelsForConfiguredProviders(),await m.loadVoicesForProvider(v.value)});async function ie(){if(!x.value.trim()&&!n.value||n.value&&!w.value.trim())return;if(!h.value){console.error("No model selected");return}if(!M.value){console.error("No voice selected");return}const E=g.getProviderInstance(v.value);if(!E){console.error("Failed to initialize speech provider");return}const s=g.getProviderConfig(v.value);L.value=!0,D.value="";try{C.value&&ee();const N=n.value?w.value:m.generateSSML(x.value,M.value,{...s,pitch:p.value}),G=await Se({...E.speech(h.value,s),input:N,voice:M.value.id});C.value=URL.createObjectURL(new Blob([G])),setTimeout(()=>{_.value&&_.value.play()},100)}catch(N){console.error("Error generating speech:",N),D.value=N instanceof Error?N.message:"An unknown error occurred"}finally{L.value=!1}}function ee(){_.value&&(_.value.pause(),_.value.currentTime=0),C.value&&(URL.revokeObjectURL(C.value),C.value="")}xe(()=>{C.value&&URL.revokeObjectURL(C.value)});function ue(E){M.value={id:E,name:E,description:E,previewURL:E,languages:[{code:"en",title:"English"}],provider:v.value,gender:"male"}}function de(E){h.value=E}return(E,s)=>{var G;const N=he("motion");return i(),u(H,null,[e("div",ut,[e("div",dt,[e("div",null,[e("div",ct,[e("div",null,[e("h2",vt,y(t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.title")),1),e("div",mt,[e("span",null,y(t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.description")),1)])]),e("div",pt,[t(c).length>0?(i(),u("fieldset",ft,[(i(!0),u(H,null,Y(t(f),d=>(i(),J(t($e),{id:d.id,key:d.id,modelValue:t(v),"onUpdate:modelValue":s[0]||(s[0]=ce=>F(v)?v.value=ce:null),name:"speech-provider",value:d.id,title:d.localizedName,description:d.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(i(),u("div",gt,[S(t(be),{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:I(()=>s[13]||(s[13]=[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(U)?(i(),u("div",xt,[e("div",ht,[e("div",null,[e("h2",bt,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",yt,[e("span",null,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),t(R)?(i(),u("div",kt,[s[14]||(s[14]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):t(T)?(i(),u("div",wt,[s[15]||(s[15]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",_t,[e("span",St,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",Vt,y(t(T)),1)])])):t(q).length===0&&!t(R)?(i(),u("div",Mt,[s[16]||(s[16]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",Ct,[e("span",$t,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",Pt,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):t(q).length>0?(i(),J(t(Ce),{key:3,modelValue:t(h),"onUpdate:modelValue":s[1]||(s[1]=d=>F(h)?h.value=d:null),"search-query":t(A),"onUpdate:searchQuery":s[2]||(s[2]=d=>F(A)?A.value=d:null),items:t(q),searchable:!0,"search-placeholder":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:t(A)}),"search-results-text":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":de},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"])):P("",!0)])])):P("",!0)])]),t(v)?(i(),u("div",Ut,[e("div",Lt,[s[27]||(s[27]=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(k)?(i(),u("div",qt,[e("div",At,[S(t(O),{class:"w-full rounded-lg p-2.5 text-sm"},{default:I(()=>s[17]||(s[17]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),e("div",Rt,[S(t(O),{class:"w-full rounded-lg p-4 text-sm"},{default:I(()=>s[18]||(s[18]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(O),{class:"w-full rounded-lg p-4 text-sm"},{default:I(()=>s[19]||(s[19]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(O),{class:"w-full rounded-lg p-4 text-sm"},{default:I(()=>s[20]||(s[20]=[e("div",{class:"h-1lh"},null,-1)])),_:1})]),S(t(O),{class:"w-full rounded-lg p-3 text-sm"},{default:I(()=>s[21]||(s[21]=[e("div",{class:"h-1lh"},null,-1)])),_:1})])])):t(a)[t(v)]&&t(a)[t(v)].length>0?(i(),u("div",Et,[S(t(nt),{"search-query":r.value,"onUpdate:searchQuery":s[3]||(s[3]=d=>r.value=d),"voice-id":t(b),"onUpdate:voiceId":s[4]||(s[4]=d=>F(b)?b.value=d:null),voices:(G=t(a)[t(v)])==null?void 0:G.map(d=>({id:d.id,name:d.name,description:d.description,previewURL:d.previewURL,customizable:!1})),searchable:!0,"search-placeholder":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_placeholder"),"search-no-results-title":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices"),"search-no-results-description":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices_description"),"search-results-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_results",{count:0,total:0}),"custom-input-placeholder":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.custom_voice_placeholder"),"expand-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_more"),"collapse-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_less"),"play-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.play_sample"),"pause-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.pause"),"onUpdate:customValue":ue},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(z)?(i(),u("div",Tt,[s[23]||(s[23]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",zt,[s[22]||(s[22]=e("span",{class:"font-medium"},"Error loading voices",-1)),e("span",Bt,y(t(z)),1)])])):(i(),u("div",Ft,s[24]||(s[24]=[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",It,[S(t(se),{modelValue:t(p),"onUpdate:modelValue":s[5]||(s[5]=d=>F(p)?p.value=d:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":d=>`${d}%`},null,8,["modelValue","format-value"]),S(t(le),{modelValue:t(B),"onUpdate:modelValue":s[6]||(s[6]=d=>F(B)?B.value=d: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?(i(),u("div",Nt,[S(t(Ve),{modelValue:t(b),"onUpdate:modelValue":s[7]||(s[7]=d=>F(b)?b.value=d: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"?(i(),u("div",jt,[s[26]||(s[26]=e("label",{class:"mb-1 block text-sm font-medium"}," Model ",-1)),Q(e("select",{"onUpdate:modelValue":s[8]||(s[8]=d=>F(h)?h.value=d:null),class:"w-full border border-neutral-300 rounded bg-white px-3 py-2 dark:border-neutral-700 dark:bg-neutral-900"},s[25]||(s[25]=[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),[[ye,t(h)]])])):P("",!0),e("div",Dt,[S(t(se),{modelValue:t(p),"onUpdate:modelValue":s[9]||(s[9]=d=>F(p)?p.value=d:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":d=>`${d}%`},null,8,["modelValue","format-value"])])])):P("",!0)])])):P("",!0)]),e("div",Ot,[e("div",Qt,[e("h2",Ht,[e("div",Gt,[S(t(ke)),e("div",null,y(t(o)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),e("div",Jt,[S(t(le),{modelValue:n.value,"onUpdate:modelValue":s[10]||(s[10]=d=>n.value=d),label:"Use Custom SSML",description:"Enable to input raw SSML instead of plain text"},null,8,["modelValue"]),n.value?Q((i(),u("textarea",{key:1,"onUpdate:modelValue":s[12]||(s[12]=d=>w.value=d),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)),[[ne,w.value]]):(i(),J(t(Me),{key:0,modelValue:x.value,"onUpdate:modelValue":s[11]||(s[11]=d=>x.value=d),"h-24":"","w-full":"",placeholder:t(o)("settings.pages.providers.provider.elevenlabs.playground.fields.field.input.placeholder")},null,8,["modelValue","placeholder"])),e("div",Kt,[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:L.value||!x.value.trim()&&!n.value||n.value&&!w.value.trim()||!t(M),class:$({"opacity-50 cursor-not-allowed":L.value||!x.value.trim()&&!n.value||n.value&&!w.value.trim()||!t(M)}),bg:"neutral-700 dark:neutral-300",onClick:ie},[e("div",Wt,[s[28]||(s[28]=e("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),e("span",null,y(L.value?t(o)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):t(o)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,Yt),C.value?(i(),u("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:ee},s[29]||(s[29]=[e("div",{flex:"~ row","items-center":"","gap-2":""},[e("div",{"i-solar:stop-circle-bold-duotone":""}),e("span",null,"Stop")],-1)]))):P("",!0)]),C.value?(i(),u("audio",{key:2,ref_key:"audioPlayer",ref:_,src:C.value,controls:"",class:"mt-2 w-full"},null,8,Xt)):P("",!0)])])])]),Q((i(),u("div",Zt,s[30]||(s[30]=[e("div",{text:"60","i-solar:user-speak-rounded-bold-duotone":""},null,-1)]))),[[N]])],64)}}});typeof oe=="function"&&oe(es);export{es as default}; +import{d as j,r as V,H as ae,v as X,f as re,c as u,o as i,F as H,l as Y,e,z as ve,n as $,m as W,u as K,x as Q,ba as me,j as P,t as y,i as S,b as t,w as I,_ as Z,h as pe,aS as fe,y as ne,A as J,g as ge,s as te,I as xe,K as he,P as be,Q as F,av as ye}from"./index-CQudhZin.js";import{_ as se,a as le,b as ke}from"./FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js";import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as we}from"./providers-Y3Mr8_DF.js";import{u as _e,g as Se}from"./speech-nVAae-rt.js";import{_ as Ve}from"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as Me}from"./Textarea.vue_vue_type_script_setup_true_lang-C31IYM5N.js";import{R as Ce,a as $e}from"./RadioCardSimple-B-Oog_Qf.js";import{_ as Pe}from"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import{_ as Ue}from"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import{b as oe}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Basic.vue_vue_type_script_setup_true_lang-CE9v8NjX.js";const Le=j({__name:"AudioSpectrum",props:{stream:null,bars:{default:32},minFreq:{default:60},maxFreq:{default:4e3}},setup(l){const o=l,g=V(Array.from({length:o.bars}).fill(0));ae(()=>{m()}),X(()=>o.stream,()=>{m()});function m(){if(!o.stream)return;const c=new(window.AudioContext||window.webkitAudioContext),f=c.createMediaStreamSource(o.stream),v=c.createAnalyser();v.fftSize=2048,f.connect(v);const h=v.frequencyBinCount,M=new Uint8Array(h),p=c.sampleRate/v.fftSize,k=Math.floor(o.minFreq/p),U=Math.floor(o.maxFreq/p),q=U-k,R=Math.floor(q/o.bars),T=()=>{try{requestAnimationFrame(T),v.getByteFrequencyData(M);const A=Array.from({length:o.bars}).fill(0);for(let z=0;zre(c.$slots,"default",{frequencies:g.value})}}),qe={"h-full":"",flex:"","items-center":"","gap-1":""},Ae=5,Re=j({__name:"AudioSpectrumVisualizer",props:{frequencies:null,barsClass:null},setup(l){const o=l;function g(c,f){return .1+(1-.1)*(c/f)}function m(c,f){const v=g(f,o.frequencies.length);return Math.min(100,Math.max(10,c*100*Ae*v))}return(c,f)=>(i(),u("div",qe,[(i(!0),u(H,null,Y(l.frequencies,(v,h)=>(i(),u("div",{key:h,"h-full":"",flex:"","flex-1":"","items-end":""},[e("div",{transition:"all 100 ease-in-out","mx-auto":"","my-0":"","w-full":"","rounded-full":"",class:$(l.barsClass),style:ve({height:`${m(v,h)}%`})},null,6)]))),128))]))}}),Ee={class:"p-3"},Te={class:"flex items-start"},ze=["checked","name","value"],Be={class:"relative mr-3 mt-0.5 flex-shrink-0"},Fe={key:0,class:"i-solar:pause-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},Ie={key:1,class:"i-solar:play-circle-bold-duotone text-xl text-neutral-400 dark:text-neutral-500"},Ne={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"},De={class:"flex items-center"},Oe={key:0,class:"mt-1 flex flex-wrap gap-1"},Qe={key:1,class:"mt-3"},He={relative:""},Ge={key:0,class:"h-16 px-3 pb-2"},Je=j({__name:"VoiceCard",props:W({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:W(["togglePlayback"],["update:voice-id","update:custom-voice-name"]),setup(l,{emit:o}){const g=l,m=o,c=K(l,"voice-id"),f=K(l,"custom-voice-name");function v(b){return b.previewURL||b.preview_audio_url}function h(b){var k,U,q;const p=[];if((k=b.labels)!=null&&k.gender&&p.push(b.labels.gender),(U=b.labels)!=null&&U.age&&p.push(b.labels.age),(q=b.labels)!=null&&q.accent&&p.push(b.labels.accent),b.languages&&b.languages.length>0){const R=b.languages.map(T=>T.name).join(", ");p.push(R)}return p}function M(){m("togglePlayback",g.voice)}return(b,p)=>(i(),u("label",{border:"2px solid",class:$(["scroll-snap-align-start form_voice-card relative flex flex-col overflow-hidden rounded-xl",[c.value===g.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===g.voice.id?"form_voice-card-active":""]]),transition:"all duration-200 ease-in-out"},[e("div",Ee,[e("div",Te,[Q(e("input",{"onUpdate:modelValue":p[0]||(p[0]=k=>c.value=k),checked:c.value===g.voice.id,type:"radio",name:l.name,value:g.voice.id,class:"absolute cursor-pointer opacity-0"},null,8,ze),[[me,c.value]]),e("div",Be,[e("div",{class:$(["size-5 border-2 rounded-full transition-colors duration-200",[c.value===g.voice.id?"border-primary-500 dark:border-primary-400":"border-neutral-300 dark:border-neutral-600"]])},[e("div",{class:$(["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===g.voice.id?"opacity-100 bg-primary-500 dark:bg-primary-400":"opacity-0"]])},null,2)],2)]),v(l.voice)?(i(),u("button",{key:0,absolute:"","right-0":"",top:"0","z-3":"",class:$(["translate-x-[-50%] translate-y-[50%]",[l.currentlyPlayingId===l.voice.id?"text-white dark:text-white":""]]),onClick:M},[l.currentlyPlayingId===l.voice.id?(i(),u("div",Fe)):(i(),u("div",Ie))],2)):(i(),u("div",Ne," No preview available ")),e("div",je,[e("div",De,[e("span",{class:$(["line-clamp-1 font-medium",[c.value===l.voice.id?"text-neutral-700 dark:text-neutral-300":"text-neutral-700 dark:text-neutral-400"]])},y(l.voice.name),3)]),h(l.voice).length>0?(i(),u("div",Oe,[(i(!0),u(H,null,Y(h(l.voice),(k,U)=>(i(),u("span",{key:U,class:$(["inline-flex items-center rounded-md px-1.5 py-0.5 text-xs",[c.value===l.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"]])},y(k),3))),128))])):P("",!0),l.voice.customizable&&c.value===l.voice.id?(i(),u("div",Qe,[S(t(Ue),{modelValue:f.value,"onUpdate:modelValue":p[1]||(p[1]=k=>f.value=k),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:l.customInputPlaceholder},null,8,["modelValue","placeholder"])])):P("",!0),l.voice.description?(i(),u("div",{key:2,class:$(["line-clamp-2 mt-1 text-xs",[c.value===l.voice.id?"text-neutral-600 dark:text-neutral-400":"text-neutral-500 dark:text-neutral-500"]])},y(l.voice.description),3)):P("",!0)])])]),e("div",He,[S(t(Pe),null,{default:I(()=>[l.showVisualizer&&l.currentlyPlayingId===l.voice.id&&l.audioStream?(i(),u("div",Ge,[S(t(Le),{stream:l.audioStream,bars:24,"min-freq":60,"max-freq":4e3},{default:I(({frequencies:k})=>[S(t(Re),{frequencies:k,"bars-class":c.value===l.voice.id?"bg-primary-500 dark:bg-primary-400":"bg-neutral-400 dark:bg-neutral-600"},null,8,["frequencies","bars-class"])]),_:1},8,["stream"])])):P("",!0)]),_:1})])],2))}}),Ke=Z(Je,[["__scopeId","data-v-a5ae8da9"]]),Ye={class:"voice-preview-player"},We={key:0,class:"relative","inline-flex":"~","w-full":"","items-center":""},Xe=["placeholder"],Ze={class:"mt-4 space-y-2"},et={key:0,class:"text-sm text-neutral-500 dark:text-neutral-400"},tt={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"},st={class:"flex flex-col"},lt={class:"font-medium"},ot={class:"text-sm text-amber-600 dark:text-amber-400"},at={class:"relative"},rt=j({__name:"VoiceCardManySelect",props:W({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(l){const o=l,g=V(!1),m=V(),c=V(new Map),f=V(new Map),v=V(new Map),h=V(new Map),M=V(null);function b(){return M.value||(M.value=new(window.AudioContext||window.webkitAudioContext)),M.value}const p=K(l,"search-query"),k=K(l,"voice-id"),U=pe(()=>{if(!p.value)return o.voices;const a=p.value.toLowerCase();return o.voices.filter(r=>{const n=r.name.toLowerCase().includes(a),x=r.description&&r.description.toLowerCase().includes(a),w=r.tags&&r.tags.some(_=>_.toLowerCase().includes(a)),L=r.labels&&Object.values(r.labels).some(_=>typeof _=="string"&&_.toLowerCase().includes(a)),C=r.languages&&r.languages.some(_=>_.name.toLowerCase().includes(a)||_.code.toLowerCase().includes(a));return n||x||w||L||C})});function q(a){return a.previewURL||a.preview_audio_url}function R(a){const r=q(a);if(!r)return null;if(c.value.has(a.id))return c.value.get(a.id)||null;const n=new Audio(r);return n.crossOrigin="anonymous",n.preload="auto",n.addEventListener("ended",()=>{if(m.value===a.id){m.value=void 0;const x=f.value.get(a.id);x&&(x.getTracks().forEach(w=>w.stop()),f.value.delete(a.id))}}),c.value.set(a.id,n),n}function T(a,r){try{if(f.value.has(r))return f.value.get(r)||null;const n=b();if(h.value.has(r)){const C=h.value.get(r),_=n.createMediaStreamDestination();C.connect(_);const D=_.stream;return f.value.set(r,D),D}const x=n.createMediaElementSource(a);h.value.set(r,x),x.connect(n.destination);const w=n.createMediaStreamDestination();x.connect(w);const L=w.stream;return f.value.set(r,L),L}catch(n){return console.error("Failed to create audio stream for visualizer:",n),null}}function A(a){try{if(!q(a))return;const n=R(a);if(!n)return;if(m.value===a.id){n.pause(),m.value=void 0;const x=f.value.get(a.id);x&&(x.getTracks().forEach(w=>w.stop()),f.value.delete(a.id));return}if(m.value){const x=c.value.get(m.value);x&&x.pause();const w=f.value.get(m.value);w&&(w.getTracks().forEach(L=>L.stop()),f.value.delete(m.value))}o.showVisualizer&&!f.value.has(a.id)&&T(n,a.id),n.currentTime=0,n.play().catch(x=>{console.error("Failed to play audio:",x)}),m.value=a.id}catch(r){console.error(r),m.value=void 0}}function z(){c.value.forEach(a=>{a.pause(),a.src=""}),c.value.clear(),f.value.forEach(a=>{a.getTracks().forEach(r=>r.stop())}),f.value.clear(),v.value.forEach(a=>{a.state!=="closed"&&a.close()}),v.value.clear(),h.value.clear(),m.value=void 0}X(p,()=>{if(m.value){const a=c.value.get(m.value);a&&a.pause();const r=f.value.get(m.value);r&&(r.getTracks().forEach(n=>n.stop()),f.value.delete(m.value)),m.value=void 0}}),fe(z);const B=V("");return(a,r)=>(i(),u("div",Ye,[l.searchable?(i(),u("div",We,[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)),Q(e("input",{"onUpdate:modelValue":r[0]||(r[0]=n=>p.value=n),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:l.searchPlaceholder},null,8,Xe),[[ne,p.value]])])):P("",!0),e("div",Ze,[p.value?(i(),u("div",et,y(l.searchResultsText.replace("{count}",U.value.length.toString()).replace("{total}",l.voices.length.toString())),1)):P("",!0),p.value&&U.value.length===0?(i(),u("div",tt,[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",st,[e("span",lt,y(l.searchNoResultsTitle),1),e("span",ot,y(l.searchNoResultsDescription.replace("{query}",p.value)),1)])])):P("",!0),e("div",at,[e("div",{class:$(["grid auto-cols-[350px] grid-flow-col max-h-[calc(100dvh-7lh)] gap-4 overflow-x-auto scrollbar-none",[g.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"}},[(i(!0),u(H,null,Y(U.value,n=>(i(),J(Ke,{key:n.id,"voice-id":k.value,"onUpdate:voiceId":r[1]||(r[1]=x=>k.value=x),"custom-voice-name":B.value,"onUpdate:customVoiceName":r[2]||(r[2]=x=>B.value=x),name:"voice",voice:n,"currently-playing-id":m.value,"custom-input-placeholder":l.customInputPlaceholder,"show-visualizer":l.showVisualizer,"audio-stream":f.value.get(n.id),onTogglePlayback:A},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:$([g.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:$([g.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]=n=>g.value=!g.value)},[e("span",null,y(g.value?l.collapseButtonText:l.expandButtonText),1),e("div",{class:$([g.value?"rotate-180":"","text-lg"]),"i-solar:alt-arrow-down-bold-duotone":"",transition:"transform duration-200 ease-in-out"},null,2)],2)],2)])])]))}}),nt=Z(rt,[["__scopeId","data-v-4dd3b9e2"]]),it=j({__name:"Skeleton",props:{animation:{default:"pulse"}},setup(l){const o=l;return(g,m)=>(i(),u("div",{class:$(["skeleton",o.animation!=="none"?`skeleton-${o.animation}`:""]),bg:"neutral-200 dark:neutral-800",overflow:"hidden"},[re(g.$slots,"default",{},void 0,!0)],2))}}),O=Z(it,[["__scopeId","data-v-f404da2a"]]),ut={flex:"~ col md:row gap-6"},dt={bg:"neutral-100 dark:[rgba(0,0,0,0.3)]","rounded-xl":"","p-4":"",flex:"~ col gap-4",class:"w-full md:w-[40%]"},ct={flex:"~ col gap-4"},vt={class:"text-lg text-neutral-500 md:text-2xl dark:text-neutral-400"},mt={text:"neutral-400 dark:neutral-500"},pt={"max-w-full":""},ft={key:0,flex:"~ row gap-4",style:{"scrollbar-width":"none"},"min-w-0":"","of-x-scroll":"","scroll-smooth":"",role:"radiogroup"},gt={key:1},xt={key:0},ht={flex:"~ col gap-4"},bt={class:"text-lg md:text-2xl"},yt={text:"neutral-400 dark:neutral-400"},kt={key:0,class:"flex items-center justify-center py-4"},wt={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"},_t={class:"flex flex-col"},St={class:"font-medium"},Vt={class:"text-sm text-red-600 dark:text-red-400"},Mt={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"},Ct={class:"flex flex-col"},$t={class:"font-medium"},Pt={class:"text-sm text-amber-600 dark:text-amber-400"},Ut={key:0},Lt={flex:"~ col gap-4"},qt={key:0},At={class:"flex flex-col gap-4"},Rt={flex:"~ row gap-4"},Et={key:1,class:"space-y-6"},Tt={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"},zt={class:"flex flex-col"},Bt={class:"text-sm text-red-600 dark:text-red-400"},Ft={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"},It={flex:"~ col gap-4"},Nt={key:4,class:"mt-2 space-y-6"},jt={key:0},Dt={flex:"~ col gap-4"},Ot={flex:"~ col gap-6",class:"w-full md:w-[60%]"},Qt={"w-full":"","rounded-xl":""},Ht={class:"mb-4 text-lg text-neutral-500 md:text-2xl dark:text-neutral-400","w-full":""},Gt={class:"inline-flex items-center gap-4"},Jt={flex:"~ col gap-4"},Kt={flex:"~ row","gap-4":""},Yt=["disabled"],Wt={flex:"~ row","items-center":"","gap-2":""},Xt=["src"],Zt={text:"neutral-200/50 dark:neutral-600/20","pointer-events-none":"",fixed:"",top:"[calc(100dvh-15rem)]","bottom-0":"","right--5":"","z--1":"",initial:{scale:.9,opacity:0,x:20},enter:{scale:1,opacity:1,x:0},duration:500,"size-60":"",flex:"","items-center":"","justify-center":""},es=j({__name:"speech",setup(l){const{t:o}=ge(),g=we(),m=_e(),{availableProviders:c,availableAudioSpeechProvidersMetadata:f}=te(g),{activeSpeechProvider:v,activeSpeechModel:h,activeSpeechVoice:M,activeSpeechVoiceId:b,pitch:p,isLoadingSpeechProviderVoices:k,supportsModelListing:U,providerModels:q,isLoadingActiveProviderModels:R,activeProviderModelError:T,modelSearchQuery:A,speechProviderError:z,ssmlEnabled:B,availableVoices:a}=te(m),r=V(""),n=V(!1),x=V("Hello, my name is AI Assistant"),w=V(""),L=V(!1),C=V(""),_=V(null),D=V("");ae(async()=>{await g.loadModelsForConfiguredProviders(),await m.loadVoicesForProvider(v.value)}),X(v,async()=>{await g.loadModelsForConfiguredProviders(),await m.loadVoicesForProvider(v.value)});async function ie(){if(!x.value.trim()&&!n.value||n.value&&!w.value.trim())return;if(!h.value){console.error("No model selected");return}if(!M.value){console.error("No voice selected");return}const E=g.getProviderInstance(v.value);if(!E){console.error("Failed to initialize speech provider");return}const s=g.getProviderConfig(v.value);L.value=!0,D.value="";try{C.value&&ee();const N=n.value?w.value:m.generateSSML(x.value,M.value,{...s,pitch:p.value}),G=await Se({...E.speech(h.value,s),input:N,voice:M.value.id});C.value=URL.createObjectURL(new Blob([G])),setTimeout(()=>{_.value&&_.value.play()},100)}catch(N){console.error("Error generating speech:",N),D.value=N instanceof Error?N.message:"An unknown error occurred"}finally{L.value=!1}}function ee(){_.value&&(_.value.pause(),_.value.currentTime=0),C.value&&(URL.revokeObjectURL(C.value),C.value="")}xe(()=>{C.value&&URL.revokeObjectURL(C.value)});function ue(E){M.value={id:E,name:E,description:E,previewURL:E,languages:[{code:"en",title:"English"}],provider:v.value,gender:"male"}}function de(E){h.value=E}return(E,s)=>{var G;const N=he("motion");return i(),u(H,null,[e("div",ut,[e("div",dt,[e("div",null,[e("div",ct,[e("div",null,[e("h2",vt,y(t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.title")),1),e("div",mt,[e("span",null,y(t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.description")),1)])]),e("div",pt,[t(c).length>0?(i(),u("fieldset",ft,[(i(!0),u(H,null,Y(t(f),d=>(i(),J(t($e),{id:d.id,key:d.id,modelValue:t(v),"onUpdate:modelValue":s[0]||(s[0]=ce=>F(v)?v.value=ce:null),name:"speech-provider",value:d.id,title:d.localizedName,description:d.localizedDescription},null,8,["id","modelValue","value","title","description"]))),128))])):(i(),u("div",gt,[S(t(be),{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:I(()=>s[13]||(s[13]=[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(U)?(i(),u("div",xt,[e("div",ht,[e("div",null,[e("h2",bt,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.title")),1),e("div",yt,[e("span",null,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.subtitle")),1)])]),t(R)?(i(),u("div",kt,[s[14]||(s[14]=e("div",{class:"mr-2 animate-spin"},[e("div",{"i-solar:spinner-line-duotone":"","text-xl":""})],-1)),e("span",null,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.loading")),1)])):t(T)?(i(),u("div",wt,[s[15]||(s[15]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",_t,[e("span",St,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.error")),1),e("span",Vt,y(t(T)),1)])])):t(q).length===0&&!t(R)?(i(),u("div",Mt,[s[16]||(s[16]=e("div",{"i-solar:info-circle-line-duotone":"",class:"text-2xl text-amber-500 dark:text-amber-400"},null,-1)),e("div",Ct,[e("span",$t,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models")),1),e("span",Pt,y(t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_models_description")),1)])])):t(q).length>0?(i(),J(t(Ce),{key:3,modelValue:t(h),"onUpdate:modelValue":s[1]||(s[1]=d=>F(h)?h.value=d:null),"search-query":t(A),"onUpdate:searchQuery":s[2]||(s[2]=d=>F(A)?A.value=d:null),items:t(q),searchable:!0,"search-placeholder":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_placeholder"),"search-no-results-title":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results"),"search-no-results-description":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.no_search_results_description",{query:t(A)}),"search-results-text":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.search_results",{count:"{count}",total:"{total}"}),"custom-input-placeholder":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.custom_model_placeholder"),"expand-button-text":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.expand"),"collapse-button-text":t(o)("settings.pages.modules.consciousness.sections.section.provider-model-selection.collapse"),"onUpdate:customValue":de},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"])):P("",!0)])])):P("",!0)])]),t(v)?(i(),u("div",Ut,[e("div",Lt,[s[27]||(s[27]=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(k)?(i(),u("div",qt,[e("div",At,[S(t(O),{class:"w-full rounded-lg p-2.5 text-sm"},{default:I(()=>s[17]||(s[17]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),e("div",Rt,[S(t(O),{class:"w-full rounded-lg p-4 text-sm"},{default:I(()=>s[18]||(s[18]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(O),{class:"w-full rounded-lg p-4 text-sm"},{default:I(()=>s[19]||(s[19]=[e("div",{class:"h-1lh"},null,-1)])),_:1}),S(t(O),{class:"w-full rounded-lg p-4 text-sm"},{default:I(()=>s[20]||(s[20]=[e("div",{class:"h-1lh"},null,-1)])),_:1})]),S(t(O),{class:"w-full rounded-lg p-3 text-sm"},{default:I(()=>s[21]||(s[21]=[e("div",{class:"h-1lh"},null,-1)])),_:1})])])):t(a)[t(v)]&&t(a)[t(v)].length>0?(i(),u("div",Et,[S(t(nt),{"search-query":r.value,"onUpdate:searchQuery":s[3]||(s[3]=d=>r.value=d),"voice-id":t(b),"onUpdate:voiceId":s[4]||(s[4]=d=>F(b)?b.value=d:null),voices:(G=t(a)[t(v)])==null?void 0:G.map(d=>({id:d.id,name:d.name,description:d.description,previewURL:d.previewURL,customizable:!1})),searchable:!0,"search-placeholder":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_placeholder"),"search-no-results-title":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices"),"search-no-results-description":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.no_voices_description"),"search-results-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.search_voices_results",{count:0,total:0}),"custom-input-placeholder":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.custom_voice_placeholder"),"expand-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_more"),"collapse-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.show_less"),"play-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.play_sample"),"pause-button-text":t(o)("settings.pages.modules.speech.sections.section.provider-voice-selection.pause"),"onUpdate:customValue":ue},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(z)?(i(),u("div",Tt,[s[23]||(s[23]=e("div",{"i-solar:close-circle-line-duotone":"",class:"text-2xl text-red-500 dark:text-red-400"},null,-1)),e("div",zt,[s[22]||(s[22]=e("span",{class:"font-medium"},"Error loading voices",-1)),e("span",Bt,y(t(z)),1)])])):(i(),u("div",Ft,s[24]||(s[24]=[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",It,[S(t(se),{modelValue:t(p),"onUpdate:modelValue":s[5]||(s[5]=d=>F(p)?p.value=d:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":d=>`${d}%`},null,8,["modelValue","format-value"]),S(t(le),{modelValue:t(B),"onUpdate:modelValue":s[6]||(s[6]=d=>F(B)?B.value=d: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?(i(),u("div",Nt,[S(t(Ve),{modelValue:t(b),"onUpdate:modelValue":s[7]||(s[7]=d=>F(b)?b.value=d: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"?(i(),u("div",jt,[s[26]||(s[26]=e("label",{class:"mb-1 block text-sm font-medium"}," Model ",-1)),Q(e("select",{"onUpdate:modelValue":s[8]||(s[8]=d=>F(h)?h.value=d:null),class:"w-full border border-neutral-300 rounded bg-white px-3 py-2 dark:border-neutral-700 dark:bg-neutral-900"},s[25]||(s[25]=[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),[[ye,t(h)]])])):P("",!0),e("div",Dt,[S(t(se),{modelValue:t(p),"onUpdate:modelValue":s[9]||(s[9]=d=>F(p)?p.value=d:null),label:"Pitch",description:"Tune the pitch of the voice",min:-100,max:100,step:1,"format-value":d=>`${d}%`},null,8,["modelValue","format-value"])])])):P("",!0)])])):P("",!0)]),e("div",Ot,[e("div",Qt,[e("h2",Ht,[e("div",Gt,[S(t(ke)),e("div",null,y(t(o)("settings.pages.providers.provider.elevenlabs.playground.title")),1)])]),e("div",Jt,[S(t(le),{modelValue:n.value,"onUpdate:modelValue":s[10]||(s[10]=d=>n.value=d),label:"Use Custom SSML",description:"Enable to input raw SSML instead of plain text"},null,8,["modelValue"]),n.value?Q((i(),u("textarea",{key:1,"onUpdate:modelValue":s[12]||(s[12]=d=>w.value=d),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)),[[ne,w.value]]):(i(),J(t(Me),{key:0,modelValue:x.value,"onUpdate:modelValue":s[11]||(s[11]=d=>x.value=d),"h-24":"","w-full":"",placeholder:t(o)("settings.pages.providers.provider.elevenlabs.playground.fields.field.input.placeholder")},null,8,["modelValue","placeholder"])),e("div",Kt,[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:L.value||!x.value.trim()&&!n.value||n.value&&!w.value.trim()||!t(M),class:$({"opacity-50 cursor-not-allowed":L.value||!x.value.trim()&&!n.value||n.value&&!w.value.trim()||!t(M)}),bg:"neutral-700 dark:neutral-300",onClick:ie},[e("div",Wt,[s[28]||(s[28]=e("div",{"i-solar:play-circle-bold-duotone":""},null,-1)),e("span",null,y(L.value?t(o)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.generating"):t(o)("settings.pages.providers.provider.elevenlabs.playground.buttons.button.test-voice.label")),1)])],10,Yt),C.value?(i(),u("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:ee},s[29]||(s[29]=[e("div",{flex:"~ row","items-center":"","gap-2":""},[e("div",{"i-solar:stop-circle-bold-duotone":""}),e("span",null,"Stop")],-1)]))):P("",!0)]),C.value?(i(),u("audio",{key:2,ref_key:"audioPlayer",ref:_,src:C.value,controls:"",class:"mt-2 w-full"},null,8,Xt)):P("",!0)])])])]),Q((i(),u("div",Zt,s[30]||(s[30]=[e("div",{text:"60","i-solar:user-speak-rounded-bold-duotone":""},null,-1)]))),[[N]])],64)}}});typeof oe=="function"&&oe(es);export{es as default}; diff --git a/assets/speech-Db_L6FBm.js b/assets/speech-nVAae-rt.js similarity index 98% rename from assets/speech-Db_L6FBm.js rename to assets/speech-nVAae-rt.js index b32ee7987cb59c1355efdf4d37db594f6ffc0c50..a246fb8f7bce239517d7318d56e75897d058902f 100644 --- a/assets/speech-Db_L6FBm.js +++ b/assets/speech-nVAae-rt.js @@ -1,2 +1,2 @@ -import{p as te,q as p,r as b,h as f,v as P,H as re}from"./index-BQKiy4UR.js";import{r as ne,a as ae,b as oe,d as se}from"./index-LHmcipjy.js";import{u as ce}from"./providers-kjOpfeNb.js";const ie=async e=>(e.fetch??globalThis.fetch)(ne("audio/speech",e.baseURL),{body:oe(e),headers:ae({"Content-Type":"application/json",...e.headers},e.apiKey),method:"POST",signal:e.abortSignal}).then(se).then(async t=>t.arrayBuffer()),ue=/["&'<>`]/g,le=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,de=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,me=/[|\\{}()[\]^$+*?.]/g,U=new WeakMap;function D(e,t){if(e=e.replace(t.subset?ge(t.subset):ue,n),t.subset||t.escapeOnly)return e;return e.replace(le,r).replace(de,n);function r(a,s,l){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,l.charCodeAt(s+2),t)}function n(a,s,l){return t.format(a.charCodeAt(0),l.charCodeAt(s+1),t)}}function ge(e){let t=U.get(e);return t||(t=pe(e),U.set(e,t)),t}function pe(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:"€"},Se=["cent","copy","divide","gt","lt","not","para","times"],j={}.hasOwnProperty,L={};let S;for(S in C)j.call(C,S)&&(L[C[S]]=S);const xe=/[^\dA-Za-z]/;function Ee(e,t,r,n){const a=String.fromCharCode(e);if(j.call(L,a)){const s=L[a],l="&"+s;return r&&be.includes(s)&&!Se.includes(s)&&(!n||t&&t!==61&&xe.test(String.fromCharCode(t)))?l:l+";"}return""}function we(e,t,r){let n=he(e,t,r.omitOptionalSemicolons),a;if((r.useNamedReferences||r.useShortestReferences)&&(a=Ee(e,t,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!a)&&r.useShortestReferences){const s=ye(e,t,r.omitOptionalSemicolons);s.length/g,Te=[">"];function Le(e){return""}function Me(e){return""}const Re=[" ",` +import{p as te,q as p,r as b,h as f,v as P,H as re}from"./index-CQudhZin.js";import{r as ne,a as ae,b as oe,d as se}from"./index-LHmcipjy.js";import{u as ce}from"./providers-Y3Mr8_DF.js";const ie=async e=>(e.fetch??globalThis.fetch)(ne("audio/speech",e.baseURL),{body:oe(e),headers:ae({"Content-Type":"application/json",...e.headers},e.apiKey),method:"POST",signal:e.abortSignal}).then(se).then(async t=>t.arrayBuffer()),ue=/["&'<>`]/g,le=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,de=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,me=/[|\\{}()[\]^$+*?.]/g,U=new WeakMap;function D(e,t){if(e=e.replace(t.subset?ge(t.subset):ue,n),t.subset||t.escapeOnly)return e;return e.replace(le,r).replace(de,n);function r(a,s,l){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,l.charCodeAt(s+2),t)}function n(a,s,l){return t.format(a.charCodeAt(0),l.charCodeAt(s+1),t)}}function ge(e){let t=U.get(e);return t||(t=pe(e),U.set(e,t)),t}function pe(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:"€"},Se=["cent","copy","divide","gt","lt","not","para","times"],j={}.hasOwnProperty,L={};let S;for(S in C)j.call(C,S)&&(L[C[S]]=S);const xe=/[^\dA-Za-z]/;function Ee(e,t,r,n){const a=String.fromCharCode(e);if(j.call(L,a)){const s=L[a],l="&"+s;return r&&be.includes(s)&&!Se.includes(s)&&(!n||t&&t!==61&&xe.test(String.fromCharCode(t)))?l:l+";"}return""}function we(e,t,r){let n=he(e,t,r.omitOptionalSemicolons),a;if((r.useNamedReferences||r.useShortestReferences)&&(a=Ee(e,t,r.omitOptionalSemicolons,r.attribute)),(r.useShortestReferences||!a)&&r.useShortestReferences){const s=ye(e,t,r.omitOptionalSemicolons);s.length/g,Te=[">"];function Le(e){return""}function Me(e){return""}const Re=[" ",` `," ",'"',"&","'","/","<","=",">"];function x(e){return y(e,Re)}function F(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 M(e,t){const r=String(e);let n=t.options.quote||'"';if(t.options.quoteSmart){const a=n==='"'?"'":'"';F(r,n)>F(r,a)&&(n=a)}return n+y(r,["<","&",n])+n}function $e(e,t){const r=x(e.name),n=e.public,a=e.system;let s=""}const Ue={}.hasOwnProperty;function Fe(e,t){const r=x(e.name),n=k(e,t),a=e.attributes||{},s=n?!1:t.options.closeEmptyElements,l=[];let h;for(h in a)if(Ue.call(a,h)){const g=a[h];g!=null&&l.push(x(h)+"="+M(g,t))}return"<"+r+(l.length===0?"":" "+l.join(" "))+(s?(t.options.tightClose?"":" ")+"/":"")+">"+n+(s?"":"")}const Ne=/\?>/g,De=[">"];function je(e){const t=x(e.name)||"x",r=y(e.value,De,Ne);return""}const Ie=["&","<"];function I(e){return y(e.value,Ie)}function ze(e,t){return t.options.allowDangerousXml?e.value:I(e)}const ke={}.hasOwnProperty,N={cdata:Le,comment:Me,doctype:$e,element:Fe,instruction:je,raw:ze,root:k,text:I};function z(e,t){const r=e&&e.type;if(!r)throw new Error("Expected node, not `"+e+"`");if(!ke.call(N,r))throw new Error("Cannot compile unknown node `"+r+"`");const n=N[r];return n(e,t)}function k(e,t){const r=e&&e.children||[];let n=-1;const a=[];for(;++n{const e=ce(),t=p("settings/speech/active-provider",""),r=p("settings/speech/active-model","eleven_multilingual_v2"),n=p("settings/speech/voice",""),a=b(),s=p("settings/speech/pitch",0),l=p("settings/speech/rate",1),h=p("settings/speech/ssml-enabled",!1),g=b(!1),E=b(null),v=b({}),H=p("settings/speech/language","en-US"),w=b(""),B=f(()=>e.availableProviders.filter(o=>O(o)).map(o=>e.getProviderMetadata(o))),V=f(()=>{var o;return((o=e.getProviderMetadata(t.value))==null?void 0:o.capabilities.listModels)!==void 0}),A=f(()=>e.getModelsForProvider(t.value)),Y=f(()=>e.isLoadingModels[t.value]||!1),X=f(()=>e.modelLoadError[t.value]||null),G=f(()=>{if(!w.value.trim())return A.value;const o=w.value.toLowerCase().trim();return A.value.filter(c=>c.name.toLowerCase().includes(o)||c.id.toLowerCase().includes(o)||c.description&&c.description.toLowerCase().includes(o))}),_=f(()=>["elevenlabs","microsoft-speech","azure-speech","google","alibaba-cloud-model-studio","volcengine"].includes(t.value));function O(o){return["elevenlabs","microsoft-speech","azure-speech","google","amazon","alibaba-cloud-model-studio","volcengine"].includes(o)}async function q(o){var c,i;if(!o||!O(o))return[];g.value=!0,E.value=null;try{const u=await((i=(c=e.getProviderMetadata(o).capabilities).listVoices)==null?void 0:i.call(c,e.getProviderConfig(o)))||[];return v.value[o]=u,u}catch(u){return console.error(`Error fetching voices for ${o}:`,u),E.value=u instanceof Error?u.message:"Unknown error",[]}finally{g.value=!1}}function K(o){return v.value[o]||[]}P(t,async o=>{o&&await q(o)}),re(()=>{q(t.value).then(()=>{var o;n.value&&(a.value=(o=v.value[t.value])==null?void 0:o.find(c=>c.id===n.value))})}),P(n,o=>{var c;o&&(a.value=(c=v.value[t.value])==null?void 0:c.find(i=>i.id===o))},{immediate:!0}),P(v,o=>{var c;n.value&&(a.value=(c=o[t.value])==null?void 0:c.find(i=>i.id===n.value))},{immediate:!0});async function Q(o,c,i,u,m={}){return await ie({...o.speech(c,{...m}),input:i,voice:u})}function Z(o,c,i){var $;const u=i==null?void 0:i.pitch,m=i==null?void 0:i.speed,d=i==null?void 0:i.volume,W={pitch:u!=null?u>0?`+${u}%`:`-${u}%`:void 0,rate:m!=null?m!==1?`${m}`:"1":void 0,volume:d!=null?d>0?`+${d}%`:`${d}%`:void 0},J=T("speak",{version:"1.0",xmlns:"http://www.w3.org/2001/10/synthesis","xml:lang":(($=c.languages[0])==null?void 0:$.code)||"en-US"},[T("voice",{name:c.id,gender:c.gender||"neutral"},[Object.entries(W).filter(([Ve,ee])=>ee!=null).length>0?T("prosody",{pitch:u!=null?u>0?`+${u}%`:`-${u}%`:void 0,rate:m!=null?m!==1?`${m}`:"1":void 0,volume:d!=null?d>0?`+${d}%`:`${d}%`:void 0},[o]):o])]);return He(J)}return{activeSpeechProvider:t,activeSpeechModel:r,activeSpeechVoice:a,activeSpeechVoiceId:n,pitch:s,rate:l,ssmlEnabled:h,selectedLanguage:H,isLoadingSpeechProviderVoices:g,speechProviderError:E,availableVoices:v,modelSearchQuery:w,availableSpeechProvidersMetadata:B,supportsSSML:_,supportsModelListing:V,providerModels:A,isLoadingActiveProviderModels:Y,activeProviderModelError:X,filteredModels:G,speech:Q,loadVoicesForProvider:q,getVoicesForProvider:K,generateSSML:Z,isSpeechProvider:O}});export{F as c,ie as g,_e as s,Ke as u}; diff --git a/assets/stage-BD_fFd6P.js b/assets/stage-Q-xHGzY4.js similarity index 84% rename from assets/stage-BD_fFd6P.js rename to assets/stage-Q-xHGzY4.js index 89f380178f0c22b6d4ba1c21234b6eae3ab370cb..8f5cf64430e9e02c290c26f81c62cfc6099d818f 100644 --- a/assets/stage-BD_fFd6P.js +++ b/assets/stage-Q-xHGzY4.js @@ -1 +1 @@ -import{d as p,M as s,c,i,N as d,z as m,b as e,o as l}from"./index-BQKiy4UR.js";const x=p({__name:"stage",setup(f){const{top:t,right:o,bottom:a,left:n}=s();return(u,_)=>{const r=d("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`})},[i(r)],4)}}});export{x as default}; +import{d as p,M as s,c,i,N as d,z as m,b as e,o as l}from"./index-CQudhZin.js";const x=p({__name:"stage",setup(f){const{top:t,right:o,bottom:a,left:n}=s();return(u,_)=>{const r=d("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`})},[i(r)],4)}}});export{x as default}; diff --git a/assets/three-vrm-animation.module-DtlqIxay.js b/assets/three-vrm-animation.module-Dklr5eVx.js similarity index 99% rename from assets/three-vrm-animation.module-DtlqIxay.js rename to assets/three-vrm-animation.module-Dklr5eVx.js index 407353fb7c47ff239f9361203fe6d67eabc097ba..7c78fc368c1ee7965f87bad9132219e664032b2b 100644 --- a/assets/three-vrm-animation.module-DtlqIxay.js +++ b/assets/three-vrm-animation.module-Dklr5eVx.js @@ -1,4 +1,4 @@ -import{W as N,X as ae,Y as _,Z as z,$ as X,a0 as Bi,a1 as ki,a2 as C,a3 as T,a4 as ee,a5 as le,a6 as zt,a7 as jt,a8 as Xt,a9 as Oe,aa as at,ab as Fi,ac as Hi,ad as Wi,ae as zi,af as ce,ag as xe,ah as U,ai as ji,aj as Y,ak as Xi,al as qi,am as qt,an as lt,ao as Yi,ap as be,aq as Gi,ar as Qi,as as $i}from"./index-BQKiy4UR.js";const et=400,j=[[.075,800],[.11,0],[.125,0],[.14,0],[.125,0],[.05,0],[.04,0],[.03,0],[.02,0],[1,0]];for(let e=1;ed.getProviderMetadata(o)),i=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.apiKey)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].apiKey=e}}),s=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.baseUrl)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].baseUrl=e}});$(()=>{var e,r;d.initializeProvider(o),i.value=((e=a.value[o])==null?void 0:e.apiKey)||"",s.value=((r=a.value[o])==null?void 0:r.baseUrl)||""}),K([i,s],()=>{a.value[o]={...a.value[o],apiKey:i.value,baseUrl:s.value||""}});function b(){var e;a.value[o]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,r)=>{var v,f;return z(),x(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(g).back()},{default:u(()=>[l(t(N),null,{default:u(()=>[l(t(P),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:u(()=>{var p;return[l(t(M),{modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=h=>i.value=h),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"togetherapi-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(w),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":r[1]||(r[1]=p=>s.value=p),placeholder:"https://api.together.xyz/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as y,g as U,S as V,s as k,h as c,H as $,v as K,A as x,o as z,w as u,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as S}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as w,a as C}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as M}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as N,a as P}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as R}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const o="together-ai",B=y({__name:"together-ai",setup(I){const{t:m}=U(),g=V(),d=S(),{providers:a}=k(d),n=c(()=>d.getProviderMetadata(o)),i=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.apiKey)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].apiKey=e}}),s=c({get:()=>{var e;return((e=a.value[o])==null?void 0:e.baseUrl)||""},set:e=>{a.value[o]||(a.value[o]={}),a.value[o].baseUrl=e}});$(()=>{var e,r;d.initializeProvider(o),i.value=((e=a.value[o])==null?void 0:e.apiKey)||"",s.value=((r=a.value[o])==null?void 0:r.baseUrl)||""}),K([i,s],()=>{a.value[o]={...a.value[o],apiKey:i.value,baseUrl:s.value||""}});function b(){var e;a.value[o]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,r)=>{var v,f;return z(),x(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(g).back()},{default:u(()=>[l(t(N),null,{default:u(()=>[l(t(P),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":b},{default:u(()=>{var p;return[l(t(M),{modelValue:i.value,"onUpdate:modelValue":r[0]||(r[0]=h=>i.value=h),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"togetherapi-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(w),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(C),{modelValue:s.value,"onUpdate:modelValue":r[1]||(r[1]=p=>s.value=p),placeholder:"https://api.together.xyz/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon-color","on-back"])}}});typeof _=="function"&&_(B);export{B as default}; diff --git a/assets/useIconAnimation-ITs7Jlod.js b/assets/useIconAnimation-BCxWQrf7.js similarity index 69% rename from assets/useIconAnimation-ITs7Jlod.js rename to assets/useIconAnimation-BCxWQrf7.js index 47c8971eca7acf26b06a8746b57e5bc029df4a04..9473bd385295ea588393e7ad2a9186ad5d973ffa 100644 --- a/assets/useIconAnimation-ITs7Jlod.js +++ b/assets/useIconAnimation-BCxWQrf7.js @@ -1 +1 @@ -import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{r as t,G as r,h as u,H as m,I as c}from"./index-BQKiy4UR.js";function d(s){const n=t(!1),o=t(!1),a=t(s),e=r(),i=u(()=>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{d as u}; +import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{r as t,G as r,h as u,H as m,I as c}from"./index-CQudhZin.js";function d(s){const n=t(!1),o=t(!1),a=t(s),e=r(),i=u(()=>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{d as u}; diff --git a/assets/valibot-BI4iQMg3-C6wv93uD.js b/assets/valibot-BI4iQMg3-C6wv93uD.js deleted file mode 100644 index 914cee5fbcd731877a799d8c1cf55234ef6b7753..0000000000000000000000000000000000000000 --- a/assets/valibot-BI4iQMg3-C6wv93uD.js +++ /dev/null @@ -1 +0,0 @@ -import{L as r}from"./index-BQKiy4UR.js";import{t as a}from"./mcp-DQCTu0C2.js";const s=async()=>{const{toJsonSchema:o}=await a(r(()=>import("./index-CShXCEpO.js"),[]),"@valibot/to-json-schema");return t=>o(t)};export{s as getToJsonSchemaFn}; diff --git a/assets/valibot-BI4iQMg3-DivldWga.js b/assets/valibot-BI4iQMg3-DivldWga.js new file mode 100644 index 0000000000000000000000000000000000000000..0474e85891b983221d28fc4de50f078a427a6331 --- /dev/null +++ b/assets/valibot-BI4iQMg3-DivldWga.js @@ -0,0 +1 @@ +import{L as r}from"./index-CQudhZin.js";import{t as a}from"./mcp-C9U4MroK.js";const s=async()=>{const{toJsonSchema:o}=await a(r(()=>import("./index-CShXCEpO.js"),[]),"@valibot/to-json-schema");return t=>o(t)};export{s as getToJsonSchemaFn}; diff --git a/assets/vibrant-BaXmXZtH.js b/assets/vibrant-DQTTh5Yn.js similarity index 88% rename from assets/vibrant-BaXmXZtH.js rename to assets/vibrant-DQTTh5Yn.js index f1b1e37c7356ddd7226e2417d991a44178e8896a..d33edd7db37acd76142ebefdb7a908e47901fb55 100644 --- a/assets/vibrant-BaXmXZtH.js +++ b/assets/vibrant-DQTTh5Yn.js @@ -1 +1 @@ -import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as p}from"./InputFile.vue_vue_type_script_setup_true_lang-w1WUowyN.js";import{V as g}from"./browser-CkchkNbv.js";import{d as v,r as n,v as _,c as r,o,e as s,F as b,l as h,t as k,i as w,b as x,j as y,z as V}from"./index-BQKiy4UR.js";import"./floating-ui.core-CgBsuaUc.js";const j={flex:"","flex-col":"","gap-4":""},C={border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","w-full":"",flex:"","gap-2":"","rounded-lg":"","p-4":""},L={border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","w-full":"",flex:"","gap-2":"","rounded-lg":"","p-4":""},N={flex:"","gap-2":""},O={"h-60":"",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","rounded-lg":""},z=["src"],R=v({__name:"vibrant",setup(B){const u=n([]),t=n(),d=n([]),i=n([]);function c(l){const a=new Image;a.src=URL.createObjectURL(l),a.onload=f,t.value=a}async function f(){if(!t.value)return;const a=await new g(t.value).getPalette();d.value=Object.values(a).map(e=>e==null?void 0:e.hex).filter(e=>typeof e=="string"),i.value=Object.values(a).map(e=>JSON.stringify(e))}return _(u,l=>{c(l[0])},{deep:!0}),(l,a)=>(o(),r("div",j,[s("div",C,[(o(!0),r(b,null,h(d.value,(e,m)=>(o(),r("div",{key:m,style:V({backgroundColor:e}),"size-20":"","rounded-full":""},null,4))),128))]),s("div",L,k(i.value),1),s("div",N,[w(x(p),{modelValue:u.value,"onUpdate:modelValue":a[0]||(a[0]=e=>u.value=e),"h-60":"","w-full":""},null,8,["modelValue"])]),s("div",O,[t.value?(o(),r("img",{key:0,src:t.value.src,"h-full":"","w-full":"","object-contain":""},null,8,z)):y("",!0)])]))}});export{R as default}; +import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as p}from"./InputFile.vue_vue_type_script_setup_true_lang-Bro_JZ7u.js";import{V as g}from"./browser-CkchkNbv.js";import{d as v,r as n,v as _,c as r,o,e as s,F as b,l as h,t as k,i as w,b as x,j as y,z as V}from"./index-CQudhZin.js";import"./floating-ui.core-CgBsuaUc.js";const j={flex:"","flex-col":"","gap-4":""},C={border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","w-full":"",flex:"","gap-2":"","rounded-lg":"","p-4":""},L={border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","w-full":"",flex:"","gap-2":"","rounded-lg":"","p-4":""},N={flex:"","gap-2":""},O={"h-60":"",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","rounded-lg":""},z=["src"],R=v({__name:"vibrant",setup(B){const u=n([]),t=n(),d=n([]),i=n([]);function c(l){const a=new Image;a.src=URL.createObjectURL(l),a.onload=f,t.value=a}async function f(){if(!t.value)return;const a=await new g(t.value).getPalette();d.value=Object.values(a).map(e=>e==null?void 0:e.hex).filter(e=>typeof e=="string"),i.value=Object.values(a).map(e=>JSON.stringify(e))}return _(u,l=>{c(l[0])},{deep:!0}),(l,a)=>(o(),r("div",j,[s("div",C,[(o(!0),r(b,null,h(d.value,(e,m)=>(o(),r("div",{key:m,style:V({backgroundColor:e}),"size-20":"","rounded-full":""},null,4))),128))]),s("div",L,k(i.value),1),s("div",N,[w(x(p),{modelValue:u.value,"onUpdate:modelValue":a[0]||(a[0]=e=>u.value=e),"h-60":"","w-full":""},null,8,["modelValue"])]),s("div",O,[t.value?(o(),r("img",{key:0,src:t.value.src,"h-full":"","w-full":"","object-contain":""},null,8,z)):y("",!0)])]))}});export{R as default}; diff --git a/assets/volcengine-gKPE4jbw.js b/assets/volcengine-C-Sx5RRX.js similarity index 68% rename from assets/volcengine-gKPE4jbw.js rename to assets/volcengine-C-Sx5RRX.js index 0c7a225fb0f591f66d4c5fbe177046c6e5fc0c1e..3da0155e736ee9c21efa5668e391ba469ac1943d 100644 --- a/assets/volcengine-gKPE4jbw.js +++ b/assets/volcengine-C-Sx5RRX.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as y,r as w,s as M,g as I,h as v,H as S,v as g,A as x,o as k,w as c,i as f,b as r,e as F}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as $}from"./providers-kjOpfeNb.js";import{u as B}from"./speech-Db_L6FBm.js";import{_ as R}from"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import{_ as E}from"./FieldRange.vue_vue_type_script_setup_true_lang-DD22ckZ1.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as H,a as K}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-a6SVCBpU.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";const L={flex:"~ col gap-4"},o="volcengine",b="v1",N=y({__name:"volcengine",setup(T){const s=w(1),d=B(),a=$(),{providers:t}=M(a),{t:n}=I(),p=v({get:()=>{var e,i;return((i=(e=t.value[o])==null?void 0:e.app)==null?void 0:i.appId)||""},set:e=>{t.value[o]||(t.value[o]={}),t.value[o].app={appId:e}}}),C=v(()=>{var e;return!!((e=t.value[o])!=null&&e.apiKey)}),h=v(()=>d.availableVoices[o]||[]);async function P(e,i,l){const m=a.getProviderInstance(o);if(!m)throw new Error("Failed to initialize speech provider");const u=a.getProviderConfig(o),V=u.model||b;return await d.speech(m,V,e,i,{...u})}return S(async()=>{const e=a.getProviderConfig(o);await a.getProviderMetadata(o).validators.validateProviderConfig(e)?await d.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)}),g(s,async()=>{const e=a.getProviderConfig(o);e.audio||(e.audio={}),e.audio.speedRatio=s.value}),g([t,p],async()=>{const e=a.getProviderConfig(o);await a.getProviderMetadata(o).validators.validateProviderConfig(e)?await d.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)},{immediate:!0}),(e,i)=>(k(),x(r(K),{"provider-id":o,"default-model":b},{"basic-settings":c(()=>[F("div",L,[f(r(R),{modelValue:p.value,"onUpdate:modelValue":i[0]||(i[0]=l=>p.value=l),label:r(n)("settings.pages.providers.provider.volcengine.fields.field.appId.label"),description:r(n)("settings.pages.providers.provider.volcengine.fields.field.appId.description"),required:""},null,8,["modelValue","label","description"])])]),"voice-settings":c(()=>[f(r(E),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=l=>s.value=l),label:r(n)("settings.pages.providers.provider.common.fields.field.speed.label"),description:r(n)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"])]),playground:c(()=>[f(r(H),{"available-voices":h.value,"generate-speech":P,"api-key-configured":C.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof _=="function"&&_(N);export{N as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as y,r as w,s as M,g as I,h as v,H as S,v as g,A as x,o as k,w as c,i as f,b as r,e as F}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as $}from"./providers-Y3Mr8_DF.js";import{u as B}from"./speech-nVAae-rt.js";import{_ as R}from"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import{_ as E}from"./FieldRange.vue_vue_type_script_setup_true_lang-NNQ86Eje.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as H,a as K}from"./SpeechProviderSettings.vue_vue_type_script_setup_true_lang-D7YNFI1r.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";import"./floating-ui.core-CgBsuaUc.js";import"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";const L={flex:"~ col gap-4"},o="volcengine",b="v1",N=y({__name:"volcengine",setup(T){const s=w(1),d=B(),a=$(),{providers:t}=M(a),{t:n}=I(),p=v({get:()=>{var e,i;return((i=(e=t.value[o])==null?void 0:e.app)==null?void 0:i.appId)||""},set:e=>{t.value[o]||(t.value[o]={}),t.value[o].app={appId:e}}}),C=v(()=>{var e;return!!((e=t.value[o])!=null&&e.apiKey)}),h=v(()=>d.availableVoices[o]||[]);async function P(e,i,l){const m=a.getProviderInstance(o);if(!m)throw new Error("Failed to initialize speech provider");const u=a.getProviderConfig(o),V=u.model||b;return await d.speech(m,V,e,i,{...u})}return S(async()=>{const e=a.getProviderConfig(o);await a.getProviderMetadata(o).validators.validateProviderConfig(e)?await d.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)}),g(s,async()=>{const e=a.getProviderConfig(o);e.audio||(e.audio={}),e.audio.speedRatio=s.value}),g([t,p],async()=>{const e=a.getProviderConfig(o);await a.getProviderMetadata(o).validators.validateProviderConfig(e)?await d.loadVoicesForProvider(o):console.error("Failed to validate provider config",e)},{immediate:!0}),(e,i)=>(k(),x(r(K),{"provider-id":o,"default-model":b},{"basic-settings":c(()=>[F("div",L,[f(r(R),{modelValue:p.value,"onUpdate:modelValue":i[0]||(i[0]=l=>p.value=l),label:r(n)("settings.pages.providers.provider.volcengine.fields.field.appId.label"),description:r(n)("settings.pages.providers.provider.volcengine.fields.field.appId.description"),required:""},null,8,["modelValue","label","description"])])]),"voice-settings":c(()=>[f(r(E),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=l=>s.value=l),label:r(n)("settings.pages.providers.provider.common.fields.field.speed.label"),description:r(n)("settings.pages.providers.provider.common.fields.field.speed.description"),min:.5,max:2,step:.01},null,8,["modelValue","label","description"])]),playground:c(()=>[f(r(H),{"available-voices":h.value,"generate-speech":P,"api-key-configured":C.value,"default-text":"Hello! This is a test of the ElevenLabs voice synthesis."},null,8,["available-voices","api-key-configured"])]),_:1}))}});typeof _=="function"&&_(N);export{N as default}; diff --git a/assets/worker-LE59aox_.js b/assets/worker-LE59aox_.js new file mode 100644 index 0000000000000000000000000000000000000000..c5727285cb74d64043975591964057a04c1388ed --- /dev/null +++ b/assets/worker-LE59aox_.js @@ -0,0 +1,2888 @@ +var rT=Object.defineProperty;var sT=(Cs,jr,Ln)=>jr in Cs?rT(Cs,jr,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):Cs[jr]=Ln;var Y=(Cs,jr,Ln)=>sT(Cs,typeof jr!="symbol"?jr+"":jr,Ln);(function(){"use strict";const Cs=new Map,jr=[],Ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=Cs.get(e);if(s===void 0)Cs.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 o=jr.indexOf(e);o!==-1&&jr.splice(o,1);for(let n=0;n{const r=Cs.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}}},K0=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?jr:t;let o;const n=[],i=new Set;for(const l of s){const u=await G0(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},H0="1.21.1";let Ec="warning";const ds={wasm:{},webgl:{},webgpu:{},versions:{common:H0},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}`);Ec=e}},get logLevel(){return Ec}};Object.defineProperty(ds,"logLevel",{enumerable:!0});const q0=ds,Q0=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let c=0,d=p,_=p*2,f=-1;i==="RGBA"?(c=0,d=p,_=p*2,f=p*3):i==="RGB"?(c=0,d=p,_=p*2):i==="RBG"&&(c=0,_=p,d=p*2);for(let T=0;T{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 c=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const d=4;let _=0,f=1,T=2,k=3,w=0,g=c,S=c*2,E=-1;a==="RGBA"?(w=0,g=c,S=c*2,E=c*3):a==="RGB"?(w=0,g=c,S=c*2):a==="RBG"&&(w=0,S=c,g=c*2),s=t.createImageData(o,n);for(let v=0;v{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,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let c=4,d=0,_=1,f=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(c=3,d=0,_=1,f=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let v=0;v{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,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")},u=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 c=u(p);if(c!=null){let d=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,_=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=d,a.width=_}else a.tensorFormat="RGBA",a.height=d,a.width=_;c.drawImage(e,0,0),i=c.getImageData(0,0,_,d).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){const d=l();d.width=c,d.height=p;const _=u(d);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 c=u(p);if(c!=null){const d=e.height,_=e.width;return c.drawImage(e,0,0,_,d),i=c.getImageData(0,0,_,d).data,a.height=d,a.width=_,ga(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{const d=l(),_=u(d);if(!e||!_)return c();const f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{d.width=f.width,d.height=f.height,_.drawImage(f,0,0,d.width,d.height);const T=_.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(ga(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ga(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Y0=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Zr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Z0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Zr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},ev=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Zr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},tv=(e,r,t)=>new Zr({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]]),ti=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Pc=!1;const rv=()=>{if(!Pc){Pc=!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),ti.set(BigInt64Array,"int64")),r&&(zn.set("uint64",BigUint64Array),ti.set(BigUint64Array,"uint64")),s?(zn.set("float16",t),ti.set(t,"float16")):zn.set("float16",Uint16Array)}},sv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Zr(e.type,e.data,r);case"cpu-pinned":return new Zr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Zr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Zr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Zr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Zr=class{constructor(r,t,s){rv();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=zn.get(o);if(!a)throw new TypeError(`unsupported type "${o}" 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(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" 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(o=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 u=zn.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)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&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=ti.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,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 i=sv(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return J0(r,t)}static fromTexture(r,t){return Y0(r,t)}static fromGpuBuffer(r,t){return Z0(r,t)}static fromMLTensor(r,t){return ev(r,t)}static fromPinnedBuffer(r,t,s){return tv(r,t,s)}toDataURL(r){return Q0(this,r)}toImageData(r){return X0(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 nv(this,r)}};const Bn=Zr,Cc=(e,r)=>{(typeof ds.trace>"u"?!ds.wasm.trace:!ds.trace)||console.timeStamp(`${e}::ORT::${r}`)},Sc=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ds.trace>"u"?!ds.wasm.trace:!ds.trace)||Sc("BEGIN",e)},Ma=e=>{(typeof ds.trace>"u"?!ds.wasm.trace:!ds.trace)||Sc("END",e)};var ov=Object.freeze({__proto__:null,InferenceSession:class V0{constructor(r){this.handler=r}async run(r,t,s){wa();const o={};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 i=!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.");i=!1;for(const u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const c of this.outputNames)if(p.indexOf(c)!==-1){const d=t[c];(d===null||d instanceof Bn)&&(u=!0,i=!1,o[c]=d)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof Bn?l[u]=p:l[u]=new Bn(p.type,p.data,p.dims)}return Ma(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){wa();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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 c=0,d=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-c,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await K0(i),u=await a.createInferenceSessionHandler(n,l);return Ma(),new V0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Cc,TRACE_FUNC_BEGIN:wa,TRACE_FUNC_END:Ma,Tensor:Bn,env:q0,registerBackend:Ln});/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ba=Object.defineProperty,iv=Object.getOwnPropertyDescriptor,av=Object.getOwnPropertyNames,lv=Object.prototype.hasOwnProperty,uv=(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),Rn=(e,r)=>{for(var t in r)ba(e,t,{get:r[t],enumerable:!0})},cv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of av(r))!lv.call(e,o)&&o!==t&&ba(e,o,{get:()=>r[o],enumerable:!(s=iv(r,o))||s.enumerable});return e},io=e=>cv(ba({},"__esModule",{value:!0}),e),ao,Vs,rn,$c,kc,Ic=je(()=>{ao=new Map,Vs=[],rn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=ao.get(e);if(s===void 0)ao.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 o=Vs.indexOf(e);o!==-1&&Vs.splice(o,1);for(let n=0;n{let r=ao.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}}},kc=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Vs:t,o,n=[],i=new Set;for(let l of s){let u=await $c(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),dv=je(()=>{Ic()}),Ac,pv=je(()=>{Ac="1.22.0-dev.20250409-89f8206ba4"}),ya,es,Fc=je(()=>{pv(),ya="warning",es={wasm:{},webgl:{},webgpu:{},versions:{common:Ac},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}`);ya=e}},get logLevel(){return ya}},Object.defineProperty(es,"logLevel",{enumerable:!0})}),Xt,hv=je(()=>{Fc(),Xt=es}),Oc,Dc,mv=je(()=>{Oc=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,c=0,d=p,_=p*2,f=-1;i==="RGBA"?(c=0,d=p,_=p*2,f=p*3):i==="RGB"?(c=0,d=p,_=p*2):i==="RBG"&&(c=0,_=p,d=p*2);for(let T=0;T{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 c=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,_=0,f=1,T=2,k=3,w=0,g=c,S=c*2,E=-1;a==="RGBA"?(w=0,g=c,S=c*2,E=c*3):a==="RGB"?(w=0,g=c,S=c*2):a==="RBG"&&(w=0,S=c,g=c*2),s=t.createImageData(o,n);for(let v=0;v{xa(),ri=(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,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),c=4,d=0,_=1,f=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(c=3,d=0,_=1,f=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,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")},u=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 c=u(p);if(c!=null){let d=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,_=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=d,a.width=_}else a.tensorFormat="RGBA",a.height=d,a.width=_;c.drawImage(e,0,0),i=c.getImageData(0,0,_,d).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){let d=l();d.width=c,d.height=p;let _=u(d);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 c=u(p);if(c!=null){let d=e.height,_=e.width;return c.drawImage(e,0,0,_,d),i=c.getImageData(0,0,_,d).data,a.height=d,a.width=_,ri(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{let d=l(),_=u(d);if(!e||!_)return c();let f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{d.width=f.width,d.height=f.height,_.drawImage(f,0,0,d.width,d.height);let T=_.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(ri(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ri(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},zc=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Kr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Bc=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Kr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Rc=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Kr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},jc=(e,r,t)=>new Kr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),sn,lo,va,Nc,_v=je(()=>{sn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),lo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),va=!1,Nc=()=>{if(!va){va=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(sn.set("int64",BigInt64Array),lo.set(BigInt64Array,"int64")),r&&(sn.set("uint64",BigUint64Array),lo.set(BigUint64Array,"uint64")),s?(sn.set("float16",t),lo.set(t,"float16")):sn.set("float16",Uint16Array)}}}),Vc,Uc,gv=je(()=>{xa(),Vc=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Kr(e.type,e.data,r);case"cpu-pinned":return new Kr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Kr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Kr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Kr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Kr,xa=je(()=>{mv(),fv(),_v(),gv(),Kr=class{constructor(e,r,t){Nc();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=sn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,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.");i=r}else{let l=sn.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"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=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)i=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",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=lo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=Vc(o);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=o,this.size=n}static async fromImage(e,r){return Lc(e,r)}static fromTexture(e,r){return zc(e,r)}static fromGpuBuffer(e,r){return Bc(e,r)}static fromMLTensor(e,r){return Rc(e,r)}static fromPinnedBuffer(e,r,t){return jc(e,r,t)}toDataURL(e){return Oc(this,e)}toImageData(e){return Dc(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 Uc(this,e)}}}),ps,Wc=je(()=>{xa(),ps=Kr}),uo,Ta,hs,ts,Gc=je(()=>{Fc(),uo=(e,r)=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ta=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Ta("BEGIN",e)},ts=e=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Ta("END",e)}}),Kc,wv=je(()=>{Ic(),Wc(),Gc(),Kc=class U0{constructor(r){this.handler=r}async run(r,t,s){hs();let o={},n={};if(typeof r!="object"||r===null||r instanceof ps||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ps)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.");i=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let c of this.outputNames)if(p.indexOf(c)!==-1){let d=t[c];(d===null||d instanceof ps)&&(u=!0,i=!1,o[c]=d)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof ps?l[u]=p:l[u]=new ps(p.type,p.data,p.dims)}return ts(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){hs();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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,c=0,d=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-c,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await kc(i),u=await a.createInferenceSessionHandler(n,l);return ts(),new U0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ea,Mv=je(()=>{wv(),Ea=Kc}),bv=je(()=>{}),yv=je(()=>{}),vv=je(()=>{}),xv=je(()=>{}),Hc={};Rn(Hc,{InferenceSession:()=>Ea,TRACE:()=>uo,TRACE_FUNC_BEGIN:()=>hs,TRACE_FUNC_END:()=>ts,Tensor:()=>ps,env:()=>Xt,registerBackend:()=>rn});var ms=je(()=>{dv(),hv(),Mv(),Wc(),bv(),yv(),Gc(),vv(),xv()}),Pa=je(()=>{}),qc={};Rn(qc,{default:()=>Qc});var Ca,Sa,Qc,Tv=je(()=>{var e;$g(),nn(),La(),Ca="ort-wasm-proxy-worker",Sa=((e=globalThis.self)==null?void 0:e.name)===Ca,Sa&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Ra(s.wasm).then(()=>{Yl(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;Zl(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=yi(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;tu(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":ru(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;nu(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},iu([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":ou(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Qc=Sa?null:r=>new Worker(r??Hr,{type:"module",name:Ca})}),Xc={};Rn(Xc,{default:()=>Jc});var $a,ka,Jc,Yc,Ev=je(()=>{var e,r;ka=($a=self.location.href,async function(t={}){var ro;var s,o,n=t,i=new Promise((h,x)=>{s=h,o=x}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((ro=self.name)==null?void 0:ro.startsWith("em-pthread"));n.mountExternalData=(h,x)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,x)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...x)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:x[0],errors:[]},N=await h(...x);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let ue=L.errors;if(0Le),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=x;let I=n.Jb;n.jsepRegisterBuffer=(L,N,ue,Te)=>I.registerBuffer(L,N,ue,Te),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,N,ue)=>I.createDownloader(L,N,ue),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,N)=>{I.upload(L,N)}}else if(h==="webnn"){let I=x[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=x.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,N)=>{I.registerMLContext(L,N)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,N)=>I.createMLTensorDownloader(L,N),n.webnnRegisterMLTensor=(L,N,ue,Te)=>I.registerMLTensor(L,N,ue,Te),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,N,ue,Te,Le,Ke)=>I.registerMLConstant(L,N,ue,Te,Le,n.Eb,Ke),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let d=()=>{let h=(x,I,L)=>(...N)=>{let ue=Zt,Te=I==null?void 0:I();N=x(...N);let Le=I==null?void 0:I();return Te!==Le&&(x=Le,L(Te),I=L=null),Zt!=ue?new Promise((Ke,tt)=>{Jr={resolve:Ke,reject:tt}}):N};(()=>{for(let x of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[x]=h(n[x],()=>n[x],I=>n[x]=I)})(),c!==void 0&&(n._OrtRun=c(n._OrtRun),n._OrtRunWithBinding=c(n._OrtRunWithBinding)),d=void 0};n.asyncInit=()=>{d==null||d()};var _,f,T=Object.assign({},n),k=(h,x)=>{throw x},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),$a&&(w=$a),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(f=h=>{var x=new XMLHttpRequest;return x.open("GET",h,!1),x.responseType="arraybuffer",x.send(null),new Uint8Array(x.response)}),_=async h=>{if(V(h))return new Promise((I,L)=>{var N=new XMLHttpRequest;N.open("GET",h,!0),N.responseType="arraybuffer",N.onload=()=>{N.status==200||N.status==0&&N.response?I(N.response):L(N.status)},N.onerror=L,N.send(null)});var x=await fetch(h,{credentials:"same-origin"});if(x.ok)return x.arrayBuffer();throw Error(x.status+" : "+x.url)});var g=console.log.bind(console),S=console.error.bind(console),E=g,v=S;Object.assign(n,T),T=null;var M,y,C,F,z,K,q,R,Z,H,J,Q,se,fe=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function A(){return M.buffer!=F.buffer&&re(),F}function U(){return M.buffer!=F.buffer&&re(),z}function ee(){return M.buffer!=F.buffer&&re(),K}function _e(){return M.buffer!=F.buffer&&re(),q}function le(){return M.buffer!=F.buffer&&re(),R}function ye(){return M.buffer!=F.buffer&&re(),Z}function ze(){return M.buffer!=F.buffer&&re(),H}function Ue(){return M.buffer!=F.buffer&&re(),se}if(u){let h=function(x){try{var I=x.data,L=I.Bb;if(L==="load"){let N=[];self.onmessage=ue=>N.push(ue),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ue of N)h(ue);self.onmessage=h};for(let ue of I.Rb)n[ue]&&!n[ue].proxy||(n[ue]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ue,args:Te})},ue=="print"&&(E=n[ue]),ue=="printErr"&&(v=n[ue]));M=I.kc,re(),pe(I.lc)}else if(L==="run"){B(I.Ab),Jn(I.Ab,0,0,1,0,0),rs(),xe(I.Ab),W||(Uo(),W=!0);try{te(I.fc,I.Hb)}catch(N){if(N!="unwind")throw N}}else I.target!=="setimmediate"&&(L==="checkMailbox"?W&&Re():L&&(v(`worker: received unknown command ${L}`),v(I)))}catch(N){throw Yn(),N}};var pe,W=!1;v=function(...x){x=x.join(" "),console.error(x)},self.alert=function(...x){postMessage({Bb:"alert",text:x.join(" "),ic:Pn()})},self.onunhandledrejection=x=>{throw x.reason||x},self.onmessage=h}function re(){var h=M.buffer;n.HEAP8=F=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=z=new Uint8Array(h),n.HEAPU16=q=new Uint16Array(h),n.HEAP32=R=new Int32Array(h),n.HEAPU32=Z=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=se=new Float64Array(h),n.HEAP64=J=new BigInt64Array(h),n.HEAPU64=Q=new BigUint64Array(h)}function G(){u?startWorker(n):ct.Ca()}u||(M=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),re());var be,we=0,Se=null;function Ce(){if(--we==0&&Se){var h=Se;Se=null,h()}}function $e(h){throw v(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function Fe(){return{a:{L:qe,Aa:He,b:Oe,$:vt,A:rt,pa:jt,X:Jt,Z:Or,qa:ss,na:ys,ga:ns,ma:$s,J:Vr,Y:ks,V:Qr,oa:vs,W:Is,va:Fs,E:it,Q:os,O:fn,D:gn,u:wn,r:Mn,P:Os,z:j,R:X,ja:ie,T:Qe,aa:Ye,M:_t,F:Ot,ia:xe,sa:At,t:mr,Ba:Mr,w:br,o:dr,l:us,c:as,n:Ti,j:qs,v:Ci,p:Si,f:$i,s:ki,m:Ii,e:Eo,k:Ai,i:Fi,g:Po,d:Oi,da:Co,ea:Li,fa:$o,ba:ko,ca:Tn,N:Io,xa:Bi,ua:ji,h:Ao,C:Ni,G:Fo,ta:Ri,x:Ns,ra:Vi,U:pu,q:zi,y:Ui,K:hu,S:Wi,za:Gi,ya:Ki,ka:Lo,la:zo,_:St,B:Qn,I:Bo,ha:Ro,H:No,a:M,wa:Ie}}}var Be={829644:(h,x,I,L,N)=>{if(n===void 0||!n.Eb)return 1;if((h=ut(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(x=Number(x>>>0),I=Number(I>>>0),L=Number(L>>>0),x+I>h.byteLength)return 3;try{let ue=h.subarray(x,x+I);switch(N){case 0:U().set(ue,L>>>0);break;case 1:n.mc?n.mc(L,ue):n.bc(L,ue);break;default:return 4}return 0}catch{return 4}},830468:(h,x,I)=>{n.Ob(h,U().subarray(x>>>0,x+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I),!0)},830824:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,x,I)=>{n.jb("HardSigmoid",h,{alpha:x,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,x,I)=>{n.jb("Clip",h,{min:x,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,x)=>{n.jb("Elu",h,{alpha:x})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,x)=>{n.jb("LeakyRelu",h,{alpha:x})},832564:(h,x)=>{n.jb("ThresholdedRelu",h,{alpha:x})},832634:(h,x)=>{n.jb("Cast",h,{to:x})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,x,I,L,N)=>{n.jb("ReduceMean",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833403:(h,x,I,L,N)=>{n.jb("ReduceMax",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833577:(h,x,I,L,N)=>{n.jb("ReduceMin",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833751:(h,x,I,L,N)=>{n.jb("ReduceProd",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},833926:(h,x,I,L,N)=>{n.jb("ReduceSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834100:(h,x,I,L,N)=>{n.jb("ReduceL1",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834273:(h,x,I,L,N)=>{n.jb("ReduceL2",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834446:(h,x,I,L,N)=>{n.jb("ReduceLogSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834623:(h,x,I,L,N)=>{n.jb("ReduceSumSquare",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834803:(h,x,I,L,N)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,x,I)=>{n.jb("Transpose",h,{perm:x?Array.from(le().subarray(Number(x)>>>0,Number(I)>>>0)):[]})},835160:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:ut(I),format:L?"NHWC":"NCHW"})},835293:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:ut(I),format:L?"NHWC":"NCHW"})},835426:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr,Ls)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[N],pads:[ue,Te],strides:[Le],wIsConst:()=>!!A()[tt>>>0],outputPadding:bt?Array.from(le().subarray(Number(bt)>>>0,Number(kt)>>>0)):[],outputShape:Wt?Array.from(le().subarray(Number(Wt)>>>0,Number(yr)>>>0)):[],activation:ut(Ls)})},835859:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr)=>{n.jb("ConvTranspose",h,{format:Le?"NHWC":"NCHW",autoPad:x,dilations:Array.from(le().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(le().subarray(Number(N)>>>0,2+(Number(N)>>>0)>>>0)),pads:Array.from(le().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(le().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!A()[Ke>>>0],outputPadding:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],outputShape:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],activation:ut(yr)})},836520:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr,Ls)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[N],pads:[ue,Te],strides:[Le],wIsConst:()=>!!A()[tt>>>0],outputPadding:bt?Array.from(le().subarray(Number(bt)>>>0,Number(kt)>>>0)):[],outputShape:Wt?Array.from(le().subarray(Number(Wt)>>>0,Number(yr)>>>0)):[],activation:ut(Ls)})},836953:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr)=>{n.jb("ConvTranspose",h,{format:Le?"NHWC":"NCHW",autoPad:x,dilations:Array.from(le().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(le().subarray(Number(N)>>>0,2+(Number(N)>>>0)>>>0)),pads:Array.from(le().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(le().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!A()[Ke>>>0],outputPadding:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],outputShape:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[],activation:ut(yr)})},837614:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},837705:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},838184:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},838275:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},838754:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},838841:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},839316:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},839403:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:N,dilations:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],pads:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],strides:kt?Array.from(le().subarray(Number(kt)>>>0,Number(Wt)>>>0)):[]})},839878:(h,x,I,L,N)=>{n.jb("Gemm",h,{alpha:x,beta:I,transA:L,transB:N})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,x,I,L)=>{n.jb("ArgMax",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840144:(h,x,I,L)=>{n.jb("ArgMin",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840252:(h,x)=>{n.jb("Softmax",h,{axis:x})},840315:(h,x)=>{n.jb("Concat",h,{axis:x})},840375:(h,x,I,L,N)=>{n.jb("Split",h,{axis:x,numOutputs:I,splitSizes:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,x)=>{n.jb("Gather",h,{axis:Number(x)})},840656:(h,x)=>{n.jb("GatherElements",h,{axis:Number(x)})},840735:(h,x)=>{n.jb("GatherND",h,{batch_dims:Number(x)})},840814:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt)=>{n.jb("Resize",h,{antialias:x,axes:I?Array.from(le().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:ut(N),cubicCoeffA:ue,excludeOutside:Te,extrapolationValue:Le,keepAspectRatioPolicy:ut(Ke),mode:ut(tt),nearestMode:ut(bt)})},841176:(h,x,I,L,N,ue,Te)=>{n.jb("Slice",h,{starts:x?Array.from(le().subarray(Number(x)>>>0,Number(I)>>>0)):[],ends:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[],axes:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841606:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,x)=>{n.jb("Einsum",h,{equation:ut(x)})},841854:(h,x,I,L,N)=>{n.jb("Pad",h,{mode:x,value:I,pads:L?Array.from(le().subarray(Number(L)>>>0,Number(N)>>>0)):[]})},841997:(h,x,I,L,N,ue)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!N,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842166:(h,x,I,L,N,ue)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!N,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842335:(h,x,I)=>{n.jb("CumSum",h,{exclusive:Number(x),reverse:Number(I)})},842432:(h,x,I)=>{n.jb("DequantizeLinear",h,{axis:x,blockSize:I})},842522:(h,x,I,L,N)=>{n.jb("GridSample",h,{align_corners:x,mode:ut(I),padding_mode:ut(L),format:N?"NHWC":"NCHW"})},842692:(h,x,I,L,N)=>{n.jb("GridSample",h,{align_corners:x,mode:ut(I),padding_mode:ut(L),format:N?"NHWC":"NCHW"})},842862:(h,x)=>{n.jb("ScatterND",h,{reduction:ut(x)})},842947:(h,x,I,L,N,ue,Te,Le,Ke)=>{n.jb("Attention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:N,doRotary:ue,qkvHiddenSizes:Te?Array.from(le().subarray(Number(Le)>>>0,Number(Le)+Te>>>0)):[],pastPresentShareBuffer:!!Ke})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,x,I,L,N,ue,Te,Le,Ke,tt,bt,kt,Wt,yr,Ls,qi)=>{n.jb("Conv",h,{format:kt?"NHWC":"NCHW",auto_pad:x,dilations:I?Array.from(le().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:N,kernel_shape:ue?Array.from(le().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],pads:Le?Array.from(le().subarray(Number(Le)>>>0,Number(Ke)>>>0)):[],strides:tt?Array.from(le().subarray(Number(tt)>>>0,Number(bt)>>>0)):[],w_is_const:()=>!!A()[Number(Wt)>>>0],activation:ut(yr),activation_params:Ls?Array.from(ze().subarray(Number(Ls)>>>0,Number(qi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,x,I,L,N,ue,Te,Le,Ke)=>{n.jb("GroupQueryAttention",h,{numHeads:x,kvNumHeads:I,scale:L,softcap:N,doRotary:ue,rotaryInterleaved:Te,smoothSoftmax:Le,localWindowSize:Ke})},844244:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844355:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844466:(h,x,I,L,N,ue)=>{n.jb("MatMulNBits",h,{k:x,n:I,accuracyLevel:L,bits:N,blockSize:ue})},844593:(h,x,I,L,N,ue)=>{n.jb("MultiHeadAttention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:N,doRotary:ue})},844752:(h,x)=>{n.jb("QuickGelu",h,{alpha:x})},844816:(h,x,I,L,N)=>{n.jb("RotaryEmbedding",h,{interleaved:!!x,numHeads:I,rotaryEmbeddingDim:L,scale:N})},844955:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845057:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845159:(h,x,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:x,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,x)=>n.ac(Number(h),Number(x),n.Fb.dc,n.Fb.errors)};function He(h,x,I){return Lr(async()=>{await n.Xb(Number(h),Number(x),Number(I))})}function qe(){return typeof wasmOffsetConverter<"u"}class ke{constructor(x){Y(this,"name","ExitStatus");this.message=`Program terminated with exit(${x})`,this.status=x}}var Ve=h=>{h.terminate(),h.onmessage=()=>{}},Ze=[],nt=h=>{Vt.length==0&&(oe(),D(Vt[0]));var x=Vt.pop();if(!x)return 6;Rt.push(x),ir[h.Ab]=x,x.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return x.postMessage(I,h.Mb),0},lt=0,Ge=(h,x,...I)=>{for(var L=2*I.length,N=kn(),ue=eo(8*L),Te=ue>>>3,Le=0;Le>>0]=Ke)}return h=Wo(h,0,L,ue,x),$n(N),h};function Ie(h){if(u)return Ge(0,1,h);if(C=h,!(0{if(C=h,u)throw pt(h),"unwind";Ie(h)},Vt=[],Rt=[],gr=[],ir={},Mt=h=>{var x=h.Ab;delete ir[x],Vt.push(h),Rt.splice(Rt.indexOf(h),1),h.Ab=0,Go(x)};function rs(){gr.forEach(h=>h())}var D=h=>new Promise(x=>{h.onmessage=N=>{var ue=(N=N.data).Bb;if(N.Gb&&N.Gb!=Pn()){var Te=ir[N.Gb];Te?Te.postMessage(N,N.Mb):v(`Internal error! Worker sent a message "${ue}" to target pthread ${N.Gb}, but that thread no longer exists!`)}else ue==="checkMailbox"?Re():ue==="spawnThread"?nt(N):ue==="cleanupThread"?Mt(ir[N.hc]):ue==="loaded"?(h.loaded=!0,x(h)):ue==="alert"?alert(`Thread ${N.ic}: ${N.text}`):N.target==="setimmediate"?h.postMessage(N):ue==="callHandler"?n[N.Qb](...N.args):ue&&v(`worker sent an unknown command ${ue}`)},h.onerror=N=>{throw v(`worker sent an error! ${N.filename}:${N.lineno}: ${N.message}`),N};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:M,lc:y})});function oe(){var h=new Worker((()=>{let x=URL;return self.location.href>"file:"&&self.location.href<"file;"?new x("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Vt.push(h)}var B=h=>{re();var x=ye()[h+52>>>2>>>0];h=ye()[h+56>>>2>>>0],Zn(x,x-h),$n(x)},te=(h,x)=>{lt=0,h=qo(h,x),0>>=0);throw x>>>=0,I>>>=0,ye()[L.Ib+16>>>2>>>0]=0,ye()[L.Ib+4>>>2>>>0]=x,ye()[L.Ib+8>>>2>>>0]=I,h}function ve(h,x,I,L){return u?Ge(2,1,h,x,I,L):vt(h,x,I,L)}function vt(h,x,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var N=[];return u&&N.length===0?ve(h,x>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:N},u?(h.Bb="spawnThread",postMessage(h,N),0):nt(h))}var Ft=typeof TextDecoder<"u"?new TextDecoder:void 0,ht=(h,x=0,I=NaN)=>{var L=(x>>>=0)+I;for(I=x;h[I]&&!(I>=L);)++I;if(16(N=(240&N)==224?(15&N)<<12|ue<<6|Te:(7&N)<<18|ue<<12|Te<<6|63&h[x++])?L+=String.fromCharCode(N):(N-=65536,L+=String.fromCharCode(55296|N>>10,56320|1023&N))}}else L+=String.fromCharCode(N)}return L},ut=(h,x)=>(h>>>=0)?ht(U(),h,x):"";function rt(h,x,I){return u?Ge(3,1,h,x,I):0}function jt(h,x){if(u)return Ge(4,1,h,x)}var Ht=h=>{for(var x=0,I=0;I=L?x++:2047>=L?x+=2:55296<=L&&57343>=L?(x+=4,++I):x+=3}return x},wr=(h,x,I)=>{var L=U();if(x>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&h.charCodeAt(++ue)),127>=Te){if(x>=I)break;L[x++>>>0]=Te}else{if(2047>=Te){if(x+1>=I)break;L[x++>>>0]=192|Te>>6}else{if(65535>=Te){if(x+2>=I)break;L[x++>>>0]=224|Te>>12}else{if(x+3>=I)break;L[x++>>>0]=240|Te>>18,L[x++>>>0]=128|Te>>12&63}L[x++>>>0]=128|Te>>6&63}L[x++>>>0]=128|63&Te}}L[x>>>0]=0,h=x-N}else h=0;return h};function Jt(h,x){if(u)return Ge(5,1,h,x)}function Or(h,x,I){if(u)return Ge(6,1,h,x,I)}function ss(h,x,I){return u?Ge(7,1,h,x,I):0}function ys(h,x){if(u)return Ge(8,1,h,x)}function ns(h,x,I){if(u)return Ge(9,1,h,x,I)}function $s(h,x,I,L){if(u)return Ge(10,1,h,x,I,L)}function Vr(h,x,I,L){if(u)return Ge(11,1,h,x,I,L)}function ks(h,x,I,L){if(u)return Ge(12,1,h,x,I,L)}function Qr(h){if(u)return Ge(13,1,h)}function vs(h,x){if(u)return Ge(14,1,h,x)}function Is(h,x,I){if(u)return Ge(15,1,h,x,I)}var As,ar,Fs=()=>$e(""),Er=h=>{for(var x="";U()[h>>>0];)x+=As[U()[h++>>>0]];return x},xs={},Br={};function Ae(h,x,I={}){return function(L,N,ue={}){var Te=N.name;if(!L)throw new ar(`type "${Te}" must have a positive integer typeid pointer`);if(Br.hasOwnProperty(L)){if(ue.Sb)return;throw new ar(`Cannot register type '${Te}' twice`)}Br[L]=N,xs.hasOwnProperty(L)&&(N=xs[L],delete xs[L],N.forEach(Le=>Le()))}(h,x,I)}var Je=(h,x,I)=>{switch(x){case 1:return I?L=>A()[L>>>0]:L=>U()[L>>>0];case 2:return I?L=>ee()[L>>>1>>>0]:L=>_e()[L>>>1>>>0];case 4:return I?L=>le()[L>>>2>>>0]:L=>ye()[L>>>2>>>0];case 8:return I?L=>J[L>>>3]:L=>Q[L>>>3];default:throw new TypeError(`invalid integer width (${x}): ${h}`)}};function it(h,x,I){I>>>=0,Ae(h>>>=0,{name:x=Er(x>>>0),fromWireType:L=>L,toWireType:function(L,N){if(typeof N!="bigint"&&typeof N!="number")throw N=N===null?"null":(L=typeof N)=="object"||L==="array"||L==="function"?N.toString():""+N,new TypeError(`Cannot convert "${N}" to ${this.name}`);return typeof N=="number"&&(N=BigInt(N)),N},Cb:Nt,readValueFromPointer:Je(x,I,x.indexOf("u")==-1),Db:null})}var Nt=8;function os(h,x,I,L){Ae(h>>>=0,{name:x=Er(x>>>0),fromWireType:function(N){return!!N},toWireType:function(N,ue){return ue?I:L},Cb:Nt,readValueFromPointer:function(N){return this.fromWireType(U()[N>>>0])},Db:null})}var is=[],ur=[];function as(h){9<(h>>>=0)&&--ur[h+1]==0&&(ur[h]=void 0,is.push(h))}var cr=h=>{if(!h)throw new ar("Cannot use deleted val. handle = "+h);return ur[h]},hr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let x=is.pop()||ur.length;return ur[x]=h,ur[x+1]=1,x}};function ls(h){return this.fromWireType(ye()[h>>>2>>>0])}var Ts={name:"emscripten::val",fromWireType:h=>{var x=cr(h);return as(h),x},toWireType:(h,x)=>hr(x),Cb:Nt,readValueFromPointer:ls,Db:null};function fn(h){return Ae(h>>>0,Ts)}var _n=(h,x)=>{switch(x){case 4:return function(I){return this.fromWireType(ze()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ue()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${x}): ${h}`)}};function gn(h,x,I){I>>>=0,Ae(h>>>=0,{name:x=Er(x>>>0),fromWireType:L=>L,toWireType:(L,N)=>N,Cb:Nt,readValueFromPointer:_n(x,I),Db:null})}function wn(h,x,I,L,N){if(h>>>=0,I>>>=0,x=Er(x>>>0),N===-1&&(N=4294967295),N=Le=>Le,L===0){var ue=32-8*I;N=Le=>Le<>>ue}var Te=x.includes("unsigned")?function(Le,Ke){return Ke>>>0}:function(Le,Ke){return Ke};Ae(h,{name:x,fromWireType:N,toWireType:Te,Cb:Nt,readValueFromPointer:Je(x,I,L!==0),Db:null})}function Mn(h,x,I){function L(ue){var Te=ye()[ue>>>2>>>0];return ue=ye()[ue+4>>>2>>>0],new N(A().buffer,ue,Te)}var N=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][x];Ae(h>>>=0,{name:I=Er(I>>>0),fromWireType:L,Cb:Nt,readValueFromPointer:L},{Sb:!0})}function Os(h,x){Ae(h>>>=0,{name:x=Er(x>>>0),fromWireType:function(I){for(var L,N=ye()[I>>>2>>>0],ue=I+4,Te=ue,Le=0;Le<=N;++Le){var Ke=ue+Le;Le!=N&&U()[Ke>>>0]!=0||(Te=ut(Te,Ke-Te),L===void 0?L=Te:(L+="\0",L+=Te),Te=Ke+1)}return Gr(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var N=typeof L=="string";if(!(N||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new ar("Cannot pass non-string to std::string");var ue=N?Ht(L):L.length,Te=Cn(4+ue+1),Le=Te+4;if(ye()[Te>>>2>>>0]=ue,N)wr(L,Le,ue+1);else if(N)for(N=0;N>>0]=Ke}else for(N=0;N>>0]=L[N];return I!==null&&I.push(Gr,Te),Te},Cb:Nt,readValueFromPointer:ls,Db(I){Gr(I)}})}var Hs=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,bn=(h,x)=>{for(var I=h>>1,L=I+x/2;!(I>=L)&&_e()[I>>>0];)++I;if(32<(I<<=1)-h&&Hs)return Hs.decode(U().slice(h,I));for(I="",L=0;!(L>=x/2);++L){var N=ee()[h+2*L>>>1>>>0];if(N==0)break;I+=String.fromCharCode(N)}return I},yn=(h,x,I)=>{if(I??(I=2147483647),2>I)return 0;var L=x;I=(I-=2)<2*h.length?I/2:h.length;for(var N=0;N>>1>>>0]=ue,x+=2}return ee()[x>>>1>>>0]=0,x-L},vn=h=>2*h.length,Ds=(h,x)=>{for(var I=0,L="";!(I>=x/4);){var N=le()[h+4*I>>>2>>>0];if(N==0)break;++I,65536<=N?(N-=65536,L+=String.fromCharCode(55296|N>>10,56320|1023&N)):L+=String.fromCharCode(N)}return L},de=(h,x,I)=>{if(x>>>=0,I??(I=2147483647),4>I)return 0;var L=x;I=L+I-4;for(var N=0;N=ue&&(ue=65536+((1023&ue)<<10)|1023&h.charCodeAt(++N)),le()[x>>>2>>>0]=ue,(x+=4)+4>I)break}return le()[x>>>2>>>0]=0,x-L},$=h=>{for(var x=0,I=0;I=L&&++I,x+=4}return x};function j(h,x,I){if(h>>>=0,x>>>=0,I=Er(I>>>=0),x===2)var L=bn,N=yn,ue=vn,Te=Le=>_e()[Le>>>1>>>0];else x===4&&(L=Ds,N=de,ue=$,Te=Le=>ye()[Le>>>2>>>0]);Ae(h,{name:I,fromWireType:Le=>{for(var Ke,tt=ye()[Le>>>2>>>0],bt=Le+4,kt=0;kt<=tt;++kt){var Wt=Le+4+kt*x;kt!=tt&&Te(Wt)!=0||(bt=L(bt,Wt-bt),Ke===void 0?Ke=bt:(Ke+="\0",Ke+=bt),bt=Wt+x)}return Gr(Le),Ke},toWireType:(Le,Ke)=>{if(typeof Ke!="string")throw new ar(`Cannot pass non-string to C++ string type ${I}`);var tt=ue(Ke),bt=Cn(4+tt+x);return ye()[bt>>>2>>>0]=tt/x,N(Ke,bt+4,tt+x),Le!==null&&Le.push(Gr,bt),bt},Cb:Nt,readValueFromPointer:ls,Db(Le){Gr(Le)}})}function X(h,x){Ae(h>>>=0,{Tb:!0,name:x=Er(x>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){Jn(h>>>0,!l,1,!a,131072,!1),rs()}var ce=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(le(),h>>>2,h).value.then(Re),h+=128,Atomics.store(le(),h>>>2,1))}var Re=()=>{var h=Pn();h&&(xe(h),ce(Ho))};function Qe(h,x){(h>>>=0)==x>>>0?setTimeout(Re):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=ir[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function Ye(h,x,I,L,N){for(x>>>=0,L/=2,We.length=L,I=N>>>0>>>3,N=0;N>>0];return(x?Be[x]:Hi[h])(...We)}var _t=()=>{lt=0};function Ot(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):Mt(ir[h])}function At(h){}var Yt=(h,x)=>{var I=Br[h];if(I===void 0)throw h=Xn(h),I=Er(h),Gr(h),new ar(`${x} has unknown type ${I}`);return I},Ut=(h,x,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ye()[x>>>2>>>0]=hr(L)),h};function mr(h,x,I){return x>>>=0,I>>>=0,h=cr(h>>>0),x=Yt(x,"emval::as"),Ut(x,I,h)}function Mr(h,x){return x>>>=0,h=cr(h>>>0),(x=Yt(x,"emval::as")).toWireType(null,h)}var Pr=h=>{try{h()}catch(x){$e(x)}},Cr=0,Zt=null,Es=0,Kt=[],fr={},Dr={},Xr=0,Jr=null,Ir=[];function Lr(h){return function(x){if(!ae){if(Cr===0){var I=!1,L=!1;x((N=0)=>{if(!ae&&(Es=N,I=!0,L)){Cr=2,Pr(()=>Xo(Zt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),N=!1;try{var ue=function(){var Ke=le()[Zt+8>>>2>>>0];return Ke=ct[Dr[Ke]],--lt,Ke()}()}catch(Ke){ue=Ke,N=!0}var Te=!1;if(!Zt){var Le=Jr;Le&&(Jr=null,(N?Le.reject:Le.resolve)(ue),Te=!0)}if(N&&!Te)throw ue}}),L=!0,I||(Cr=1,Zt=function(){var N=Cn(65548),ue=N+12;ye()[N>>>2>>>0]=ue,ye()[N+4>>>2>>>0]=ue+65536,ue=Kt[0];var Te=fr[ue];return Te===void 0&&(Te=Xr++,fr[ue]=Te,Dr[Te]=ue),ue=Te,le()[N+8>>>2>>>0]=ue,N}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Pr(()=>Qo(Zt)))}else Cr===2?(Cr=0,Pr(Jo),Gr(Zt),Zt=null,Ir.forEach(ce)):$e(`invalid state: ${Cr}`);return Es}}(x=>{h().then(x)})}function br(h){return h>>>=0,Lr(async()=>{var x=await cr(h);return hr(x)})}var er=[];function dr(h,x,I,L){return I>>>=0,L>>>=0,(h=er[h>>>0])(null,x=cr(x>>>0),I,L)}var pr={},Ar=h=>{var x=pr[h];return x===void 0?Er(h):x};function us(h,x,I,L,N){return I>>>=0,L>>>=0,N>>>=0,(h=er[h>>>0])(x=cr(x>>>0),x[I=Ar(I)],L,N)}var xn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ti(h){return(h>>>=0)==0?hr(xn()):(h=Ar(h),hr(xn()[h]))}var Ei=h=>{var x=er.length;return er.push(h),x},Pi=(h,x)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},To=(h,x)=>Object.defineProperty(x,"name",{value:h});function qs(h,x,I){var L=(x=Pi(h,x>>>0)).shift();h--;var N=`return function (obj, func, destructorsRef, args) { +`,ue=0,Te=[];I===0&&Te.push("obj");for(var Le=["retType"],Ke=[L],tt=0;ttbt.name).join(", ")}) => ${L.name}>`,Ei(To(I,h))}function Ci(h){return h=Ar(h>>>0),hr(n[h])}function Si(h,x){return x>>>=0,h=cr(h>>>0),x=cr(x),hr(h[x])}function $i(h){9<(h>>>=0)&&(ur[h+1]+=1)}function ki(){return hr([])}function Ii(h){h=cr(h>>>0);for(var x=Array(h.length),I=0;I>>0))}function Ai(){return hr({})}function Fi(h){for(var x=cr(h>>>=0);x.length;){var I=x.pop();x.pop()(I)}as(h)}function Po(h,x,I){x>>>=0,I>>>=0,h=cr(h>>>0),x=cr(x),I=cr(I),h[x]=I}function Oi(h,x){return x>>>=0,h=(h=Yt(h>>>0,"_emval_take_value")).readValueFromPointer(x),hr(h)}function Co(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),le()[x>>>2>>>0]=h.getUTCSeconds(),le()[x+4>>>2>>>0]=h.getUTCMinutes(),le()[x+8>>>2>>>0]=h.getUTCHours(),le()[x+12>>>2>>>0]=h.getUTCDate(),le()[x+16>>>2>>>0]=h.getUTCMonth(),le()[x+20>>>2>>>0]=h.getUTCFullYear()-1900,le()[x+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,le()[x+28>>>2>>>0]=h}var So=h=>h%4==0&&(h%100!=0||h%400==0),Kn=[0,31,60,91,121,152,182,213,244,274,305,335],Di=[0,31,59,90,120,151,181,212,243,273,304,334];function Li(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),le()[x>>>2>>>0]=h.getSeconds(),le()[x+4>>>2>>>0]=h.getMinutes(),le()[x+8>>>2>>>0]=h.getHours(),le()[x+12>>>2>>>0]=h.getDate(),le()[x+16>>>2>>>0]=h.getMonth(),le()[x+20>>>2>>>0]=h.getFullYear()-1900,le()[x+24>>>2>>>0]=h.getDay();var I=(So(h.getFullYear())?Kn:Di)[h.getMonth()]+h.getDate()-1|0;le()[x+28>>>2>>>0]=I,le()[x+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),le()[x+32>>>2>>>0]=h}function $o(h){h>>>=0;var x=new Date(le()[h+20>>>2>>>0]+1900,le()[h+16>>>2>>>0],le()[h+12>>>2>>>0],le()[h+8>>>2>>>0],le()[h+4>>>2>>>0],le()[h>>>2>>>0],0),I=le()[h+32>>>2>>>0],L=x.getTimezoneOffset(),N=new Date(x.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(x.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ue,N);return 0>I?le()[h+32>>>2>>>0]=+(N!=ue&&Te==L):0>>2>>>0]=x.getDay(),I=(So(x.getFullYear())?Kn:Di)[x.getMonth()]+x.getDate()-1|0,le()[h+28>>>2>>>0]=I,le()[h>>>2>>>0]=x.getSeconds(),le()[h+4>>>2>>>0]=x.getMinutes(),le()[h+8>>>2>>>0]=x.getHours(),le()[h+12>>>2>>>0]=x.getDate(),le()[h+16>>>2>>>0]=x.getMonth(),le()[h+20>>>2>>>0]=x.getYear(),h=x.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function ko(h,x,I,L,N,ue,Te){return u?Ge(16,1,h,x,I,L,N,ue,Te):-52}function Tn(h,x,I,L,N,ue){if(u)return Ge(17,1,h,x,I,L,N,ue)}var Qs={},zi=()=>performance.timeOrigin+performance.now();function Io(h,x){if(u)return Ge(18,1,h,x);if(Qs[h]&&(clearTimeout(Qs[h].id),delete Qs[h]),!x)return 0;var I=setTimeout(()=>{delete Qs[h],ce(()=>Ko(h,performance.timeOrigin+performance.now()))},x);return Qs[h]={id:I,qc:x},0}function Bi(h,x,I,L){h>>>=0,x>>>=0,I>>>=0,L>>>=0;var N=new Date().getFullYear(),ue=new Date(N,0,1).getTimezoneOffset();N=new Date(N,6,1).getTimezoneOffset();var Te=Math.max(ue,N);ye()[h>>>2>>>0]=60*Te,le()[x>>>2>>>0]=+(ue!=N),h=(x=Le=>{var Ke=Math.abs(Le);return`UTC${0<=Le?"-":"+"}${String(Math.floor(Ke/60)).padStart(2,"0")}${String(Ke%60).padStart(2,"0")}`})(ue),x=x(N),NDate.now();function ji(h,x,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),J[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Hn=[],En=(h,x)=>{Hn.length=0;for(var I;I=U()[h++>>>0];){var L=I!=105;x+=(L&=I!=112)&&x%8?4:0,Hn.push(I==112?ye()[x>>>2>>>0]:I==106?J[x>>>3]:I==105?le()[x>>>2>>>0]:Ue()[x>>>3>>>0]),x+=L?8:4}return Hn};function Ao(h,x,I){return h>>>=0,x=En(x>>>0,I>>>0),Be[h](...x)}function Ni(h,x,I){return h>>>=0,x=En(x>>>0,I>>>0),Be[h](...x)}var Fo=()=>{};function Ns(h,x){return v(ut(h>>>0,x>>>0))}var Vi=()=>{throw lt+=1,"unwind"};function pu(){return 4294901760}var Ui=()=>navigator.hardwareConcurrency;function hu(){return $e("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Wi(h){h>>>=0;var x=U().length;if(h<=x||4294901760=I;I*=2){var L=x*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-M.buffer.byteLength+65535)/65536|0;try{M.grow(L),re();var N=1;break e}catch{}N=void 0}if(N)return!0}return!1}var Xs=()=>($e("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Js={},Oo=h=>{h.forEach(x=>{Xs()})};function Gi(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),Oo(h),Js.Lb=Xs(),Js.cc=h,Js.Lb}function Ki(h,x,I){if(h>>>=0,x>>>=0,Js.Lb==h)var L=Js.cc;else(L=Error().stack.toString().split(` +`))[0]=="Error"&&L.shift(),Oo(L);for(var N=3;L[N]&&Xs()!=h;)++N;for(h=0;h>>2>>>0]=Xs();return h}var qn,Ys={},Do=()=>{if(!qn){var h,x={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(h in Ys)Ys[h]===void 0?delete x[h]:x[h]=Ys[h];var I=[];for(h in x)I.push(`${h}=${x[h]}`);qn=I}return qn};function Lo(h,x){if(u)return Ge(19,1,h,x);h>>>=0,x>>>=0;var I=0;return Do().forEach((L,N)=>{var ue=x+I;for(N=ye()[h+4*N>>>2>>>0]=ue,ue=0;ue>>0]=L.charCodeAt(ue);A()[N>>>0]=0,I+=L.length+1}),0}function zo(h,x){if(u)return Ge(20,1,h,x);h>>>=0,x>>>=0;var I=Do();ye()[h>>>2>>>0]=I.length;var L=0;return I.forEach(N=>L+=N.length+1),ye()[x>>>2>>>0]=L,0}function Qn(h){return u?Ge(21,1,h):52}function Bo(h,x,I,L){return u?Ge(22,1,h,x,I,L):52}function Ro(h,x,I,L){return u?Ge(23,1,h,x,I,L):70}var jo=[null,[],[]];function No(h,x,I,L){if(u)return Ge(24,1,h,x,I,L);x>>>=0,I>>>=0,L>>>=0;for(var N=0,ue=0;ue>>2>>>0],Le=ye()[x+4>>>2>>>0];x+=8;for(var Ke=0;Ke>>0],bt=jo[h];tt===0||tt===10?((h===1?E:v)(ht(bt)),bt.length=0):bt.push(tt)}N+=Le}return ye()[L>>>2>>>0]=N,0}u||function(){for(var h=n.numThreads-1;h--;)oe();Ze.unshift(()=>{we++,function(x){u?x():Promise.all(Vt.map(D)).then(x)}(()=>Ce())})}();for(var Vo=Array(256),Zs=0;256>Zs;++Zs)Vo[Zs]=String.fromCharCode(Zs);As=Vo,ar=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},ur.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>ur.length/2-5-is.length;var ct,Hi=[Ie,pt,ve,rt,jt,Jt,Or,ss,ys,ns,$s,Vr,ks,Qr,vs,Is,ko,Tn,Io,Lo,zo,Qn,Bo,Ro,No];(async function(){function h(L,N){return ct=L.exports,ct=function(){var ue=ct,Te={};for(let[Le,Ke]of Object.entries(ue))Te[Le]=typeof Ke=="function"?(...tt)=>{Kt.push(Le);try{return Ke(...tt)}finally{ae||(Kt.pop(),Zt&&Cr===1&&Kt.length===0&&(Cr=0,lt+=1,Pr(to),typeof Fibers<"u"&&Fibers.rc()))}}:Ke;return Te}(),ct=function(){var ue=ct,Te=Ke=>tt=>Ke(tt)>>>0,Le=Ke=>()=>Ke()>>>0;return(ue=Object.assign({},ue)).Da=Te(ue.Da),ue.fb=Le(ue.fb),ue.hb=Te(ue.hb),ue.tb=Te(ue.tb),ue.ub=Le(ue.ub),ue.__cxa_get_exception_ptr=Te(ue.__cxa_get_exception_ptr),ue}(),gr.push(ct.ib),y=N,Ce(),ct}we++;var x=Fe();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(x,(N,ue)=>{h(N,ue),L(N.exports)})});if(u)return new Promise(L=>{pe=N=>{var ue=new WebAssembly.Instance(N,Fe());L(h(ue,N))}});be??(be=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",w):w+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href);try{var I=await async function(L){var N=be;if(!fe&&typeof WebAssembly.instantiateStreaming=="function"&&!V(N))try{var ue=fetch(N,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ue,L)}catch(Te){v(`wasm streaming compile failed: ${Te}`),v("falling back to ArrayBuffer instantiation")}return async function(Te,Le){try{var Ke=await async function(tt){if(!fe)try{var bt=await _(tt);return new Uint8Array(bt)}catch{}if(tt==be&&fe)tt=new Uint8Array(fe);else{if(!f)throw"both async and sync fetching of the wasm failed";tt=f(tt)}return tt}(Te);return await WebAssembly.instantiate(Ke,Le)}catch(tt){v(`failed to asynchronously prepare wasm: ${tt}`),$e(tt)}}(N,L)}(x);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var Xn=h=>(Xn=ct.Da)(h),Uo=()=>(Uo=ct.Ea)();n._OrtInit=(h,x)=>(n._OrtInit=ct.Fa)(h,x),n._OrtGetLastError=(h,x)=>(n._OrtGetLastError=ct.Ga)(h,x),n._OrtCreateSessionOptions=(h,x,I,L,N,ue,Te,Le,Ke,tt)=>(n._OrtCreateSessionOptions=ct.Ha)(h,x,I,L,N,ue,Te,Le,Ke,tt),n._OrtAppendExecutionProvider=(h,x,I,L,N)=>(n._OrtAppendExecutionProvider=ct.Ia)(h,x,I,L,N),n._OrtAddFreeDimensionOverride=(h,x,I)=>(n._OrtAddFreeDimensionOverride=ct.Ja)(h,x,I),n._OrtAddSessionConfigEntry=(h,x,I)=>(n._OrtAddSessionConfigEntry=ct.Ka)(h,x,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=ct.La)(h),n._OrtCreateSession=(h,x,I)=>(n._OrtCreateSession=ct.Ma)(h,x,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=ct.Na)(h),n._OrtGetInputOutputCount=(h,x,I)=>(n._OrtGetInputOutputCount=ct.Oa)(h,x,I),n._OrtGetInputOutputMetadata=(h,x,I,L)=>(n._OrtGetInputOutputMetadata=ct.Pa)(h,x,I,L),n._OrtFree=h=>(n._OrtFree=ct.Qa)(h),n._OrtCreateTensor=(h,x,I,L,N,ue)=>(n._OrtCreateTensor=ct.Ra)(h,x,I,L,N,ue),n._OrtGetTensorData=(h,x,I,L,N)=>(n._OrtGetTensorData=ct.Sa)(h,x,I,L,N),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=ct.Ta)(h),n._OrtCreateRunOptions=(h,x,I,L)=>(n._OrtCreateRunOptions=ct.Ua)(h,x,I,L),n._OrtAddRunConfigEntry=(h,x,I)=>(n._OrtAddRunConfigEntry=ct.Va)(h,x,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=ct.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=ct.Xa)(h),n._OrtBindInput=(h,x,I)=>(n._OrtBindInput=ct.Ya)(h,x,I),n._OrtBindOutput=(h,x,I,L)=>(n._OrtBindOutput=ct.Za)(h,x,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=ct._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=ct.$a)(h),n._OrtRunWithBinding=(h,x,I,L,N)=>(n._OrtRunWithBinding=ct.ab)(h,x,I,L,N),n._OrtRun=(h,x,I,L,N,ue,Te,Le)=>(n._OrtRun=ct.bb)(h,x,I,L,N,ue,Te,Le),n._OrtEndProfiling=h=>(n._OrtEndProfiling=ct.cb)(h),n._JsepOutput=(h,x,I)=>(n._JsepOutput=ct.db)(h,x,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=ct.eb)(h);var Pn=()=>(Pn=ct.fb)(),Gr=n._free=h=>(Gr=n._free=ct.gb)(h),Cn=n._malloc=h=>(Cn=n._malloc=ct.hb)(h),Jn=(h,x,I,L,N,ue)=>(Jn=ct.kb)(h,x,I,L,N,ue),Yn=()=>(Yn=ct.lb)(),Wo=(h,x,I,L,N)=>(Wo=ct.mb)(h,x,I,L,N),Go=h=>(Go=ct.nb)(h),Sn=h=>(Sn=ct.ob)(h),Ko=(h,x)=>(Ko=ct.pb)(h,x),Ho=()=>(Ho=ct.qb)(),Zn=(h,x)=>(Zn=ct.rb)(h,x),$n=h=>($n=ct.sb)(h),eo=h=>(eo=ct.tb)(h),kn=()=>(kn=ct.ub)(),qo=n.dynCall_ii=(h,x)=>(qo=n.dynCall_ii=ct.vb)(h,x),Qo=h=>(Qo=ct.wb)(h),to=()=>(to=ct.xb)(),Xo=h=>(Xo=ct.yb)(h),Jo=()=>(Jo=ct.zb)();return n.stackSave=()=>kn(),n.stackRestore=h=>$n(h),n.stackAlloc=h=>eo(h),n.setValue=function(h,x,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":A()[h>>>0]=x;break;case"i16":ee()[h>>>1>>>0]=x;break;case"i32":le()[h>>>2>>>0]=x;break;case"i64":J[h>>>3]=BigInt(x);break;case"float":ze()[h>>>2>>>0]=x;break;case"double":Ue()[h>>>3>>>0]=x;break;case"*":ye()[h>>>2>>>0]=x;break;default:$e(`invalid type for setValue: ${I}`)}},n.getValue=function(h,x="i8"){switch(x.endsWith("*")&&(x="*"),x){case"i1":case"i8":return A()[h>>>0];case"i16":return ee()[h>>>1>>>0];case"i32":return le()[h>>>2>>>0];case"i64":return J[h>>>3];case"float":return ze()[h>>>2>>>0];case"double":return Ue()[h>>>3>>>0];case"*":return ye()[h>>>2>>>0];default:$e(`invalid type for getValue: ${x}`)}},n.UTF8ToString=ut,n.stringToUTF8=wr,n.lengthBytesUTF8=Ht,function h(){if(0{Pa(),Ia=typeof location>"u"?void 0:location.origin,Aa=self.location.href>"file:"&&self.location.href<"file;",Zc=()=>{{if(Aa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Ia).href}return self.location.href}},Hr=Zc(),ed=()=>{if(Hr&&!Hr.startsWith("blob:"))return Hr.substring(0,Hr.lastIndexOf("/")+1)},si=(e,r)=>{try{let t=r??Hr;return(t?new URL(e,t):new URL(e)).origin===Ia}catch{return!1}},td=(e,r)=>{let t=r??Hr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},rd=(e,r)=>`${r??"./"}${e}`,Fa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},sd=async e=>(await import(e)).default,Oa=(Tv(),io(qc)).default,nd=async()=>{if(!Hr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(si(Hr))return[void 0,Oa()];let e=await Fa(Hr);return[e,Oa(e)]},Da=(Ev(),io(Xc)).default,od=async(e,r,t)=>{if(!e&&!r&&Da&&Hr&&si(Hr))return[void 0,Da];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??td(s,r),n=t&&o&&!si(o,r),i=n?await Fa(o):o??rd(s,r);return[n?i:void 0,await sd(i)]}}}),za,ni,co,Ba,id,ad,ld,Ra,Qt,nn=je(()=>{La(),ni=!1,co=!1,Ba=!1,id=()=>{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}},ad=()=>{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}},ld=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ra=async e=>{if(ni)return Promise.resolve();if(co)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ba)throw new Error("previous call to 'initializeWebAssembly()' failed.");co=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ld())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ad())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=id();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 o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[c,d]=await od(a,n,t>1),_=!1,f=[];if(r>0&&f.push(new Promise(T=>{setTimeout(()=>{_=!0,T()},r)})),f.push(new Promise((T,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(u||n)w.locateFile=g=>u??n+g;else if(a&&a.indexOf("blob:")!==0)w.locateFile=g=>new URL(g,a).href;else if(c){let g=ed();g&&(w.locateFile=S=>g+S)}d(w).then(g=>{co=!1,ni=!0,za=g,T(),c&&URL.revokeObjectURL(c)},g=>{co=!1,Ba=!0,k(g)})})),await Promise.race(f),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qt=()=>{if(ni&&za)return za;throw new Error("WebAssembly is not initialized yet.")}}),fs,oi,Gt,ja=je(()=>{nn(),fs=(e,r)=>{let t=Qt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},oi=(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(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")oi(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Gt=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),ud,Pv=je(()=>{nn(),ja(),ud=e=>{let r=Qt(),t=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.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)o.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&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=fs(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&Gt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&oi(e.extra,"",new WeakSet,(i,a)=>{let l=fs(i,s),u=fs(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&Gt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),cd,dd,pd,po,hd,md,Cv=je(()=>{nn(),ja(),cd=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}`)}},dd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},pd=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)},po=(e,r,t,s)=>{let o=fs(r,s),n=fs(t,s);Qt()._OrtAddSessionConfigEntry(e,o,n)!==0&&Gt(`Can't set a session config entry: ${r} - ${t}.`)},hd=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&po(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);po(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=fs(o,t),a=n.length,l=0,u=0;if(a>0){l=Qt()._malloc(a*Qt().PTR_SIZE),t.push(l),u=Qt()._malloc(a*Qt().PTR_SIZE),t.push(u);for(let p=0;p{let r=Qt(),t=0,s=[],o=e||{};pd(o);try{let n=cd(o.graphOptimizationLevel??"all"),i=dd(o.executionMode??"sequential"),a=typeof o.logId=="string"?fs(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?fs(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&Gt("Can't create session options."),o.executionProviders&&await hd(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);po(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[c,d]of Object.entries(o.freeDimensionOverrides)){if(typeof c!="string")throw new Error(`free dimension override name must be a string: ${c}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let _=fs(c,s);r._OrtAddFreeDimensionOverride(t,_,d)!==0&&Gt(`Can't set a free dimension override: ${c} - ${d}.`)}return o.extra!==void 0&&oi(o.extra,"",new WeakSet,(c,d)=>{po(t,c,d,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Gt("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),jn,zs,on,Na,ii,Va,Ua,Wa,ft=je(()=>{jn=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}`)}},zs=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}`)}},on=(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((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},Na=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}`)}},ii=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}`)}},Va=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ua=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wa=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}`)}}}),Ga,fd=je(()=>{Pa(),Ga=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 o=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 i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),_d,gd,wd,Md,Ka,bd,It,Bs=je(()=>{ft(),_d=["V","I","W","E","F"],gd=(e,r)=>{console.log(`[${_d[e]},${new Date().toISOString()}]${r}`)},Ka=(e,r)=>{wd=e,Md=r},bd=(e,r)=>{let t=ii(e),s=ii(wd);t>=s&&gd(t,typeof r=="function"?r():r)},It=(...e)=>{Md&&bd(...e)}}),yd,Nn,Me,ai,vd,xd,Td,yt=je(()=>{yd=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,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=yd.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},Me=class _a{static size(r){return _a.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}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 _a.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 _a.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+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((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ai=class ei{static adjustPoolAttributes(r,t,s,o,n,i){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]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,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(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ft(),Ha=(e,r)=>new(Na(r))(e)}),qa,Qa,Pd,Xa,Cd,Ja,Ya,Za,Sd,$d,Sv=je(()=>{Bs(),qa=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Qa=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Pd=1,Xa=()=>Pd++,Cd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ja=(e,r)=>{let t=Cd.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Ya=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ja(this.dataType,this.tensorShape)}destroy(){It("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Qa(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):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,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},Za=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 o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",It("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Ja(o,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 a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=qa(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else It("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Qa(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Sd=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=Xa();return this.tensorTrackersById.set(e,new Za(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,o){It("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){It("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 o=this.getMLContext(e),n=Xa(),i=new Ya({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new Za(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){It("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let c=this.freeTensors.splice(u,1)[0];return c.sessionId=e,c}It("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Ya({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},$d=(...e)=>new Sd(...e)}),li,kd,Id,$v=je(()=>{ft(),nn(),Ed(),Sv(),Bs(),li=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),kd=(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((o,n)=>o===s[n]&&e[o]===r[o])},Id=class{constructor(e){this.tensorManager=$d(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ka(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){It("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){It("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)It("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=>kd(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(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){It("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=li.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){It("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=li.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!Qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");It("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 Ha(t,r)}}registerMLTensor(e,r,t,s){let o=li.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return It("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=qa(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return It("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),el=je(()=>{}),tl,ui,ci,Ad,Fd,rl,sl,Od,Dd,kv=je(()=>{Bs(),el(),tl=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]]),ui=[],ci=e=>Math.ceil(Number(e)/16)*16,Ad=e=>{for(let r=0;rFd++,sl=async(e,r,t,s)=>{let o=ci(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),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()}},Od=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 tl)ui.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=ci(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);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,o)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),It("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 o=ci(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return It("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=rl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),It("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),It("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Ad(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?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 i={id:rl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),It("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}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 It("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 sl(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=tl.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&&(It("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Dd=(...e)=>new Od(...e)}),Ld,zt,or=je(()=>{Ld=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}},zt=e=>new Ld(e)}),Vn,di,Tr,zr,at,sr,nl,Un,Us,st,ho,Pe,et,zd,ol,Bd,Rd,Tt=je(()=>{ft(),yt(),Vn=64,di=(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}`)}},Tr=(e,r=1)=>{let t=di(e,r);return typeof t=="string"?t:t[0]},zr=(e,r=1)=>{let t=di(e,r);return typeof t=="string"?t:t[1]},at=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:Me.computeStrides(t)})}),r},sr=e=>e%4===0?4:e%2===0?2:1,nl=(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})`,Us=(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,st=(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,ho=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=di(r,o),p=typeof u=="string"?u:u[1],c=typeof u=="string"?u:u[0],d={indices:l,value:p,storage:c,tensor:r},_=V=>typeof V=="string"?V:`${V}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},T=n?"uniforms.":"",k=`${T}${e}_shape`,w=`${T}${e}_strides`,g="";for(let V=0;V ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${g} + return indices; + }`,E=V=>(f.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),v=[];if(i>=2)for(let V=i-1;V>=0;V--)v.push(`${st(w,V,i)} * (indices[${V}])`);let M=i<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${v.join("+")}; + }`,y=V=>(f.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),C=(...V)=>i===0?"0u":`${d.indices}(${V.map(_).join(",")})`,F=(V,A)=>i<2?`${V}`:`${st(V,A,i)}`,z=(V,A,U)=>i<2?`${V}=${U};`:`${st(V,A,i)}=${U};`,K={},q=(V,A)=>{f.broadcastedIndicesToOffset=!0;let U=`${A.name}broadcastedIndicesTo${e}Offset`;if(U in K)return`${U}(${V})`;let ee=[];for(let _e=i-1;_e>=0;_e--){let le=A.indicesGet("outputIndices",_e+A.rank-i);ee.push(`${F(w,_e)} * (${le} % ${F(k,_e)})`)}return K[U]=`fn ${U}(outputIndices: ${A.type.indices}) -> u32 { + return ${ee.length>0?ee.join("+"):"0u"}; + }`,`${U}(${V})`},R=(V,A)=>(()=>{if(d.storage===d.value)return`${e}[${V}]=${A};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${V}]=vec2(u32(${A}), select(0u, 0xFFFFFFFFu, ${A} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${V}]=vec2(u32(${A}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${A}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),Z=V=>(()=>{if(d.storage===d.value)return`${e}[${V}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${V}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${V}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${p} { + return ${Z(`i2o_${e}(indices)`)}; + }`,J=i<2?"":(()=>{let V=a.map(U=>`d${U}: u32`).join(", "),A=a.map(U=>`d${U}`).join(", ");return` + fn get_${e}(${V}) -> ${p} { + return get_${e}ByIndices(${C(A)}); + }`})(),Q=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let A=V.map(_).join(",");return i===0?Z("0u"):i===1?Z(A[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${A})`)},se=V=>i<2?Z(V):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${V})`),fe=i<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${p}) { + ${R(`i2o_${e}(indices)`,"value")} + }`,ae=i<2?"":(()=>{let V=a.map(U=>`d${U}: u32`).join(", "),A=a.map(U=>`d${U}`).join(", ");return` + fn set_${e}(${V}, value: ${p}) { + set_${e}ByIndices(${C(A)}, value); + }`})();return{impl:()=>{let V=[],A=!1;return f.offsetToIndices&&(V.push(S),A=!0),f.indicesToOffset&&(V.push(M),A=!0),f.broadcastedIndicesToOffset&&(Object.values(K).forEach(U=>V.push(U)),A=!0),f.set&&(V.push(ae),A=!0),f.setByIndices&&(V.push(fe),A=!0),f.get&&(V.push(J),A=!0),f.getByIndices&&(V.push(H),A=!0),!n&&A&&V.unshift(`const ${k} = ${d.indices}(${t.join(",")});`,`const ${w} = ${d.indices}(${Me.computeStrides(t).join(",")});`),V.join(` +`)},type:d,offsetToIndices:E,indicesToOffset:y,broadcastedIndicesToOffset:q,indices:C,indicesGet:F,indicesSet:z,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let A=V[i];if(typeof A!="string")throw new Error("value must be string");let U=V.slice(0,i).map(_).join(",");return i===0?R("0u",A):i===1?R(U[0],A):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${U}, ${A})`)},setByOffset:R,setByIndices:(V,A)=>i<2?R(V,A):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${A});`),get:Q,getByOffset:Z,getByIndices:se,usage:s,name:e,strides:w,shape:k,rank:i}},Pe=(e,r,t,s=1)=>ho(e,r,t,"input",s),et=(e,r,t,s=1)=>ho(e,r,t,"output",s),zd=(e,r,t)=>ho(e,r,t,"atomicOutput",1),ol=(e,r,t,s=1)=>ho(e,r,t,"internal",s),Bd=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=Vn){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 o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@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, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` + 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])}},Rd=(e,r)=>new Bd(e,r)}),jd,il,Nd,Vd,Ud,Wd,qr,Gd,Kd,Ws=je(()=>{ft(),yt(),or(),Tt(),jd=(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}`)},il=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Nd=(e,r)=>Me.sortBasedOnPerm(e,il(e.length,r)),Vd=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=il(s,r),n=Nd(e.dims,o),i=e.dims,a=n,l=s<2||Wd(o,e.dims),u;if(l)return u=f=>{let T=Pe("input",t,i,4),k=et("output",t,a,4);return` + ${f.registerUniform("output_size","u32").declareVariables(T,k)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let f=Me.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:u};let{newShape:p,newPerm:c}=Ud(e.dims,o),d=Me.areEqual(c,[2,3,1]),_=Me.areEqual(c,[3,1,2]);if(p.length===2||d||_){i=d?[p[0],p[1]*p[2]]:_?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let f=16;return u=T=>{let k=Pe("a",t,i.length),w=et("output",t,a.length);return` + ${T.registerUniform("output_size","u32").declareVariables(k,w)} + var tile : array, ${f}>; + ${T.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 * ${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] = ${k.getByIndices(`${k.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + 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]) { + ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let T=Me.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:T},...at(i,a)]}},getShaderSource:u}}return u=f=>{let T=Pe("a",t,i.length),k=et("output",t,a.length);return` + ${f.registerUniform("output_size","u32").declareVariables(T,k)} + + ${Vd(o,s,T,k)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",T.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let f=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...at(i,a)]}},getShaderSource:u}},Gd=(e,r)=>{jd(e.inputs,r.perm),e.compute(qr(e.inputs[0],r.perm))},Kd=e=>zt({perm:e.perm})}),Hd,qd,Qd,Xd,Jd,Yd,Zd,ep,tp,rp,_s,sp,np,op,ip,ap,lp,up,cp,dp,pp,Iv=je(()=>{ft(),yt(),Tt(),ll(),Ws(),Hd={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"},qd={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"},Qd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Xd={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Jd=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},Zd=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!ep(e,r)){for(let s=0;st.push(s))}return t},rp=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=Me.size(n),u=Me.size(i),p=Pe("_A",t[0].dataType,a),c=et("output",o,n),d=64;l===1&&(d=256);let _=` + var aBestValues : array; + `,f=T=>` + ${T.registerUniform("reduceSize","u32").declareVariables(p,c)} + ${_} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${T.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Qd[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Hd[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${qd[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${c.setByOffset("outputIndex",`${s==="mean"?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${Xd[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${d}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},_s=(e,r,t,s)=>{let o=e.inputs.length===1?t:al(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((_,f)=>f));let i=Me.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=tp(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(qr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=Jd(a.length,l.dims.length));let[p,c]=Yd(l.dims,a),d=p;o.keepDims&&(d=Zd(p,i)),e.compute(rp(r,o.cacheKey,[l],s,e.inputs[0].dataType,d,c),{inputs:[l]})},sp=(e,r)=>{_s(e,"ReduceMeanShared",r,"mean")},np=(e,r)=>{_s(e,"ReduceL1Shared",r,"l1")},op=(e,r)=>{_s(e,"ReduceL2Shared",r,"l2")},ip=(e,r)=>{_s(e,"ReduceLogSumExpShared",r,"logSumExp")},ap=(e,r)=>{_s(e,"ReduceMaxShared",r,"max")},lp=(e,r)=>{_s(e,"ReduceMinShared",r,"min")},up=(e,r)=>{_s(e,"ReduceProdShared",r,"prod")},cp=(e,r)=>{_s(e,"ReduceSumShared",r,"sum")},dp=(e,r)=>{_s(e,"ReduceSumSquareShared",r,"sumSquare")},pp=(e,r)=>{_s(e,"ReduceLogSumShared",r,"logSum")}}),gs,hp,pi,al,ws,mp,fp,_p,gp,wp,Mp,bp,yp,vp,xp,Ms,Tp,Ep,Pp,Cp,Sp,$p,kp,Ip,Ap,Fp,ll=je(()=>{ft(),yt(),or(),Tt(),Iv(),gs=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.")},hp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],pi=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,c=Me.normalizeAxes(o,p),d=!a&&c.length===0;u.forEach((T,k)=>{d||c.indexOf(k)>=0?i&&l.push(1):l.push(T)});let _=l.length,f=Me.size(l);return{name:e,shaderCache:r,getShaderSource:T=>{let k=[],w=Pe("_A",t[0].dataType,p),g=et("output",n,_),S=s(w,g,c),E=S[2];for(let v=0,M=0;v=0?(i&&M++,E=`for(var j${v}: u32 = 0; j${v} < ${u[v]}; j${v}++) { + ${S[2].includes("last_index")?`let last_index = j${v};`:""} + ${w.indicesSet("input_indices",v,`j${v}`)} + ${E} + }`):(k.push(`${w.indicesSet("input_indices",v,g.indicesGet("output_indices",M))};`),M++);return` + + ${T.registerUniform("output_size","u32").declareVariables(w,g)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${w.type.indices}; + let output_indices = ${g.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${S[0]} // init ops for reduce max/min + ${S[1]} + ${E} + ${S[3]} + ${S.length===4?g.setByOffset("global_idx","value"):S.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...at(u,l)]})}},al=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),zt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},ws=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:al(o,t);e.compute(pi(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?hp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},mp=(e,r)=>{gs(e.inputs),ws(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},fp=(e,r)=>{gs(e.inputs),ws(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},_p=(e,r)=>{gs(e.inputs),ws(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);"])},gp=(e,r)=>{gs(e.inputs),ws(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},wp=(e,r)=>{gs(e.inputs),ws(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Mp=(e,r)=>{gs(e.inputs),ws(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},bp=(e,r)=>{gs(e.inputs),ws(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},yp=(e,r)=>{gs(e.inputs),ws(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},vp=(e,r)=>{gs(e.inputs),ws(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},xp=(e,r)=>{gs(e.inputs),ws(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;`,""])},Ms=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},Tp=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mp(e,r):sp(e,r)},Ep=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?fp(e,r):np(e,r)},Pp=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_p(e,r):op(e,r)},Cp=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gp(e,r):ip(e,r)},Sp=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wp(e,r):ap(e,r)},$p=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bp(e,r):lp(e,r)},kp=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yp(e,r):up(e,r)},Ip=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vp(e,r):cp(e,r)},Ap=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?xp(e,r):dp(e,r)},Fp=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?mp(e,r):pp(e,r)}}),ul,Op,Dp,cl,Av=je(()=>{ft(),or(),ll(),ul=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.")},Op=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(pi("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Dp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(pi("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},cl=e=>zt(e)}),Lp,hi,zp,Bp,Rp,mo,jp,Np,dl=je(()=>{ft(),yt(),el(),Tt(),Lp=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&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],u=t.dims[1],p=t.dims[2];if(o.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(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=o.dims[0]/3,d=c,_=d;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");c=r.qkvHiddenSizes[0],d=r.qkvHiddenSizes[1],_=r.qkvHiddenSizes[2]}let f=u;if(c!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==c+d+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let T=0;if(i){if(d!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==d/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(T=i.dims[3])}let k=f+T,w=-1,g=0;if(n)throw new Error("Mask not supported");if(i)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]!==u||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:T,kvSequenceLength:f,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:c,vHiddenSize:_,headSize:Math.floor(c/r.numHeads),vHeadSize:Math.floor(_/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},hi=(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; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,zp=(e,r,t,s,o,n,i,a)=>{let l=sr(i?1:n),u=64,p=n/l;p{let g=et("x",e.dataType,e.dims,l),S=[g],E=i?Pe("seq_lens",i.dataType,i.dims):void 0;E&&S.push(E);let v=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;v&&S.push(v);let M=zr(e.dataType),y=[{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; + ${w.registerUniforms(y).declareVariables(...S)} + ${w.mainStart([u,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; + ${hi(E,v,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + 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(${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(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${u}; i++) { + max_value = max(thread_max[i], max_value); + } + + 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(${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(); + + var sum: f32 = 0; + for (var i = 0u; i < ${u}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${g.type.value}(${M}(1.0) / ${M}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${f}(x[offset + i]); + x[offset + i] = ${g.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + 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] = ${g.type.value}(${M}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${_};${l}`,inputDependencies:T},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:d})}},Bp=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],c=e>1&&s,d=n.kvNumHeads?n.kvNumHeads:n.numHeads,_=c?[n.batchSize,d,u,n.headSize]:void 0,f=n.nReps?n.nReps:1,T=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=sr(n.headSize),w=n.headSize/k,g=12,S={x:Math.ceil(u/g),y:Math.ceil(n.sequenceLength/g),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:T},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:f}],v=c&&s&&Me.size(s.dims)>0,M=["type","type"];v&&M.push("type"),o&&M.push("type"),a&&M.push("type"),l&&M.push("type");let y=[{dims:p,dataType:r.dataType,gpuDataType:0}];c&&y.push({dims:_,dataType:r.dataType,gpuDataType:0});let C=F=>{let z=Pe("q",r.dataType,r.dims,k),K=Pe("key",t.dataType,t.dims,k),q=[z,K];if(v){let fe=Pe("past_key",s.dataType,s.dims,k);q.push(fe)}o&&q.push(Pe("attention_bias",o.dataType,o.dims));let R=a?Pe("seq_lens",a.dataType,a.dims):void 0;R&&q.push(R);let Z=l?Pe("total_sequence_length_input",l.dataType,l.dims):void 0;Z&&q.push(Z);let H=et("output",r.dataType,p),J=[H];c&&J.push(et("present_key",r.dataType,_,k));let Q=zr(1,k),se=[{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 = ${g}u; + + var tileQ: array<${z.type.storage}, ${g*g}>; + var tileK: array<${z.type.storage}, ${g*g}>; + ${F.registerUniforms(se).declareVariables(...q,...J)} + ${F.mainStart([g,g,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + 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; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${hi(R,Z,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${v&&c?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${c?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${Q}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${v&&c?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${c?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${Q}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){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: ${k}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${o!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:y,dispatchGroup:S,programUniforms:E}),getShaderSource:C}},Rp=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,c=e>1&&s,d=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=c?[o.batchSize,d,l,o.headSize]:void 0,f=[o.batchSize,o.sequenceLength,p],T=12,k={x:Math.ceil(o.vHeadSize/T),y:Math.ceil(o.sequenceLength/T),z:o.batchSize*o.numHeads},w=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:u}],g=c&&s&&Me.size(s.dims)>0,S=["type","type"];g&&S.push("type"),i&&S.push("type"),a&&S.push("type");let E=[{dims:f,dataType:r.dataType,gpuDataType:0}];c&&E.push({dims:_,dataType:r.dataType,gpuDataType:0});let v=M=>{let y=Pe("probs",r.dataType,r.dims),C=Pe("v",t.dataType,t.dims),F=[y,C];g&&F.push(Pe("past_value",s.dataType,s.dims));let z=i?Pe("seq_lens",i.dataType,i.dims):void 0;i&&F.push(z);let K=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;a&&F.push(K);let q=[et("output",r.dataType,f)];c&&q.push(et("present_value",r.dataType,_));let R=[{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 = ${T}u; + var tileQ: array<${y.type.value}, ${T*T}>; + var tileV: array<${y.type.value}, ${T*T}>; + ${M.registerUniforms(R).declareVariables(...F,...q)} + ${M.mainStart([T,T,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${u===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${hi(z,K,!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 + ${g&&c?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${c?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${y.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${g&&c?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${c?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:E,dispatchGroup:k,programUniforms:w}),getShaderSource:v}},mo=(e,r,t,s,o,n,i,a,l,u,p=void 0,c=void 0)=>{let d=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),_=d>1?u.pastSequenceLength:0,f=_+u.kvSequenceLength,T=l&&Me.size(l.dims)>0?l:void 0,k=[r,t];d>1&&i&&Me.size(i.dims)>0&&k.push(i),T&&k.push(T),p&&k.push(p),c&&k.push(c);let w=e.compute(Bp(d,r,t,i,T,u,_,p,c),{inputs:k,outputs:d>1?[-1,1]:[-1]})[0];e.compute(zp(w,u.batchSize,u.numHeads,_,u.sequenceLength,f,p,c),{inputs:p&&c?[w,p,c]:[w],outputs:[]});let g=[w,s];d>1&&a&&Me.size(a.dims)>0&&g.push(a),p&&g.push(p),c&&g.push(c),e.compute(Rp(d,w,s,a,u,_,p,c),{inputs:g,outputs:d>1?[0,2]:[0]})},jp=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:o},{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=c=>{let d=et("output_q",l[0].dataType,t),_=et("output_k",l[0].dataType,t),f=et("output_v",l[0].dataType,t),T=Pe("input",l[0].dataType,l[0].dims),k=Pe("weight",l[1].dataType,l[1].dims),w=Pe("bias",l[2].dataType,l[2].dims),g=T.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` + const TILE_SIZE = ${i}u; + var tileInput: array<${g}, ${i*i}>; + var tileWeightQ: array<${g}, ${i*i}>; + var tileWeightK: array<${g}, ${i*i}>; + var tileWeightV: array<${g}, ${i*i}>; + ${c.registerUniforms(S).declareVariables(T,k,w,d,_,f)} + ${c.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${g}(0); + var valueK = ${g}(0); + var valueV = ${g}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({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:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Np=(e,r)=>{let t=Lp(e.inputs,r),[s,o,n]=jp(e,t);return mo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),Vp,Up,Wp,Gp,Fv=je(()=>{ms(),ft(),yt(),or(),Tt(),Vp=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.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")},Up=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?sr(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=Me.size(n)/i,u=s,p=u?n.length:n,c=Pe("x",e[0].dataType,e[0].dims,i),d=Pe("scale",e[1].dataType,e[1].dims,a),_=Pe("bias",e[2].dataType,e[2].dims,a),f=Pe("inputMean",e[3].dataType,e[3].dims,a),T=Pe("inputVar",e[4].dataType,e[4].dims,a),k=et("y",e[0].dataType,p,i),w=()=>{let S="";if(s)S=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")S=` + ${k.indicesSet("outputIndices","0","0")} + let cOffset = ${k.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` + const epsilon = ${t}; + ${S.registerUniform("outputSize","u32").declareVariables(c,d,_,f,T,k)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${w()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${_.getByOffset("cOffset")}; + let inputMean = ${f.getByOffset("cOffset")}; + let inputVar = ${T.getByOffset("cOffset")}; + let x = ${c.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${k.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...at(n)]:[{type:12,data:l}]})}},Wp=e=>zt(e),Gp=(e,r)=>{let{inputs:t,outputCount:s}=e,o=Wp({...r,outputCount:s});if(Xt.webgpu.validateInputContent&&Vp(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Up(t,o))}}),Kp,Hp,qp,Ov=je(()=>{yt(),Tt(),Kp=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")},Hp=e=>{let r=e[0].dims,t=e[0].dims[2],s=Me.size(r)/4,o=e[0].dataType,n=Pe("input",o,r,4),i=Pe("bias",o,[t],4),a=Pe("residual",o,r,4),l=et("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` + const channels = ${t}u / 4; + ${u.declareVariables(n,i,a,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},qp=e=>{Kp(e.inputs),e.compute(Hp(e.inputs))}}),Qp,Dt,Xp,Jp,Yp,Zp,eh,th,rh,sh,nh,oh,ih,ah,lh,uh,fo,ch,mi,dh,ph,hh,mh,fh,_h,gh,wh,Mh,bh,yh,vh,xh,Th,Eh,Ph,pl,Ch,hl,ml,Sh,$h,kh,Ih,Ah,Fh,fl=je(()=>{ft(),yt(),or(),Tt(),Qp=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Pe("inputData",t,[a],4),p=et("outputData",s,[a],4),c=[{name:"vec_size",type:"u32"}];return i&&c.push(...i),` + ${e.registerUniforms(c).declareVariables(u,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Dt=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(Me.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:u=>Qp(u,Me.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Me.size(u[0].dims)/64/4)},programUniforms:l})}},Xp=e=>{e.compute(Dt(e.inputs[0],"Abs","abs"))},Jp=e=>{e.compute(Dt(e.inputs[0],"Acos","acos"))},Yp=e=>{e.compute(Dt(e.inputs[0],"Acosh","acosh"))},Zp=e=>{e.compute(Dt(e.inputs[0],"Asin","asin"))},eh=e=>{e.compute(Dt(e.inputs[0],"Asinh","asinh"))},th=e=>{e.compute(Dt(e.inputs[0],"Atan","atan"))},rh=e=>{e.compute(Dt(e.inputs[0],"Atanh","atanh"))},sh=e=>zt(e),nh=(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(Dt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},oh=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return zt({min:r,max:t})},ih=(e,r)=>{let t=r||oh(e.inputs),s=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Clip",o=>`clamp(${o}, 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]})},ah=e=>{e.compute(Dt(e.inputs[0],"Ceil","ceil"))},lh=e=>{e.compute(Dt(e.inputs[0],"Cos","cos"))},uh=e=>{e.compute(Dt(e.inputs[0],"Cosh","cosh"))},fo=e=>zt(e),ch=(e,r)=>{let t=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},mi=(e="f32")=>` +const r0: ${e} = 0.3275911; +const r1: ${e} = 0.254829592; +const r2: ${e} = -0.284496736; +const r3: ${e} = 1.421413741; +const r4: ${e} = -1.453152027; +const r5: ${e} = 1.061405429; + +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)); +}`,dh=e=>{let r=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,mi(r)))},ph=e=>{e.compute(Dt(e.inputs[0],"Exp","exp"))},hh=e=>{e.compute(Dt(e.inputs[0],"Floor","floor"))},mh=e=>{let r=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,mi(r)))},fh=(e,r)=>{let t=zr(e.inputs[0].dataType);e.compute(Dt(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))},_h=e=>{e.compute(Dt(e.inputs[0],"Not",r=>`!${r}`))},gh=e=>{e.compute(Dt(e.inputs[0],"Neg",r=>`-${r}`))},wh=e=>{e.compute(Dt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Mh=e=>{let r=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},bh=e=>{e.compute(Dt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},yh=e=>zt(e),vh=(e,r)=>{let t=zr(e.inputs[0].dataType);e.compute(Dt(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))},xh=e=>{e.compute(Dt(e.inputs[0],"Sin","sin"))},Th=e=>{e.compute(Dt(e.inputs[0],"Sinh","sinh"))},Eh=e=>{e.compute(Dt(e.inputs[0],"Sqrt","sqrt"))},Ph=e=>{e.compute(Dt(e.inputs[0],"Tan","tan"))},pl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ch=e=>{e.compute(Dt(e.inputs[0],"Tanh",pl))},hl=(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 ${pl("v")}; +} +`,ml=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Sh=e=>{let r=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"FastGelu",ml,hl(r),void 0,e.inputs[0].dataType))},$h=(e,r)=>{let t=zr(e.inputs[0].dataType);return e.compute(Dt(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},kh=e=>{e.compute(Dt(e.inputs[0],"Log","log"))},Ih=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,Ah=e=>`quick_gelu_impl(${e})`,Fh=(e,r)=>{let t=zr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"QuickGelu",Ah,Ih(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Oh,Dh,Lh,Dv=je(()=>{yt(),Tt(),fl(),Oh=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")},Dh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Pe("input",e[0].dataType,e[0].dims,4),s=Pe("bias",e[0].dataType,[e[0].dims[2]],4),o=et("output",e[0].dataType,r,4),n=Me.size(r)/4,i=Tr(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; + + ${a.declareVariables(t,s,o)} + + ${mi(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Lh=e=>{Oh(e.inputs),e.compute(Dh(e.inputs))}}),zh,Bh,bs,Rh,jh,Nh,Vh,Uh,Wh,Gh,Kh,Hh,qh,Lv=je(()=>{ft(),yt(),Tt(),zh=(e,r,t,s,o,n,i,a,l,u,p,c)=>{let d,_;typeof a=="string"?d=_=(g,S)=>`${a}((${g}),(${S}))`:typeof a=="function"?d=_=a:(d=a.scalar,_=a.vector);let f=et("outputData",p,s.length,4),T=Pe("aData",l,r.length,4),k=Pe("bData",u,t.length,4),w;if(o)if(n){let g=Me.size(r)===1,S=Me.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,v=t.length>0&&t[t.length-1]%4===0;g||S?w=f.setByOffset("global_idx",_(g?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"),S?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` + let outputIndices = ${f.offsetToIndices("global_idx * 4u")}; + let offsetA = ${T.broadcastedIndicesToOffset("outputIndices",f)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",f)}; + ${f.setByOffset("global_idx",_(i||E?T.getByOffset("offsetA / 4u"):`${T.type.value}(${T.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||v?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else w=f.setByOffset("global_idx",_(T.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let g=(S,E,v="")=>{let M=`aData[indexA${E}][componentA${E}]`,y=`bData[indexB${E}][componentB${E}]`;return` + let outputIndices${E} = ${f.offsetToIndices(`global_idx * 4u + ${E}u`)}; + let offsetA${E} = ${T.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let offsetB${E} = ${k.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let indexA${E} = offsetA${E} / 4u; + let indexB${E} = offsetB${E} / 4u; + let componentA${E} = offsetA${E} % 4u; + let componentB${E} = offsetB${E} % 4u; + ${S}[${E}] = ${v}(${d(M,y)}); + `};p===9?w=` + var data = vec4(0); + ${g("data",0,"u32")} + ${g("data",1,"u32")} + ${g("data",2,"u32")} + ${g("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` + ${g("outputData[global_idx]",0)} + ${g("outputData[global_idx]",1)} + ${g("outputData[global_idx]",2)} + ${g("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(T,k,f)} + + ${c??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w} + }`},Bh=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(T=>Number(T)??1),l=s.dims.map(T=>Number(T)??1),u=!Me.areEqual(a,l),p=a,c=Me.size(a),d=!1,_=!1,f=[u];if(u){let T=Nn.calcShape(a,l,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");p=T.slice(),c=Me.size(p);let k=Me.size(a)===1,w=Me.size(l)===1,g=a.length>0&&a[a.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;f.push(k),f.push(w),f.push(g),f.push(S);let E=1;for(let v=1;vT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>zh(T,a,l,p,d,u,_,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Me.size(p)/4)},...at(a,l,p)]})}},bs=(e,r,t,s,o,n)=>{e.compute(Bh(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},Rh=e=>{bs(e,"Add",(r,t)=>`${r}+${t}`)},jh=e=>{bs(e,"Div",(r,t)=>`${r}/${t}`)},Nh=e=>{bs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Vh=e=>{bs(e,"Mul",(r,t)=>`${r}*${t}`)},Uh=e=>{let r=Pe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;bs(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); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // 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)); + } + `)},Wh=e=>{bs(e,"Sub",(r,t)=>`${r}-${t}`)},Gh=e=>{bs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Kh=e=>{bs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Hh=e=>{bs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},qh=e=>{bs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Qh,Xh,Jh,Yh,Zh,em,zv=je(()=>{ft(),yt(),or(),Tt(),Qh=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},Xh=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,Jh=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=Me.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:o}];for(let T=0;T`uniforms.sizeInConcatAxis${T}`).join(","),f=T=>` + + ${(()=>{T.registerUniform("outputSize","u32");for(let k=0;k(${_}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Jh(i,c)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:f}},Zh=(e,r)=>{let t=e.inputs,s=t[0].dims,o=Me.normalizeAxis(r.axis,s.length);Qh(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>Me.size(a.dims)>0);e.compute(Yh(i,o,n,t[0].dataType),{inputs:i})},em=e=>zt({axis:e.axis})}),an,ln,un,_l,cn=je(()=>{ft(),yt(),an=(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}`)}},ln=(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})},un=(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"})},_l=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)||[xd,Td];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}}}),kr,tm,gl=je(()=>{kr=(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.`)}},tm=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),rm,Bv=je(()=>{rm=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)); +} +fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); +} +`}),_o,wl,Ml=je(()=>{ft(),yt(),Tt(),cn(),_o=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${st(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,st(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},wl=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],c=sr(u),d=sr(p),_=sr(l),f=Me.size(t)/c/_,T=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[Me.size(k),l,u],g=[{type:12,data:f},{type:12,data:l},{type:12,data:u},{type:12,data:p}];ln(r,g),g.push(...at(k,i,a)),T&&g.push(...at(e[2].dims)),g.push(...at(w));let S=E=>{let v=ol("batch_dims",e[0].dataType,k.length),M=Pe("a",e[0].dataType,i.length,d),y=Pe("b",e[1].dataType,a.length,c),C=et("output",e[0].dataType,w.length,c),F=Tr(C.type.tensor),z=an(r,C.type.value,F),K=[M,y],q="";if(T){let H=o?c:1;K.push(Pe("bias",e[2].dataType,e[2].dims.length,H)),q=`${o?`value += bias[col / ${H}];`:`value += ${C.type.value}(bias[row + i]);`}`}let R=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];un(r,R);let Z=()=>{let H=`var a_data: ${M.type.value};`;for(let J=0;J; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${Z()} + } + for (var i = 0u; i < ${_}u; i++) { + var value = values[i]; + ${q} + ${z} + let cur_indices = ${C.type.indices}(batch, row + i, col); + let offset = ${C.indicesToOffset("cur_indices")}; + ${C.setByOffset(`offset / ${c}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${c};${d};${_};${o}`,inputDependencies:T?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:g}),getShaderSource:S}}}),sm,nm,bl,yl,om,vl,im,fi,xl=je(()=>{ft(),yt(),Tt(),cn(),Ml(),gl(),sm=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,nm=(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]; + ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,bl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,c=o?n:l,d=p/r[0],_=n/r[1];if(!((o&&d===4&&e[1]===4||!o&&(d===3||d===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${d} 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/d}>, ${c}>; +var mm_Bsub: array, ${u/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${_}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${sm(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${nm(o,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},yl=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,om=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",vl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],c=o?u:n,d=o?n:u;if(!(d%r[1]===0&&c%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let _=d/r[1],f=c/r[0],T=n/r[1],k=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + let globalColStart = i32(workgroupId.x) * ${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 inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${r[0]}) { + ${yl(o,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${u}; + +let tileRowA = i32(localId.y) * ${_}; +let tileColA = i32(localId.x) * ${f}; +let tileRowB = i32(localId.y) * ${T}; +// 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 < ${_}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${yl(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${T}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${om(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${d}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${k} + } +`},im=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=Tr(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${kr(e,u)} { + var value = ${kr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${_o("aIndices",i,i.rank-2,n.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${kr(e,u)} { + var value = ${kr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${_o("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${kr(e,u)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${o?"bias[colIn]":`${kr(e,u)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},fi=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),c=Me.size(p),d=i[i.length-2],_=i[i.length-1],f=a[a.length-1],T=_%4===0&&f%4===0,k=d<=8?[4,1,1]:[4,4,1],w=[8,8,1],g=[Math.ceil(f/w[0]/k[0]),Math.ceil(d/w[1]/k[1]),Math.ceil(c/w[2]/k[2])],S=T?4:1,E=[...l,d,_/S],v=E.length,M=[...u,_,f/S],y=M.length,C=[c,d,f/S],F=[{type:6,data:d},{type:6,data:f},{type:6,data:_}];ln(r,F),F.push(...at(p,E,M));let z=["rank","rank"],K=e.length>2;K&&(F.push(...at(e[2].dims)),z.push("rank")),F.push(...at(C));let q=R=>{let Z=p.length,H=ol("batchDims",e[0].dataType,Z,1),J=Tr(e[0].dataType),Q=Pe("a",e[0].dataType,v,S),se=Pe("b",e[1].dataType,y,S),fe=et("result",e[0].dataType,C.length,S),ae=[Q,se];if(K){let _e=o?S:1;ae.push(Pe("bias",e[2].dataType,e[2].dims.length,_e))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];un(r,V);let A=Tr(fe.type.tensor),U=an(r,fe.type.value,A),ee=im(S,K,U,[H,Q,se,fe],o);return` + ${R.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,fe)} + ${ee} + ${T?bl(k,w,J,H):vl(k,w,J,H)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${T};${o}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:F}),getShaderSource:q}}}),am,lm,Rv=je(()=>{ft(),Bs(),Tt(),cn(),gl(),Bv(),xl(),am=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=F=>{switch(F){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${F} is not supported.`)}},c=F=>{switch(F){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 ${F} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,_=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",T=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",w=e?"col":"row",g=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${k} / outWidth; + let outCol = ${k} % outWidth; + + let WRow = ${w} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${w} / 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 = ${w} % inChannels; + var resData = ${kr(i,u)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${T}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,S=e?r&&s?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${g} + } + return ${kr(i,u)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${g} + } + return ${kr(i,u)}(0.0);`,E=e?s&&t?c(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${c(a)} + } + return ${kr(a,u)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${c(a)} + } + return ${kr(a,u)}(0.0);`,v=kr(l,u),M=kr(e?i:a,u),y=kr(e?a:i,u),C=an(n,v,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { + ${e?S:E} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${y} { + ${e?E:S} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${v}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${_} + ${tm(o)} + ${C} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},lm=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],c=t[0],d=u?t[2]:t[3],_=u?t[1]:t[2],f=u?t[3]:t[1],T=u&&(p%4===0||p%3===0)&&f%4===0,k=u?f:d*_,w=u?d*_:f,g=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil(k/g[0]/S[0]),Math.ceil(w/g[1]/S[1]),Math.ceil(c/g[2]/S[2])];It("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let v=T?u&&p%4!==0?3:4:1,M=g[1]*S[1],y=g[0]*S[0],C=Math.max(g[0]*v,g[1]),F=s%M===0,z=o%y===0,K=n%C===0,q=T?[v,4,4]:[1,1,1],R=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];ln(r,R),R.push(...at(e[0].dims,e[1].dims));let Z=["rank","rank"];i&&(R.push(...at(e[2].dims)),Z.push("rank")),R.push(...at(t));let H=J=>{let Q=[{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}];un(r,Q);let se=T?4:1,fe=Tr(e[0].dataType),ae=` + fn setOutputAtIndex(flatIndex : i32, value : ${T?`vec4<${fe}>`:fe}) { + result[flatIndex] = ${T?`vec4<${fe}>`:fe}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${T?`vec4<${fe}>`:fe}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${T?"/ 4":""}, value); + }`,V=Pe("x",e[0].dataType,e[0].dims.length,v===3?1:v),A=Pe("w",e[1].dataType,e[1].dims.length,se),U=[V,A],ee=et("result",e[0].dataType,t.length,se);if(i){let _e=Pe("bias",e[2].dataType,e[2].dims.length,se);U.push(_e),ae+=` + fn getBiasByOutputCoords(coords : vec4) -> ${T?`vec4<${fe}>`:fe} { + return bias[coords.${u?"w":"y"}${T?"/ 4":""}]; + }`}return` + ${rm("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 }; + ${J.registerUniforms(Q).declareVariables(...U,ee)} + ${ae} + ${am(u,F,z,K,i,r,q[0],q[1],q[2],fe)} + ${T?bl(S,g,fe,void 0,!u,C):vl(S,g,fe,void 0,!u,C,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${v};${T};${F};${z};${K};${M};${y};${C}`,inputDependencies:Z},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:R}),getShaderSource:H}}}),um,Tl,go,cm,El,dm,pm,hm,jv=je(()=>{ft(),Bs(),yt(),Tt(),cn(),gl(),um=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,go=(e,r)=>r<=1?e:e+(e-1)*(r-1),cm=(e,r,t,s=1)=>{let o=go(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},El=(e,r,t,s,o)=>{o==null&&(o=cm(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},dm=(e,r,t,s,o,n,i,a,l,u)=>{let p,c,d,_;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=El([r,t,s,1],[a,l,u],1,[o,n,i],e);c=f[0],d=f[1],_=f[2]}else if(Array.isArray(e)){if(!e.every((T,k,w)=>T===w[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=El([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);c=f[0],d=f[1],_=f[2]}else if(e==="SAME_UPPER"){c=Math.ceil(r/o),d=Math.ceil(t/n),_=Math.ceil(s/i);let f=(c-1)*o+a-r,T=(d-1)*n+l-t,k=(_-1)*i+u-s,w=Math.floor(f/2),g=f-w,S=Math.floor(T/2),E=T-S,v=Math.floor(k/2),M=k-v;p={top:S,bottom:E,left:v,right:M,front:w,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:c,outHeight:d,outWidth:_}},pm=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,c;if(i==="channelsLast")[a,l,u,p,c]=e;else if(i==="channelsFirst")[a,c,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,,_,f,T]=r,[k,w,g]=Tl(t),[S,E,v]=Tl(s),M=go(_,S),y=go(f,E),C=go(T,v),{padInfo:F,outDepth:z,outHeight:K,outWidth:q}=dm(o,l,u,p,k,w,g,M,y,C),R=n?d*c:d,Z=[0,0,0,0,0];return i==="channelsFirst"?Z=[a,R,z,K,q]:i==="channelsLast"&&(Z=[a,z,K,q,R]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:c,outDepth:z,outHeight:K,outWidth:q,outChannels:R,padInfo:F,strideDepth:k,strideHeight:w,strideWidth:g,filterDepth:_,filterHeight:f,filterWidth:T,effectiveFilterDepth:M,effectiveFilterHeight:y,effectiveFilterWidth:C,dilationDepth:S,dilationHeight:E,dilationWidth:v,inShape:e,outShape:Z,filterShape:r}},hm=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},u=[Math.ceil(um(l.x.map(k=>t[k]))/a[0]),1,1];It("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,c=Me.size(t),d=[{type:12,data:c},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];ln(r,d),d.push(...at(e[0].dims,e[1].dims));let _=["rank","rank"],f=e.length===3;f&&(d.push(...at(e[2].dims)),_.push("rank")),d.push(...at(t));let T=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];un(r,w);let g=1,S=Tr(e[0].dataType),E=Pe("x",e[0].dataType,e[0].dims.length,p),v=Pe("W",e[1].dataType,e[1].dims.length,g),M=[E,v],y=et("result",e[0].dataType,t.length,g),C="";if(f){let K=Pe("bias",e[2].dataType,e[2].dims.length,g);M.push(K),C+=` + fn getBiasByOutputCoords(coords : array) -> ${S} { + return bias[${i?st("coords",4,5):st("coords",1,5)}]; + }`}let F=kr(p,S),z=an(r,F,S);return` + ${C} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${E.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${v.getByIndices("aIndices")}; + } + ${k.registerUniforms(w).declareVariables(...M,y)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${y.offsetToIndices("global_idx")}; + let batch = ${st("coords",0,E.rank)}; + let d2 = ${i?st("coords",E.rank-1,E.rank):st("coords",1,E.rank)}; + let xFRCCorner = vec3(${i?st("coords",1,E.rank):st("coords",2,E.rank)}, + ${i?st("coords",2,E.rank):st("coords",3,E.rank)}, + ${i?st("coords",3,E.rank):st("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?st("uniforms.x_shape",1,E.rank):st("uniforms.x_shape",2,E.rank)}; + let xShapeZ = ${i?st("uniforms.x_shape",2,E.rank):st("uniforms.x_shape",3,E.rank)}; + let xShapeW = ${i?st("uniforms.x_shape",3,E.rank):st("uniforms.x_shape",4,E.rank)}; + let xShapeU = ${i?st("uniforms.x_shape",4,E.rank):st("uniforms.x_shape",1,E.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${f?"value = value + getBiasByOutputCoords(coords)":""}; + ${z} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:d}),getShaderSource:T}}}),mm,fm,Nv=je(()=>{ft(),yt(),Tt(),cn(),mm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,c=l&&p>=4?sr(u):1,d=Me.size(t)/c,_=[{type:12,data:d},{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}];ln(r,_),_.push(...at(i,[a[0],a[1],a[2],a[3]/c]));let f=o?["rank","rank","rank"]:["rank","rank"];_.push(...at([t[0],t[1],t[2],t[3]/c]));let T=k=>{let w=et("output",e[0].dataType,t.length,c),g=Tr(w.type.tensor),S=an(r,w.type.value,g),E=Pe("x",e[0].dataType,i.length),v=Pe("w",e[1].dataType,a.length,c),M=[E,v];o&&M.push(Pe("b",e[2].dataType,e[2].dims,c));let y=[{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"}];un(r,y);let C=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${v.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${v.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(y).declareVariables(...M,w)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${w.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 * ${c} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${w.type.value} = ${w.type.value}(0); + ${C} + ${n} + ${S} + ${w.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${c}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:T}},fm=(e,r,t,s)=>{let o=e.length>2,n=sr(t[3]),i=sr(t[2]),a=Me.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],u=[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],c=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];ln(r,c),c.push(...at(l,u,p));let d=(i-1)*r.strides[1]+u[1],_=f=>{let T=et("output",e[0].dataType,p.length,n),k=Tr(T.type.tensor),w=an(r,T.type.value,k),g=Pe("x",e[0].dataType,l.length,n),S=Pe("w",e[1].dataType,u.length,n),E=[g,S];o&&E.push(Pe("b",e[2].dataType,e[2].dims,n));let v=o?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return un(r,M),` + ${f.registerUniforms(M).declareVariables(...E,T)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${g.type.value}, ${d}>; + var values: array<${T.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${d}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${g.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${g.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${S.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${v} + ${w} + ${T.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${d};${u[0]};${u[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:_}}}),_m,_i,gm,gi,Pl,Cl,wm,Mm,Sl,Vv=je(()=>{yt(),Rv(),jv(),xl(),Nv(),cn(),Ml(),Ws(),_m=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((d,_)=>d+(d-1)*(t[_]-1)),c=a.map((d,_)=>d+s[_]+s[_+l]).map((d,_)=>Math.floor((d-p[_]+o[_])/o[_]));return c.splice(0,0,i),c.splice(n?3:1,0,u),c},_i=[2,3,1,0],gm=(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 o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},gi=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=_l(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},Cl=(e,r,t,s)=>{let o=t.format==="NHWC",n=_m(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let M=[r[0]];if(o){let y=e.kernelCustomData.wT??e.compute(qr(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=y),M.push(y)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(fm(M,t,n,s),{inputs:M}):e.compute(mm(M,t,n,s),{inputs:M});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],c=r[1].dims[3],d=n[o?1:2],_=n[o?2:3],f=n[o?3:1],T=o&&p===a&&c===l&&t.pads[0]===0&&t.pads[1]===0;if(T||p===1&&c===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],y,C,F,z=[];if(o){let R=e.kernelCustomData.wT??e.compute(qr(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=R),T){let Z=a*l*u;y=r[0].reshape([1,M,Z]),C=R.reshape([1,Z,f]),F=[1,M,f]}else y=r[0].reshape([M,a*l,u]),C=R.reshape([1,u,f]),F=[M,d*_,f];z.push(y),z.push(C)}else y=r[0].reshape([M,u,a*l]),C=r[1].reshape([1,f,u]),F=[M,f,d*_],z.push(C),z.push(y);i&&z.push(r[2]);let K=F[2],q=z[0].dims[z[0].dims.length-1];K<8&&q<8?e.compute(wl(z,t,n,F,o,s),{inputs:z}):e.compute(fi(z,t,n,F,o,s),{inputs:z});return}let k=!0,w=e.kernelCustomData.wT??e.compute(qr(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let g=[r[0],w];i&&g.push(r[2]);let S=o?d*_:f,E=o?f:d*_,v=p*c*u;e.compute(lm(g,t,n,S,E,v,i,k,s),{inputs:g})},wm=(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 o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=gi({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);Cl(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},Mm=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=gi(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=pm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(hm(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Sl=(e,r)=>{if(gm(e.inputs,r),e.inputs[0].dims.length===3)wm(e,r);else if(e.inputs[0].dims.length===5)Mm(e,e.inputs,r);else{let t=gi(r,e.inputs);Cl(e,e.inputs,t)}}}),bm,Uv=je(()=>{ft(),Bs(),yt(),Tt(),bm=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,u=a[3],p=n?sr(l):1,c=n&&u===1&&l>=4,d=c?Math.floor(l/4)*4:Math.floor(l/p)*p,_=l-d,f=n?sr(u):1,T=n?u===1?p:f:1,k=Me.size(o)/f,w=[Math.ceil(k/64),1,1];It("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let g=["rank","rank"],S=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],v=[r.dilations[0],r.dilations[1]],M=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],y=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],C=[{type:12,data:k},{type:12,data:S},{type:12,data:E},{type:12,data:v},{type:12,data:M},{type:6,data:y},{type:12,data:d},{type:12,data:l},{type:12,data:u},...at(e[0].dims,e[1].dims)];s&&(C.push(...at(e[2].dims)),g.push("rank")),C.push(...at(o));let F=z=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:S.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:M.length},{name:"pads",type:"i32",length:y.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=Tr(e[0].dataType),R=n?1:2,Z=n?2:3,H=n?3:1,J=Pe("W",e[1].dataType,e[1].dims.length,T),Q=Pe("Dy",e[0].dataType,e[0].dims.length,p),se=[Q,J];s&&se.push(Pe("bias",e[2].dataType,[o[H]].length,f));let fe=et("result",e[0].dataType,o.length,f),ae=()=>{let U="";if(c)p===4?U+=` + let xValue = ${Q.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?U+=` + dotProd = dotProd + dot(vec4<${q}>(${Q.getByOffset("x_offset")}, ${Q.getByOffset("x_offset + 1u")}), vec4<${q}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(U+=` + dotProd = dotProd + dot(vec4<${q}>(${Q.getByOffset("x_offset")}, ${Q.getByOffset("x_offset + 1u")}, ${Q.getByOffset("x_offset + 2u")}, ${Q.getByOffset("x_offset + 3u")}), vec4<${q}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")}, ${J.getByOffset("w_offset + 2u")}, ${J.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(U+=` + let xValue = ${n?Q.getByOffset(`${Q.indicesToOffset(`${Q.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Q.get("batch","inputChannel","idyR","idyC")}; + `,p===1)U+=` + let w_offset = ${J.indicesToOffset(`${J.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${J.getByOffset(`w_offset / ${T}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let ee=0;ee{if(_===0)return"";if(!c)throw new Error(`packInputAs4 ${c} is not true.`);let U="";if(p===1){U+="dotProd = dotProd";for(let ee=0;ee<_;ee++)U+=` + + ${Q.getByOffset(`x_offset + ${ee}`)} * ${J.getByOffset(`w_offset + ${ee}`)}`;U+=";"}else if(p===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);U+=` + let xValue = ${Q.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue);`}return U},A=` + let outputIndices = ${fe.offsetToIndices(`global_idx * ${f}`)}; + let batch = ${fe.indicesGet("outputIndices",0)}; + let d1 = ${fe.indicesGet("outputIndices",H)}; + let r = ${fe.indicesGet("outputIndices",R)}; + let c = ${fe.indicesGet("outputIndices",Z)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${fe.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${q}(dyRCorner) + ${q}(wR)) / ${q}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${q}(uniforms.Dy_shape[${R}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${q}(dyCCorner) + ${q}(wC)) / ${q}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${q}(uniforms.Dy_shape[${Z}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${c?` + var x_offset = ${Q.indicesToOffset(`${Q.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${J.indicesToOffset(`${J.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${T}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${c?4:p}) { + ${ae()} + inputChannel = inputChannel + ${c?4:p}; + } + ${V()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${f}]`:""}; + ${fe.setByOffset("global_idx","value")}; + `;return` + ${z.registerUniforms(K).declareVariables(...se,fe)} + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${A}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${T}${f}${c}${_}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:C}),getShaderSource:F}}}),ym,vm,xm,$l,Tm,Em,kl,Pm,Cm,Wv=je(()=>{Uv(),cn(),Ws(),ym=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,vm=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},xm=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,c=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((c,d)=>c*d,1)===0){t.length=0;for(let c=2;cc+d,0)===0){let c=r[0].dims.length-2;l=new Array(c).fill(1)}let u=e.strides.slice();if(u.reduce((c,d)=>c+d,0)===0){let c=r[0].dims.length-2;u=new Array(c).fill(1)}xm(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},Tm=e=>{let r=_l(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,c=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:c,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},Em=(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 o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+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((i,a)=>i+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")},kl=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(qr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(bm(n,t,s),{inputs:n})},Pm=(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 o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let u=$l({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);kl(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Cm=(e,r)=>{if(Em(e.inputs,r),e.inputs[0].dims.length===3)Pm(e,r);else{let t=$l(r,e.inputs);kl(e,e.inputs,t)}}}),Sm,$m,km,Gv=je(()=>{ft(),yt(),or(),Tt(),Sm=(e,r,t,s)=>{let o=Me.size(r),n=r.length,i=Pe("input",e,n),a=et("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Me.normalizeAxis(l,n),p=c=>{let d=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,_=st("uniforms.input_shape","uniforms.axis",n),f=s.reverse?d+(s.exclusive?" + 1":""):"0",T=s.reverse?_:d+(s.exclusive?"":" + 1");return` + ${c.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${f}; + let last : i32 = ${T}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.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(o/64)},programUniforms:[{type:12,data:o},{type:12,data:u},...at(r,r)]}),getShaderSource:p}},$m=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(Sm(s,t,o,r),{inputs:[0]})},km=e=>{let r=e.exclusive===1,t=e.reverse===1;return zt({exclusive:r,reverse:t})}}),Im,Am,Fm,Om,Dm,Kv=je(()=>{ft(),yt(),or(),Tt(),Im=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.")},Am=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let c=e.reshape(i),d=c.dims.length,_=e.dataType,f=Pe("a",_,d),T=et("output",_,d),k=w=>` + ${w.registerUniform("output_size","u32").declareVariables(f,T)} + + ${Am(a,d,f,T)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${T.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${T.setByOffset("global_idx",f.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let g=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],S=Me.size(g),E=c.dims,v=Me.sortBasedOnPerm(E,a);return{outputs:[{dims:g,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...at(E,v)]}},getShaderSource:k}},Om=(e,r)=>{Im(e.inputs),e.compute(Fm(e.inputs[0],r))},Dm=e=>zt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),wi,wo,Il,Lm,zm,Bm,Rm,Al,jm,Nm,Vm,Hv=je(()=>{ft(),yt(),or(),Tt(),wi="[a-zA-Z]|\\.\\.\\.",wo="("+wi+")+",Il="^"+wo+"$",Lm="("+wo+",)*"+wo,zm="^"+Lm+"$",Bm=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)}},Rm=class{constructor(e,r){var o;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(zm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(Il)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(wo)))throw new Error("Invalid RHS");(o=s.match(RegExp(wi,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.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 o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(Il))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(wi,"g")),u=new Bm(s);return l==null||l.forEach((p,c)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let d=o-l.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+d),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let _=0;_e+"_max",jm=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Pe(`input${p}`,r,u)),n=Me.size(s),i=et("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],c="var prod = 1.0;",d="var sum = 0.0;",_="sum += prod;",f=[],T=[],k=[],w=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,v)=>{var M;if(t.rhs.symbolToIndices.has(v)){let y=(M=t.rhs.symbolToIndices.get(v))==null?void 0:M[0];y!==void 0&&t.lhs.forEach((C,F)=>{if(E.inputIndices.includes(F)){let z=C.symbolToIndices.get(v);if(z===void 0)throw new Error("Invalid symbol error");z.forEach(K=>{p.push(`${o[F].indicesSet(`input${F}Indices`,K,i.indicesGet("outputIndices",y))}`)})}})}else t.lhs.forEach((y,C)=>{if(E.inputIndices.includes(C)){let F=y.symbolToIndices.get(v);if(F===void 0)throw new Error("Invalid symbol error");F.forEach(z=>{f.push(`${o[C].indicesSet(`input${C}Indices`,z,`${v}`)}`)}),w.push(`prod *= ${o[C].getByIndices(`input${C}Indices`)};`)}}),T.push(`for(var ${v}: u32 = 0; ${v} < uniforms.${Al(v)}; ${v}++) {`),k.push("}")});let S=g?[...p,`let sum = ${o.map((E,v)=>E.getByIndices(`input${v}Indices`)).join(" * ")};`]:[...p,d,...T,...f,c,...w,_,...k];return` + ${u.registerUniforms(a.map(E=>({name:`${Al(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((E,v)=>`var input${v}Indices: ${o[v].type.indices};`).join(` +`)} + ${S.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(c=>t.symbolToInfo.has(c)).map(c=>{var d;return{type:12,data:((d=t.symbolToInfo.get(c))==null?void 0:d.dimValue)||0}});u.push({type:12,data:n});let p=e.map((c,d)=>[...at(c)]).reduce((c,d)=>c.concat(d),u);return p.push(...at(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Nm=(e,r)=>{let t=new Rm(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(jm(o,e.inputs[0].dataType,t,s))},Vm=e=>{let r=e.equation.replace(/\s+/g,"");return zt({equation:r})}}),Um,Fl,Wm,Gm,Km,qv=je(()=>{ft(),yt(),Tt(),Um=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 o=0;oe.length>r.length?Fl(e,r):Fl(r,e),Gm=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Wm(r,t),o=e[0].dataType,n=o===9||Me.size(r)===1,i=o===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(Me.size(s)/a),u=c=>{let d=Pe("input",o,r.length,i),_=et("output",o,s.length,a),f;if(o===9){let T=(k,w,g="")=>` + let outputIndices${w} = ${_.offsetToIndices(`outputOffset + ${w}u`)}; + let offset${w} = ${d.broadcastedIndicesToOffset(`outputIndices${w}`,_)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${k}[${w}] = ${g}(${d.getByOffset(`index${w}`)}[component${w}]); + `;f=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${T("data",0,"u32")} + ${T("data",1,"u32")} + ${T("data",2,"u32")} + ${T("data",3,"u32")} + ${_.setByOffset("global_idx","data")} + }`}else f=` + let outputIndices = ${_.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",_)}; + let data = ${_.type.value}(${d.getByOffset(`inputOffset / ${i}`)}); + ${_.setByOffset("global_idx","data")} + }`;return` + ${c.registerUniform("vec_size","u32").declareVariables(d,_)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${f}`},p=[{type:12,data:l},...at(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Km=e=>{Um(e.inputs),e.compute(Gm(e.inputs),{inputs:[0]})}}),Hm,qm,Qv=je(()=>{ft(),yt(),Tt(),fl(),Hm=e=>{let r=e[0].dataType,t=Me.size(e[0].dims),s=Me.size(e[1].dims),o=s%4===0,n=i=>{let a=Pe("x",r,[1],4),l=Pe("bias",r,[1],4),u=et("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],c=_=>` + let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size; + let bias${_} = ${l.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,d=o?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${c(0)}${c(1)}${c(2)}${c(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,u)} + + ${hl(zr(r))} + + ${i.mainStart(Vn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${u.setByOffset("global_idx",ml("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Vn/4)}})}},qm=e=>{e.inputs.length<2||Me.size(e.inputs[1].dims)===0?Sh(e):e.compute(Hm(e.inputs))}}),Qm,Xm,Jm,Ym,Xv=je(()=>{ft(),yt(),or(),Tt(),Qm=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Xm=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(Me.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...at(e[0].dims,e[1].dims,i)],c=d=>{let _=Pe("data",e[0].dataType,e[0].dims.length,l),f=Pe("inputIndices",e[1].dataType,e[1].dims.length),T=et("output",e[0].dataType,i.length,l),k=g=>{let S=s.length,E=`var indicesIndices${g} = ${f.type.indices}(0);`;for(let v=0;v1?`indicesIndices${g}[${v}]`:`indicesIndices${g}`} = ${i.length>1?`outputIndices${g}[uniforms.axis + ${v}]`:`outputIndices${g}`};`;E+=` + var idx${g} = ${f.getByIndices(`indicesIndices${g}`)}; + if (idx${g} < 0) { + idx${g} = idx${g} + uniforms.axisDimLimit; + } + var dataIndices${g} : ${_.type.indices}; + `;for(let v=0,M=0;v1?`dataIndices${g}[${v}]`:`dataIndices${g}`} = u32(idx${g});`,M+=S):(E+=`${o>1?`dataIndices${g}[${v}]`:`dataIndices${g}`} = ${i.length>1?`outputIndices${g}[${M}]`:`outputIndices${g}`};`,M++);return E},w;if(e[0].dataType===9){let g=(S,E,v="")=>` + let outputIndices${E} = ${T.offsetToIndices(`outputOffset + ${E}u`)}; + ${k(E)}; + let offset${E} = ${_.indicesToOffset(`dataIndices${E}`)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${S}[${E}] = ${v}(${_.getByOffset(`index${E}`)}[component${E}]); + `;w=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${g("value",0,"u32")} + ${g("value",1,"u32")} + ${g("value",2,"u32")} + ${g("value",3,"u32")} + ${T.setByOffset("global_idx","value")} + `}else w=` + let outputIndices = ${T.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${_.getByIndices("dataIndices")}; + ${T.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,f,T)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${w} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:c}},Jm=e=>zt({axis:e.axis}),Ym=(e,r)=>{let t=e.inputs;Qm(t),e.compute(Xm(e.inputs,r))}}),Zm,ef,tf,Jv=je(()=>{ft(),yt(),Tt(),Zm=(e,r,t,s,o,n,i,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...at(r.dims,p));let c=d=>{let _=Pe("indices_data",r.dataType,r.dims.length),f=et("input_slice_offsets_data",12,1,1),T=[_,f],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.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` + ${d.registerUniforms(k).declareVariables(...T)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:c},{inputs:[r],outputs:[-1]})[0]},ef=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=Me.sizeToDimension(n,n.length-1),l=Me.sizeFromDimension(s,r.batchDims+i),u=Me.sizeToDimension(s,r.batchDims),p=Me.sizeFromDimension(s,r.batchDims),c=a/u,d=new Array(i),_=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=n.slice(0,-1).concat(s.slice(T)),w=Me.size(k),g=[{type:12,data:w},{type:12,data:l},...at(t[0].dims,f.dims,k)],S=E=>{let v=Pe("data",t[0].dataType,t[0].dims.length),M=Pe("slice_offsets",12,f.dims.length),y=et("output",t[0].dataType,k.length);return` + ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(v,M,y)} + ${E.mainStart()} + ${E.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:k,dataType:o}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:g}),getShaderSource:S},{inputs:[t[0],f]})},tf=e=>({batchDims:e.batch_dims,cacheKey:""})}),rf,sf,nf,of,Yv=je(()=>{ft(),yt(),or(),Tt(),rf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Me.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.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(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.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,o=t.length,n=Me.normalizeAxis(r.gatherAxis,o),i=Me.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=Me.size(a),u=e[2].dataType,p=e[0].dataType===22,c=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...at(...e.map((_,f)=>_.dims),a)],d=_=>{let f=Pe("data",e[0].dataType,e[0].dims.length),T=Pe("inputIndices",e[1].dataType,e[1].dims.length),k=Pe("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Pe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=et("output",u,a.length),S=[f,T,k];w&&S.push(w);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${_.registerUniforms(E).declareVariables(...S,g)} + ${_.mainStart()} + let output_indices = ${g.offsetToIndices("global_idx")}; + var indices_indices = ${T.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${g.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${T.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${f.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${g.indicesGet("output_indices","i")}; + ${f.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${T.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${g.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${f.indicesSet("data_indices","i","index")}; + } + 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 = ${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]; + var scale_indices = data_indices; + let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${k.getByIndices("scale_indices")}; + ${w?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${w.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 = ${zr(u)}(quantized_data - zero_point) * scale; + ${g.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((_,f)=>f!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,f)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:d}},nf=(e,r)=>{let t=e.inputs;rf(t,r),e.compute(sf(e.inputs,r))},of=e=>zt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),af,lf,uf,cf,Zv=je(()=>{ft(),yt(),or(),Tt(),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,o=t.length,n=e[1].dims,i=e[1].dataType,a=Me.normalizeAxis(r.axis,o),l=t[a],u=n.slice(0),p=Me.size(u),c=Pe("input",s,o),d=Pe("indicesInput",i,n.length),_=et("output",s,u.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return f.push(...at(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:T=>` + ${T.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,d,_)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${_.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${c.type.indices}(outputIndices); + ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${c.getByIndices("inputIndices")}; + + ${_.setByOffset("global_idx","value")}; + }`}},uf=e=>zt({axis:e.axis}),cf=(e,r)=>{let t=e.inputs;af(t),e.compute(lf(e.inputs,r))}}),df,pf,hf,mf,ex=je(()=>{ft(),yt(),Tt(),df=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(),[o,n,i]=vd.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(n/l),p=Math.ceil(o/l),c=!0,d=Me.size(a),_=[{type:12,data:c?u:d},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(_.push(...at(e[2].dims)),f.push("rank")),_.push(...at(a));let T=w=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",E=Pe("a",e[0].dataType,e[0].dims),v=Pe("b",e[1].dataType,e[1].dims),M=E.type.value,y=null,C=[E,v];e.length===3&&(y=Pe("c",e[2].dataType,e[2].dims.length),C.push(y));let F=et("output",e[0].dataType,a.length);C.push(F);let z=[{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` + ${w.registerUniforms(z).declareVariables(...C)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${M}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${g} + } + + ${S} + ${y!=null?`let cOffset = ${y.broadcastedIndicesToOffset("vec2(m, n)",F)}; value += ${M}(uniforms.beta) * ${y.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=w=>{let g=Pe("a",e[0].dataType,e[0].dims),S=Pe("b",e[1].dataType,e[1].dims),E=null,v=[g,S];e.length===3&&(E=Pe("c",e[2].dataType,e[2].dims.length),v.push(E));let M=et("output",e[0].dataType,a.length);v.push(M);let y=[{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"}],C="",F="";r.transA&&r.transB?(F=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + 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); + } + `,C="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(F=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + 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); + } + `,C="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(F=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + 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); + } + `,C="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(F=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + 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); + } + `,C="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let z=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${w.registerUniforms(y).declareVariables(...v)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${w.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; + var k_start = 0u; + var value = ${M.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${F} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${C} + } + workgroupBarrier(); + } + + ${z} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",M)}; value += ${M.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return c?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:_}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:T}},hf=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},mf=(e,r)=>{df(e.inputs),e.compute(pf(e.inputs,r))}}),Ss,Rs,dn,pn,ff,_f,gf,wf,Mf,bf,yf,vf,xf,Tf,tx=je(()=>{ft(),yt(),or(),Tt(),[Ss,Rs,dn,pn]=[0,1,2,3],ff=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=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,gf=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,wf=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,Mf=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,bf=(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); + indices[${Ss}] = batch; + indices[${Rs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${dn}] = u32(r); + indices[${pn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${dn}] = u32(clamp(r, 0, H - 1)); + indices[${pn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${dn}] = gs_reflect(r, border[1], border[3]); + indices[${pn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,yf=(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[${Ss}], indices[${Rs}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + } + } + + 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")}`,vf=(e,r)=>{let t=Pe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Pe("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]],[Ss,Rs,dn,pn]=[0,3,1,2]);let i=et("output",e[0].dataType,n.length),a=t.type.value,l=Me.size(n),u=[{type:12,data:l},...at(e[0].dims,s,n)],p=c=>` + ${c.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${_f} + ${gf(a)} + ${wf(r)} + ${Mf(r)} + ${bf(t,a,r)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${dn}]); + let W_in = i32(uniforms.x_shape[${pn}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Ss}], indices[${dn}], indices[${pn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${yf(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:c=>{let d=Me.size(n);return{outputs:[{dims:n,dataType:c[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:u}},getShaderSource:p}},xf=(e,r)=>{ff(e.inputs),e.compute(vf(e.inputs,r))},Tf=e=>zt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Nr,Ef,Pf,Ol,Cf,Mo,Sf,$f=je(()=>{ft(),yt(),or(),el(),dl(),Tt(),Ws(),Nr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Ef=(e,r)=>{let t=e[0],s=Nr(e,1),o=Nr(e,2),n=Nr(e,3),i=Nr(e,4),a=Nr(e,5),l=Nr(e,6),u=Nr(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],c=t.dims[1],d=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],_=c,f=0,T=0,k=Math.floor(d/r.numHeads);if(l&&u&&Me.size(l.dims)&&Me.size(u.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]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],T=l.dims[2]}else if(l&&Me.size(l.dims)||u&&Me.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&Me.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)');w=2,_=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,_=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,_=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');w=3}if(n&&Me.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 g=f+_,S=0;if(i&&Me.size(i.dims)>0){S=8;let y=i.dims;throw y.length===1?y[0]===p?S=1:y[0]===3*p+2&&(S=3):y.length===2&&y[0]===p&&y[1]===g&&(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 E=!1,v=d;if(o&&Me.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');v=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');v=o.dims[1]*o.dims[3],E=!0}}let M=!1;if(i&&Me.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&Me.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]!==c||a.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:c,pastSequenceLength:f,kvSequenceLength:_,totalSequenceLength:g,maxSequenceLength:T,inputHiddenSize:0,hiddenSize:d,vHiddenSize:v,headSize:k,vHeadSize:Math.floor(v/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:M,passPastInKv:E,qkvFormat:w}},Pf=e=>zt({...e}),Ol=zt({perm:[0,2,1,3]}),Cf=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=Me.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=c=>{let d=et("qkv_with_bias",r.dataType,a),_=Pe("qkv",r.dataType,a),f=Pe("bias",t.dataType,a),T=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${c.registerUniforms(T).declareVariables(_,f,d)} + ${c.mainStart()} + ${c.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:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Mo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&Me.size(i.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,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(qr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(qr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]},Sf=(e,r)=>{let t=Ef(e.inputs,r),s=e.inputs[0],o=Nr(e.inputs,1),n=Nr(e.inputs,2),i=Nr(e.inputs,3),a=Nr(e.inputs,4),l=Nr(e.inputs,5),u=Nr(e.inputs,6),p=Nr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let c=o&&n&&o.dims.length===4&&n.dims.length===4,d=Mo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(c)return mo(e,d,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let _=Mo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),f=Mo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);mo(e,d,_,f,a,void 0,u,p,l,t)}}),kf,If,Af,Ff,Dl,Of,Df,Lf=je(()=>{ft(),yt(),or(),Tt(),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(o=>t.push(Number(o))),s=t.length),zt({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 < ${st("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Ff=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Me.size(t),o=e[0].dataType,n=Me.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Pe("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],c=0,d=[{type:12,data:s}];for(let f=0;f` + ${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${Af(l.length)} + ${Ff(i)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${st("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d})}},Of=(e,r)=>{kf(e.inputs);let t=e.inputs.length===1?r:If(e.inputs,r);e.compute(Dl(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 zt({axis:r,numOutputs:s,splitSizes:t})}}),zf,Mi,Bf,Rf=je(()=>{ft(),yt(),or(),Tt(),zf=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,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(!Me.areEqual(s.dims,[])&&!Me.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(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Me.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],p=o.dims[0],c=Me.sizeFromDimension(t.dims,1)/u,d=a===0?o.dims[1]*2:c/i;if(a>d)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(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(d/2!==o.dims[1]&&a/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Mi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=Me.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],c=o===0?p*2:u/s,d=new Array(i,l,u/c,c-p),_=Me.computeStrides(d),f=[{type:1,data:n},{type:12,data:d},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[a,u,c,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,c,l*c,1]}):[],...at(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],T=k=>{let w=Pe("input",e[0].dataType,e[0].dims.length),g=Pe("position_ids",e[1].dataType,e[1].dims.length),S=Pe("cos_cache",e[2].dataType,e[2].dims.length),E=Pe("sin_cache",e[3].dataType,e[3].dims.length),v=et("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),` + ${k.declareVariables(w,g,S,E,v)} + + ${k.mainStart(Vn)} + let half_rotary_emb_dim = uniforms.${S.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${g.broadcastedIndicesToOffset("bsnh.xy",et("",g.type.tensor,2))}; + let position_id = + u32(${g.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 = ${w.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - + ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; + ${v.setByOffset("i","re")} + let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + + ${w.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; + ${v.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${v.setByOffset("k",w.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:zt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:T,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(d)/Vn)},programUniforms:f})}},Bf=(e,r)=>{zf(e.inputs,r),e.compute(Mi(e.inputs,r))}}),jf,Nf,Ll,Vf,Uf,rx=je(()=>{or(),ft(),dl(),$f(),Lf(),Ws(),Rf(),Tt(),jf=(e,r)=>{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],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");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],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],c=u,d=0,_=!s||s.dims.length===0,f=Math.floor(_?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);_&&(p=f*r.numHeads);let T=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(T&&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(T&&k){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=n.dims[2]}else if(T||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=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"');c=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');c=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');c=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');w=3}let g=0,S=!1,E=r.kvNumHeads?f*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(c!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(c!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],S=!0}}let v=e.length>4?e[5]:void 0;if(v&&v.dims.length!==1&&v.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:u,pastSequenceLength:d,kvSequenceLength:c,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:f,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:w}},Nf=zt({perm:[0,2,1,3]}),Ll=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(qr(s,Nf.perm),{inputs:[s],outputs:[-1]})[0]),s},Vf=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],u=p=>{let c=Pe("seq_lens",t.dataType,t.dims),d=Pe("total_seq_lens",s.dataType,s.dims),_=et("pos_ids",o,i),f=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(f).declareVariables(c,d,_)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${d.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${c.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${_.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:u}},Uf=(e,r)=>{var E;let t=jf(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=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,i=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,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,c=zt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[d,_,f]=!o&&!n?e.compute(Dl([s],c),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],T,k;if(r.doRotary){let v=e.compute(Vf(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],M=e.inputs[7],y=e.inputs[8],C=zt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),F=[d,v,M,y],z=[-1];T=e.compute(Mi(F,C),{inputs:F,outputs:z})[0],F.splice(0,1,_);let K=zt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(Mi(F,K),{inputs:F,outputs:z})[0]}let w=Mo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?T:d,void 0,0),g=Ll(e,r.doRotary?k:_,t),S=Ll(e,f,t);mo(e,w,g,S,void 0,void 0,i,a,void 0,t,l,u)}}),zl,Wf,Gf,Kf,sx=je(()=>{ft(),yt(),Ws(),Tt(),zl=(e,r,t,s,o,n,i,a)=>{let l=sr(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,c=o*i,d=64;c===1&&(d=256);let _=[o,i,n/l],f=[o,i,2],T=["rank","type","type"],k=[];k.push(...at(_,f));let w=g=>{let S=Pe("x",r.dataType,3,l),E=Pe("scale",t.dataType,t.dims),v=Pe("bias",s.dataType,s.dims),M=et("output",1,3,2),y=[S,E,v,M];return` + var workgroup_shared : array<${p}, ${d}>; + const workgroup_size = ${d}u; + ${g.declareVariables(...y)} + ${g.mainStart(d)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${u}(0); + var squared_sum = ${u}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${u}(${S.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Us("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Us("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + 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};${d}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:c},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},Wf=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=Me.sizeFromDimension(s,n),u=sr(l),p=Me.size(o)/u,c=zl(e,r[0],r[1],r[2],i,l,a,t.epsilon),d=[i,a,l/u],_=[i,a],f=["type","none"],T=k=>{let w=Pe("x",r[0].dataType,d.length,u),g=Pe("scale_shift",1,_.length,2),S=et("output",r[0].dataType,d.length,u),E=[w,g,S];return` + ${k.registerUniform("output_size","u32").declareVariables(...E)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${S.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${g.getByIndices("vec2(batch, channel)")}; + let value = ${w.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:`${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...at(d,_,d)]}),getShaderSource:T},{inputs:[r[0],c]})},Gf=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=Me.sizeFromDimension(s,1)/i,l=sr(i),u=Me.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],c=["type","type"],d=!1,_=[0,s.length-1];for(let w=0;ws[_[g]])),T=zl(e,f,r[1],r[2],n,a,i,t.epsilon),k=w=>{let g=Tr(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,E=y=>{let C=y===0?"x":"y",F=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${F}(scale.${C}))`;case 2:return`vec2<${g}>(${F}(scale[0].${C}, scale[1].${C}))`;case 4:return`vec4<${g}>(${F}(scale[0].${C}, scale[1].${C}, scale[2].${C}, scale[3].${C}))`;default:throw new Error(`Not supported compoents ${l}`)}},v=Pe("input",r[0].dataType,r[0].dims,l),M=et("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${v.type.storage}>; + @group(0) @binding(1) var scale_input : array<${S}>; + @group(0) @binding(2) var output : array<${M.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${w.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], ${E(0)}, ${E(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],T]})},Kf=(e,r)=>{r.format==="NHWC"?Gf(e,e.inputs,r):Wf(e,e.inputs,r)}}),Hf,qf,Qf,nx=je(()=>{ft(),yt(),Tt(),Hf=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},qf=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=Me.normalizeAxis(r.axis,o.length),u=Me.sizeToDimension(o,l),p=Me.sizeFromDimension(o,l),c=Me.size(n.dims),d=i?Me.size(i.dims):0;if(c!==p||i&&d!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${c} and bias size of ${d}`);let _=[];for(let v=0;v1,g=t>2,S=v=>{let M=Tr(e[0].dataType),y=[Pe("x",e[0].dataType,e[0].dims,f),Pe("scale",n.dataType,n.dims,f)];i&&y.push(Pe("bias",i.dataType,i.dims,f)),y.push(et("output",e[0].dataType,a,f)),w&&y.push(et("mean_data_output",1,_)),g&&y.push(et("inv_std_output",1,_));let C=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${v.registerUniforms(C).declareVariables(...y)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${nl("f32",f)}; + var mean_square_vector = ${nl("f32",f)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Un(M,f,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Us("mean_vector",f)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Us("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,f,"x[j + offset]")}; + let f32scale = ${Un(M,f,"scale[j]")}; + output[j + offset] = ${y[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Un(M,f,"bias[j]")}`:""} + ); + } + + ${w?"mean_data_output[global_idx] = mean":""}; + ${g?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:_,dataType:1}),g&&E.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:T},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:k}),getShaderSource:S}},Qf=(e,r)=>{Hf(e.inputs),e.compute(qf(e.inputs,r,e.outputCount))}}),Xf,Jf,ox=je(()=>{yt(),Ml(),xl(),Xf=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.")},Jf=e=>{Xf(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(wl(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=Me.size(e.inputs[0].dims.slice(0,-2)),i=Me.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),u=[1,n,t],p=[a,l];e.compute(fi(p,{activation:""},r,u),{inputs:p})}else e.compute(fi(e.inputs,{activation:""},r))}}}),Yf,Zf,e_,t_,r_,ix=je(()=>{ft(),yt(),or(),Tt(),Yf=(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 o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!Me.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(Me.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(Me.size(l)!==u)throw new Error("zeroPoints input size error.")}},Zf=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=sr(r.k),d=sr(u),_=sr(i),f=a.concat([o,i]),T=o>1&&i/_%2===0?2:1,k=Me.size(f)/_/T,w=64,g=[],S=[l,o,n/c],E=Me.convertShape(e[1].dims).slice();E.splice(-1,1,u/d),g.push(...at(S)),g.push(...at(E)),g.push(...at(e[2].dims)),e.length===4&&g.push(...at(Me.convertShape(e[3].dims)));let v=[l,o,i/_];g.push(...at(v));let M=y=>{let C=S.length,F=Pe("a",e[0].dataType,C,c),z=Pe("b",12,E.length,d),K=Pe("scales",e[2].dataType,e[2].dims.length),q=[F,z,K],R=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;R&&q.push(R);let Z=v.length,H=et("output",e[0].dataType,Z,_),J=Tr(e[0].dataType),Q=(()=>{switch(c){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${c}-component is not supported.`)}})(),se=()=>{let V=` + // reuse a data + var input_offset = ${F.indicesToOffset(`${F.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Q}; + for (var j: u32 = 0; j < ${8/c}; j++) { + a_data[j] = ${F.getByOffset("input_offset")}; + input_offset++; + } + `;for(let A=0;A<_*T;A++)V+=` + b_value = ${d===1?`b${A}_data`:`b${A}_data[i]`}; + b_value_lower = unpack4xU8(b_value & b_mask); + b_value_upper = unpack4xU8((b_value >> 4) & b_mask); + b_quantized_values = ${Q}(${Array.from({length:4},(U,ee)=>`${J}(b_value_lower[${ee}]), ${J}(b_value_upper[${ee}])`).join(", ")}); + b_dequantized_values = ${c===1?`${Q}(${Array.from({length:8},(U,ee)=>`(b_quantized_values[${ee}] - ${R?`zero_point${A}`:"zero_point"}) * scale${A}`).join(", ")});`:`(b_quantized_values - ${Q}(${Array(8).fill(`${R?`zero_point${A}`:"zero_point"}`).join(",")})) * scale${A};`}; + workgroup_shared[local_id.x * ${T} + ${Math.floor(A/_)}]${_>1?`[${A%_}]`:""} += ${Array.from({length:8/c},(U,ee)=>`${c===1?`a_data[${ee}] * b_dequantized_values[${ee}]`:`dot(a_data[${ee}], b_dequantized_values[${ee}])`}`).join(" + ")}; + `;return V},fe=()=>{let V=` + var col_index = col * ${_}; + ${R?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${J}(8);`} + `;for(let A=0;A<_*T;A++)V+=` + let scale${A} = ${K.getByOffset("col_index * nBlocksPerCol + block")}; + ${R?` + zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${R.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${A} = ${J}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${_};`;for(let A=0;A<_*T;A++)V+=` + let b${A}_data = ${z.getByIndices(`${z.type.indices}(col_index, block, word)`)}; + col_index += 1;`;return V+=` + var b_value: u32; + let b_mask: u32 = 0x0F0F0F0Fu; + var b_value_lower: vec4; + var b_value_upper: vec4; + var b_quantized_values: ${Q}; + var b_dequantized_values: ${Q};`,V};return` + var workgroup_shared: array<${H.type.value}, ${T*w}>; + ${y.declareVariables(...q,H)} + ${y.mainStart([w,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${T}`)}; + 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 += ${w}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/c}; + ${fe()} + for (var word: u32 = 0; word < ${u}; word += ${d}) { + ${ae()} + for (var i: u32 = 0; i < ${d}; i++) { + ${se()} + word_offset += ${8/c}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${T}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${w}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${T}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${c};${d};${_};${T};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:k},programUniforms:g}),getShaderSource:M}},e_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=sr(r.k),d=sr(u),_=a.concat([o,i]),f=128,T=i%8===0?8:i%4===0?4:1,k=f/T,w=k*d*8,g=w/c,S=w/r.blockSize,E=Me.size(_)/T,v=[],M=[l,o,n/c],y=Me.convertShape(e[1].dims).slice();y.splice(-1,1,u/d),v.push(...at(M)),v.push(...at(y)),v.push(...at(e[2].dims)),e.length===4&&v.push(...at(Me.convertShape(e[3].dims)));let C=[l,o,i];v.push(...at(C));let F=z=>{let K=M.length,q=Pe("a",e[0].dataType,K,c),R=Pe("b",12,y.length,d),Z=Pe("scales",e[2].dataType,e[2].dims.length),H=[q,R,Z],J=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;J&&H.push(J);let Q=C.length,se=et("output",e[0].dataType,Q),fe=Tr(e[0].dataType),ae=()=>{switch(c){case 1:return` + let a_data0 = vec4<${fe}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${fe}>(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<${fe}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${fe}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${c}-component is not supported.`)}};return` + var sub_a: array<${q.type.value}, ${g}>; + var inter_results: array, ${T}>; + ${z.declareVariables(...H,se)} + ${z.mainStart([k,T,1])} + let output_indices = ${se.offsetToIndices(`workgroup_index * ${T}`)}; + 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; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${g}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${g}; a_offset += ${f}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${q.getByIndices(`${q.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${q.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${S} + local_id.x; + ${J?` + 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); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${fe}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${fe}(8);`} + let scale = ${Z.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${R.getByIndices(`${R.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/c}; + for (var i: u32 = 0; i < ${d}; i++) { + ${ae()} + let b_value = ${d===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<${fe}>(${Array.from({length:4},(V,A)=>`${fe}(b_value_lower[${A}]), ${fe}(b_value_upper[${A}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${fe}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,A)=>`${`dot(a_data${A}, b_dequantized_values[${A}])`}`).join(" + ")}; + word_offset += ${8/c}; + } + workgroupBarrier(); + } + + if (local_idx < ${T}) { + var output_value: ${se.type.value} = ${se.type.value}(0); + for (var b = 0u; b < ${k}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${se.setByIndices(`${se.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${c};${d};${k};${T}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:E},programUniforms:v}),getShaderSource:F}},t_=(e,r)=>{Yf(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(e_(e.inputs,r)):e.compute(Zf(e.inputs,r))},r_=e=>zt(e)}),s_,n_,o_,i_,a_,l_,u_,c_,d_,ax=je(()=>{ft(),yt(),Tt(),s_=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].")}},n_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${st("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${st("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${st("uniforms.x_strides",o,r)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + } + `},o_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${st("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${st("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${st("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${st("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},i_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${st("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${st("uniforms.x_shape",o,r)})) { + k = i32(${st("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${st("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},a_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${st("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${st("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${st("uniforms.x_shape",o,r)})) { + k -= i32(${st("uniforms.x_shape",o,r)}); + } + offset += k * i32(${st("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},l_=(e,r,t)=>{switch(t.mode){case 0:return n_(e,r,t.pads.length);case 1:return o_(e,r,t.pads.length);case 2:return i_(e,r,t.pads.length);case 3:return a_(e,r,t.pads.length);default:throw new Error("Invalid mode")}},u_=(e,r)=>{let t=Me.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=Me.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...at(e[0].dims,t));let a=["rank"],l=u=>{let p=et("output",e[0].dataType,t.length),c=Pe("x",e[0].dataType,s.length),d=c.type.value,_=l_(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:i?d:"f32"}),` + ${u.registerUniforms(f).declareVariables(c,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${_} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(t)/64)},programUniforms:n}),getShaderSource:l}},c_=(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,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},d_=(e,r)=>{s_(e.inputs);let t=c_(e.inputs,r);e.compute(u_(e.inputs,t),{inputs:[0]})}}),bo,Bl,Rl,jl,Nl,p_,h_,Vl,Ul,m_,f_,Wl,__,g_,Gl,w_,M_,b_,y_,lx=je(()=>{ms(),ft(),yt(),Tt(),bo=e=>{if(Xt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Bl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();ai.adjustPoolAttributes(t,o,i,a,l,u);let p=ai.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),c=Object.assign({},r);n?Object.assign(c,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(c,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let d=p.slice();return d.push(d.splice(1,1)[0]),[c,s?d:p]},Rl=(e,r)=>{let t=r.format==="NHWC",s=Me.size(e),o=Me.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{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],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],c=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(r.kernelShape.length===2){let _=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],T=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];d=!!(T+k),n.push({type:12,data:_},{type:12,data:f},{type:12,data:T},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,c,d]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=Me.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.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((u,p)=>u+p);return[n,i,!!l,!1,!1]}},jl=(e,r,t,s,o,n,i,a,l,u,p,c)=>{let d=o.format==="NHWC",_=r.type.value,f=et("output",r.type.tensor,s);if(o.kernelShape.length<=2){let T="",k="",w="",g=t-(d?2:1);if(p?T=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${g}] < 0 || xIndices[${g}] + >= uniforms.x_shape[${g}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:T=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let S=t-(d?3:2);c?k=` + 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}]) { + pad += i32(uniforms.kw); + continue; + } + `:k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; + `,w=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var value = ${_}(${a}); + var pad = 0; + ${k} + ${T} + ${w} + ${i} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let T=o.kernelShape.length,k=o.pads.length,w="";return u?w=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:w=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${_}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${T-1}u; j++) { + offsets[j] = offset / ${st("uniforms.kernelStrides","j",T)}; + offset -= offsets[j] * ${st("uniforms.kernelStrides","j",T)}; + } + offsets[${T-1}] = offset; + + isPad = false; + for (var j = ${t-T}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${st("uniforms.strides",`j - ${t-T}u`,T)} + + offsets[j - ${t-T}u] - ${st("uniforms.pads","j - 2u",k)}; + ${w} + } + ${i} + + output[global_idx] = value; + }`}},Nl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,p_=e=>`${Nl(e)};${e.countIncludePad}`,h_=e=>`${Nl(e)};${e.storageOrder};${e.dilations}`,Vl=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}),Ul=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=Pe("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,c,d,_,f]=Rl(n,o);p.push(...at(r.dims,n));let T=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${d};${_};${f}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:k=>jl(k,i,r.dims.length,n.length,o,l,u,0,c,d,_,f)}},m_=e=>{let r=e.count_include_pad!==0,t=Vl(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:p_(s)}},f_=(e,r)=>{bo(e.inputs),e.compute(Ul("AveragePool",e.inputs[0],!1,r))},Wl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},__=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},g_=(e,r)=>{bo(e.inputs),e.compute(Ul("GlobalAveragePool",e.inputs[0],!0,r))},Gl=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=` + value = max(x_val, value); + `,a="",l=Pe("x",r.dataType,r.dims.length),u=["rank"],[p,c,d,_,f]=Rl(n,o);return p.push(...at(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${d};${_};${f}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:T=>jl(T,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,c,d,_,f)}},w_=(e,r)=>{bo(e.inputs),e.compute(Gl("MaxPool",e.inputs[0],!1,r))},M_=e=>{let r=e.storage_order,t=e.dilations,s=Vl(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 o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:h_(o)}},b_=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},y_=(e,r)=>{bo(e.inputs),e.compute(Gl("GlobalMaxPool",e.inputs[0],!0,r))}}),v_,x_,T_,E_,ux=je(()=>{ft(),yt(),or(),Tt(),v_=(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((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&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)].")}},x_=(e,r)=>{let t=Me.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=Me.size(n),l=s===3||s===2,u=l?[Math.ceil(Me.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,c=e.length>2?e[2]:void 0,d=c?l?[Math.ceil(Me.size(c.dims)/4)]:c.dims:void 0,_=p.length===0||p.length===1&&p[0]===1,f=_===!1&&p.length===1,T=sr(a),k=_&&(!l||T===4),w=k?T:1,g=k&&!l?T:1,S=Pe("input",l?12:s,u.length,g),E=Pe("scale",i,p.length),v=c?Pe("zero_point",l?12:s,d.length):void 0,M=et("output",i,n.length,w),y=[S,E];v&&y.push(v);let C=[u,p];c&&C.push(d);let F=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...at(...C,n)],z=K=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(q).declareVariables(...y,M)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${M.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${S.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; + + // Set scale input + ${_?`let scale_value= ${E.getByOffset("0")}`:f?` + let scale_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${E.getByOffset("scale_index")};`:` + var scale_indices: ${E.type.indices} = output_indices; + let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${E.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${E.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${v?_?l?` + let zero_point_input = ${v.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${v.getByOffset("0")}`:f?l?` + let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${v.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"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 = ${v.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${E.indicesToOffset("scale_indices")}; + let zero_point_input = ${v.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${v.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":S.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:v?["rank","rank","rank"]:["rank","rank"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:F})}},T_=(e,r)=>{v_(e.inputs,r),e.compute(x_(e.inputs,r))},E_=e=>zt({axis:e.axis,blockSize:e.blockSize})}),P_,C_,S_,cx=je(()=>{ms(),ft(),Tt(),P_=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},C_=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...at(n)],l=u=>{let p=et("output",s,n.length),c=p.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:c},{name:"delta",type:c}];return` + ${u.registerUniforms(d).declareVariables(p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${c}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},S_=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]),Xt.webgpu.validateInputContent&&P_(r,t,s),e.compute(C_(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),$_,Kl,Hl,k_,I_,A_,dx=je(()=>{ft(),yt(),or(),Tt(),$_=(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 o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Kl=(e,r)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,Hl=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${$_(e.reduction,"output[data_offset + i]","value",r)} + }`,k_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(Me.size(s)/n),a=s[s.length-1],l=Me.sizeFromDimension(t,a),u=Me.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...at(e[1].dims,e[2].dims,o)],c=d=>{let _=Pe("indices",e[1].dataType,e[1].dims.length),f=Pe("updates",e[2].dataType,e[2].dims.length,n),T=r.reduction!=="none"&&r.reduction!==""?zd("output",e[0].dataType,o.length):et("output",e[0].dataType,o.length,n);return` + ${d.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(_,f,T)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${u}; i = i + 1) { + for (var j = i + 1; j < ${u}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${u}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Kl(t.length,!1)} + } + ${Hl(r,T.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${Kl(t.length,!0)} + } + ${Hl(r,T.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:c}},I_=e=>zt({reduction:e.reduction}),A_=(e,r)=>{e.compute(k_(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),F_,O_,D_,ql,L_,z_,B_,R_,j_,N_,V_,U_,Ql,W_,G_,K_,H_,q_,Q_,X_,px=je(()=>{ft(),yt(),or(),Tt(),F_=(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")}},O_=(e,r,t)=>{r.every(o=>o>=0&&o{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((o,n)=>s[o]=e[n]),s},D_=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].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!==u&&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");F_(s,r),r.axes.length>0&&O_(s,r.axes,u).forEach((p,c)=>s[c]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==u&&t>=18&&o.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(o.length!==0&&o.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 o<"u"&&s.length>0&&o.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},ql=(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(). + let big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,L_=(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 { + ${ql("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;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 { + ${ql("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)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + 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`)}})()+"}",z_=(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`)}})()+"}",B_=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},R_=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},j_=(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 o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},N_=(e,r,t,s,o)=>` + 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++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${st("uniforms.scales","i",s)}; + var roi_low = ${st("uniforms.roi","i",o)}; + var roi_hi = ${st("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${st("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${st("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,V_=(e,r,t,s,o,n,i)=>` + 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++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${st("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${st("uniforms.roi","i",n)}; + var roi_hi = ${st("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${st("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${st("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,U_=(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")}; + if (input_index < 0 || input_index >= ${st("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Ql=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",W_=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Ql(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${i}]; + var col:${u} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${u} = getInputValue(batch, channel, row1, col1); + var x12: ${u} = getInputValue(batch, channel, row1, col2); + var x21: ${u} = getInputValue(batch, channel, row2, col1); + var x22: ${u} = getInputValue(batch, channel, row2, col2); + var dx1: ${u} = abs(row - ${u}(row1)); + var dx2: ${u} = abs(${u}(row2) - row); + var dy1: ${u} = abs(col - ${u}(col1)); + var dy2: ${u} = abs(${u}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},G_=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[c,d]=p?[0,1]:[2,3],_=e.type.value,f=T=>{let k=T===c?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${_} { + var output_index = ${r.indicesGet("output_indices",T)}; + var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[T]}, + ${s[T]}, ${t[T]}, ${n[T]}, ${n[T]} + ${t.length}); + var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[T]} - 1))) { + return ${l}; + } + var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${_} = originalIdx + ${_}(i); + if (${k} < 0 || ${k} >= ${t[T]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[T]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",T,`u32(${k})`)}; + data[i + 1] = ${T===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${f(c)}; + ${f(d)}; + fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> { + var absS = abs(s); + var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${_} = 1.0 - absS; + var twoMinusAbsS: ${_} = 2.0 - absS; + var onePlusAbsS: ${_} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} { + var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${_} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},K_=(e,r,t,s,o)=>{let[n,i,a,l,u]=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",i,`max(0, min(depth, ${t[i]} - 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))`)}; + ${Ql(e,u,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + 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); + }`},H_=(e,r,t,s,o,n)=>{let i=e.dims,a=B_(n,r.axes,i.length),l=R_(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((g,S)=>g===0?1:l[S]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=j_(i,u,r)));let p=et("output",e.dataType,l.length),c=Pe("input",e.dataType,i.length),d=Me.size(l),_=i.length===l.length&&i.every((g,S)=>g===l[S]),f=r.coordinateTransformMode==="tf_crop_and_resize",T=r.extrapolationValue,k=c.type.value,w=g=>` + ${_?"":` + ${L_(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${U_(c,i)}; + ${z_(r.nearestMode,t,k)}; + ${V_(c,p,i,l,u.length,a.length,f)}; + `;case"linear":return` + ${N_(p,i,l,u.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${W_(c,p,i,f,T)}`;if(i.length===3||i.length===5)return`${K_(c,p,i,f,T)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${G_(c,p,i,l,u,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")}})()}; + `} + ${g.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(c,p)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${_?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${c.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${c.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.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}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${_}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:u},{type:1,data:a},...at(i,l)]})}},q_=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Q_=(e,r)=>{let t=[],s=[],o=[],n=q_(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");D_(e.inputs,r,n,t,s,o),e.compute(H_(e.inputs[0],r,n,t,s,o),{inputs:[0]})},X_=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return zt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),J_,Y_,Z_,hx=je(()=>{ft(),yt(),Tt(),J_=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 o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)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]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Y_=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=Me.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],c=!o&&e.length>3,d=e.length>4,_=s&&t>1,f=s&&t>2,T=t>3,k=64,w=sr(u),g=[{type:12,data:l},{type:12,data:w},{type:12,data:u},{type:1,data:r.epsilon}],S=v=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],y=[Pe("x",e[0].dataType,e[0].dims,w),Pe("skip",e[1].dataType,e[1].dims,w),Pe("gamma",e[2].dataType,e[2].dims,w)];c&&y.push(Pe("beta",e[3].dataType,e[3].dims,w)),d&&y.push(Pe("bias",e[4].dataType,e[4].dims,w)),y.push(et("output",e[0].dataType,a,w)),_&&y.push(et("mean_output",1,p)),f&&y.push(et("inv_std_output",1,p)),T&&y.push(et("input_skip_bias_sum",e[0].dataType,a,w));let C=Tr(e[0].dataType),F=Tr(1,w);return` + + ${v.registerUniforms(M).declareVariables(...y)} + var sum_shared : array<${F}, ${k}>; + var sum_squared_shared : array<${F}, ${k}>; + + ${v.mainStart([k,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${k}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${k}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${k-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":C+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${T?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Un(C,w,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${k}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Us("sum",w)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Us("square_sum",w)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${_?"mean_output[global_idx] = mean;":""} + ${f?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${C}(mean)`}) * + ${C}(inv_std_dev) * gamma[offset1d + i] + ${c?"+ beta[offset1d + i]":""}; + } + }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${_};${f};${T}`,inputDependencies:e.map((v,M)=>"type")},getShaderSource:S,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:g})}},Z_=(e,r)=>{J_(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(Y_(e.inputs,r,e.outputCount,!1),{outputs:t})}}),eg,yo,tg,Xl,rg,sg,ng,og,mx=je(()=>{ft(),yt(),or(),Tt(),eg=(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`)})},yo=(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},tg=(e,r)=>{if(e.length>1){let t=yo(e,1),s=yo(e,2),o=yo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),zt({starts:t,ends:s,axes:o})}else return r},Xl=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},rg=(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--) { + let input_shape_i = ${st("uniforms.input_shape","i",t.length)}; + let steps_i = ${st("uniforms.steps","i",t.length)}; + let signs_i = ${st("uniforms.signs","i",t.length)}; + let starts_i = ${st("uniforms.starts","i",t.length)}; + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,sg=(e,r)=>{let t=e[0].dims,s=Me.size(t),o=r.axes.length>0?Me.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=yo(e,4);n.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((w,g)=>Xl(w,g,t,o,n)),a=r.ends.map((w,g)=>Xl(w,g,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let w=0;wMath.sign(w));n.forEach((w,g,S)=>{if(w<0){let E=(a[g]-i[g])/w,v=i[g],M=v+E*n[g];i[g]=M,a[g]=v,S[g]=-w}});let u=t.slice(0);o.forEach((w,g)=>{u[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:u,dataType:e[0].dataType},c=et("output",e[0].dataType,u.length),d=Pe("input",e[0].dataType,e[0].dims.length),_=Me.size(u),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],T=[{type:12,data:_},{type:12,data:i},{type:6,data:l},{type:12,data:n},...at(e[0].dims,u)],k=w=>` + ${w.registerUniforms(f).declareVariables(d,c)} + ${rg(d,c,t)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${c.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${c.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:T})}},ng=(e,r)=>{eg(e.inputs,r);let t=tg(e.inputs,r);e.compute(sg(e.inputs,t),{inputs:[0]})},og=e=>{let r=e.starts,t=e.ends,s=e.axes;return zt({starts:r,ends:t,axes:s})}}),ig,ag,lg,ug,fx=je(()=>{ft(),yt(),or(),Ws(),Tt(),ig=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ag=(e,r)=>{let t=e.inputs[0],s=t.dims,o=Me.size(s),n=s.length,i=Me.normalizeAxis(r.axis,n),a=iC),u[i]=n-1,u[n-1]=i,l=e.compute(qr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,c=p[n-1],d=o/c,_=sr(c),f=c/_,T=64;d===1&&(T=256);let k=(y,C)=>C===4?`max(max(${y}.x, ${y}.y), max(${y}.z, ${y}.w))`:C===2?`max(${y}.x, ${y}.y)`:C===3?`max(max(${y}.x, ${y}.y), ${y}.z)`:y,w=Pe("x",l.dataType,l.dims,_),g=et("result",l.dataType,l.dims,_),S=w.type.value,E=Tr(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,v=y=>` + var rowMaxShared : ${S}; + var rowSumShared : ${S}; + var threadShared : array<${S}, ${T}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) { + let index = row * row_stride + col; + result[index] = value; + } + ${y.registerUniform("packedCols","i32").declareVariables(w,g)} + ${y.mainStart(T)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${T}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${E} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${S}(${k("threadShared[0]",_)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${S}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${S}(${Us("threadShared[0]",_)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${_};${T}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:f}]}),getShaderSource:v},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(qr(M,u),{inputs:[M]})},lg=(e,r)=>{ig(e.inputs),ag(e,r)},ug=e=>zt({axis:e.axis})}),Jl,cg,dg,pg,hg,_x=je(()=>{ft(),yt(),Tt(),Jl=e=>Array.from(e.getBigInt64Array(),Number),cg=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(Jl(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")},dg=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Jl(e[1]),o=dg(t,s),n=Me.size(o),i=e[0].dataType,a=Pe("input",i,t.length),l=et("output",i,o.length),u=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${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:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...at(e[0].dims,o)]}),getShaderSource:u}},hg=e=>{cg(e.inputs),e.compute(pg(e.inputs),{inputs:[0]})}}),mg,fg,_g,gx=je(()=>{ft(),yt(),Tt(),mg=(e,r,t,s,o)=>{let n=et("output_data",o,t.length,4),i=Pe("a_data",r[1].dataType,r[1].dims.length,4),a=Pe("b_data",r[2].dataType,r[2].dims.length,4),l=Pe("c_data",r[0].dataType,r[0].dims.length,4),u,p=(c,d,_)=>`select(${d}, ${c}, ${_})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let c=(d,_,f="")=>{let T=`a_data[index_a${_}][component_a${_}]`,k=`b_data[index_b${_}][component_b${_}]`,w=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return` + let output_indices${_} = ${n.offsetToIndices(`global_idx * 4u + ${_}u`)}; + let offset_a${_} = ${i.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_b${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_c${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let index_a${_} = offset_a${_} / 4u; + let index_b${_} = offset_b${_} / 4u; + let index_c${_} = offset_c${_} / 4u; + let component_a${_} = offset_a${_} % 4u; + let component_b${_} = offset_b${_} % 4u; + let component_c${_} = offset_c${_} % 4u; + ${d}[${_}] = ${f}(${p(T,k,w)}); + `};o===9?u=` + var data = vec4(0); + ${c("data",0,"u32")} + ${c("data",1,"u32")} + ${c("data",2,"u32")} + ${c("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${c("output_data[global_idx]",0)} + ${c("output_data[global_idx]",1)} + ${c("output_data[global_idx]",2)} + ${c("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},fg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(Me.areEqual(r,t)&&Me.areEqual(t,s)),i=r,a=Me.size(r);if(n){let u=Nn.calcShape(Nn.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=Me.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>mg(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...at(s,r,t,i)]})}},_g=e=>{e.compute(fg(e.inputs))}}),gg,wx=je(()=>{Av(),dl(),Fv(),Ov(),Dv(),Lv(),zv(),Vv(),Wv(),Gv(),Kv(),Hv(),qv(),Qv(),Xv(),Jv(),Yv(),Zv(),ex(),tx(),rx(),sx(),nx(),ox(),ix(),$f(),ax(),lx(),ux(),cx(),dx(),ll(),px(),Rf(),hx(),mx(),fx(),Lf(),_x(),Ws(),fl(),gx(),gg=new Map([["Abs",[Xp]],["Acos",[Jp]],["Acosh",[Yp]],["Add",[Rh]],["ArgMax",[Dp,cl]],["ArgMin",[Op,cl]],["Asin",[Zp]],["Asinh",[eh]],["Atan",[th]],["Atanh",[rh]],["Attention",[Np]],["AveragePool",[f_,m_]],["BatchNormalization",[Gp]],["BiasAdd",[qp]],["BiasSplitGelu",[Lh]],["Cast",[nh,sh]],["Ceil",[ah]],["Clip",[ih]],["Concat",[Zh,em]],["Conv",[Sl,Pl]],["ConvTranspose",[Cm,Tm]],["Cos",[lh]],["Cosh",[uh]],["CumSum",[$m,km]],["DepthToSpace",[Om,Dm]],["DequantizeLinear",[T_,E_]],["Div",[jh]],["Einsum",[Nm,Vm]],["Elu",[ch,fo]],["Equal",[Nh]],["Erf",[dh]],["Exp",[ph]],["Expand",[Km]],["FastGelu",[qm]],["Floor",[hh]],["FusedConv",[Sl,Pl]],["Gather",[Ym,Jm]],["GatherElements",[cf,uf]],["GatherBlockQuantized",[nf,of]],["GatherND",[ef,tf]],["Gelu",[mh]],["Gemm",[mf,hf]],["GlobalAveragePool",[g_,__]],["GlobalMaxPool",[y_,b_]],["Greater",[Gh]],["GreaterOrEqual",[Hh]],["GridSample",[xf,Tf]],["GroupQueryAttention",[Uf]],["HardSigmoid",[vh,yh]],["InstanceNormalization",[Kf]],["LayerNormalization",[Qf]],["LeakyRelu",[fh,fo]],["Less",[Kh]],["LessOrEqual",[qh]],["Log",[kh]],["MatMul",[Jf]],["MatMulNBits",[t_,r_]],["MaxPool",[w_,M_]],["Mul",[Vh]],["MultiHeadAttention",[Sf,Pf]],["Neg",[gh]],["Not",[_h]],["Pad",[d_]],["Pow",[Uh]],["QuickGelu",[Fh,fo]],["Range",[S_]],["Reciprocal",[wh]],["ReduceMin",[$p]],["ReduceMean",[Tp]],["ReduceMax",[Sp]],["ReduceSum",[Ip]],["ReduceProd",[kp]],["ReduceL1",[Ep]],["ReduceL2",[Pp]],["ReduceLogSum",[Fp]],["ReduceLogSumExp",[Cp]],["ReduceSumSquare",[Ap]],["Relu",[Mh]],["Resize",[Q_,X_]],["RotaryEmbedding",[Bf]],["ScatterND",[A_,I_]],["Sigmoid",[bh]],["Sin",[xh]],["Sinh",[Th]],["Slice",[ng,og]],["SkipLayerNormalization",[Z_]],["Split",[Of,Df]],["Sqrt",[Eh]],["Softmax",[lg,ug]],["Sub",[Wh]],["Tan",[Ph]],["Tanh",[Ch]],["ThresholdedRelu",[$h,fo]],["Tile",[hg]],["Transpose",[Gd,Kd]],["Where",[_g]]])}),wg,Mx=je(()=>{ms(),Bs(),Tt(),wg=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,o){hs(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.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(),ts(e.programInfo.name)}dispose(){}build(e,r){hs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=Rd(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});It("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return ts(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.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,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),Mg={};Rn(Mg,{WebGpuBackend:()=>xg});var bg,yg,vg,xg,bx=je(()=>{ms(),ft(),Bs(),Ed(),kv(),wx(),Mx(),bg=(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 o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${bg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},vg=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},xg=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},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new vg(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Dd(this),this.programManager=new wg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ka(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;hs(),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 o=0;o"u"&&(this.queryTimeBase=_);let T=Number(_-this.queryTimeBase),k=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(T)||!Number.isSafeInteger(k))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:c.map(w=>({dims:w.dims,dataType:zs(w.dataType)})),outputsMetadata:d.map(w=>({dims:w.dims,dataType:zs(w.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:T,endTime:k});else{let w="";c.forEach((S,E)=>{w+=`input[${E}]: [${S.dims}] | ${zs(S.dataType)}, `});let g="";d.forEach((S,E)=>{g+=`output[${E}]: [${S.dims}] | ${zs(S.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${w}${g}execution time: ${k-T} ns`)}uo("GPU",`${p}::${_}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),ts()}run(e,r,t,s,o,n){hs(e.name);let i=[];for(let g=0;gS):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let c=[],d=[];for(let g=0;g=n)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let S=p[g]===-1,E=p[g]===-2,v=S||E?o(a[g].dataType,a[g].dims):s(p[g],a[g].dataType,a[g].dims);if(c.push(v),v.data===0)continue;let M=this.gpuDataManager.get(v.data);if(!M)throw new Error(`no GPU data for output: ${v.data}`);if(S&&this.temporaryData.push(M),E){let y=this.kernelPersistentData.get(this.currentKernelId);y||(y=[],this.kernelPersistentData.set(this.currentKernelId,y)),y.push(M)}d.push(M)}if(i.length!==r.length||d.length!==c.length){if(d.length===0)return ts(e.name),c;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(u){let g=0,S=[];u.forEach(y=>{let C=typeof y.data=="number"?[y.data]:y.data;if(C.length===0)return;let F=y.type===10?2:4,z,K;y.type===10?(K=C.length>4?16:C.length>2?8:C.length*F,z=C.length>4?16:F*C.length):(K=C.length<=2?C.length*F:16,z=16),g=Math.ceil(g/K)*K,S.push(g);let q=y.type===10?8:4;g+=C.length>4?Math.ceil(C.length/q)*z:C.length*F});let E=16;g=Math.ceil(g/E)*E;let v=new ArrayBuffer(g);u.forEach((y,C)=>{let F=S[C],z=typeof y.data=="number"?[y.data]:y.data;if(y.type===6)new Int32Array(v,F,z.length).set(z);else if(y.type===12)new Uint32Array(v,F,z.length).set(z);else if(y.type===10)new Uint16Array(v,F,z.length).set(z);else if(y.type===1)new Float32Array(v,F,z.length).set(z);else throw new Error(`Unsupported uniform type: ${zs(y.type)}`)});let M=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,v,0,g),this.gpuDataManager.release(M.id),_={offset:0,size:g,buffer:M.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),T=f[1]===1&&f[2]===1,k=yg(e,r,T),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,f),this.programManager.setArtifact(k,w),It("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),u&&w.uniformVariablesInfo){if(u.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${u.length} in program "${w.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${k}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:c};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(w,i,d,f,_),ts(e.name),c}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 o=gg.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[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 o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),It("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}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 sl(this,e,r);return Ha(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(){It("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(){It("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){It("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()}}}),Tg={};Rn(Tg,{init:()=>Pg});var bi,Eg,Pg,yx=je(()=>{ft(),Bs(),yt(),$v(),bi=class W0{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Me.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=Me.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=Me.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=Me.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Me.size(r)!==Me.size(this.dims))throw new Error("Invalid new shape");return new W0(this.module,this.dataType,this.data,r)}},Eg=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,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,u)=>new bi(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=on(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new bi(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(bx(),io(Mg)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)It("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{It("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let c=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),c)}},async(a,l,u)=>{It("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{It("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let c=new Eg(r,i,Number(l));return i.computeKernel(Number(a),c,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Id(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Cg,Yl,Zl,Gs,Sg,eu,yi,tu,ru,su,nu,ou,iu,$g=je(()=>{Pv(),Cv(),ft(),nn(),ja(),fd(),Cg=(e,r)=>{Qt()._OrtInit(e,r)!==0&&Gt("Can't initialize onnxruntime.")},Yl=async e=>{Cg(e.wasm.numThreads,ii(e.logLevel))},Zl=async(e,r)=>{var t,s;(s=(t=Qt()).asyncInit)==null||s.call(t);{let o=(yx(),io(Tg)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",Qt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",Qt(),e)}}},Gs=new Map,Sg=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&Gt("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},eu=(e,r)=>{let t=Qt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&Gt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let u=t.HEAPU32[o/4+1],p=[];for(let c=0;c{let r=Qt(),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]},tu=async(e,r)=>{var c,d,_,f;let t,s,o=Qt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=yi(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await md(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let C=[];for(let F of r.externalData){let z=typeof F=="string"?F:F.path;C.push(Ga(typeof F=="string"?F:F.data).then(K=>{o.mountExternalData(z,K)}))}await Promise.all(C)}for(let C of(r==null?void 0:r.executionProviders)??[])if((typeof C=="string"?C:C.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof C!="string"){let F=C,z=F==null?void 0:F.context,K=F==null?void 0:F.gpuDevice,q=F==null?void 0:F.deviceType,R=F==null?void 0:F.powerPreference;z?o.currentContext=z:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:q,powerPreference:R})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(c=o.webgpuOnCreateSession)==null||c.call(o,n),n===0&&Gt("Can't create a session."),(d=o.jsepOnCreateSession)==null||d.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[T,k]=Sg(n),w=!!(r!=null&&r.enableGraphCapture),g=[],S=[],E=[],v=[],M=[];for(let C=0;CC==="gpu-buffer"||C==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&Gt("Can't create IO binding."),y={handle:a,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(C=>Wa(C))}),Gs.set(n,[n,u,p,y,w,!1]),[n,g,S,E,v]}catch(T){throw u.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&Gt("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&Gt("Can't release session."),T}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&Gt("Can't release session options."),l.forEach(T=>o._free(T)),(f=o.unmountExternalData)==null||f.call(o)}},ru=e=>{var l,u,p;let r=Qt(),t=Gs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Gt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Gt("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(c=>r._OrtFree(c)),n.forEach(c=>r._OrtFree(c)),r._OrtReleaseSession(s)!==0&&Gt("Can't release session."),Gs.delete(e)},su=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=Qt(),l=a.PTR_SIZE,u=e[0],p=e[1],c=e[3],d=c,_,f;if(u==="string"&&(c==="gpu-buffer"||c==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let w=e[2].gpuBuffer;f=on(jn(u),p);{let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=g(s,n,w,f)}}else if(c==="ml-tensor"){let w=e[2].mlTensor;f=on(jn(u),p);let g=a.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=g(s,w,jn(u),p)}else{let w=e[2];if(Array.isArray(w)){f=l*w.length,_=a._malloc(f),t.push(_);for(let g=0;ga.setValue(k+S*l,g,l===4?"i32":"i64"));let w=a._OrtCreateTensor(jn(u),_,f,k,p.length,Wa(d));w===0&&Gt(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(T)}},nu=async(e,r,t,s,o,n)=>{var K,q,R,Z;let i=Qt(),a=i.PTR_SIZE,l=Gs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],c=l[2],d=l[3],_=l[4],f=l[5],T=r.length,k=s.length,w=0,g=[],S=[],E=[],v=[],M=i.stackSave(),y=i.stackAlloc(T*a),C=i.stackAlloc(T*a),F=i.stackAlloc(k*a),z=i.stackAlloc(k*a);try{[w,g]=ud(n);for(let Q=0;QW*re,1);A=zs(_e);let pe=d==null?void 0:d.outputPreferredLocations[s[Q]];if(A==="string"){if(pe==="gpu-buffer"||pe==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let W=[];for(let re=0;re0){let W=i.jsepGetBuffer;if(!W)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let re=W(U),G=on(_e,Ue);if(G===void 0||!Va(A))throw new Error(`Unsupported data type: ${A}`);V=!0,J.push([A,ze,{gpuBuffer:re,download:i.jsepCreateDownloader(re,G,A),dispose:()=>{i._OrtReleaseTensor(se)!==0&&Gt("Can't release tensor.")}},"gpu-buffer"])}else if(pe==="ml-tensor"&&Ue>0){let W=i.webnnEnsureTensor,re=i.webnnIsInt64Supported;if(!W||!re)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(on(_e,Ue)===void 0||!Ua(A))throw new Error(`Unsupported data type: ${A}`);if(A==="int64"&&!re(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let G=await W(e,U,_e,ze,!1);V=!0,J.push([A,ze,{mlTensor:G,download:i.webnnCreateMLTensorDownloader(U,A),dispose:()=>{i.webnnReleaseTensorId(U),i._OrtReleaseTensor(se)}},"ml-tensor"])}else{let W=Na(A),re=new W(Ue);new Uint8Array(re.buffer,re.byteOffset,re.byteLength).set(i.HEAPU8.subarray(U,U+re.byteLength)),J.push([A,ze,re,"cpu"])}}finally{i.stackRestore(fe),A==="string"&&U&&i._free(U),V||i._OrtReleaseTensor(se),(Z=i.webnnOnRunEnd)==null||Z.call(i,u)}}return d&&!_&&(i._OrtClearBoundOutputs(d.handle)!==0&&Gt("Can't clear bound outputs."),Gs.set(e,[u,p,c,d,_,!1])),J}finally{i.stackRestore(M),S.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),v.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),g.forEach(H=>i._free(H))}},ou=e=>{let r=Qt(),t=Gs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&Gt("Can't get an profile file name."),r._OrtFree(o)},iu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Ks,Wr,Wn,vo,xo,vi,au,xi,hn,mn,kg,Ig,Ag,Fg,Og,Dg,Lg,zg,Bg=je(()=>{ms(),$g(),nn(),La(),Ks=()=>!!Xt.wasm.proxy&&typeof document<"u",Wn=!1,vo=!1,xo=!1,xi=new Map,hn=(e,r)=>{let t=xi.get(e);t?t.push(r):xi.set(e,[r])},mn=()=>{if(Wn||!vo||xo||!Wr)throw new Error("worker not ready")},kg=e=>{switch(e.data.type){case"init-wasm":Wn=!1,e.data.err?(xo=!0,au[1](e.data.err)):(vo=!0,au[0]()),vi&&(URL.revokeObjectURL(vi),vi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=xi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Ig=async()=>{if(!vo){if(Wn)throw new Error("multiple calls to 'initWasm()' detected.");if(xo)throw new Error("previous call to 'initWasm()' failed.");if(Wn=!0,Ks())return new Promise((e,r)=>{Wr==null||Wr.terminate(),nd().then(([t,s])=>{try{Wr=s,Wr.onerror=n=>r(n),Wr.onmessage=kg,au=[e,r];let o={type:"init-wasm",in:Xt};!o.in.wasm.wasmPaths&&(t||Aa)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),Wr.postMessage(o),vi=t}catch(o){r(o)}},r)});try{await Ra(Xt.wasm),await Yl(Xt),vo=!0}catch(e){throw xo=!0,e}finally{Wn=!1}}},Ag=async e=>{if(Ks())return mn(),new Promise((r,t)=>{hn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Xt}};Wr.postMessage(s)});await Zl(Xt,e)},Fg=async e=>Ks()?(mn(),new Promise((r,t)=>{hn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Wr.postMessage(s,[e.buffer])})):yi(e),Og=async(e,r)=>{if(Ks()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return mn(),new Promise((t,s)=>{hn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Wr.postMessage(o,n)})}else return tu(e,r)},Dg=async e=>{if(Ks())return mn(),new Promise((r,t)=>{hn("release",[r,t]);let s={type:"release",in:e};Wr.postMessage(s)});ru(e)},Lg=async(e,r,t,s,o,n)=>{if(Ks()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return mn(),new Promise((i,a)=>{hn("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Wr.postMessage(u,iu(l))})}else return nu(e,r,t,s,o,n)},zg=async e=>{if(Ks())return mn(),new Promise((r,t)=>{hn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Wr.postMessage(s)});ou(e)}}),lu,Rg,jg,vx=je(()=>{ms(),Bg(),ft(),Pa(),fd(),lu=(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()}`)}},Rg=e=>{switch(e[3]){case"cpu":return new ps(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Va(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return ps.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!Ua(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return ps.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},jg=class{async fetchModelAndCopyToWasmMemory(e){return Fg(await Ga(e))}async loadModel(e,r){hs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Og(t,r),ts()}async dispose(){return Dg(this.sessionId)}async run(e,r,t){hs();let s=[],o=[];Object.entries(e).forEach(c=>{let d=c[0],_=c[1],f=this.inputNames.indexOf(d);if(f===-1)throw new Error(`invalid input '${d}'`);s.push(_),o.push(f)});let n=[],i=[];Object.entries(r).forEach(c=>{let d=c[0],_=c[1],f=this.outputNames.indexOf(d);if(f===-1)throw new Error(`invalid output '${d}'`);n.push(_),i.push(f)});let a=s.map((c,d)=>lu(c,()=>`input "${this.inputNames[o[d]]}"`)),l=n.map((c,d)=>c?lu(c,()=>`output "${this.outputNames[i[d]]}"`):null),u=await Lg(this.sessionId,o,a,i,l,t),p={};for(let c=0;ccu,initializeFlags:()=>uu,wasmBackend:()=>Vg});var uu,cu,Vg,xx=je(()=>{ms(),Bg(),vx(),uu=()=>{(typeof Xt.wasm.initTimeout!="number"||Xt.wasm.initTimeout<0)&&(Xt.wasm.initTimeout=0);let e=Xt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Xt.wasm.simd=!1),typeof Xt.wasm.proxy!="boolean"&&(Xt.wasm.proxy=!1),typeof Xt.wasm.trace!="boolean"&&(Xt.wasm.trace=!1),typeof Xt.wasm.numThreads!="number"||!Number.isInteger(Xt.wasm.numThreads)||Xt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Xt.wasm.numThreads=1;else{let r=typeof navigator>"u"?uv("node:os").cpus().length:navigator.hardwareConcurrency;Xt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},cu=class{async init(e){uu(),await Ig(),await Ag(e)}async createInferenceSessionHandler(e,r){let t=new jg;return await t.loadModel(e,r),t}},Vg=new cu});ms(),ms(),ms();var Tx="1.22.0-dev.20250409-89f8206ba4",Ex=Hc;{let e=(xx(),io(Ng)).wasmBackend;rn("webgpu",e,5),rn("webnn",e,5),rn("cpu",e,10),rn("wasm",e,10)}Object.defineProperty(Xt.versions,"web",{value:Tx,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Px=Object.freeze({__proto__:null,get InferenceSession(){return Ea},get TRACE(){return uo},get TRACE_FUNC_BEGIN(){return hs},get TRACE_FUNC_END(){return ts},get Tensor(){return ps},default:Ex,get env(){return Xt},get registerBackend(){return rn}}),js={},Cx={"onnxruntime-common":e=>{e.exports=ov},"onnxruntime-web":e=>{e.exports=Px},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Be,Interpreter:()=>He,Template:()=>rs,parse:()=>U,tokenize:()=>c});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",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro",Break:"Break",Continue:"Continue"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,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,break:s.Break,continue:s.Continue,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(D,oe){this.value=D,this.type=oe}};function i(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]],u=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(D,oe={}){return D.endsWith(` +`)&&(D=D.slice(0,-1)),D=D.replace(/{#.*?#}/gs,"{##}"),oe.lstrip_blocks&&(D=D.replace(/^[ \t]*({[#%])/gm,"$1")),oe.trim_blocks&&(D=D.replace(/([#%]})\n/g,"$1")),D.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function c(D,oe={}){var ve,vt,Ft;const B=[],te=p(D,oe);let me=0;const Oe=ht=>{let ut="";for(;ht(te[me]);){if(te[me]==="\\"){if(++me,me>=te.length)throw new SyntaxError("Unexpected end of input");const rt=te[me++],jt=u.get(rt);if(jt===void 0)throw new SyntaxError(`Unexpected escaped character: ${rt}`);ut+=jt;continue}if(ut+=te[me++],me>=te.length)throw new SyntaxError("Unexpected end of input")}return ut};e:for(;me0){B.push(new n(rt,s.Text));continue}}Oe(rt=>/\s/.test(rt));const ut=te[me];if(ut==="-"||ut==="+"){const rt=(vt=B.at(-1))==null?void 0:vt.type;if(rt===s.Text||rt===void 0)throw new SyntaxError(`Unexpected character: ${ut}`);switch(rt){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++me;const jt=Oe(a);B.push(new n(`${ut}${jt}`,jt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[rt,jt]of l)if(te.slice(me,me+rt.length)===rt){B.push(new n(rt,jt)),me+=rt.length;continue e}if(ut==="'"||ut==='"'){++me;const rt=Oe(jt=>jt!==ut);B.push(new n(rt,s.StringLiteral)),++me;continue}if(a(ut)){const rt=Oe(a);B.push(new n(rt,s.NumericLiteral));continue}if(i(ut)){const rt=Oe(i),jt=Object.hasOwn(o,rt)?o[rt]:s.Identifier;jt===s.In&&((Ft=B.at(-1))==null?void 0:Ft.type)===s.Not?(B.pop(),B.push(new n("not in",s.NotIn))):B.push(new n(rt,jt));continue}throw new SyntaxError(`Unexpected character: ${ut}`)}return B}var d=class{constructor(){Y(this,"type","Statement")}},_=class extends d{constructor(oe){super();Y(this,"type","Program");this.body=oe}},f=class extends d{constructor(oe,B,te){super();Y(this,"type","If");this.test=oe,this.body=B,this.alternate=te}},T=class extends d{constructor(oe,B,te,me){super();Y(this,"type","For");this.loopvar=oe,this.iterable=B,this.body=te,this.defaultBlock=me}},k=class extends d{constructor(){super(...arguments);Y(this,"type","Break")}},w=class extends d{constructor(){super(...arguments);Y(this,"type","Continue")}},g=class extends d{constructor(oe,B,te){super();Y(this,"type","Set");this.assignee=oe,this.value=B,this.body=te}},S=class extends d{constructor(oe,B,te){super();Y(this,"type","Macro");this.name=oe,this.args=B,this.body=te}},E=class extends d{constructor(){super(...arguments);Y(this,"type","Expression")}},v=class extends E{constructor(oe,B,te){super();Y(this,"type","MemberExpression");this.object=oe,this.property=B,this.computed=te}},M=class extends E{constructor(oe,B){super();Y(this,"type","CallExpression");this.callee=oe,this.args=B}},y=class extends E{constructor(oe){super();Y(this,"type","Identifier");this.value=oe}},C=class extends E{constructor(oe){super();Y(this,"type","Literal");this.value=oe}},F=class extends C{constructor(){super(...arguments);Y(this,"type","NumericLiteral")}},z=class extends C{constructor(){super(...arguments);Y(this,"type","StringLiteral")}},K=class extends C{constructor(){super(...arguments);Y(this,"type","BooleanLiteral")}},q=class extends C{constructor(){super(...arguments);Y(this,"type","NullLiteral")}},R=class extends C{constructor(){super(...arguments);Y(this,"type","ArrayLiteral")}},Z=class extends C{constructor(){super(...arguments);Y(this,"type","TupleLiteral")}},H=class extends C{constructor(){super(...arguments);Y(this,"type","ObjectLiteral")}},J=class extends E{constructor(oe,B,te){super();Y(this,"type","BinaryExpression");this.operator=oe,this.left=B,this.right=te}},Q=class extends E{constructor(oe,B){super();Y(this,"type","FilterExpression");this.operand=oe,this.filter=B}},se=class extends E{constructor(oe,B){super();Y(this,"type","SelectExpression");this.iterable=oe,this.test=B}},fe=class extends E{constructor(oe,B,te){super();Y(this,"type","TestExpression");this.operand=oe,this.negate=B,this.test=te}},ae=class extends E{constructor(oe,B){super();Y(this,"type","UnaryExpression");this.operator=oe,this.argument=B}},V=class extends E{constructor(oe=void 0,B=void 0,te=void 0){super();Y(this,"type","SliceExpression");this.start=oe,this.stop=B,this.step=te}},A=class extends E{constructor(oe,B){super();Y(this,"type","KeywordArgumentExpression");this.key=oe,this.value=B}};function U(D){const oe=new _([]);let B=0;function te(Ae,Je){const it=D[B++];if(!it||it.type!==Ae)throw new Error(`Parser Error: ${Je}. ${it.type} !== ${Ae}.`);return it}function me(){switch(D[B].type){case s.Text:return vt();case s.OpenStatement:return Ft();case s.OpenExpression:return ht();default:throw new SyntaxError(`Unexpected token type: ${D[B].type}`)}}function Oe(...Ae){return B+Ae.length<=D.length&&Ae.some((Je,it)=>Je!==D[B+it].type)}function ve(...Ae){return B+Ae.length<=D.length&&Ae.every((Je,it)=>Je===D[B+it].type)}function vt(){return new z(te(s.Text,"Expected text token").value)}function Ft(){te(s.OpenStatement,"Expected opening statement token");let Ae;switch(D[B].type){case s.Set:++B,Ae=ut(),te(s.CloseStatement,"Expected closing statement token");break;case s.If:++B,Ae=rt(),te(s.OpenStatement,"Expected {% token"),te(s.EndIf,"Expected endif token"),te(s.CloseStatement,"Expected %} token");break;case s.Macro:++B,Ae=jt(),te(s.OpenStatement,"Expected {% token"),te(s.EndMacro,"Expected endmacro token"),te(s.CloseStatement,"Expected %} token");break;case s.For:++B,Ae=wr(),te(s.OpenStatement,"Expected {% token"),te(s.EndFor,"Expected endfor token"),te(s.CloseStatement,"Expected %} token");break;case s.Break:++B,te(s.CloseStatement,"Expected closing statement token"),Ae=new k;break;case s.Continue:++B,te(s.CloseStatement,"Expected closing statement token"),Ae=new w;break;default:throw new SyntaxError(`Unknown statement type: ${D[B].type}`)}return Ae}function ht(){te(s.OpenExpression,"Expected opening expression token");const Ae=Jt();return te(s.CloseExpression,"Expected closing expression token"),Ae}function ut(){var Je,it;const Ae=Jt();if(ve(s.Equals)){++B;const Nt=Jt();return new g(Ae,Nt,[])}else{const Nt=[];for(te(s.CloseStatement,"Expected %} token");!(((Je=D[B])==null?void 0:Je.type)===s.OpenStatement&&((it=D[B+1])==null?void 0:it.type)===s.EndSet);){const os=me();Nt.push(os)}return te(s.OpenStatement,"Expected {% token"),te(s.EndSet,"Expected endset token"),new g(Ae,null,Nt)}}function rt(){var Nt,os,is,ur,as,cr,hr,ls;const Ae=Jt();te(s.CloseStatement,"Expected closing statement token");const Je=[],it=[];for(;!(((Nt=D[B])==null?void 0:Nt.type)===s.OpenStatement&&(((os=D[B+1])==null?void 0:os.type)===s.ElseIf||((is=D[B+1])==null?void 0:is.type)===s.Else||((ur=D[B+1])==null?void 0:ur.type)===s.EndIf));)Je.push(me());if(((as=D[B])==null?void 0:as.type)===s.OpenStatement&&((cr=D[B+1])==null?void 0:cr.type)!==s.EndIf)if(++B,ve(s.ElseIf))te(s.ElseIf,"Expected elseif token"),it.push(rt());else for(te(s.Else,"Expected else token"),te(s.CloseStatement,"Expected closing statement token");!(((hr=D[B])==null?void 0:hr.type)===s.OpenStatement&&((ls=D[B+1])==null?void 0:ls.type)===s.EndIf);)it.push(me());return new f(Ae,Je,it)}function jt(){const Ae=Br();if(Ae.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Je=vs();te(s.CloseStatement,"Expected closing statement token");const it=[];for(;Oe(s.OpenStatement,s.EndMacro);)it.push(me());return new S(Ae,Je,it)}function Ht(Ae=!1){const Je=Ae?Br:Jt,it=[Je()],Nt=ve(s.Comma);for(;Nt&&(++B,it.push(Je()),!!ve(s.Comma)););return Nt?new Z(it):it[0]}function wr(){const Ae=Ht(!0);if(!(Ae instanceof y||Ae instanceof Z))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Ae.type} instead`);te(s.In,"Expected `in` keyword following loop variable");const Je=Jt();te(s.CloseStatement,"Expected closing statement token");const it=[];for(;Oe(s.OpenStatement,s.EndFor)&&Oe(s.OpenStatement,s.Else);)it.push(me());const Nt=[];if(ve(s.OpenStatement,s.Else))for(++B,++B,te(s.CloseStatement,"Expected closing statement token");Oe(s.OpenStatement,s.EndFor);)Nt.push(me());return new T(Ae,Je,it,Nt)}function Jt(){return Or()}function Or(){const Ae=ss();if(ve(s.If)){++B;const Je=ss();if(ve(s.Else)){++B;const it=ss();return new f(Je,[Ae],[it])}else return new se(Ae,Je)}return Ae}function ss(){let Ae=ys();for(;ve(s.Or);){const Je=D[B];++B;const it=ys();Ae=new J(Je,Ae,it)}return Ae}function ys(){let Ae=ns();for(;ve(s.And);){const Je=D[B];++B;const it=ns();Ae=new J(Je,Ae,it)}return Ae}function ns(){let Ae;for(;ve(s.Not);){const Je=D[B];++B;const it=ns();Ae=new ae(Je,it)}return Ae??$s()}function $s(){let Ae=Vr();for(;ve(s.ComparisonBinaryOperator)||ve(s.In)||ve(s.NotIn);){const Je=D[B];++B;const it=Vr();Ae=new J(Je,Ae,it)}return Ae}function Vr(){let Ae=Fs();for(;ve(s.AdditiveBinaryOperator);){const Je=D[B];++B;const it=Fs();Ae=new J(Je,Ae,it)}return Ae}function ks(){const Ae=ar(Br());return ve(s.OpenParen)?Qr(Ae):Ae}function Qr(Ae){let Je=new M(Ae,vs());return Je=ar(Je),ve(s.OpenParen)&&(Je=Qr(Je)),Je}function vs(){te(s.OpenParen,"Expected opening parenthesis for arguments list");const Ae=Is();return te(s.CloseParen,"Expected closing parenthesis for arguments list"),Ae}function Is(){const Ae=[];for(;!ve(s.CloseParen);){let Je=Jt();if(ve(s.Equals)){if(++B,!(Je instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const it=Jt();Je=new A(Je,it)}Ae.push(Je),ve(s.Comma)&&++B}return Ae}function As(){const Ae=[];let Je=!1;for(;!ve(s.CloseSquareBracket);)ve(s.Colon)?(Ae.push(void 0),++B,Je=!0):(Ae.push(Jt()),ve(s.Colon)&&(++B,Je=!0));if(Ae.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Je){if(Ae.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new V(...Ae)}return Ae[0]}function ar(Ae){for(;ve(s.Dot)||ve(s.OpenSquareBracket);){const Je=D[B];++B;let it;const Nt=Je.type!==s.Dot;if(Nt)it=As(),te(s.CloseSquareBracket,"Expected closing square bracket");else if(it=Br(),it.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Ae=new v(Ae,it,Nt)}return Ae}function Fs(){let Ae=Er();for(;ve(s.MultiplicativeBinaryOperator);){const Je=D[B];++B;const it=Er();Ae=new J(Je,Ae,it)}return Ae}function Er(){let Ae=xs();for(;ve(s.Is);){++B;const Je=ve(s.Not);Je&&++B;let it=Br();if(it instanceof K?it=new y(it.value.toString()):it instanceof q&&(it=new y("none")),!(it instanceof y))throw new SyntaxError("Expected identifier for the test");Ae=new fe(Ae,Je,it)}return Ae}function xs(){let Ae=ks();for(;ve(s.Pipe);){++B;let Je=Br();if(!(Je instanceof y))throw new SyntaxError("Expected identifier for the filter");ve(s.OpenParen)&&(Je=Qr(Je)),Ae=new Q(Ae,Je)}return Ae}function Br(){const Ae=D[B];switch(Ae.type){case s.NumericLiteral:return++B,new F(Number(Ae.value));case s.StringLiteral:return++B,new z(Ae.value);case s.BooleanLiteral:return++B,new K(Ae.value.toLowerCase()==="true");case s.NullLiteral:return++B,new q(null);case s.Identifier:return++B,new y(Ae.value);case s.OpenParen:{++B;const Je=Ht();if(D[B].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${D[B].type} instead`);return++B,Je}case s.OpenSquareBracket:{++B;const Je=[];for(;!ve(s.CloseSquareBracket);)Je.push(Jt()),ve(s.Comma)&&++B;return++B,new R(Je)}case s.OpenCurlyBracket:{++B;const Je=new Map;for(;!ve(s.CloseCurlyBracket);){const it=Jt();te(s.Colon,"Expected colon between key and value in object literal");const Nt=Jt();Je.set(it,Nt),ve(s.Comma)&&++B}return++B,new H(Je)}default:throw new SyntaxError(`Unexpected token: ${Ae.type}`)}}for(;B=0?(oe=(oe??(oe=0))<0?Math.max(D.length+oe,0):Math.min(oe,D.length),B=(B??(B=D.length))<0?Math.max(D.length+B,0):Math.min(B,D.length)):(oe=(oe??(oe=D.length-1))<0?Math.max(D.length+oe,-1):Math.min(oe,D.length-1),B=(B??(B=-1))<-1?Math.max(D.length+B,-1):Math.min(B,D.length-1));const Oe=[];for(let ve=oe;me*veoe.toUpperCase())}var ye=class extends Error{},ze=class extends Error{},Ue=class{constructor(D=void 0){Y(this,"type","RuntimeValue");Y(this,"value");Y(this,"builtins",new Map);this.value=D}__bool__(){return new re(!!this.value)}},pe=class extends Ue{constructor(){super(...arguments);Y(this,"type","NumericValue")}},W=class extends Ue{constructor(){super(...arguments);Y(this,"type","StringValue");Y(this,"builtins",new Map([["upper",new Ce(()=>new W(this.value.toUpperCase()))],["lower",new Ce(()=>new W(this.value.toLowerCase()))],["strip",new Ce(()=>new W(this.value.trim()))],["title",new Ce(()=>new W(le(this.value)))],["length",new pe(this.value.length)],["rstrip",new Ce(()=>new W(this.value.trimEnd()))],["lstrip",new Ce(()=>new W(this.value.trimStart()))],["startswith",new Ce(oe=>{if(oe.length===0)throw new Error("startswith() requires at least one argument");const B=oe[0];if(!(B instanceof W))throw new Error("startswith() argument must be a string");return new re(this.value.startsWith(B.value))})],["endswith",new Ce(oe=>{if(oe.length===0)throw new Error("endswith() requires at least one argument");const B=oe[0];if(!(B instanceof W))throw new Error("endswith() argument must be a string");return new re(this.value.endsWith(B.value))})],["split",new Ce(oe=>{const B=oe[0]??new $e;if(!(B instanceof W||B instanceof $e))throw new Error("sep argument must be a string or null");const te=oe[1]??new pe(-1);if(!(te instanceof pe))throw new Error("maxsplit argument must be a number");let me=[];if(B instanceof $e){const Oe=this.value.trimStart();for(const{0:ve,index:vt}of Oe.matchAll(/\S+/g)){if(te.value!==-1&&me.length>=te.value&&vt!==void 0){me.push(ve+Oe.slice(vt+ve.length));break}me.push(ve)}}else{if(B.value==="")throw new Error("empty separator");me=this.value.split(B.value),te.value!==-1&&me.length>te.value&&me.push(me.splice(te.value).join(B.value))}return new we(me.map(Oe=>new W(Oe)))})]]))}},re=class extends Ue{constructor(){super(...arguments);Y(this,"type","BooleanValue")}},G=class extends Ue{constructor(){super(...arguments);Y(this,"type","ObjectValue");Y(this,"builtins",new Map([["get",new Ce(([oe,B])=>{if(!(oe instanceof W))throw new Error(`Object key must be a string: got ${oe.type}`);return this.value.get(oe.value)??B??new $e})],["items",new Ce(()=>new we(Array.from(this.value.entries()).map(([oe,B])=>new we([new W(oe),B]))))]]))}__bool__(){return new re(this.value.size>0)}},be=class extends G{constructor(){super(...arguments);Y(this,"type","KeywordArgumentsValue")}},we=class extends Ue{constructor(){super(...arguments);Y(this,"type","ArrayValue");Y(this,"builtins",new Map([["length",new pe(this.value.length)]]))}__bool__(){return new re(this.value.length>0)}},Se=class extends we{constructor(){super(...arguments);Y(this,"type","TupleValue")}},Ce=class extends Ue{constructor(){super(...arguments);Y(this,"type","FunctionValue")}},$e=class extends Ue{constructor(){super(...arguments);Y(this,"type","NullValue")}},Fe=class extends Ue{constructor(){super(...arguments);Y(this,"type","UndefinedValue")}},Be=class{constructor(D){Y(this,"variables",new Map([["namespace",new Ce(D=>{if(D.length===0)return new G(new Map);if(D.length!==1||!(D[0]instanceof G))throw new Error("`namespace` expects either zero arguments or a single object argument");return D[0]})]]));Y(this,"tests",new Map([["boolean",D=>D.type==="BooleanValue"],["callable",D=>D instanceof Ce],["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 oe=D.value;return D.type==="StringValue"&&oe===oe.toLowerCase()}],["upper",D=>{const oe=D.value;return D.type==="StringValue"&&oe===oe.toUpperCase()}],["none",D=>D.type==="NullValue"],["defined",D=>D.type!=="UndefinedValue"],["undefined",D=>D.type==="UndefinedValue"],["equalto",(D,oe)=>D.value===oe.value],["eq",(D,oe)=>D.value===oe.value]]));this.parent=D}set(D,oe){return this.declareVariable(D,qe(oe))}declareVariable(D,oe){if(this.variables.has(D))throw new SyntaxError(`Variable already declared: ${D}`);return this.variables.set(D,oe),oe}setVariable(D,oe){return this.variables.set(D,oe),oe}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 Fe}catch{return new Fe}}},He=class{constructor(D){Y(this,"global");this.global=D??new Be}run(D){return this.evaluate(D,this.global)}evaluateBinaryExpression(D,oe){const B=this.evaluate(D.left,oe);switch(D.operator.value){case"and":return B.__bool__().value?this.evaluate(D.right,oe):B;case"or":return B.__bool__().value?B:this.evaluate(D.right,oe)}const te=this.evaluate(D.right,oe);switch(D.operator.value){case"==":return new re(B.value==te.value);case"!=":return new re(B.value!=te.value)}if(B instanceof Fe||te instanceof Fe)throw new Error("Cannot perform operation on undefined values");if(B instanceof $e||te instanceof $e)throw new Error("Cannot perform operation on null values");if(B instanceof pe&&te instanceof pe)switch(D.operator.value){case"+":return new pe(B.value+te.value);case"-":return new pe(B.value-te.value);case"*":return new pe(B.value*te.value);case"/":return new pe(B.value/te.value);case"%":return new pe(B.value%te.value);case"<":return new re(B.value":return new re(B.value>te.value);case">=":return new re(B.value>=te.value);case"<=":return new re(B.value<=te.value)}else if(B instanceof we&&te instanceof we)switch(D.operator.value){case"+":return new we(B.value.concat(te.value))}else if(te instanceof we){const me=te.value.find(Oe=>Oe.value===B.value)!==void 0;switch(D.operator.value){case"in":return new re(me);case"not in":return new re(!me)}}if(B instanceof W||te instanceof W)switch(D.operator.value){case"+":return new W(B.value.toString()+te.value.toString())}if(B instanceof W&&te instanceof W)switch(D.operator.value){case"in":return new re(te.value.includes(B.value));case"not in":return new re(!te.value.includes(B.value))}if(B instanceof W&&te instanceof G)switch(D.operator.value){case"in":return new re(te.value.has(B.value));case"not in":return new re(!te.value.has(B.value))}throw new SyntaxError(`Unknown operator "${D.operator.value}" between ${B.type} and ${te.type}`)}evaluateArguments(D,oe){const B=[],te=new Map;for(const me of D)if(me.type==="KeywordArgumentExpression"){const Oe=me;te.set(Oe.key.value,this.evaluate(Oe.value,oe))}else{if(te.size>0)throw new Error("Positional arguments must come before keyword arguments");B.push(this.evaluate(me,oe))}return[B,te]}evaluateFilterExpression(D,oe){const B=this.evaluate(D.operand,oe);if(D.filter.type==="Identifier"){const te=D.filter;if(te.value==="tojson")return new W(ke(B));if(B instanceof we)switch(te.value){case"list":return B;case"first":return B.value[0];case"last":return B.value[B.value.length-1];case"length":return new pe(B.value.length);case"reverse":return new we(B.value.reverse());case"sort":return new we(B.value.sort((me,Oe)=>{if(me.type!==Oe.type)throw new Error(`Cannot compare different types: ${me.type} and ${Oe.type}`);switch(me.type){case"NumericValue":return me.value-Oe.value;case"StringValue":return me.value.localeCompare(Oe.value);default:throw new Error(`Cannot compare type: ${me.type}`)}}));case"join":return new W(B.value.map(me=>me.value).join(""));case"string":return new W(ke(B));default:throw new Error(`Unknown ArrayValue filter: ${te.value}`)}else if(B instanceof W)switch(te.value){case"length":return new pe(B.value.length);case"upper":return new W(B.value.toUpperCase());case"lower":return new W(B.value.toLowerCase());case"title":return new W(le(B.value));case"capitalize":return new W(B.value.charAt(0).toUpperCase()+B.value.slice(1));case"trim":return new W(B.value.trim());case"indent":return new W(B.value.split(` +`).map((me,Oe)=>Oe===0||me.length===0?me:" "+me).join(` +`));case"join":case"string":return B;default:throw new Error(`Unknown StringValue filter: ${te.value}`)}else if(B instanceof pe)switch(te.value){case"abs":return new pe(Math.abs(B.value));default:throw new Error(`Unknown NumericValue filter: ${te.value}`)}else if(B instanceof G)switch(te.value){case"items":return new we(Array.from(B.value.entries()).map(([me,Oe])=>new we([new W(me),Oe])));case"length":return new pe(B.value.size);default:throw new Error(`Unknown ObjectValue filter: ${te.value}`)}throw new Error(`Cannot apply filter "${te.value}" to type: ${B.type}`)}else if(D.filter.type==="CallExpression"){const te=D.filter;if(te.callee.type!=="Identifier")throw new Error(`Unknown filter: ${te.callee.type}`);const me=te.callee.value;if(me==="tojson"){const[,Oe]=this.evaluateArguments(te.args,oe),ve=Oe.get("indent")??new $e;if(!(ve instanceof pe||ve instanceof $e))throw new Error("If set, indent must be a number");return new W(ke(B,ve.value))}else if(me==="join"){let Oe;if(B instanceof W)Oe=Array.from(B.value);else if(B instanceof we)Oe=B.value.map(ht=>ht.value);else throw new Error(`Cannot apply filter "${me}" to type: ${B.type}`);const[ve,vt]=this.evaluateArguments(te.args,oe),Ft=ve.at(0)??vt.get("separator")??new W("");if(!(Ft instanceof W))throw new Error("separator must be a string");return new W(Oe.join(Ft.value))}if(B instanceof we){switch(me){case"selectattr":case"rejectattr":{const Oe=me==="selectattr";if(B.value.some(rt=>!(rt instanceof G)))throw new Error(`\`${me}\` can only be applied to array of objects`);if(te.args.some(rt=>rt.type!=="StringLiteral"))throw new Error(`arguments of \`${me}\` must be strings`);const[ve,vt,Ft]=te.args.map(rt=>this.evaluate(rt,oe));let ht;if(vt){const rt=oe.tests.get(vt.value);if(!rt)throw new Error(`Unknown test: ${vt.value}`);ht=rt}else ht=(...rt)=>rt[0].__bool__().value;const ut=B.value.filter(rt=>{const jt=rt.value.get(ve.value),Ht=jt?ht(jt,Ft):!1;return Oe?Ht:!Ht});return new we(ut)}case"map":{const[,Oe]=this.evaluateArguments(te.args,oe);if(Oe.has("attribute")){const ve=Oe.get("attribute");if(!(ve instanceof W))throw new Error("attribute must be a string");const vt=Oe.get("default"),Ft=B.value.map(ht=>{if(!(ht instanceof G))throw new Error("items in map must be an object");return ht.value.get(ve.value)??vt??new Fe});return new we(Ft)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${me}`)}else if(B instanceof W){switch(me){case"indent":{const[Oe,ve]=this.evaluateArguments(te.args,oe),vt=Oe.at(0)??ve.get("width")??new pe(4);if(!(vt instanceof pe))throw new Error("width must be a number");const Ft=Oe.at(1)??ve.get("first")??new re(!1),ht=Oe.at(2)??ve.get("blank")??new re(!1),ut=B.value.split(` +`),rt=" ".repeat(vt.value),jt=ut.map((Ht,wr)=>!Ft.value&&wr===0||!ht.value&&Ht.length===0?Ht:rt+Ht);return new W(jt.join(` +`))}}throw new Error(`Unknown StringValue filter: ${me}`)}else throw new Error(`Cannot apply filter "${me}" to type: ${B.type}`)}throw new Error(`Unknown filter: ${D.filter.type}`)}evaluateTestExpression(D,oe){const B=this.evaluate(D.operand,oe),te=oe.tests.get(D.test.value);if(!te)throw new Error(`Unknown test: ${D.test.value}`);const me=te(B);return new re(D.negate?!me:me)}evaluateUnaryExpression(D,oe){const B=this.evaluate(D.argument,oe);switch(D.operator.value){case"not":return new re(!B.value);default:throw new SyntaxError(`Unknown operator: ${D.operator.value}`)}}evalProgram(D,oe){return this.evaluateBlock(D.body,oe)}evaluateBlock(D,oe){let B="";for(const te of D){const me=this.evaluate(te,oe);me.type!=="NullValue"&&me.type!=="UndefinedValue"&&(B+=me.value)}return new W(B)}evaluateIdentifier(D,oe){return oe.lookupVariable(D.value)}evaluateCallExpression(D,oe){const[B,te]=this.evaluateArguments(D.args,oe);te.size>0&&B.push(new be(te));const me=this.evaluate(D.callee,oe);if(me.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${me.type}`);return me.value(B,oe)}evaluateSliceExpression(D,oe,B){if(!(D instanceof we||D instanceof W))throw new Error("Slice object must be an array or string");const te=this.evaluate(oe.start,B),me=this.evaluate(oe.stop,B),Oe=this.evaluate(oe.step,B);if(!(te instanceof pe||te instanceof Fe))throw new Error("Slice start must be numeric or undefined");if(!(me instanceof pe||me instanceof Fe))throw new Error("Slice stop must be numeric or undefined");if(!(Oe instanceof pe||Oe instanceof Fe))throw new Error("Slice step must be numeric or undefined");return D instanceof we?new we(_e(D.value,te.value,me.value,Oe.value)):new W(_e(Array.from(D.value),te.value,me.value,Oe.value).join(""))}evaluateMemberExpression(D,oe){const B=this.evaluate(D.object,oe);let te;if(D.computed){if(D.property.type==="SliceExpression")return this.evaluateSliceExpression(B,D.property,oe);te=this.evaluate(D.property,oe)}else te=new W(D.property.value);let me;if(B instanceof G){if(!(te instanceof W))throw new Error(`Cannot access property with non-string: got ${te.type}`);me=B.value.get(te.value)??B.builtins.get(te.value)}else if(B instanceof we||B instanceof W)if(te instanceof pe)me=B.value.at(te.value),B instanceof W&&(me=new W(B.value.at(te.value)));else if(te instanceof W)me=B.builtins.get(te.value);else throw new Error(`Cannot access property with non-string/non-number: got ${te.type}`);else{if(!(te instanceof W))throw new Error(`Cannot access property with non-string: got ${te.type}`);me=B.builtins.get(te.value)}return me instanceof Ue?me:new Fe}evaluateSet(D,oe){const B=D.value?this.evaluate(D.value,oe):this.evaluateBlock(D.body,oe);if(D.assignee.type==="Identifier"){const te=D.assignee.value;oe.setVariable(te,B)}else if(D.assignee.type==="MemberExpression"){const te=D.assignee,me=this.evaluate(te.object,oe);if(!(me instanceof G))throw new Error("Cannot assign to member of non-object");if(te.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");me.value.set(te.property.value,B)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(D.assignee)}`);return new $e}evaluateIf(D,oe){const B=this.evaluate(D.test,oe);return this.evaluateBlock(B.__bool__().value?D.body:D.alternate,oe)}evaluateFor(D,oe){const B=new Be(oe);let te,me;if(D.iterable.type==="SelectExpression"){const ht=D.iterable;me=this.evaluate(ht.iterable,B),te=ht.test}else me=this.evaluate(D.iterable,B);if(!(me instanceof we))throw new Error(`Expected iterable type in for loop: got ${me.type}`);const Oe=[],ve=[];for(let ht=0;htHt.setVariable(D.loopvar.value,rt);else if(D.loopvar.type==="TupleLiteral"){const Ht=D.loopvar;if(rt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${rt.type}`);const wr=rt;if(Ht.value.length!==wr.value.length)throw new Error(`Too ${Ht.value.length>wr.value.length?"few":"many"} items to unpack`);jt=Jt=>{for(let Or=0;Or0?Oe[ht-1]:new Fe],["nextitem",ht{var ve;const me=new Be(te);B=B.slice();let Oe;((ve=B.at(-1))==null?void 0:ve.type)==="KeywordArgumentsValue"&&(Oe=B.pop());for(let vt=0;vtthis.evaluate(B,oe)));case"TupleLiteral":return new Se(D.value.map(B=>this.evaluate(B,oe)));case"ObjectLiteral":{const B=new Map;for(const[te,me]of D.value){const Oe=this.evaluate(te,oe);if(!(Oe instanceof W))throw new Error(`Object keys must be strings: got ${Oe.type}`);B.set(Oe.value,this.evaluate(me,oe))}return new G(B)}case"Identifier":return this.evaluateIdentifier(D,oe);case"CallExpression":return this.evaluateCallExpression(D,oe);case"MemberExpression":return this.evaluateMemberExpression(D,oe);case"UnaryExpression":return this.evaluateUnaryExpression(D,oe);case"BinaryExpression":return this.evaluateBinaryExpression(D,oe);case"FilterExpression":return this.evaluateFilterExpression(D,oe);case"TestExpression":return this.evaluateTestExpression(D,oe);default:throw new SyntaxError(`Unknown node type: ${D.type}`)}}};function qe(D){switch(typeof D){case"number":return new pe(D);case"string":return new W(D);case"boolean":return new re(D);case"undefined":return new Fe;case"object":return D===null?new $e:Array.isArray(D)?new we(D.map(qe)):new G(new Map(Object.entries(D).map(([oe,B])=>[oe,qe(B)])));case"function":return new Ce((oe,B)=>{const te=D(...oe.map(me=>me.value))??null;return qe(te)});default:throw new Error(`Cannot convert to runtime value: ${D}`)}}function ke(D,oe,B){const te=B??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 me=oe?" ".repeat(oe):"",Oe=` +`+me.repeat(te),ve=Oe+me;if(D.type==="ArrayValue"){const vt=D.value.map(Ft=>ke(Ft,oe,te+1));return oe?`[${ve}${vt.join(`,${ve}`)}${Oe}]`:`[${vt.join(", ")}]`}else{const vt=Array.from(D.value.entries()).map(([Ft,ht])=>{const ut=`"${Ft}": ${ke(ht,oe,te+1)}`;return oe?`${ve}${ut}`:ut});return oe?`{${vt.join(",")}${Oe}}`:`{${vt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${D.type}`)}}var Ve=` +`,Ze="{%- ",nt=" -%}",lt={MultiplicativeBinaryOperator:2,AdditiveBinaryOperator:1,ComparisonBinaryOperator:0};function Ge(D,oe=" "){const B=typeof oe=="number"?" ".repeat(oe):oe;return pt(D.body,0,B).replace(/\n$/,"")}function Ie(...D){return Ze+D.join(" ")+nt}function pt(D,oe,B){return D.map(te=>St(te,oe,B)).join(Ve)}function St(D,oe,B){const te=B.repeat(oe);switch(D.type){case"Program":return pt(D.body,oe,B);case"If":return Vt(D,oe,B);case"For":return Rt(D,oe,B);case"Set":return gr(D,oe,B);case"Macro":return ir(D,oe,B);case"Break":return te+Ie("break");case"Continue":return te+Ie("continue");default:return te+"{{- "+Mt(D)+" -}}"}}function Vt(D,oe,B){const te=B.repeat(oe),me=[];let Oe=D;for(;Oe&&(me.push({test:Oe.test,body:Oe.body}),Oe.alternate.length===1&&Oe.alternate[0].type==="If");)Oe=Oe.alternate[0];let ve=te+Ie("if",Mt(me[0].test))+Ve+pt(me[0].body,oe+1,B);for(let vt=1;vt0&&(ve+=Ve+te+Ie("else")+Ve+pt(Oe.alternate,oe+1,B)),ve+=Ve+te+Ie("endif"),ve}function Rt(D,oe,B){const te=B.repeat(oe);let me="";if(D.iterable.type==="SelectExpression"){const ve=D.iterable;me=`${Mt(ve.iterable)} if ${Mt(ve.test)}`}else me=Mt(D.iterable);let Oe=te+Ie("for",Mt(D.loopvar),"in",me)+Ve+pt(D.body,oe+1,B);return D.defaultBlock.length>0&&(Oe+=Ve+te+Ie("else")+Ve+pt(D.defaultBlock,oe+1,B)),Oe+=Ve+te+Ie("endfor"),Oe}function gr(D,oe,B){const te=B.repeat(oe),me=Mt(D.assignee),Oe=D.value?Mt(D.value):"",ve=te+Ie("set",`${me}${D.value?" = "+Oe:""}`);return D.body.length===0?ve:ve+Ve+pt(D.body,oe+1,B)+Ve+te+Ie("endset")}function ir(D,oe,B){const te=B.repeat(oe),me=D.args.map(Mt).join(", ");return te+Ie("macro",`${D.name.value}(${me})`)+Ve+pt(D.body,oe+1,B)+Ve+te+Ie("endmacro")}function Mt(D,oe=-1){switch(D.type){case"Identifier":return D.value;case"NullLiteral":return"none";case"NumericLiteral":case"BooleanLiteral":return`${D.value}`;case"StringLiteral":return JSON.stringify(D.value);case"BinaryExpression":{const B=D,te=lt[B.operator.type]??0,me=Mt(B.left,te),Oe=Mt(B.right,te+1),ve=`${me} ${B.operator.value} ${Oe}`;return teMt(me,-1)).join(", ");return`${Mt(B.callee,-1)}(${te})`}case"MemberExpression":{const B=D;let te=Mt(B.object,-1);B.object.type!=="Identifier"&&(te=`(${te})`);let me=Mt(B.property,-1);return!B.computed&&B.property.type!=="Identifier"&&(me=`(${me})`),B.computed?`${te}[${me}]`:`${te}.${me}`}case"FilterExpression":{const B=D,te=Mt(B.operand,1/0);return B.filter.type==="CallExpression"?`${te} | ${Mt(B.filter,-1)}`:`${te} | ${B.filter.value}`}case"SelectExpression":{const B=D;return`${Mt(B.iterable,-1)} | select(${Mt(B.test,-1)})`}case"TestExpression":{const B=D;return`${Mt(B.operand,-1)} is${B.negate?" not":""} ${B.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const B=D.value.map(me=>Mt(me,-1)),te=D.type==="ArrayLiteral"?"[]":"()";return`${te[0]}${B.join(", ")}${te[1]}`}case"ObjectLiteral":return`{ ${Array.from(D.value.entries()).map(([te,me])=>`${Mt(te,-1)}: ${Mt(me,-1)}`).join(", ")} }`;case"SliceExpression":{const B=D,te=B.start?Mt(B.start,-1):"",me=B.stop?Mt(B.stop,-1):"",Oe=B.step?`:${Mt(B.step,-1)}`:"";return`${te}:${me}${Oe}`}case"KeywordArgumentExpression":{const B=D;return`${B.key.value}=${Mt(B.value,-1)}`}case"If":{const B=D,te=Mt(B.test,-1),me=Mt(B.body[0],0),Oe=Mt(B.alternate[0],-1);return`${me} if ${te} else ${Oe}`}default:throw new Error(`Unknown expression type: ${D.type}`)}}var rs=class{constructor(D){Y(this,"parsed");const oe=c(D,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=U(oe)}render(D){const oe=new Be;if(oe.set("false",!1),oe.set("true",!0),oe.set("raise_exception",me=>{throw new Error(me)}),oe.set("range",ee),D)for(const[me,Oe]of Object.entries(D))oe.set(me,Oe);return new He(oe).run(this.parsed).value}format(D){return Ge(this.parsed,(D==null?void 0:D.indent)||" ")}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>f,isONNXProxy:()=>S,isONNXTensor:()=>w});var o=t("./src/env.js"),n=t("?2ce3"),i=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"}}),u=[];let p,c;const d=Symbol.for("onnxruntime");if(d in globalThis)c=globalThis[d];else if(o.apis.IS_NODE_ENV){switch(c=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else c=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const _=c.InferenceSession;function f(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(v=>["webgpu","cuda","dml","webnn-gpu"].includes(v))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let T=null;async function k(E,v,M){T&&await T;const y=_.create(E,v);T??(T=y);const C=await y;return C.config=M,C}function w(E){return E instanceof c.Tensor}const g=c==null?void 0:c.env;g!=null&&g.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),g.wasm.proxy=!1),g!=null&&g.webgpu&&(g.webgpu.powerPreference="high-performance");function S(){var E;return(E=g==null?void 0:g.wasm)==null?void 0:E.proxy}o.env.backends.onnx=g},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const c=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(c)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} 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:()=>E,center_to_corners_format:()=>c,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>d,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>_});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(v,M,y=0,C=null){const F=v/M;let z=(0,n.bankers_round)(F)*M;return C!==null&&z>C&&(z=Math.floor(F)*M),zM&&A.push(ee)}else{let ee=(0,n.max)(V.data)[1];if(ee===R-1||(U=(0,n.softmax)(V.data),U[ee]le*J[(ye+1)%2])),Q.boxes.push(_e),Q.classes.push(ee),Q.scores.push(U[ee])}}Z.push(Q)}return Z}function _(v,M=null){const y=v.logits,C=y.dims[0];if(M!==null&&M.length!==C)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const F=[];for(let z=0;zJ[A]&&(J[A]=V[A],Q[A]=ae)}const se=new Array(q.dims[0]);for(let ae=0;aeae!==void 0);F.push({segmentation:H,labels:fe})}return F}function f(v,M,y,C){const F=[],z=[],K=[];for(let q=0;qy&&(F.push(Z),z.push(Q),K.push(H))}return[F,z,K]}function T(v,M,y,C=.5,F=.8){const z=[];let K=0,q=0;const R=M[y].data;for(let H=0;H=C&&++q;let Z=K>0&&q>0;return Z&&(Z=K/q>F),[Z,z]}function k(v,M,y,C,F,z=null,K=null){const[q,R]=K??v[0].dims,Z=new o.Tensor("int32",new Int32Array(q*R),[q,R]),H=[];if(K!==null)for(let ae=0;aeQ[U]&&(J[U]=ae,Q[U]=A[U])}let se=0;const fe=Z.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(v,M)/Math.min(v,M)}`);let z=Math.round(v/y)*y,K=Math.round(M/y)*y;if(z*K>F){const q=Math.sqrt(v*M/F);z=Math.floor(v/q/y)*y,K=Math.floor(M/q/y)*y}else if(z*Kz?Z=Math.floor(z*R/F):z>F&&(R=Math.floor(F*Z/z)),await M.resize(Z,R,{resample:C}))}async crop_margin(M,y=200){const C=M.clone().grayscale(),F=(0,n.min)(C.data)[0],K=(0,n.max)(C.data)[0]-F;if(K===0)return M;const q=y/255;let R=C.width,Z=C.height,H=0,J=0;const Q=C.data;for(let se=0;sethis.preprocess(z)));return{pixel_values:(0,o.stack)(C.map(z=>z.pixel_values),0),original_sizes:C.map(z=>z.original_size),reshaped_input_sizes:C.map(z=>z.reshaped_input_size)}}static async from_pretrained(M,y){const C=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,y);return new this(C)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,u){super(),this.config=l,this.components=u}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,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}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,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,c]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(d=>d in this).map(async d=>{const _=await this[d].from_pretrained(l,u);return[d.replace(/_class$/,""),_]})).then(Object.fromEntries)]);return new this(p,c)}}Y(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),Y(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,c){return await(0,o.getModelJSON)(p,"config.json",!0,c)}function i(p){const c={};let d={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":d=i(p.text_config);break;case"moondream1":d=i(p.phi_config);break;case"musicgen":d=i(p.decoder);break;case"multi_modality":d=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":c.num_heads="num_attention_heads",c.num_layers="num_hidden_layers",c.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":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.hidden_size="hidden_size",c.num_attention_heads="num_attention_heads";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.dim_kv="head_dim";break;case"openelm":c.num_heads="num_kv_heads",c.num_layers="num_transformer_layers",c.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":c.num_heads="num_heads",c.num_layers="num_layers",c.hidden_size="hidden_size";break;case"bloom":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="hidden_size";break;case"mpt":c.num_heads="n_heads",c.num_layers="n_layers",c.hidden_size="d_model";break;case"exaone":c.num_heads="num_key_value_heads",c.num_layers="num_layers",c.dim_kv="head_dim",c.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":c.num_decoder_layers="num_decoder_layers",c.num_decoder_heads="num_heads",c.decoder_dim_kv="d_kv",c.num_encoder_layers="num_layers",c.num_encoder_heads="num_heads",c.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":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="d_model",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="d_model";break;case"speecht5":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="hidden_size",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="hidden_size";break;case"trocr":c.num_encoder_layers=c.num_decoder_layers="decoder_layers",c.num_encoder_heads=c.num_decoder_heads="decoder_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="d_model";break;case"musicgen_decoder":c.num_encoder_layers=c.num_decoder_layers="num_hidden_layers",c.num_encoder_heads=c.num_decoder_heads="num_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"moonshine":c.num_decoder_layers="decoder_num_hidden_layers",c.num_decoder_heads="decoder_num_key_value_heads",c.num_encoder_layers="encoder_num_hidden_layers",c.num_encoder_heads="encoder_num_key_value_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const f=i(p.decoder),T="num_decoder_layers"in f,k=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return T?(k.num_decoder_layers=f.num_decoder_layers,k.num_decoder_heads=f.num_decoder_heads,k.decoder_hidden_size=f.decoder_hidden_size,k.num_encoder_layers=f.num_encoder_layers,k.num_encoder_heads=f.num_encoder_heads,k.encoder_hidden_size=f.encoder_hidden_size):(k.num_layers=f.num_layers,k.num_heads=f.num_heads,k.hidden_size=f.hidden_size),k}const _={...d,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const f in c)_[f]=p[c[f]];return _}function a(p,{prefix:c="past_key_values",batch_size:d=1}={}){const _={},f=p.normalized_config;if(f.is_encoder_decoder&&"num_encoder_heads"in f&&"num_decoder_heads"in f){const T=f.encoder_dim_kv??f.encoder_hidden_size/f.num_encoder_heads,k=f.decoder_dim_kv??f.decoder_hidden_size/f.num_decoder_heads,w=[d,f.num_encoder_heads,0,T],g=[d,f.num_decoder_heads,0,k];for(let S=0;S{var C,F;t.r(r),t.d(r,{apis:()=>k,env:()=>M});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((C=self.constructor)==null?void 0:C.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,c=typeof navigator<"u"&&"ml"in navigator,d=typeof process<"u",_=d&&((F=process==null?void 0:process.release)==null?void 0:F.name)==="node",f=!y(s),T=!y(o),k=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:c,IS_PROCESS_AVAILABLE:d,IS_NODE_ENV:_,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:T}),w=f&&T;let g="./";if(w){const z=Object({url:self.location.href}).url;z?g=o.dirname(o.dirname(n.fileURLToPath(z))):typeof __dirname<"u"&&(g=o.dirname(__dirname))}const S=w?o.join(g,"/.cache/"):null,E="/models/",v=w?o.join(g,E):E,M={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:v,useFS:f,useBrowserCache:u,useFSCache:f,cacheDir:S,useCustomCache:!1,customCache:null};function y(z){return Object.keys(z).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){Y(this,"max_length",20);Y(this,"max_new_tokens",null);Y(this,"min_length",0);Y(this,"min_new_tokens",null);Y(this,"early_stopping",!1);Y(this,"max_time",null);Y(this,"do_sample",!1);Y(this,"num_beams",1);Y(this,"num_beam_groups",1);Y(this,"penalty_alpha",null);Y(this,"use_cache",!0);Y(this,"temperature",1);Y(this,"top_k",50);Y(this,"top_p",1);Y(this,"typical_p",1);Y(this,"epsilon_cutoff",0);Y(this,"eta_cutoff",0);Y(this,"diversity_penalty",0);Y(this,"repetition_penalty",1);Y(this,"encoder_repetition_penalty",1);Y(this,"length_penalty",1);Y(this,"no_repeat_ngram_size",0);Y(this,"bad_words_ids",null);Y(this,"force_words_ids",null);Y(this,"renormalize_logits",!1);Y(this,"constraints",null);Y(this,"forced_bos_token_id",null);Y(this,"forced_eos_token_id",null);Y(this,"remove_invalid_values",!1);Y(this,"exponential_decay_length_penalty",null);Y(this,"suppress_tokens",null);Y(this,"streamer",null);Y(this,"begin_suppress_tokens",null);Y(this,"forced_decoder_ids",null);Y(this,"guidance_scale",null);Y(this,"num_return_sequences",1);Y(this,"output_attentions",!1);Y(this,"output_hidden_states",!1);Y(this,"output_scores",!1);Y(this,"return_dict_in_generate",!1);Y(this,"pad_token_id",null);Y(this,"bos_token_id",null);Y(this,"eos_token_id",null);Y(this,"encoder_no_repeat_ngram_size",0);Y(this,"decoder_start_token_id",null);Y(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>T,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>d,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>c});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(M,y){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(M,y){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,y){let C=y;for(const F of this.processors)C=F(M,C);return C}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,y){for(let C=0;C=1&&z[z.length-1]>=this.timestamp_begin,q=z.length<2||z[z.length-2]>=this.timestamp_begin;if(K&&(q?F.subarray(this.timestamp_begin).fill(-1/0):F.subarray(0,this.eos_token_id).fill(-1/0)),M[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;F.subarray(J+1).fill(-1/0)}const R=(0,o.log_softmax)(F),Z=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((J,Q)=>J+Q)),H=(0,o.max)(R.subarray(0,this.timestamp_begin))[0];Z>H&&F.subarray(0,this.timestamp_begin).fill(-1/0)}return y}}class d extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const y=M.length,C=[];for(let z=0;z1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,y){if(y.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 ${y.dims[0]} for the logits and ${M.length} for the input ids.`);const C=M.length,F=y.slice([0,C],null),z=y.slice([C,y.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=M,this.filter_value=y,this.min_tokens_to_keep=C}}class E extends i{constructor(M,{filter_value:y=-1/0,min_tokens_to_keep:C=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,C),this.filter_value=y}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(c){super(),this.generation_config=c}async _call(c){return this.sample(c)}async sample(c){throw Error("sample should be implemented in subclasses.")}getLogits(c,d){let _=c.dims.at(-1),f=c.data;if(d===-1)f=f.slice(-_);else{let T=d*_;f=f.slice(T,T+_)}return f}randomSelect(c){let d=0;for(let f=0;f1)return new u(c);if(c.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${c.num_return_sequences}.`);return new a(c)}}class a extends i{async sample(c){const d=(0,n.max)(c.data)[1];return[[BigInt(d),0]]}}class l extends i{async sample(c){let d=c.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[_,f]=await(0,o.topk)(c,d),T=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(T);return[f.data[k],Math.log(T[k])]})}}class u extends i{async sample(c){let d=c.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[_,f]=await(0,o.topk)(c,d),T=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[f.data[w],Math.log(T[w])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,c){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 o&&(p=[p]),this.criteria.push(...p)}_call(p,c){const d=new Array(p.length).fill(!1);for(const _ of this.criteria){const f=_(p,c);for(let T=0;Tc.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,c){return p.map(d=>{const _=d.at(-1);return this.eos_token_id.some(f=>_==f)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,c){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(c){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 i{constructor(c,{skip_prompt:d=!1,callback_function:_=null,token_callback_function:f=null,skip_special_tokens:T=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=c,this.skip_prompt=d,this.callback_function=_??a,this.token_callback_function=f,this.decode_kwargs={skip_special_tokens:T,...k,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(c){var k;if(c.length>1)throw Error("TextStreamer only supports batch size of 1");const d=this.next_tokens_are_prompt;if(d&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const _=c[0];(k=this.token_callback_function)==null||k.call(this,_),this.token_cache=(0,s.mergeArrays)(this.token_cache,_);const f=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let T;d||f.endsWith(` +`)?(T=f.slice(this.print_len),this.token_cache=[],this.print_len=0):f.length>0&&(0,o.is_chinese_char)(f.charCodeAt(f.length-1))?(T=f.slice(this.print_len),this.print_len+=T.length):(T=f.slice(this.print_len,f.lastIndexOf(" ")+1),this.print_len+=T.length),this.on_finalized_text(T,!1)}end(){let c;this.token_cache.length>0?(c=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):c="",this.next_tokens_are_prompt=!0,this.on_finalized_text(c,!0)}on_finalized_text(c,d){var _,f;c.length>0&&((_=this.callback_function)==null||_.call(this,c)),d&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((f=this.callback_function)==null||f.call(this,` +`))}}class u extends l{constructor(c,{skip_prompt:d=!1,callback_function:_=null,token_callback_function:f=null,on_chunk_start:T=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:g=.02,skip_special_tokens:S=!0,decode_kwargs:E={}}={}){super(c,{skip_prompt:d,skip_special_tokens:S,callback_function:_,token_callback_function:f,decode_kwargs:E}),this.timestamp_begin=c.timestamp_begin,this.on_chunk_start=T,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=g,this.waiting_for_timestamp=!1}put(c){var _,f;if(c.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const d=c[0];if(d.length===1){const T=Number(d[0])-this.timestamp_begin;if(T>=0){const k=T*this.time_precision;this.waiting_for_timestamp?(_=this.on_chunk_end)==null||_.call(this,k):(f=this.on_chunk_start)==null||f.call(this,k),this.waiting_for_timestamp=!this.waiting_for_timestamp,c=[[]]}}return super.put(c)}end(){var c;super.end(),(c=this.on_finalize)==null||c.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Fi,ASTModel:()=>Ai,ASTPreTrainedModel:()=>Eo,AlbertForMaskedLM:()=>X,AlbertForQuestionAnswering:()=>j,AlbertForSequenceClassification:()=>$,AlbertModel:()=>de,AlbertPreTrainedModel:()=>Ds,AutoModel:()=>wc,AutoModelForAudioClassification:()=>P0,AutoModelForAudioFrameClassification:()=>S0,AutoModelForAudioTextToText:()=>z0,AutoModelForCTC:()=>E0,AutoModelForCausalLM:()=>m0,AutoModelForDepthEstimation:()=>A0,AutoModelForDocumentQuestionAnswering:()=>$0,AutoModelForImageClassification:()=>w0,AutoModelForImageFeatureExtraction:()=>D0,AutoModelForImageMatting:()=>k0,AutoModelForImageSegmentation:()=>M0,AutoModelForImageTextToText:()=>L0,AutoModelForImageToImage:()=>I0,AutoModelForMaskGeneration:()=>T0,AutoModelForMaskedLM:()=>f0,AutoModelForNormalEstimation:()=>F0,AutoModelForObjectDetection:()=>v0,AutoModelForPoseEstimation:()=>O0,AutoModelForQuestionAnswering:()=>_0,AutoModelForSemanticSegmentation:()=>b0,AutoModelForSeq2SeqLM:()=>c0,AutoModelForSequenceClassification:()=>l0,AutoModelForSpeechSeq2Seq:()=>d0,AutoModelForTextToSpectrogram:()=>p0,AutoModelForTextToWaveform:()=>h0,AutoModelForTokenClassification:()=>u0,AutoModelForUniversalSegmentation:()=>y0,AutoModelForVision2Seq:()=>g0,AutoModelForXVector:()=>C0,AutoModelForZeroShotObjectDetection:()=>x0,BartForConditionalGeneration:()=>Ut,BartForSequenceClassification:()=>mr,BartModel:()=>Yt,BartPretrainedModel:()=>At,BaseModelOutput:()=>we,BeitForImageClassification:()=>Ww,BeitModel:()=>Uw,BeitPreTrainedModel:()=>Du,BertForMaskedLM:()=>$e,BertForQuestionAnswering:()=>He,BertForSequenceClassification:()=>Fe,BertForTokenClassification:()=>Be,BertModel:()=>Ce,BertPreTrainedModel:()=>Se,BlenderbotForConditionalGeneration:()=>Dr,BlenderbotModel:()=>fr,BlenderbotPreTrainedModel:()=>Kt,BlenderbotSmallForConditionalGeneration:()=>Ir,BlenderbotSmallModel:()=>Jr,BlenderbotSmallPreTrainedModel:()=>Xr,BloomForCausalLM:()=>pw,BloomModel:()=>dw,BloomPreTrainedModel:()=>xu,CLIPModel:()=>Vi,CLIPPreTrainedModel:()=>Ns,CLIPSegForImageSegmentation:()=>Ro,CLIPSegModel:()=>Bo,CLIPSegPreTrainedModel:()=>Qn,CLIPTextModel:()=>pu,CLIPTextModelWithProjection:()=>Ui,CLIPVisionModel:()=>hu,CLIPVisionModelWithProjection:()=>Wi,CamembertForMaskedLM:()=>rt,CamembertForQuestionAnswering:()=>wr,CamembertForSequenceClassification:()=>jt,CamembertForTokenClassification:()=>Ht,CamembertModel:()=>ut,CamembertPreTrainedModel:()=>ht,CausalLMOutput:()=>In,CausalLMOutputWithPast:()=>Jx,ChineseCLIPModel:()=>qn,ChineseCLIPPreTrainedModel:()=>Ki,ClapAudioModelWithProjection:()=>Wb,ClapModel:()=>Vb,ClapPreTrainedModel:()=>ta,ClapTextModelWithProjection:()=>Ub,CodeGenForCausalLM:()=>eo,CodeGenModel:()=>$n,CodeGenPreTrainedModel:()=>Zn,CohereForCausalLM:()=>Kg,CohereModel:()=>Gg,CoherePreTrainedModel:()=>mu,ConvBertForMaskedLM:()=>rs,ConvBertForQuestionAnswering:()=>B,ConvBertForSequenceClassification:()=>D,ConvBertForTokenClassification:()=>oe,ConvBertModel:()=>Mt,ConvBertPreTrainedModel:()=>ir,ConvNextForImageClassification:()=>BM,ConvNextModel:()=>zM,ConvNextPreTrainedModel:()=>Xu,ConvNextV2ForImageClassification:()=>jM,ConvNextV2Model:()=>RM,ConvNextV2PreTrainedModel:()=>Ju,DFineForObjectDetection:()=>sM,DFineModel:()=>rM,DFinePreTrainedModel:()=>Nu,DPTForDepthEstimation:()=>MM,DPTModel:()=>wM,DPTPreTrainedModel:()=>Hu,DacDecoderModel:()=>Ay,DacDecoderOutput:()=>$y,DacEncoderModel:()=>Iy,DacEncoderOutput:()=>Sy,DacModel:()=>ky,DacPreTrainedModel:()=>la,DebertaForMaskedLM:()=>ss,DebertaForQuestionAnswering:()=>$s,DebertaForSequenceClassification:()=>ys,DebertaForTokenClassification:()=>ns,DebertaModel:()=>Or,DebertaPreTrainedModel:()=>Jt,DebertaV2ForMaskedLM:()=>Qr,DebertaV2ForQuestionAnswering:()=>As,DebertaV2ForSequenceClassification:()=>vs,DebertaV2ForTokenClassification:()=>Is,DebertaV2Model:()=>ks,DebertaV2PreTrainedModel:()=>Vr,DecisionTransformerModel:()=>dy,DecisionTransformerPreTrainedModel:()=>cy,DeiTForImageClassification:()=>lM,DeiTModel:()=>aM,DeiTPreTrainedModel:()=>Uu,DepthAnythingForDepthEstimation:()=>yM,DepthAnythingPreTrainedModel:()=>bM,DepthProForDepthEstimation:()=>PM,DepthProPreTrainedModel:()=>EM,DetrForObjectDetection:()=>Kw,DetrForSegmentation:()=>Lu,DetrModel:()=>Gw,DetrObjectDetectionOutput:()=>zu,DetrPreTrainedModel:()=>Qi,DetrSegmentationOutput:()=>Hw,Dinov2ForImageClassification:()=>VM,Dinov2Model:()=>NM,Dinov2PreTrainedModel:()=>Yu,Dinov2WithRegistersForImageClassification:()=>WM,Dinov2WithRegistersModel:()=>UM,Dinov2WithRegistersPreTrainedModel:()=>Zu,DistilBertForMaskedLM:()=>Ae,DistilBertForQuestionAnswering:()=>Br,DistilBertForSequenceClassification:()=>Er,DistilBertForTokenClassification:()=>xs,DistilBertModel:()=>Fs,DistilBertPreTrainedModel:()=>ar,DonutSwinModel:()=>LM,DonutSwinPreTrainedModel:()=>DM,EfficientNetForImageClassification:()=>Jb,EfficientNetModel:()=>Xb,EfficientNetPreTrainedModel:()=>uc,ElectraForMaskedLM:()=>Oe,ElectraForQuestionAnswering:()=>Ft,ElectraForSequenceClassification:()=>ve,ElectraForTokenClassification:()=>vt,ElectraModel:()=>me,ElectraPreTrainedModel:()=>te,EsmForMaskedLM:()=>Nt,EsmForSequenceClassification:()=>os,EsmForTokenClassification:()=>is,EsmModel:()=>it,EsmPreTrainedModel:()=>Je,ExaoneForCausalLM:()=>N,ExaoneModel:()=>L,ExaonePreTrainedModel:()=>I,FalconForCausalLM:()=>Nb,FalconModel:()=>jb,FalconPreTrainedModel:()=>ic,FastViTForImageClassification:()=>Aw,FastViTModel:()=>Iw,FastViTPreTrainedModel:()=>ku,Florence2ForConditionalGeneration:()=>Bi,Florence2PreTrainedModel:()=>Io,GLPNForDepthEstimation:()=>OM,GLPNModel:()=>FM,GLPNPreTrainedModel:()=>Qu,GPT2LMHeadModel:()=>Vo,GPT2Model:()=>No,GPT2PreTrainedModel:()=>jo,GPTBigCodeForCausalLM:()=>Ho,GPTBigCodeModel:()=>Ko,GPTBigCodePreTrainedModel:()=>Sn,GPTJForCausalLM:()=>Go,GPTJModel:()=>Wo,GPTJPreTrainedModel:()=>Yn,GPTNeoForCausalLM:()=>Pn,GPTNeoModel:()=>Uo,GPTNeoPreTrainedModel:()=>Xn,GPTNeoXForCausalLM:()=>Jn,GPTNeoXModel:()=>Cn,GPTNeoXPreTrainedModel:()=>Gr,Gemma2ForCausalLM:()=>Xg,Gemma2Model:()=>Qg,Gemma2PreTrainedModel:()=>_u,Gemma3ForCausalLM:()=>Yg,Gemma3Model:()=>Jg,Gemma3PreTrainedModel:()=>gu,GemmaForCausalLM:()=>qg,GemmaModel:()=>Hg,GemmaPreTrainedModel:()=>fu,GlmForCausalLM:()=>x,GlmModel:()=>h,GlmPreTrainedModel:()=>ro,GraniteForCausalLM:()=>Wg,GraniteModel:()=>qi,GranitePreTrainedModel:()=>Ls,GroundingDinoForObjectDetection:()=>KM,GroundingDinoPreTrainedModel:()=>GM,GroupViTModel:()=>kw,GroupViTPreTrainedModel:()=>$w,HeliumForCausalLM:()=>Jo,HeliumModel:()=>Xo,HeliumPreTrainedModel:()=>to,HieraForImageClassification:()=>cM,HieraModel:()=>uM,HieraPreTrainedModel:()=>Wu,HubertForCTC:()=>vb,HubertForSequenceClassification:()=>xb,HubertModel:()=>yb,HubertPreTrainedModel:()=>zx,IJepaForImageClassification:()=>bw,IJepaModel:()=>Mw,IJepaPreTrainedModel:()=>Cu,Idefics3ForConditionalGeneration:()=>En,Idefics3PreTrainedModel:()=>Hn,ImageMattingOutput:()=>R0,JAISLMHeadModel:()=>Hi,JAISModel:()=>ct,JAISPreTrainedModel:()=>Zs,JinaCLIPModel:()=>Do,JinaCLIPPreTrainedModel:()=>Ys,JinaCLIPTextModel:()=>Lo,JinaCLIPVisionModel:()=>zo,LiteWhisperForConditionalGeneration:()=>So,LlamaForCausalLM:()=>Qo,LlamaModel:()=>qo,LlamaPreTrainedModel:()=>kn,LlavaForConditionalGeneration:()=>Tn,LlavaOnevisionForConditionalGeneration:()=>Qs,LlavaPreTrainedModel:()=>ko,LongT5ForConditionalGeneration:()=>We,LongT5Model:()=>Qe,LongT5PreTrainedModel:()=>Re,M2M100ForConditionalGeneration:()=>rb,M2M100Model:()=>tb,M2M100PreTrainedModel:()=>rc,MBartForCausalLM:()=>Es,MBartForConditionalGeneration:()=>Cr,MBartForSequenceClassification:()=>Zt,MBartModel:()=>Pr,MBartPreTrainedModel:()=>Mr,MPNetForMaskedLM:()=>_n,MPNetForQuestionAnswering:()=>Mn,MPNetForSequenceClassification:()=>gn,MPNetForTokenClassification:()=>wn,MPNetModel:()=>fn,MPNetPreTrainedModel:()=>Ts,MT5ForConditionalGeneration:()=>Ot,MT5Model:()=>_t,MT5PreTrainedModel:()=>Ye,MarianMTModel:()=>eb,MarianModel:()=>ZM,MarianPreTrainedModel:()=>tc,MaskFormerForInstanceSegmentation:()=>AM,MaskFormerModel:()=>IM,MaskFormerPreTrainedModel:()=>qu,MaskedLMOutput:()=>Fr,Metric3DForDepthEstimation:()=>SM,Metric3DPreTrainedModel:()=>CM,Metric3Dv2ForDepthEstimation:()=>kM,Metric3Dv2PreTrainedModel:()=>$M,MgpstrForSceneTextRecognition:()=>_y,MgpstrModelOutput:()=>my,MgpstrPreTrainedModel:()=>fy,MimiDecoderModel:()=>Cy,MimiDecoderOutput:()=>Ty,MimiEncoderModel:()=>Py,MimiEncoderOutput:()=>xy,MimiModel:()=>Ey,MimiPreTrainedModel:()=>aa,MistralForCausalLM:()=>zb,MistralModel:()=>Lb,MistralPreTrainedModel:()=>nc,MobileBertForMaskedLM:()=>cr,MobileBertForQuestionAnswering:()=>ls,MobileBertForSequenceClassification:()=>hr,MobileBertModel:()=>as,MobileBertPreTrainedModel:()=>ur,MobileLLMForCausalLM:()=>Le,MobileLLMModel:()=>Te,MobileLLMPreTrainedModel:()=>ue,MobileNetV1ForImageClassification:()=>Zb,MobileNetV1ForSemanticSegmentation:()=>ey,MobileNetV1Model:()=>Yb,MobileNetV1PreTrainedModel:()=>sa,MobileNetV2ForImageClassification:()=>ry,MobileNetV2ForSemanticSegmentation:()=>sy,MobileNetV2Model:()=>ty,MobileNetV2PreTrainedModel:()=>na,MobileNetV3ForImageClassification:()=>oy,MobileNetV3ForSemanticSegmentation:()=>iy,MobileNetV3Model:()=>ny,MobileNetV3PreTrainedModel:()=>oa,MobileNetV4ForImageClassification:()=>ly,MobileNetV4ForSemanticSegmentation:()=>uy,MobileNetV4Model:()=>ay,MobileNetV4PreTrainedModel:()=>ia,MobileViTForImageClassification:()=>Lw,MobileViTModel:()=>Dw,MobileViTPreTrainedModel:()=>Iu,MobileViTV2ForImageClassification:()=>Bw,MobileViTV2Model:()=>zw,MobileViTV2PreTrainedModel:()=>Au,ModelOutput:()=>be,ModernBertForMaskedLM:()=>Ve,ModernBertForSequenceClassification:()=>Ze,ModernBertForTokenClassification:()=>nt,ModernBertModel:()=>ke,ModernBertPreTrainedModel:()=>qe,Moondream1ForConditionalGeneration:()=>zi,MoonshineForConditionalGeneration:()=>Li,MoonshineModel:()=>Di,MoonshinePreTrainedModel:()=>Kn,MptForCausalLM:()=>mw,MptModel:()=>hw,MptPreTrainedModel:()=>Tu,MultiModalityCausalLM:()=>hy,MultiModalityPreTrainedModel:()=>py,MusicgenForCausalLM:()=>Nx,MusicgenForConditionalGeneration:()=>dc,MusicgenModel:()=>jx,MusicgenPreTrainedModel:()=>cc,NomicBertModel:()=>Ge,NomicBertPreTrainedModel:()=>lt,OPTForCausalLM:()=>_w,OPTModel:()=>fw,OPTPreTrainedModel:()=>Eu,Olmo2ForCausalLM:()=>yr,Olmo2Model:()=>Wt,Olmo2PreTrainedModel:()=>kt,OlmoForCausalLM:()=>bt,OlmoModel:()=>tt,OlmoPreTrainedModel:()=>Ke,OpenELMForCausalLM:()=>ew,OpenELMModel:()=>Zg,OpenELMPreTrainedModel:()=>wu,OwlViTForObjectDetection:()=>jw,OwlViTModel:()=>Rw,OwlViTPreTrainedModel:()=>Fu,Owlv2ForObjectDetection:()=>Vw,Owlv2Model:()=>Nw,Owlv2PreTrainedModel:()=>Ou,PaliGemmaForConditionalGeneration:()=>ji,PaliGemmaPreTrainedModel:()=>Ri,PatchTSMixerForPrediction:()=>by,PatchTSMixerModel:()=>My,PatchTSMixerPreTrainedModel:()=>hc,PatchTSTForPrediction:()=>wy,PatchTSTModel:()=>gy,PatchTSTPreTrainedModel:()=>pc,Phi3ForCausalLM:()=>cw,Phi3Model:()=>uw,Phi3PreTrainedModel:()=>vu,Phi3VForCausalLM:()=>Fo,Phi3VPreTrainedModel:()=>Ni,PhiForCausalLM:()=>lw,PhiModel:()=>aw,PhiPreTrainedModel:()=>yu,PreTrainedModel:()=>G,PretrainedMixin:()=>Lt,PvtForImageClassification:()=>Tw,PvtModel:()=>xw,PvtPreTrainedModel:()=>Su,PyAnnoteForAudioFrameClassification:()=>lb,PyAnnoteModel:()=>ab,PyAnnotePreTrainedModel:()=>sc,QuestionAnsweringModelOutput:()=>Rr,Qwen2ForCausalLM:()=>rw,Qwen2Model:()=>tw,Qwen2PreTrainedModel:()=>Mu,Qwen2VLForConditionalGeneration:()=>iw,Qwen2VLPreTrainedModel:()=>ow,Qwen3ForCausalLM:()=>nw,Qwen3Model:()=>sw,Qwen3PreTrainedModel:()=>bu,RFDetrForObjectDetection:()=>eM,RFDetrModel:()=>Zw,RFDetrObjectDetectionOutput:()=>tM,RFDetrPreTrainedModel:()=>ju,RTDetrForObjectDetection:()=>Qw,RTDetrModel:()=>qw,RTDetrObjectDetectionOutput:()=>Yo,RTDetrPreTrainedModel:()=>Bu,RTDetrV2ForObjectDetection:()=>Jw,RTDetrV2Model:()=>Xw,RTDetrV2ObjectDetectionOutput:()=>Yw,RTDetrV2PreTrainedModel:()=>Ru,ResNetForImageClassification:()=>pM,ResNetModel:()=>dM,ResNetPreTrainedModel:()=>Gu,RoFormerForMaskedLM:()=>St,RoFormerForQuestionAnswering:()=>gr,RoFormerForSequenceClassification:()=>Vt,RoFormerForTokenClassification:()=>Rt,RoFormerModel:()=>pt,RoFormerPreTrainedModel:()=>Ie,RobertaForMaskedLM:()=>er,RobertaForQuestionAnswering:()=>Ar,RobertaForSequenceClassification:()=>dr,RobertaForTokenClassification:()=>pr,RobertaModel:()=>br,RobertaPreTrainedModel:()=>Lr,SamImageSegmentationOutput:()=>YM,SamModel:()=>JM,SamPreTrainedModel:()=>XM,SapiensForDepthEstimation:()=>xM,SapiensForNormalEstimation:()=>TM,SapiensForSemanticSegmentation:()=>vM,SapiensPreTrainedModel:()=>Ji,SegformerForImageClassification:()=>Kb,SegformerForSemanticSegmentation:()=>Hb,SegformerModel:()=>Rx,SegformerPreTrainedModel:()=>ra,Seq2SeqLMOutput:()=>Xx,SequenceClassifierOutput:()=>xt,SiglipModel:()=>Js,SiglipPreTrainedModel:()=>Xs,SiglipTextModel:()=>Oo,SiglipVisionModel:()=>Gi,SmolVLMForConditionalGeneration:()=>Ao,SnacDecoderModel:()=>Dy,SnacEncoderModel:()=>Oy,SnacModel:()=>Fy,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>Ib,SpeechT5ForTextToSpeech:()=>Ab,SpeechT5HifiGan:()=>Fb,SpeechT5Model:()=>Bx,SpeechT5PreTrainedModel:()=>ea,SqueezeBertForMaskedLM:()=>bn,SqueezeBertForQuestionAnswering:()=>vn,SqueezeBertForSequenceClassification:()=>yn,SqueezeBertModel:()=>Hs,SqueezeBertPreTrainedModel:()=>Os,StableLmForCausalLM:()=>Qb,StableLmModel:()=>qb,StableLmPreTrainedModel:()=>lc,Starcoder2ForCausalLM:()=>Rb,Starcoder2Model:()=>Bb,Starcoder2PreTrainedModel:()=>oc,StyleTextToSpeech2Model:()=>kb,StyleTextToSpeech2PreTrainedModel:()=>$b,Swin2SRForImageSuperResolution:()=>gM,Swin2SRModel:()=>_M,Swin2SRPreTrainedModel:()=>Ku,SwinForImageClassification:()=>mM,SwinForSemanticSegmentation:()=>fM,SwinModel:()=>hM,SwinPreTrainedModel:()=>Xi,T5ForConditionalGeneration:()=>xe,T5Model:()=>ce,T5PreTrainedModel:()=>ie,TableTransformerForObjectDetection:()=>oM,TableTransformerModel:()=>nM,TableTransformerObjectDetectionOutput:()=>iM,TableTransformerPreTrainedModel:()=>Vu,TokenClassifierOutput:()=>Sr,TrOCRForCausalLM:()=>Db,TrOCRPreTrainedModel:()=>Ob,UltravoxModel:()=>vy,UltravoxPreTrainedModel:()=>yy,UniSpeechForCTC:()=>pb,UniSpeechForSequenceClassification:()=>hb,UniSpeechModel:()=>db,UniSpeechPreTrainedModel:()=>Yi,UniSpeechSatForAudioFrameClassification:()=>gb,UniSpeechSatForCTC:()=>fb,UniSpeechSatForSequenceClassification:()=>_b,UniSpeechSatModel:()=>mb,UniSpeechSatPreTrainedModel:()=>Zo,ViTForImageClassification:()=>ww,ViTMAEModel:()=>Pw,ViTMAEPreTrainedModel:()=>Ew,ViTMSNForImageClassification:()=>Sw,ViTMSNModel:()=>Cw,ViTMSNPreTrainedModel:()=>$u,ViTModel:()=>gw,ViTPreTrainedModel:()=>Pu,VisionEncoderDecoderModel:()=>$o,VitMatteForImageMatting:()=>Ow,VitMattePreTrainedModel:()=>Fw,VitPoseForPoseEstimation:()=>vw,VitPosePreTrainedModel:()=>yw,VitsModel:()=>ac,VitsModelOutput:()=>j0,VitsPreTrainedModel:()=>Gb,Wav2Vec2BertForCTC:()=>Mb,Wav2Vec2BertForSequenceClassification:()=>bb,Wav2Vec2BertModel:()=>wb,Wav2Vec2BertPreTrainedModel:()=>Zi,Wav2Vec2ForAudioFrameClassification:()=>ib,Wav2Vec2ForCTC:()=>nb,Wav2Vec2ForSequenceClassification:()=>ob,Wav2Vec2Model:()=>sb,Wav2Vec2PreTrainedModel:()=>en,WavLMForAudioFrameClassification:()=>Sb,WavLMForCTC:()=>Eb,WavLMForSequenceClassification:()=>Pb,WavLMForXVector:()=>Cb,WavLMModel:()=>Tb,WavLMPreTrainedModel:()=>so,WeSpeakerResNetModel:()=>cb,WeSpeakerResNetPreTrainedModel:()=>ub,WhisperForConditionalGeneration:()=>Co,WhisperModel:()=>Oi,WhisperPreTrainedModel:()=>Po,XLMForQuestionAnswering:()=>To,XLMForSequenceClassification:()=>Ei,XLMForTokenClassification:()=>Pi,XLMModel:()=>xn,XLMPreTrainedModel:()=>us,XLMRobertaForMaskedLM:()=>Si,XLMRobertaForQuestionAnswering:()=>Ii,XLMRobertaForSequenceClassification:()=>$i,XLMRobertaForTokenClassification:()=>ki,XLMRobertaModel:()=>Ci,XLMRobertaPreTrainedModel:()=>qs,XLMWithLMHeadModel:()=>Ti,XVectorOutput:()=>B0,YolosForObjectDetection:()=>qM,YolosModel:()=>HM,YolosObjectDetectionOutput:()=>QM,YolosPreTrainedModel:()=>ec});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),c=t("./src/generation/configuration_utils.js"),d=t("./src/utils/tensor.js"),_=t("./src/utils/image.js"),f=t("./src/utils/maths.js"),T=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),g=t("./src/models/whisper/generation_whisper.js"),S=t("./src/models/whisper/common_whisper.js");const E={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},v=new Map,M=new Map,y=new Map;async function C(b,P,O){var $r;let ne=(($r=O.config)==null?void 0:$r["transformers.js_config"])??{},ge=O.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const he=ge??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ee=(0,o.deviceToExecutionProviders)(he),De=ne.device_config??{};De.hasOwnProperty(he)&&(ne={...ne,...De[he]});let Ne=O.dtype??ne.dtype;if(typeof Ne!="string"&&(Ne&&Ne.hasOwnProperty(P)?Ne=Ne[P]:(Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${Ne}) for this device (${he}).`))),Ne===n.DATA_TYPES.auto){let Ct=ne.dtype;typeof Ct!="string"&&(Ct=Ct==null?void 0:Ct[P]),Ct&&Ct!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Ct)?Ne=Ct:Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32}const Xe=Ne;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Xe)){if(Xe===n.DATA_TYPES.fp16&&he==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${he}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Xe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const mt=ne.kv_cache_dtype,wt=mt?typeof mt=="string"?mt:mt[Xe]??"float32":void 0;if(wt&&!["float32","float16"].includes(wt))throw new Error(`Invalid kv_cache_dtype: ${wt}. Should be one of: float32, float16`);const dt={dtype:Xe,kv_cache_dtype:wt,device:he},Pt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Xe],gt=`${P}${Pt}.onnx`,Et=`${O.subfolder??""}/${gt}`,ot={...O.session_options};ot.executionProviders??(ot.executionProviders=Ee);const $t=ne.free_dimension_overrides;$t?ot.freeDimensionOverrides??(ot.freeDimensionOverrides=$t):he.startsWith("webnn")&&!ot.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${he}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const qt=w.apis.IS_NODE_ENV&&w.env.useFSCache,tr=(0,l.getModelFile)(b,Et,!0,O,qt),lr=O.use_external_data_format??ne.use_external_data_format;let nr=[];if(lr){let Ct;typeof lr=="object"?lr.hasOwnProperty(gt)?Ct=lr[gt]:lr.hasOwnProperty(P)?Ct=lr[P]:Ct=!1:Ct=lr;const vr=+Ct;if(vr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${vr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Yr=0;Yr{const Fn=await(0,l.getModelFile)(b,Ur,!0,O,qt);cs(Fn instanceof Uint8Array?{path:An,data:Fn}:An)}))}}else ot.externalData!==void 0&&(nr=ot.externalData.map(async Ct=>{if(typeof Ct.data=="string"){const vr=await(0,l.getModelFile)(b,Ct.data,!0,O);return{...Ct,data:vr}}return Ct}));if(nr.length>0){const Ct=await Promise.all(nr);w.apis.IS_NODE_ENV||(ot.externalData=Ct)}if(he==="webgpu"){const Ct=(0,s.getKeyValueShapes)(O.config,{prefix:"present"});if(Object.keys(Ct).length>0&&!(0,o.isONNXProxy)()){const vr={};for(const Yr in Ct)vr[Yr]="gpu-buffer";ot.preferredOutputLocation=vr}}return{buffer_or_path:await tr,session_options:ot,session_config:dt}}async function F(b,P,O){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:he,session_config:Ee}=await C(b,P[ne],O),De=await(0,o.createInferenceSession)(ge,he,Ee);return[ne,De]})))}async function z(b,P,O){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(b,P[ne],!1,O);return[ne,ge]})))}function K(b,P){const O=Object.create(null),ne=[];for(const Ee of b.inputNames){const De=P[Ee];if(!(De instanceof d.Tensor)){ne.push(Ee);continue}O[Ee]=(0,o.isONNXProxy)()?De.clone():De}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,he=b.inputNames.length;if(ge>he){let Ee=Object.keys(P).filter(De=>!b.inputNames.includes(De));console.warn(`WARNING: Too many inputs were provided (${ge} > ${he}). The following inputs will be ignored: "${Ee.join(", ")}".`)}return O}let q=Promise.resolve();async function R(b,P){const O=K(b,P);try{const ne=Object.fromEntries(Object.entries(O).map(([Ee,De])=>[Ee,De.ort_tensor])),ge=()=>b.run(ne),he=await(w.apis.IS_BROWSER_ENV||w.apis.IS_WEBWORKER_ENV?q=q.then(ge):ge());return Z(he)}catch(ne){const ge=Object.fromEntries(Object.entries(O).map(([he,Ee])=>{const De={type:Ee.type,dims:Ee.dims,location:Ee.location};return De.location!=="gpu-buffer"&&(De.data=Ee.data),[he,De]}));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function Z(b){for(let P in b)(0,o.isONNXTensor)(b[P])?b[P]=new d.Tensor(b[P]):typeof b[P]=="object"&&Z(b[P]);return b}function H(b){if(b instanceof d.Tensor)return b;if(b.length===0)throw Error("items must be non-empty");if(Array.isArray(b[0])){if(b.some(P=>P.length!==b[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 d.Tensor("int64",BigInt64Array.from(b.flat().map(P=>BigInt(P))),[b.length,b[0].length])}else return new d.Tensor("int64",BigInt64Array.from(b.map(P=>BigInt(P))),[1,b.length])}function J(b){return new d.Tensor("bool",[b],[1])}async function Q(b,P){let{encoder_outputs:O,input_ids:ne,decoder_input_ids:ge,...he}=P;if(!O){const De=(0,a.pick)(P,b.sessions.model.inputNames);O=(await se(b,De)).last_hidden_state}return he.input_ids=ge,he.encoder_hidden_states=O,b.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(he.encoder_attention_mask=P.attention_mask),await ae(b,he,!0)}async function se(b,P){const O=b.sessions.model,ne=(0,a.pick)(P,O.inputNames);if(O.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await b.encode_text({input_ids:P.input_ids})}if(O.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,d.zeros_like)(ne.input_ids)}if(O.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=ne.pixel_values.dims;ne.pixel_mask=(0,d.ones)([ge[0],ge[2],ge[3]])}return await R(O,ne)}async function fe(b,P){const O=await b.encode(P);return await b.decode(O)}async function ae(b,P,O=!1){const ne=b.sessions[O?"decoder_model_merged":"model"],{past_key_values:ge,...he}=P;if(ne.inputNames.includes("use_cache_branch")&&(he.use_cache_branch=J(!!ge)),ne.inputNames.includes("position_ids")&&he.attention_mask&&!he.position_ids){const De=["paligemma","gemma3_text","gemma3"].includes(b.config.model_type)?1:0;he.position_ids=ze(he,ge,De)}b.addPastKeyValues(he,ge);const Ee=(0,a.pick)(he,ne.inputNames);return await R(ne,Ee)}function V({modality_token_id:b,inputs_embeds:P,modality_features:O,input_ids:ne,attention_mask:ge}){const he=ne.tolist().map(Xe=>Xe.reduce((mt,wt,dt)=>(wt==b&&mt.push(dt),mt),[])),Ee=he.reduce((Xe,mt)=>Xe+mt.length,0),De=O.dims[0];if(Ee!==De)throw new Error(`Number of tokens and features do not match: tokens: ${Ee}, features ${De}`);let Ne=0;for(let Xe=0;Xehe.dims[1])){if(geDe==b.config.image_token_index)){const De=b.config.num_image_tokens;if(!De)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ne=he.dims[1]-(ge-De);O.input_ids=he.slice(null,[-Ne,null]),O.attention_mask=(0,d.ones)([1,ge+Ne])}}}return O}function pe(b,P,O,ne){return O.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...O,decoder_input_ids:H(P)}}function W(b,...P){return b.config.is_encoder_decoder?pe(b,...P):Ue(b,...P)}function re(b,P,O,ne){const ge=!!O.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?O.input_ids=(0,d.cat)([O.input_ids,O.input_ids],0):(O.input_ids=(0,d.cat)([O.input_ids,(0,d.full_like)(O.input_ids,BigInt(ne.pad_token_id))],0),O.attention_mask=(0,d.cat)([O.attention_mask,(0,d.full_like)(O.attention_mask,0n)],0))),(ge||!O.pixel_values)&&(O.pixel_values=(0,d.full)([0,0,3,384,384],1)),ge&&(O.images_seq_mask=new d.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),O.images_emb_mask=new d.Tensor("bool",new Array(0).fill(!1),[1,1,0])),O}class G extends i.Callable{constructor(O,ne,ge){super();Y(this,"main_input_name","input_ids");Y(this,"forward_params",["input_ids","attention_mask"]);this.config=O,this.sessions=ne,this.configs=ge;const he=y.get(this.constructor),Ee=v.get(he);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ee){case E.DecoderOnly:this.can_generate=!0,this._forward=ae,this._prepare_inputs_for_generation=Ue;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Q,this._prepare_inputs_for_generation=pe;break;case E.EncoderDecoder:this._forward=Q;break;case E.ImageTextToText:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=W;break;case E.AudioTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=W;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=W;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=re;break;case E.AutoEncoder:this._forward=fe;break;default:this._forward=se;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const O=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&O.push(ge.handler.dispose());return await Promise.all(O)}static async from_pretrained(O,{progress_callback:ne=null,config:ge=null,cache_dir:he=null,local_files_only:Ee=!1,revision:De="main",model_file_name:Ne=null,subfolder:Xe="onnx",device:mt=null,dtype:wt=null,use_external_data_format:dt=null,session_options:Pt={}}={}){let gt={progress_callback:ne,config:ge,cache_dir:he,local_files_only:Ee,revision:De,model_file_name:Ne,subfolder:Xe,device:mt,dtype:wt,use_external_data_format:dt,session_options:Pt};const Et=y.get(this),ot=v.get(Et);ge=gt.config=await s.AutoConfig.from_pretrained(O,gt);let $t;if(ot===E.DecoderOnly)$t=await Promise.all([F(O,{model:gt.model_file_name??"model"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(ot===E.Seq2Seq||ot===E.Vision2Seq)$t=await Promise.all([F(O,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(ot===E.MaskGeneration)$t=await Promise.all([F(O,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},gt)]);else if(ot===E.EncoderDecoder)$t=await Promise.all([F(O,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},gt)]);else if(ot===E.ImageTextToText){const qt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(qt.model="encoder_model"),$t=await Promise.all([F(O,qt,gt),z(O,{generation_config:"generation_config.json"},gt)])}else if(ot===E.AudioTextToText){const qt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};$t=await Promise.all([F(O,qt,gt),z(O,{generation_config:"generation_config.json"},gt)])}else if(ot===E.Musicgen)$t=await Promise.all([F(O,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(ot===E.MultiModality)$t=await Promise.all([F(O,{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"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(ot===E.Phi3V)$t=await Promise.all([F(O,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},gt),z(O,{generation_config:"generation_config.json"},gt)]);else if(ot===E.AutoEncoder)$t=await Promise.all([F(O,{encoder_model:"encoder_model",decoder_model:"decoder_model"},gt)]);else{if(ot!==E.EncoderOnly){const qt=Et??(ge==null?void 0:ge.model_type);qt!=="custom"&&console.warn(`Model type for '${qt}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}$t=await Promise.all([F(O,{model:gt.model_file_name??"model"},gt)])}return new this(ge,...$t)}async _call(O){return await this.forward(O)}async forward(O){return await this._forward(this,O)}get generation_config(){var O;return((O=this.configs)==null?void 0:O.generation_config)??null}_get_logits_warper(O){const ne=new p.LogitsProcessorList;return O.temperature!==null&&O.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(O.temperature)),O.top_k!==null&&O.top_k!==0&&ne.push(new p.TopKLogitsWarper(O.top_k)),O.top_p!==null&&O.top_p<1&&ne.push(new p.TopPLogitsWarper(O.top_p)),ne}_get_logits_processor(O,ne,ge=null){const he=new p.LogitsProcessorList;if(O.repetition_penalty!==null&&O.repetition_penalty!==1&&he.push(new p.RepetitionPenaltyLogitsProcessor(O.repetition_penalty)),O.no_repeat_ngram_size!==null&&O.no_repeat_ngram_size>0&&he.push(new p.NoRepeatNGramLogitsProcessor(O.no_repeat_ngram_size)),O.bad_words_ids!==null&&he.push(new p.NoBadWordsLogitsProcessor(O.bad_words_ids,O.eos_token_id)),O.min_length!==null&&O.eos_token_id!==null&&O.min_length>0&&he.push(new p.MinLengthLogitsProcessor(O.min_length,O.eos_token_id)),O.min_new_tokens!==null&&O.eos_token_id!==null&&O.min_new_tokens>0&&he.push(new p.MinNewTokensLengthLogitsProcessor(ne,O.min_new_tokens,O.eos_token_id)),O.forced_bos_token_id!==null&&he.push(new p.ForcedBOSTokenLogitsProcessor(O.forced_bos_token_id)),O.forced_eos_token_id!==null&&he.push(new p.ForcedEOSTokenLogitsProcessor(O.max_length,O.forced_eos_token_id)),O.begin_suppress_tokens!==null){const Ee=ne>1||O.forced_bos_token_id===null?ne:ne+1;he.push(new p.SuppressTokensAtBeginLogitsProcessor(O.begin_suppress_tokens,Ee))}return O.guidance_scale!==null&&O.guidance_scale>1&&he.push(new p.ClassifierFreeGuidanceLogitsProcessor(O.guidance_scale)),ge!==null&&he.extend(ge),he}_prepare_generation_config(O,ne,ge=c.GenerationConfig){const he={...this.config};for(const De of["decoder","generator","text_config"])De in he&&Object.assign(he,he[De]);const Ee=new ge(he);return Object.assign(Ee,this.generation_config??{}),O&&Object.assign(Ee,O),ne&&Object.assign(Ee,(0,a.pick)(ne,Object.getOwnPropertyNames(Ee))),Ee}_get_stopping_criteria(O,ne=null){const ge=new T.StoppingCriteriaList;return O.max_length!==null&&ge.push(new T.MaxLengthCriteria(O.max_length,this.config.max_position_embeddings??null)),O.eos_token_id!==null&&ge.push(new T.EosTokenCriteria(O.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const O=[_c,gc,fc,mc],ne=y.get(this.constructor),ge=new Set,he=this.config.model_type;for(const De of O){const Ne=De.get(he);Ne&&ge.add(Ne[0])}let Ee=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ee+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ee)}}prepare_inputs_for_generation(...O){return this._prepare_inputs_for_generation(this,...O)}_update_model_kwargs_for_generation({generated_input_ids:O,outputs:ne,model_inputs:ge,is_encoder_decoder:he}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new d.Tensor("int64",O.flat(),[O.length,1]),he||(ge.attention_mask=(0,d.cat)([ge.attention_mask,(0,d.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:O,bos_token_id:ne,model_kwargs:ge}){const he=(0,a.pick)(ge,this.forward_params),Ee=this.main_input_name;if(Ee in he){if(O)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else he[Ee]=O;return{inputs_tensor:he[Ee],model_inputs:he,model_input_name:Ee}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:O,model_inputs:ne,model_input_name:ge,generation_config:he}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:De,pixel_values:Ne,attention_mask:Xe,...mt}=ne,wt=await this._prepare_inputs_embeds(ne);ne={...mt,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ee}=await se(this,ne);if(he.guidance_scale!==null&&he.guidance_scale>1)Ee=(0,d.cat)([Ee,(0,d.full_like)(Ee,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,d.cat)([ne.attention_mask,(0,d.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const De=H(ne.decoder_input_ids).dims[0];if(De!==Ee.dims[0]){if(Ee.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ee.dims[0]}) than the decoder inputs (${De}).`);Ee=(0,d.cat)(Array.from({length:De},()=>Ee),0)}}return ne.encoder_outputs=Ee,ne}_prepare_decoder_input_ids_for_generation({batch_size:O,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:he,bos_token_id:Ee,generation_config:De}){let{decoder_input_ids:Ne,...Xe}=ge;if(!(Ne instanceof d.Tensor)){if(Ne)Array.isArray(Ne[0])||(Ne=Array.from({length:O},()=>Ne));else if(he??(he=Ee),this.config.model_type==="musicgen")Ne=Array.from({length:O*this.config.decoder.num_codebooks},()=>[he]);else if(Array.isArray(he)){if(he.length!==O)throw new Error(`\`decoder_start_token_id\` expcted to have length ${O} but got ${he.length}`);Ne=he}else Ne=Array.from({length:O},()=>[he]);Ne=H(Ne)}return ge.decoder_attention_mask=(0,d.ones_like)(Ne),{input_ids:Ne,model_inputs:Xe}}async generate({inputs:O=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:he=null,streamer:Ee=null,...De}){this._validate_model_class(),ne=this._prepare_generation_config(ne,De);let{inputs_tensor:Ne,model_inputs:Xe,model_input_name:mt}=this._prepare_model_inputs({inputs:O,model_kwargs:De});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Xe||(Xe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ne,model_inputs:Xe,model_input_name:mt,generation_config:ne})));let dt;wt?{input_ids:dt,model_inputs:Xe}=this._prepare_decoder_input_ids_for_generation({batch_size:Xe[mt].dims.at(0),model_input_name:mt,model_kwargs:Xe,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):dt=Xe[mt];let Pt=dt.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=Pt+ne.max_new_tokens);const gt=this._get_logits_processor(ne,Pt,ge),Et=this._get_stopping_criteria(ne,he),ot=Xe[mt].dims.at(0),$t=k.LogitsSampler.getSampler(ne),qt=new Array(ot).fill(0),tr=dt.tolist();Ee&&Ee.put(tr);let lr,nr={};for(;;){if(Xe=this.prepare_inputs_for_generation(tr,Xe,ne),lr=await this.forward(Xe),ne.output_attentions&&ne.return_dict_in_generate){const Ur=this.getAttentions(lr);for(const cs in Ur)cs in nr||(nr[cs]=[]),nr[cs].push(Ur[cs])}const Ct=lr.logits.slice(null,-1,null),vr=gt(tr,Ct),Yr=[];for(let Ur=0;UrUr))break;Xe=this._update_model_kwargs_for_generation({generated_input_ids:Yr,outputs:lr,model_inputs:Xe,is_encoder_decoder:wt})}Ee&&Ee.end();const _r=this.getPastKeyValues(lr,Xe.past_key_values,!0),$r=new d.Tensor("int64",tr.flat(),[tr.length,tr[0].length]);if(ne.return_dict_in_generate)return{sequences:$r,past_key_values:_r,...nr};for(const Ct of Object.values(lr))Ct.location==="gpu-buffer"&&Ct.dispose();return $r}getPastKeyValues(O,ne,ge=!1){const he=Object.create(null);for(const Ee in O)if(Ee.startsWith("present")){const De=Ee.replace("present","past_key_values"),Ne=Ee.includes("encoder");if(Ne&&ne?he[De]=ne[De]:he[De]=O[Ee],ne&&(!Ne||ge)){const Xe=ne[De];Xe.location==="gpu-buffer"&&Xe.dispose()}}return he}getAttentions(O){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const he in O)he.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(O[he]));return ne}addPastKeyValues(O,ne){var ge,he,Ee;if(ne)Object.assign(O,ne);else{const De=this.sessions.decoder_model_merged??this.sessions.model,Ne=((ge=De==null?void 0:De.config)==null?void 0:ge.kv_cache_dtype)??"float32",Xe=Ne==="float16"?new d.DataTypeMap.float16:[],mt=((Ee=(he=O[this.main_input_name]??O.attention_mask)==null?void 0:he.dims)==null?void 0:Ee[0])??1,wt=(0,s.getKeyValueShapes)(this.config,{batch_size:mt});for(const dt in wt)O[dt]=new d.Tensor(Ne,Xe,wt[dt])}}async encode_image({pixel_values:O}){const ne=(await R(this.sessions.vision_encoder,{pixel_values:O})).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 (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:O}){return(await R(this.sessions.embed_tokens,{input_ids:O})).inputs_embeds}async encode_audio({audio_values:O}){return(await R(this.sessions.audio_encoder,{audio_values:O})).audio_features}}class be{}class we extends be{constructor({last_hidden_state:P,hidden_states:O=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=O,this.attentions=ne}}class Se extends G{}class Ce extends Se{}class $e extends Se{async _call(P){return new Fr(await super._call(P))}}class Fe extends Se{async _call(P){return new xt(await super._call(P))}}class Be extends Se{async _call(P){return new Sr(await super._call(P))}}class He extends Se{async _call(P){return new Rr(await super._call(P))}}class qe extends G{}class ke extends qe{}class Ve extends qe{async _call(P){return new Fr(await super._call(P))}}class Ze extends qe{async _call(P){return new xt(await super._call(P))}}class nt extends qe{async _call(P){return new Sr(await super._call(P))}}class lt extends G{}class Ge extends lt{}class Ie extends G{}class pt extends Ie{}class St extends Ie{async _call(P){return new Fr(await super._call(P))}}class Vt extends Ie{async _call(P){return new xt(await super._call(P))}}class Rt extends Ie{async _call(P){return new Sr(await super._call(P))}}class gr extends Ie{async _call(P){return new Rr(await super._call(P))}}class ir extends G{}class Mt extends ir{}class rs extends ir{async _call(P){return new Fr(await super._call(P))}}class D extends ir{async _call(P){return new xt(await super._call(P))}}class oe extends ir{async _call(P){return new Sr(await super._call(P))}}class B extends ir{async _call(P){return new Rr(await super._call(P))}}class te extends G{}class me extends te{}class Oe extends te{async _call(P){return new Fr(await super._call(P))}}class ve extends te{async _call(P){return new xt(await super._call(P))}}class vt extends te{async _call(P){return new Sr(await super._call(P))}}class Ft extends te{async _call(P){return new Rr(await super._call(P))}}class ht extends G{}class ut extends ht{}class rt extends ht{async _call(P){return new Fr(await super._call(P))}}class jt extends ht{async _call(P){return new xt(await super._call(P))}}class Ht extends ht{async _call(P){return new Sr(await super._call(P))}}class wr extends ht{async _call(P){return new Rr(await super._call(P))}}class Jt extends G{}class Or extends Jt{}class ss extends Jt{async _call(P){return new Fr(await super._call(P))}}class ys extends Jt{async _call(P){return new xt(await super._call(P))}}class ns extends Jt{async _call(P){return new Sr(await super._call(P))}}class $s extends Jt{async _call(P){return new Rr(await super._call(P))}}class Vr extends G{}class ks extends Vr{}class Qr extends Vr{async _call(P){return new Fr(await super._call(P))}}class vs extends Vr{async _call(P){return new xt(await super._call(P))}}class Is extends Vr{async _call(P){return new Sr(await super._call(P))}}class As extends Vr{async _call(P){return new Rr(await super._call(P))}}class ar extends G{}class Fs extends ar{}class Er extends ar{async _call(P){return new xt(await super._call(P))}}class xs extends ar{async _call(P){return new Sr(await super._call(P))}}class Br extends ar{async _call(P){return new Rr(await super._call(P))}}class Ae extends ar{async _call(P){return new Fr(await super._call(P))}}class Je extends G{}class it extends Je{}class Nt extends Je{async _call(P){return new Fr(await super._call(P))}}class os extends Je{async _call(P){return new xt(await super._call(P))}}class is extends Je{async _call(P){return new Sr(await super._call(P))}}class ur extends G{}class as extends ur{}class cr extends ur{async _call(P){return new Fr(await super._call(P))}}class hr extends ur{async _call(P){return new xt(await super._call(P))}}class ls extends ur{async _call(P){return new Rr(await super._call(P))}}class Ts extends G{}class fn extends Ts{}class _n extends Ts{async _call(P){return new Fr(await super._call(P))}}class gn extends Ts{async _call(P){return new xt(await super._call(P))}}class wn extends Ts{async _call(P){return new Sr(await super._call(P))}}class Mn extends Ts{async _call(P){return new Rr(await super._call(P))}}class Os extends G{}class Hs extends Os{}class bn extends Os{async _call(P){return new Fr(await super._call(P))}}class yn extends Os{async _call(P){return new xt(await super._call(P))}}class vn extends Os{async _call(P){return new Rr(await super._call(P))}}class Ds extends G{}class de extends Ds{}class $ extends Ds{async _call(P){return new xt(await super._call(P))}}class j extends Ds{async _call(P){return new Rr(await super._call(P))}}class X extends Ds{async _call(P){return new Fr(await super._call(P))}}class ie extends G{constructor(){super(...arguments);Y(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ce extends ie{}class xe extends ie{}class Re extends G{}class Qe extends Re{}class We extends Re{}class Ye extends G{}class _t extends Ye{}class Ot extends Ye{}class At extends G{}class Yt extends At{}class Ut extends At{}class mr extends At{async _call(P){return new xt(await super._call(P))}}class Mr extends G{}class Pr extends Mr{}class Cr extends Mr{}class Zt extends Mr{async _call(P){return new xt(await super._call(P))}}class Es extends Mr{}class Kt extends G{}class fr extends Kt{}class Dr extends Kt{}class Xr extends G{}class Jr extends Xr{}class Ir extends Xr{}class Lr extends G{}class br extends Lr{}class er extends Lr{async _call(P){return new Fr(await super._call(P))}}class dr extends Lr{async _call(P){return new xt(await super._call(P))}}class pr extends Lr{async _call(P){return new Sr(await super._call(P))}}class Ar extends Lr{async _call(P){return new Rr(await super._call(P))}}class us extends G{}class xn extends us{}class Ti extends us{async _call(P){return new Fr(await super._call(P))}}class Ei extends us{async _call(P){return new xt(await super._call(P))}}class Pi extends us{async _call(P){return new Sr(await super._call(P))}}class To extends us{async _call(P){return new Rr(await super._call(P))}}class qs extends G{}class Ci extends qs{}class Si extends qs{async _call(P){return new Fr(await super._call(P))}}class $i extends qs{async _call(P){return new xt(await super._call(P))}}class ki extends qs{async _call(P){return new Sr(await super._call(P))}}class Ii extends qs{async _call(P){return new Rr(await super._call(P))}}class Eo extends G{}class Ai extends Eo{}class Fi extends Eo{}class Po extends G{constructor(){super(...arguments);Y(this,"requires_attention_mask",!1);Y(this,"main_input_name","input_features");Y(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Oi extends Po{}class Co extends Po{_prepare_generation_config(P,O){return super._prepare_generation_config(P,O,g.WhisperGenerationConfig)}_retrieve_init_tokens(P){const O=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ee=`<|${(0,S.whisper_language_to_code)(ne)}|>`;O.push(P.lang_to_id[Ee]),O.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)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!P.return_timestamps&&P.no_timestamps_token_id&&O.at(-1)!==P.no_timestamps_token_id?O.push(P.no_timestamps_token_id):P.return_timestamps&&O.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),O.pop()),O.filter(he=>he!=null)}async generate({inputs:P=null,generation_config:O=null,logits_processor:ne=null,stopping_criteria:ge=null,...he}){O=this._prepare_generation_config(O,he);const Ee=he.decoder_input_ids??this._retrieve_init_tokens(O);if(O.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(O,Ee))),O.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(O.begin_suppress_tokens,Ee.length))),O.return_token_timestamps){if(!O.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.");O.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),O.output_attentions=!0,O.return_dict_in_generate=!0}const De=await super.generate({inputs:P,generation_config:O,logits_processor:ne,decoder_input_ids:Ee,...he});return O.return_token_timestamps&&(De.token_timestamps=this._extract_token_timestamps(De,O.alignment_heads,O.num_frames)),De}_extract_token_timestamps(P,O,ne=null,ge=.02){if(!P.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`.");ne==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 he=this.config.median_filter_width;he===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),he=7);const Ee=P.cross_attentions,De=Array.from({length:this.config.decoder_layers},(Et,ot)=>(0,d.cat)(Ee.map($t=>$t[ot]),2)),Ne=(0,d.stack)(O.map(([Et,ot])=>{if(Et>=De.length)throw new Error(`Layer index ${Et} is out of bounds for cross attentions (length ${De.length}).`);return ne?De[Et].slice(null,ot,null,[0,ne]):De[Et].slice(null,ot)})).transpose(1,0,2,3),[Xe,mt]=(0,d.std_mean)(Ne,-2,0,!0),wt=Ne.clone();for(let Et=0;Et$t[$r+1]-$t[$r]),lr=(0,a.mergeArrays)([1],tr).map(_r=>!!_r),nr=[];for(let _r=0;_rdt.findIndex(Pt=>Pt==he)),Ne=De.every(dt=>dt===-1),Xe=De.every(dt=>dt!==-1);if(!Ne&&!Xe)throw new Error("Every input should contain either 0 or 1 image token.");if(Ne)return{inputs_embeds:P,attention_mask:ge};const mt=[],wt=[];for(let dt=0;dtArray.from({length:P.dims[0]},tr=>Array.from({length:P.dims[1]},lr=>1))),gt=O?O.tolist():[],Et=ne?ne.tolist():[];let ot=0,$t=0;for(let qt=0;qtdt[qt][xr]==1),nr=tr.reduce((rr,xr,tn)=>(xr==Ne&&rr.push(tn),rr),[]).map(rr=>tr[rr+1]),_r=nr.filter(rr=>rr==Ee).length,$r=nr.filter(rr=>rr==De).length;let Ct=[],vr=0,Yr=_r,An=$r;for(let rr=0;rrPs>vr&&Dn==Ee),tn=tr.findIndex((Dn,Ps)=>Ps>vr&&Dn==De),On=Yr>0&&xr!==-1?xr:tr.length+1,oo=An>0&&tn!==-1?tn:tr.length+1;let ha,Mc,bc,yc;On0?(0,f.max)(Ct.at(-1))[0]+1:0;Ct.push(Array.from({length:3*xc},(Dn,Ps)=>N0+Ps%xc));const Tc=xc+N0,fa=Yx*vc*ma,Zx=Array.from({length:fa},(Dn,Ps)=>Tc+Math.floor(Ps/(vc*ma))),eT=Array.from({length:fa},(Dn,Ps)=>Tc+Math.floor(Ps/ma)%vc),tT=Array.from({length:fa},(Dn,Ps)=>Tc+Ps%ma);Ct.push([Zx,eT,tT].flat()),vr=ha+fa}if(vr0?(0,f.max)(Ct.at(-1))[0]+1:0,xr=tr.length-vr;Ct.push(Array.from({length:3*xr},(tn,On)=>rr+On%xr))}const Ur=Ct.reduce((rr,xr)=>rr+xr.length,0),cs=new Array(Ur);let ca=0;for(let rr=0;rr<3;++rr)for(let xr=0;xrwt[ot%wt.length]),gt=Array.from({length:dt[0]},(Et,ot)=>(0,f.max)(wt.subarray(dt[1]*ot,dt[1]*(ot+1)))[0]+1n+BigInt(dt[1]));return[new d.Tensor("int64",Pt,[3,...dt]),new d.Tensor("int64",gt,[gt.length,1])]}else{const[wt,dt]=P.dims,Pt=BigInt64Array.from({length:3*wt*dt},(gt,Et)=>BigInt(Math.floor(Et%dt/wt)));return[new d.Tensor("int64",Pt,[3,...P.dims]),(0,d.zeros)([wt,1])]}}async encode_image({pixel_values:P,image_grid_thw:O}){return(await R(this.sessions.vision_encoder,{pixel_values:P,grid_thw:O})).image_features}_merge_input_ids_with_image_features(P){return A({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,O,ne){if(O.attention_mask&&!O.position_ids)if(!O.past_key_values)[O.position_ids,O.rope_deltas]=this.get_rope_index(O.input_ids,O.image_grid_thw,O.video_grid_thw,O.attention_mask);else{O.pixel_values=null;const ge=BigInt(Object.values(O.past_key_values)[0].dims.at(-2)),he=O.rope_deltas.map(Ee=>ge+Ee);O.position_ids=(0,d.stack)([he,he,he],0)}return O}}class yu extends G{}class aw extends yu{}class lw extends yu{}class vu extends G{}class uw extends vu{}class cw extends vu{}class xu extends G{}class dw extends xu{}class pw extends xu{}class Tu extends G{}class hw extends Tu{}class mw extends Tu{}class Eu extends G{}class fw extends Eu{}class _w extends Eu{}class Pu extends G{}class gw extends Pu{}class ww extends Pu{async _call(P){return new xt(await super._call(P))}}class Cu extends G{}class Mw extends Cu{}class bw extends Cu{async _call(P){return new xt(await super._call(P))}}class yw extends G{}class vw extends yw{}class Su extends G{}class xw extends Su{}class Tw extends Su{async _call(P){return new xt(await super._call(P))}}class Ew extends G{}class Pw extends Ew{}class $u extends G{}class Cw extends $u{}class Sw extends $u{async _call(P){return new xt(await super._call(P))}}class $w extends G{}class kw extends $w{}class ku extends G{}class Iw extends ku{}class Aw extends ku{async _call(P){return new xt(await super._call(P))}}class Fw extends G{}class Ow extends Fw{async _call(P){return new R0(await super._call(P))}}class Iu extends G{}class Dw extends Iu{}class Lw extends Iu{async _call(P){return new xt(await super._call(P))}}class Au extends G{}class zw extends Au{}class Bw extends Au{async _call(P){return new xt(await super._call(P))}}class Fu extends G{}class Rw extends Fu{}class jw extends Fu{}class Ou extends G{}class Nw extends Ou{}class Vw extends Ou{}class Du extends G{}class Uw extends Du{}class Ww extends Du{async _call(P){return new xt(await super._call(P))}}class Qi extends G{}class Gw extends Qi{}class Kw extends Qi{async _call(P){return new zu(await super._call(P))}}class Lu extends Qi{async _call(P){return new Hw(await super._call(P))}}class zu extends be{constructor({logits:P,pred_boxes:O}){super(),this.logits=P,this.pred_boxes=O}}class Hw extends be{constructor({logits:P,pred_boxes:O,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=O,this.pred_masks=ne}}class Bu extends G{}class qw extends Bu{}class Qw extends Bu{async _call(P){return new Yo(await super._call(P))}}class Yo extends be{constructor({logits:P,pred_boxes:O}){super(),this.logits=P,this.pred_boxes=O}}class Ru extends G{}class Xw extends Ru{}class Jw extends Ru{async _call(P){return new Yw(await super._call(P))}}class Yw extends Yo{}class ju extends G{}class Zw extends ju{}class eM extends ju{async _call(P){return new tM(await super._call(P))}}class tM extends Yo{}class Nu extends G{}class rM extends Nu{}class sM extends Nu{async _call(P){return new Yo(await super._call(P))}}class Vu extends G{}class nM extends Vu{}class oM extends Vu{async _call(P){return new iM(await super._call(P))}}class iM extends zu{}class Uu extends G{}class aM extends Uu{}class lM extends Uu{async _call(P){return new xt(await super._call(P))}}class Wu extends G{}class uM extends Wu{}class cM extends Wu{async _call(P){return new xt(await super._call(P))}}class Gu extends G{}class dM extends Gu{}class pM extends Gu{async _call(P){return new xt(await super._call(P))}}class Xi extends G{}class hM extends Xi{}class mM extends Xi{async _call(P){return new xt(await super._call(P))}}class fM extends Xi{}class Ku extends G{}class _M extends Ku{}class gM extends Ku{}class Hu extends G{}class wM extends Hu{}class MM extends Hu{}class bM extends G{}class yM extends bM{}class Ji extends G{}class vM extends Ji{}class xM extends Ji{}class TM extends Ji{}class EM extends G{}class PM extends EM{}class CM extends G{}class SM extends CM{}class $M extends G{}class kM extends $M{}class qu extends G{}class IM extends qu{}class AM extends qu{}class Qu extends G{}class FM extends Qu{}class OM extends Qu{}class DM extends G{}class LM extends DM{}class Xu extends G{}class zM extends Xu{}class BM extends Xu{async _call(P){return new xt(await super._call(P))}}class Ju extends G{}class RM extends Ju{}class jM extends Ju{async _call(P){return new xt(await super._call(P))}}class Yu extends G{}class NM extends Yu{}class VM extends Yu{async _call(P){return new xt(await super._call(P))}}class Zu extends G{}class UM extends Zu{}class WM extends Zu{async _call(P){return new xt(await super._call(P))}}class GM extends G{}class KM extends GM{}class ec extends G{}class HM extends ec{}class qM extends ec{async _call(P){return new QM(await super._call(P))}}class QM extends be{constructor({logits:P,pred_boxes:O}){super(),this.logits=P,this.pred_boxes=O}}class XM extends G{}class JM extends XM{async get_image_embeddings({pixel_values:P}){return await se(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((he,Ee)=>he*Ee,1);P.input_labels=new d.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const O={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(O.input_points=P.input_points),P.input_labels&&(O.input_labels=P.input_labels),P.input_boxes&&(O.input_boxes=P.input_boxes),await R(this.sessions.prompt_encoder_mask_decoder,O)}async _call(P){return new YM(await super._call(P))}}class YM extends be{constructor({iou_scores:P,pred_masks:O}){super(),this.iou_scores=P,this.pred_masks=O}}class tc extends G{}class ZM extends tc{}class eb extends tc{}class rc extends G{}class tb extends rc{}class rb extends rc{}class en extends G{}class sb extends en{}class nb extends en{async _call(P){return new In(await super._call(P))}}class ob extends en{async _call(P){return new xt(await super._call(P))}}class ib extends en{async _call(P){return new Sr(await super._call(P))}}class sc extends G{}class ab extends sc{}class lb extends sc{async _call(P){return new Sr(await super._call(P))}}class ub extends G{}class cb extends ub{}class Yi extends G{}class db extends Yi{}class pb extends Yi{async _call(P){return new In(await super._call(P))}}class hb extends Yi{async _call(P){return new xt(await super._call(P))}}class Zo extends G{}class mb extends Zo{}class fb extends Zo{async _call(P){return new In(await super._call(P))}}class _b extends Zo{async _call(P){return new xt(await super._call(P))}}class gb extends Zo{async _call(P){return new Sr(await super._call(P))}}class Zi extends G{}class wb extends Zi{}class Mb extends Zi{async _call(P){return new In(await super._call(P))}}class bb extends Zi{async _call(P){return new xt(await super._call(P))}}class zx extends G{}class yb extends en{}class vb extends en{async _call(P){return new In(await super._call(P))}}class xb extends en{async _call(P){return new xt(await super._call(P))}}class so extends G{}class Tb extends so{}class Eb extends so{async _call(P){return new In(await super._call(P))}}class Pb extends so{async _call(P){return new xt(await super._call(P))}}class Cb extends so{async _call(P){return new B0(await super._call(P))}}class Sb extends so{async _call(P){return new Sr(await super._call(P))}}class $b extends G{}class kb extends $b{}class ea extends G{}class Bx extends ea{}class Ib extends ea{}class Ab extends ea{async generate_speech(P,O,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:he=20,vocoder:Ee=null}={}){const De={input_ids:P},{encoder_outputs:Ne,encoder_attention_mask:Xe}=await se(this,De),mt=Ne.dims[1]/this.config.reduction_factor,wt=Math.floor(mt*he),dt=Math.floor(mt*ge),Pt=this.config.num_mel_bins;let gt=[],Et=null,ot=null,$t=0;for(;;){++$t;const lr=J(!!ot);let nr;ot?nr=ot.output_sequence_out:nr=new d.Tensor("float32",new Float32Array(Pt),[1,1,Pt]);let _r={use_cache_branch:lr,output_sequence:nr,encoder_attention_mask:Xe,speaker_embeddings:O,encoder_hidden_states:Ne};this.addPastKeyValues(_r,Et),ot=await R(this.sessions.decoder_model_merged,_r),Et=this.getPastKeyValues(ot,Et);const{prob:$r,spectrum:Ct}=ot;if(gt.push(Ct),$t>=dt&&(Array.from($r.data).filter(vr=>vr>=ne).length>0||$t>=wt))break}const qt=(0,d.cat)(gt),{waveform:tr}=await R(Ee.sessions.model,{spectrogram:qt});return{spectrogram:qt,waveform:tr}}}class Fb extends G{constructor(){super(...arguments);Y(this,"main_input_name","spectrogram")}}class Ob extends G{}class Db extends Ob{}class nc extends G{}class Lb extends nc{}class zb extends nc{}class oc extends G{}class Bb extends oc{}class Rb extends oc{}class ic extends G{}class jb extends ic{}class Nb extends ic{}class ta extends G{}class Vb extends ta{}class Ub extends ta{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"text_model"})}}class Wb extends ta{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"audio_model"})}}class Gb extends G{}class ac extends Gb{async _call(P){return new j0(await super._call(P))}}class ra extends G{}class Rx extends ra{}class Kb extends ra{}class Hb extends ra{}class lc extends G{}class qb extends lc{}class Qb extends lc{}class uc extends G{}class Xb extends uc{}class Jb extends uc{async _call(P){return new xt(await super._call(P))}}class cc extends G{}class jx extends cc{}class Nx extends cc{}class dc extends G{constructor(){super(...arguments);Y(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(O){const[ne,ge]=O.dims,he=this.config.decoder.num_codebooks,Ee=ge-he;let De=0;for(let mt=0;mt0&&Pt<=Ee&&(O.data[De++]=O.data[mt])}const Ne=Math.floor(ne/he),Xe=De/(Ne*he);return new d.Tensor(O.type,O.data.slice(0,De),[Ne,he,Xe])}prepare_inputs_for_generation(O,ne,ge){let he=structuredClone(O);for(let De=0;De=Ne&&(he[De][Ne]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(he=he.concat(he)),super.prepare_inputs_for_generation(he,ne,ge)}async generate(O){const ne=await super.generate(O),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:he}=await R(this.sessions.encodec_decode,{audio_codes:ge});return he}}class sa extends G{}class Yb extends sa{}class Zb extends sa{async _call(P){return new xt(await super._call(P))}}class ey extends sa{}class na extends G{}class ty extends na{}class ry extends na{async _call(P){return new xt(await super._call(P))}}class sy extends na{}class oa extends G{}class ny extends oa{}class oy extends oa{async _call(P){return new xt(await super._call(P))}}class iy extends oa{}class ia extends G{}class ay extends ia{}class ly extends ia{async _call(P){return new xt(await super._call(P))}}class uy extends ia{}class cy extends G{}class dy extends cy{}class py extends G{}class hy extends py{constructor(...O){super(...O);Y(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(O){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!O.past_key_values){const Xe=this.sessions.prepare_inputs_embeds,mt=(0,a.pick)(O,Xe.inputNames);ge=await R(Xe,mt)}else{const Xe=this.sessions.gen_img_embeds,mt=(0,a.pick)({image_ids:O.input_ids},Xe.inputNames);ge=await R(Xe,mt)}const he={...O,...ge},Ee=await ae(this,he),De=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!De)throw new Error(`Unable to find "${De}" generation head`);const Ne=await R(De,(0,a.pick)(Ee,De.inputNames));return{...ge,...Ee,...Ne}}async generate(O){return this._generation_mode="text",super.generate(O)}async generate_images(O){this._generation_mode="image";const ne=(O.inputs??O[this.main_input_name]).dims[1],he=(await super.generate(O)).slice(null,[ne,null]),Ee=this.sessions.image_decode,{decoded_image:De}=await R(Ee,{generated_tokens:he}),Ne=De.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Xe=[];for(const mt of Ne){const wt=_.RawImage.fromTensor(mt);Xe.push(wt)}return Xe}}class my extends be{constructor({char_logits:P,bpe_logits:O,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=O,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class fy extends G{}class _y extends fy{async _call(P){return new my(await super._call(P))}}class pc extends G{}class gy extends pc{}class wy extends pc{}class hc extends G{}class My extends hc{}class by extends hc{}class yy extends G{constructor(){super(...arguments);Y(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class vy extends yy{_merge_input_ids_with_audio_features(P){const O=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,O);return U({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class aa extends G{constructor(){super(...arguments);Y(this,"main_input_name","input_values");Y(this,"forward_params",["input_values"])}}class xy extends be{constructor({audio_codes:P}){super(),this.audio_codes=P}}class Ty extends be{constructor({audio_values:P}){super(),this.audio_values=P}}class Ey extends aa{async encode(P){return new xy(await R(this.sessions.encoder_model,P))}async decode(P){return new Ty(await R(this.sessions.decoder_model,P))}}class Py extends aa{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"encoder_model"})}}class Cy extends aa{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"decoder_model"})}}class la extends G{constructor(){super(...arguments);Y(this,"main_input_name","input_values");Y(this,"forward_params",["input_values"])}}class Sy extends be{constructor({audio_codes:P}){super(),this.audio_codes=P}}class $y extends be{constructor({audio_values:P}){super(),this.audio_values=P}}class ky extends la{async encode(P){return new Sy(await R(this.sessions.encoder_model,P))}async decode(P){return new $y(await R(this.sessions.decoder_model,P))}}class Iy extends la{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"encoder_model"})}}class Ay extends la{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"decoder_model"})}}class ua extends G{constructor(){super(...arguments);Y(this,"main_input_name","input_values");Y(this,"forward_params",["input_values"])}}class Fy extends ua{async encode(P){return await R(this.sessions.encoder_model,P)}async decode(P){return await R(this.sessions.decoder_model,P)}}class Oy extends ua{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"encoder_model"})}}class Dy extends ua{static async from_pretrained(P,O={}){return super.from_pretrained(P,{...O,model_file_name:O.model_file_name??"decoder_model"})}}class Lt{static async from_pretrained(P,{progress_callback:O=null,config:ne=null,cache_dir:ge=null,local_files_only:he=!1,revision:Ee="main",model_file_name:De=null,subfolder:Ne="onnx",device:Xe=null,dtype:mt=null,use_external_data_format:wt=null,session_options:dt={}}={}){const Pt={progress_callback:O,config:ne,cache_dir:ge,local_files_only:he,revision:Ee,model_file_name:De,subfolder:Ne,device:Xe,dtype:mt,use_external_data_format:wt,session_options:dt};if(Pt.config=await s.AutoConfig.from_pretrained(P,Pt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const gt=Pt.config.model_type;for(const Et of this.MODEL_CLASS_MAPPINGS){let ot=Et.get(gt);if(!ot){for(const $t of Et.values())if($t[0]===gt){ot=$t;break}if(!ot)continue}return await ot[1].from_pretrained(P,Pt)}if(this.BASE_IF_FAIL)return a0.has(gt)||console.warn(`Unknown model class "${gt}", attempting to construct from base class.`),await G.from_pretrained(P,Pt);throw Error(`Unsupported model type: ${gt}`)}}Y(Lt,"MODEL_CLASS_MAPPINGS",null),Y(Lt,"BASE_IF_FAIL",!1);const Vx=new Map([["bert",["BertModel",Ce]],["modernbert",["ModernBertModel",ke]],["nomic_bert",["NomicBertModel",Ge]],["roformer",["RoFormerModel",pt]],["electra",["ElectraModel",me]],["esm",["EsmModel",it]],["convbert",["ConvBertModel",Mt]],["camembert",["CamembertModel",ut]],["deberta",["DebertaModel",Or]],["deberta-v2",["DebertaV2Model",ks]],["mpnet",["MPNetModel",fn]],["albert",["AlbertModel",de]],["distilbert",["DistilBertModel",Fs]],["roberta",["RobertaModel",br]],["xlm",["XLMModel",xn]],["xlm-roberta",["XLMRobertaModel",Ci]],["clap",["ClapModel",Vb]],["clip",["CLIPModel",Vi]],["clipseg",["CLIPSegModel",Bo]],["chinese_clip",["ChineseCLIPModel",qn]],["siglip",["SiglipModel",Js]],["jina_clip",["JinaCLIPModel",Do]],["mobilebert",["MobileBertModel",as]],["squeezebert",["SqueezeBertModel",Hs]],["wav2vec2",["Wav2Vec2Model",sb]],["wav2vec2-bert",["Wav2Vec2BertModel",wb]],["unispeech",["UniSpeechModel",db]],["unispeech-sat",["UniSpeechSatModel",mb]],["hubert",["HubertModel",yb]],["wavlm",["WavLMModel",Tb]],["audio-spectrogram-transformer",["ASTModel",Ai]],["vits",["VitsModel",ac]],["pyannote",["PyAnnoteModel",ab]],["wespeaker-resnet",["WeSpeakerResNetModel",cb]],["detr",["DetrModel",Gw]],["rt_detr",["RTDetrModel",qw]],["rt_detr_v2",["RTDetrV2Model",Xw]],["rf_detr",["RFDetrModel",Zw]],["d_fine",["DFineModel",rM]],["table-transformer",["TableTransformerModel",nM]],["vit",["ViTModel",gw]],["ijepa",["IJepaModel",Mw]],["pvt",["PvtModel",xw]],["vit_msn",["ViTMSNModel",Cw]],["vit_mae",["ViTMAEModel",Pw]],["groupvit",["GroupViTModel",kw]],["fastvit",["FastViTModel",Iw]],["mobilevit",["MobileViTModel",Dw]],["mobilevitv2",["MobileViTV2Model",zw]],["owlvit",["OwlViTModel",Rw]],["owlv2",["Owlv2Model",Nw]],["beit",["BeitModel",Uw]],["deit",["DeiTModel",aM]],["hiera",["HieraModel",uM]],["convnext",["ConvNextModel",zM]],["convnextv2",["ConvNextV2Model",RM]],["dinov2",["Dinov2Model",NM]],["dinov2_with_registers",["Dinov2WithRegistersModel",UM]],["resnet",["ResNetModel",dM]],["swin",["SwinModel",hM]],["swin2sr",["Swin2SRModel",_M]],["donut-swin",["DonutSwinModel",LM]],["yolos",["YolosModel",HM]],["dpt",["DPTModel",wM]],["glpn",["GLPNModel",FM]],["hifigan",["SpeechT5HifiGan",Fb]],["efficientnet",["EfficientNetModel",Xb]],["decision_transformer",["DecisionTransformerModel",dy]],["patchtst",["PatchTSTForPrediction",gy]],["patchtsmixer",["PatchTSMixerForPrediction",My]],["mobilenet_v1",["MobileNetV1Model",Yb]],["mobilenet_v2",["MobileNetV2Model",ty]],["mobilenet_v3",["MobileNetV3Model",ny]],["mobilenet_v4",["MobileNetV4Model",ay]],["maskformer",["MaskFormerModel",IM]],["mgp-str",["MgpstrForSceneTextRecognition",_y]],["style_text_to_speech_2",["StyleTextToSpeech2Model",kb]]]),Ux=new Map([["t5",["T5Model",ce]],["longt5",["LongT5Model",Qe]],["mt5",["MT5Model",_t]],["bart",["BartModel",Yt]],["mbart",["MBartModel",Pr]],["marian",["MarianModel",ZM]],["whisper",["WhisperModel",Oi]],["m2m_100",["M2M100Model",tb]],["blenderbot",["BlenderbotModel",fr]],["blenderbot-small",["BlenderbotSmallModel",Jr]]]),Wx=new Map([["mimi",["MimiModel",Ey]],["dac",["DacModel",ky]],["snac",["SnacModel",Fy]]]),Gx=new Map([["bloom",["BloomModel",dw]],["jais",["JAISModel",ct]],["gpt2",["GPT2Model",No]],["gptj",["GPTJModel",Wo]],["gpt_bigcode",["GPTBigCodeModel",Ko]],["gpt_neo",["GPTNeoModel",Uo]],["gpt_neox",["GPTNeoXModel",Cn]],["codegen",["CodeGenModel",$n]],["llama",["LlamaModel",qo]],["exaone",["ExaoneModel",L]],["olmo",["OlmoModel",tt]],["olmo2",["Olmo2Model",Wt]],["mobilellm",["MobileLLMModel",Te]],["granite",["GraniteModel",qi]],["cohere",["CohereModel",Gg]],["gemma",["GemmaModel",Hg]],["gemma2",["Gemma2Model",Qg]],["gemma3_text",["Gemma3Model",Jg]],["helium",["HeliumModel",Xo]],["glm",["GlmModel",h]],["openelm",["OpenELMModel",Zg]],["qwen2",["Qwen2Model",tw]],["qwen3",["Qwen3Model",sw]],["phi",["PhiModel",aw]],["phi3",["Phi3Model",uw]],["mpt",["MptModel",hw]],["opt",["OPTModel",fw]],["mistral",["MistralModel",Lb]],["starcoder2",["Starcoder2Model",Bb]],["falcon",["FalconModel",jb]],["stablelm",["StableLmModel",qb]]]),mc=new Map([["speecht5",["SpeechT5ForSpeechToText",Ib]],["whisper",["WhisperForConditionalGeneration",Co]],["lite-whisper",["LiteWhisperForConditionalGeneration",So]],["moonshine",["MoonshineForConditionalGeneration",Li]]]),Ly=new Map([["speecht5",["SpeechT5ForTextToSpeech",Ab]]]),zy=new Map([["vits",["VitsModel",ac]],["musicgen",["MusicgenForConditionalGeneration",dc]]]),By=new Map([["bert",["BertForSequenceClassification",Fe]],["modernbert",["ModernBertForSequenceClassification",Ze]],["roformer",["RoFormerForSequenceClassification",Vt]],["electra",["ElectraForSequenceClassification",ve]],["esm",["EsmForSequenceClassification",os]],["convbert",["ConvBertForSequenceClassification",D]],["camembert",["CamembertForSequenceClassification",jt]],["deberta",["DebertaForSequenceClassification",ys]],["deberta-v2",["DebertaV2ForSequenceClassification",vs]],["mpnet",["MPNetForSequenceClassification",gn]],["albert",["AlbertForSequenceClassification",$]],["distilbert",["DistilBertForSequenceClassification",Er]],["roberta",["RobertaForSequenceClassification",dr]],["xlm",["XLMForSequenceClassification",Ei]],["xlm-roberta",["XLMRobertaForSequenceClassification",$i]],["bart",["BartForSequenceClassification",mr]],["mbart",["MBartForSequenceClassification",Zt]],["mobilebert",["MobileBertForSequenceClassification",hr]],["squeezebert",["SqueezeBertForSequenceClassification",yn]]]),Ry=new Map([["bert",["BertForTokenClassification",Be]],["modernbert",["ModernBertForTokenClassification",nt]],["roformer",["RoFormerForTokenClassification",Rt]],["electra",["ElectraForTokenClassification",vt]],["esm",["EsmForTokenClassification",is]],["convbert",["ConvBertForTokenClassification",oe]],["camembert",["CamembertForTokenClassification",Ht]],["deberta",["DebertaForTokenClassification",ns]],["deberta-v2",["DebertaV2ForTokenClassification",Is]],["mpnet",["MPNetForTokenClassification",wn]],["distilbert",["DistilBertForTokenClassification",xs]],["roberta",["RobertaForTokenClassification",pr]],["xlm",["XLMForTokenClassification",Pi]],["xlm-roberta",["XLMRobertaForTokenClassification",ki]]]),fc=new Map([["t5",["T5ForConditionalGeneration",xe]],["longt5",["LongT5ForConditionalGeneration",We]],["mt5",["MT5ForConditionalGeneration",Ot]],["bart",["BartForConditionalGeneration",Ut]],["mbart",["MBartForConditionalGeneration",Cr]],["marian",["MarianMTModel",eb]],["m2m_100",["M2M100ForConditionalGeneration",rb]],["blenderbot",["BlenderbotForConditionalGeneration",Dr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Ir]]]),_c=new Map([["bloom",["BloomForCausalLM",pw]],["gpt2",["GPT2LMHeadModel",Vo]],["jais",["JAISLMHeadModel",Hi]],["gptj",["GPTJForCausalLM",Go]],["gpt_bigcode",["GPTBigCodeForCausalLM",Ho]],["gpt_neo",["GPTNeoForCausalLM",Pn]],["gpt_neox",["GPTNeoXForCausalLM",Jn]],["codegen",["CodeGenForCausalLM",eo]],["llama",["LlamaForCausalLM",Qo]],["exaone",["ExaoneForCausalLM",N]],["olmo",["OlmoForCausalLM",bt]],["olmo2",["Olmo2ForCausalLM",yr]],["mobilellm",["MobileLLMForCausalLM",Le]],["granite",["GraniteForCausalLM",Wg]],["cohere",["CohereForCausalLM",Kg]],["gemma",["GemmaForCausalLM",qg]],["gemma2",["Gemma2ForCausalLM",Xg]],["gemma3_text",["Gemma3ForCausalLM",Yg]],["helium",["HeliumForCausalLM",Jo]],["glm",["GlmForCausalLM",x]],["openelm",["OpenELMForCausalLM",ew]],["qwen2",["Qwen2ForCausalLM",rw]],["qwen3",["Qwen3ForCausalLM",nw]],["phi",["PhiForCausalLM",lw]],["phi3",["Phi3ForCausalLM",cw]],["mpt",["MptForCausalLM",mw]],["opt",["OPTForCausalLM",_w]],["mbart",["MBartForCausalLM",Es]],["mistral",["MistralForCausalLM",zb]],["starcoder2",["Starcoder2ForCausalLM",Rb]],["falcon",["FalconForCausalLM",Nb]],["trocr",["TrOCRForCausalLM",Db]],["stablelm",["StableLmForCausalLM",Qb]],["phi3_v",["Phi3VForCausalLM",Fo]]]),Kx=new Map([["multi_modality",["MultiModalityCausalLM",hy]]]),jy=new Map([["bert",["BertForMaskedLM",$e]],["modernbert",["ModernBertForMaskedLM",Ve]],["roformer",["RoFormerForMaskedLM",St]],["electra",["ElectraForMaskedLM",Oe]],["esm",["EsmForMaskedLM",Nt]],["convbert",["ConvBertForMaskedLM",rs]],["camembert",["CamembertForMaskedLM",rt]],["deberta",["DebertaForMaskedLM",ss]],["deberta-v2",["DebertaV2ForMaskedLM",Qr]],["mpnet",["MPNetForMaskedLM",_n]],["albert",["AlbertForMaskedLM",X]],["distilbert",["DistilBertForMaskedLM",Ae]],["roberta",["RobertaForMaskedLM",er]],["xlm",["XLMWithLMHeadModel",Ti]],["xlm-roberta",["XLMRobertaForMaskedLM",Si]],["mobilebert",["MobileBertForMaskedLM",cr]],["squeezebert",["SqueezeBertForMaskedLM",bn]]]),Ny=new Map([["bert",["BertForQuestionAnswering",He]],["roformer",["RoFormerForQuestionAnswering",gr]],["electra",["ElectraForQuestionAnswering",Ft]],["convbert",["ConvBertForQuestionAnswering",B]],["camembert",["CamembertForQuestionAnswering",wr]],["deberta",["DebertaForQuestionAnswering",$s]],["deberta-v2",["DebertaV2ForQuestionAnswering",As]],["mpnet",["MPNetForQuestionAnswering",Mn]],["albert",["AlbertForQuestionAnswering",j]],["distilbert",["DistilBertForQuestionAnswering",Br]],["roberta",["RobertaForQuestionAnswering",Ar]],["xlm",["XLMForQuestionAnswering",To]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ii]],["mobilebert",["MobileBertForQuestionAnswering",ls]],["squeezebert",["SqueezeBertForQuestionAnswering",vn]]]),gc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]],["idefics3",["Idefics3ForConditionalGeneration",En]],["smolvlm",["SmolVLMForConditionalGeneration",Ao]]]),Vy=new Map([["llava",["LlavaForConditionalGeneration",Tn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Qs]],["moondream1",["Moondream1ForConditionalGeneration",zi]],["florence2",["Florence2ForConditionalGeneration",Bi]],["qwen2-vl",["Qwen2VLForConditionalGeneration",iw]],["idefics3",["Idefics3ForConditionalGeneration",En]],["smolvlm",["SmolVLMForConditionalGeneration",Ao]],["paligemma",["PaliGemmaForConditionalGeneration",ji]]]),Uy=new Map([["ultravox",["UltravoxModel",vy]]]),Hx=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]]]),Wy=new Map([["vit",["ViTForImageClassification",ww]],["ijepa",["IJepaForImageClassification",bw]],["pvt",["PvtForImageClassification",Tw]],["vit_msn",["ViTMSNForImageClassification",Sw]],["fastvit",["FastViTForImageClassification",Aw]],["mobilevit",["MobileViTForImageClassification",Lw]],["mobilevitv2",["MobileViTV2ForImageClassification",Bw]],["beit",["BeitForImageClassification",Ww]],["deit",["DeiTForImageClassification",lM]],["hiera",["HieraForImageClassification",cM]],["convnext",["ConvNextForImageClassification",BM]],["convnextv2",["ConvNextV2ForImageClassification",jM]],["dinov2",["Dinov2ForImageClassification",VM]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",WM]],["resnet",["ResNetForImageClassification",pM]],["swin",["SwinForImageClassification",mM]],["segformer",["SegformerForImageClassification",Kb]],["efficientnet",["EfficientNetForImageClassification",Jb]],["mobilenet_v1",["MobileNetV1ForImageClassification",Zb]],["mobilenet_v2",["MobileNetV2ForImageClassification",ry]],["mobilenet_v3",["MobileNetV3ForImageClassification",oy]],["mobilenet_v4",["MobileNetV4ForImageClassification",ly]]]),Gy=new Map([["detr",["DetrForObjectDetection",Kw]],["rt_detr",["RTDetrForObjectDetection",Qw]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Jw]],["rf_detr",["RFDetrForObjectDetection",eM]],["d_fine",["DFineForObjectDetection",sM]],["table-transformer",["TableTransformerForObjectDetection",oM]],["yolos",["YolosForObjectDetection",qM]]]),Ky=new Map([["owlvit",["OwlViTForObjectDetection",jw]],["owlv2",["Owlv2ForObjectDetection",Vw]],["grounding-dino",["GroundingDinoForObjectDetection",KM]]]),no=new Map([["detr",["DetrForSegmentation",Lu]],["clipseg",["CLIPSegForImageSegmentation",Ro]]]),Hy=new Map([["segformer",["SegformerForSemanticSegmentation",Hb]],["sapiens",["SapiensForSemanticSegmentation",vM]],["swin",["SwinForSemanticSegmentation",fM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",ey]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",sy]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",iy]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",uy]]]),qy=new Map([["detr",["DetrForSegmentation",Lu]],["maskformer",["MaskFormerForInstanceSegmentation",AM]]]),Qy=new Map([["sam",["SamModel",JM]]]),Xy=new Map([["wav2vec2",["Wav2Vec2ForCTC",nb]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Mb]],["unispeech",["UniSpeechForCTC",pb]],["unispeech-sat",["UniSpeechSatForCTC",fb]],["wavlm",["WavLMForCTC",Eb]],["hubert",["HubertForCTC",vb]]]),Jy=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ob]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",bb]],["unispeech",["UniSpeechForSequenceClassification",hb]],["unispeech-sat",["UniSpeechSatForSequenceClassification",_b]],["wavlm",["WavLMForSequenceClassification",Pb]],["hubert",["HubertForSequenceClassification",xb]],["audio-spectrogram-transformer",["ASTForAudioClassification",Fi]]]),Yy=new Map([["wavlm",["WavLMForXVector",Cb]]]),Zy=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",gb]],["wavlm",["WavLMForAudioFrameClassification",Sb]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ib]],["pyannote",["PyAnnoteForAudioFrameClassification",lb]]]),e0=new Map([["vitmatte",["VitMatteForImageMatting",Ow]]]),qx=new Map([["patchtst",["PatchTSTForPrediction",wy]],["patchtsmixer",["PatchTSMixerForPrediction",by]]]),t0=new Map([["swin2sr",["Swin2SRForImageSuperResolution",gM]]]),r0=new Map([["dpt",["DPTForDepthEstimation",MM]],["depth_anything",["DepthAnythingForDepthEstimation",yM]],["glpn",["GLPNForDepthEstimation",OM]],["sapiens",["SapiensForDepthEstimation",xM]],["depth_pro",["DepthProForDepthEstimation",PM]],["metric3d",["Metric3DForDepthEstimation",SM]],["metric3dv2",["Metric3Dv2ForDepthEstimation",kM]]]),s0=new Map([["sapiens",["SapiensForNormalEstimation",TM]]]),n0=new Map([["vitpose",["VitPoseForPoseEstimation",vw]]]),o0=new Map([["clip",["CLIPVisionModelWithProjection",Wi]],["siglip",["SiglipVisionModel",Gi]],["jina_clip",["JinaCLIPVisionModel",zo]]]),i0=[[Vx,E.EncoderOnly],[Ux,E.EncoderDecoder],[Gx,E.DecoderOnly],[Wx,E.AutoEncoder],[By,E.EncoderOnly],[Ry,E.EncoderOnly],[fc,E.Seq2Seq],[mc,E.Seq2Seq],[_c,E.DecoderOnly],[Kx,E.MultiModality],[jy,E.EncoderOnly],[Ny,E.EncoderOnly],[gc,E.Vision2Seq],[Vy,E.ImageTextToText],[Uy,E.AudioTextToText],[Wy,E.EncoderOnly],[no,E.EncoderOnly],[qy,E.EncoderOnly],[Hy,E.EncoderOnly],[e0,E.EncoderOnly],[qx,E.EncoderOnly],[t0,E.EncoderOnly],[r0,E.EncoderOnly],[s0,E.EncoderOnly],[n0,E.EncoderOnly],[Gy,E.EncoderOnly],[Ky,E.EncoderOnly],[Qy,E.MaskGeneration],[Xy,E.EncoderOnly],[Jy,E.EncoderOnly],[Ly,E.Seq2Seq],[zy,E.EncoderOnly],[Yy,E.EncoderOnly],[Zy,E.EncoderOnly],[o0,E.EncoderOnly]];for(const[b,P]of i0)for(const[O,ne]of b.values())v.set(O,P),y.set(ne,O),M.set(O,ne);const Qx=[["MusicgenForConditionalGeneration",dc,E.Musicgen],["Phi3VForCausalLM",Fo,E.Phi3V],["CLIPTextModelWithProjection",Ui,E.EncoderOnly],["SiglipTextModel",Oo,E.EncoderOnly],["JinaCLIPTextModel",Lo,E.EncoderOnly],["ClapTextModelWithProjection",Ub,E.EncoderOnly],["ClapAudioModelWithProjection",Wb,E.EncoderOnly],["DacEncoderModel",Iy,E.EncoderOnly],["DacDecoderModel",Ay,E.EncoderOnly],["MimiEncoderModel",Py,E.EncoderOnly],["MimiDecoderModel",Cy,E.EncoderOnly],["SnacEncoderModel",Oy,E.EncoderOnly],["SnacDecoderModel",Dy,E.EncoderOnly]];for(const[b,P,O]of Qx)v.set(b,O),y.set(P,b),M.set(b,P);const a0=new Map([["modnet",no],["birefnet",no],["isnet",no],["ben",no]]);for(const[b,P]of a0.entries())P.set(b,["PreTrainedModel",G]),v.set(b,E.EncoderOnly),y.set(G,b),M.set(b,G);class wc extends Lt{}Y(wc,"MODEL_CLASS_MAPPINGS",i0.map(P=>P[0])),Y(wc,"BASE_IF_FAIL",!0);class l0 extends Lt{}Y(l0,"MODEL_CLASS_MAPPINGS",[By]);class u0 extends Lt{}Y(u0,"MODEL_CLASS_MAPPINGS",[Ry]);class c0 extends Lt{}Y(c0,"MODEL_CLASS_MAPPINGS",[fc]);class d0 extends Lt{}Y(d0,"MODEL_CLASS_MAPPINGS",[mc]);class p0 extends Lt{}Y(p0,"MODEL_CLASS_MAPPINGS",[Ly]);class h0 extends Lt{}Y(h0,"MODEL_CLASS_MAPPINGS",[zy]);class m0 extends Lt{}Y(m0,"MODEL_CLASS_MAPPINGS",[_c]);class f0 extends Lt{}Y(f0,"MODEL_CLASS_MAPPINGS",[jy]);class _0 extends Lt{}Y(_0,"MODEL_CLASS_MAPPINGS",[Ny]);class g0 extends Lt{}Y(g0,"MODEL_CLASS_MAPPINGS",[gc]);class w0 extends Lt{}Y(w0,"MODEL_CLASS_MAPPINGS",[Wy]);class M0 extends Lt{}Y(M0,"MODEL_CLASS_MAPPINGS",[no]);class b0 extends Lt{}Y(b0,"MODEL_CLASS_MAPPINGS",[Hy]);class y0 extends Lt{}Y(y0,"MODEL_CLASS_MAPPINGS",[qy]);class v0 extends Lt{}Y(v0,"MODEL_CLASS_MAPPINGS",[Gy]);class x0 extends Lt{}Y(x0,"MODEL_CLASS_MAPPINGS",[Ky]);class T0 extends Lt{}Y(T0,"MODEL_CLASS_MAPPINGS",[Qy]);class E0 extends Lt{}Y(E0,"MODEL_CLASS_MAPPINGS",[Xy]);class P0 extends Lt{}Y(P0,"MODEL_CLASS_MAPPINGS",[Jy]);class C0 extends Lt{}Y(C0,"MODEL_CLASS_MAPPINGS",[Yy]);class S0 extends Lt{}Y(S0,"MODEL_CLASS_MAPPINGS",[Zy]);class $0 extends Lt{}Y($0,"MODEL_CLASS_MAPPINGS",[Hx]);class k0 extends Lt{}Y(k0,"MODEL_CLASS_MAPPINGS",[e0]);class I0 extends Lt{}Y(I0,"MODEL_CLASS_MAPPINGS",[t0]);class A0 extends Lt{}Y(A0,"MODEL_CLASS_MAPPINGS",[r0]);class F0 extends Lt{}Y(F0,"MODEL_CLASS_MAPPINGS",[s0]);class O0 extends Lt{}Y(O0,"MODEL_CLASS_MAPPINGS",[n0]);class D0 extends Lt{}Y(D0,"MODEL_CLASS_MAPPINGS",[o0]);class L0 extends Lt{}Y(L0,"MODEL_CLASS_MAPPINGS",[Vy]);class z0 extends Lt{}Y(z0,"MODEL_CLASS_MAPPINGS",[Uy]);class Xx extends be{constructor({logits:P,past_key_values:O,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:he=null}){super(),this.logits=P,this.past_key_values=O,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=he}}class xt extends be{constructor({logits:P,...O}){super(),this.logits=P;const ne=Object.values(O);ne.length>0&&(this.attentions=ne)}}class B0 extends be{constructor({logits:P,embeddings:O}){super(),this.logits=P,this.embeddings=O}}class Sr extends be{constructor({logits:P}){super(),this.logits=P}}class Fr extends be{constructor({logits:P}){super(),this.logits=P}}class Rr extends be{constructor({start_logits:P,end_logits:O}){super(),this.start_logits=P,this.end_logits=O}}class In extends be{constructor({logits:P}){super(),this.logits=P}}class Jx extends be{constructor({logits:P,past_key_values:O}){super(),this.logits=P,this.past_key_values=O}}class R0 extends be{constructor({alphas:P}){super(),this.alphas=P}}class j0 extends be{constructor({waveform:P,spectrogram:O}){super(),this.waveform=P,this.spectrogram=O}}},"./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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.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,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const u=this.std*2,p=l.data;for(let c=0;c{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),c=p.feature_extractor_type,d=n[c];if(!d)throw new Error(`Unknown feature_extractor_type: '${c}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new d(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"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const c=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),d=c.image_processor_type??c.feature_extractor_type;let _=i[d];return _||(d!==void 0&&console.warn(`Image processor type '${d}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),_=n.ImageProcessor),new _(c)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class u{static async from_pretrained(c,d={}){const _=await(0,o.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,d),{image_processor_type:f,feature_extractor_type:T,processor_class:k}=_;if(k&&i[k])return i[k].from_pretrained(c,d);if(!f&&!T)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(f){const S=a[f];if(!S)throw new Error(`Unknown image_processor_type: '${f}'.`);w.image_processor=new S(_)}if(T){const S=a[T];if(S)w.image_processor=new S(_);else{const E=l[T];if(!E)throw new Error(`Unknown feature_extractor_type: '${T}'.`);w.feature_extractor=new E(_)}}const g={};return new n.Processor(g,w)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.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,o.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,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let c;const d=a.length-l;if(d>0)if(u==="rand_trunc"){const _=Math.floor(Math.random()*(d+1));a=a.subarray(_,_+l),c=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(d<0){let _=new Float64Array(l);if(_.set(a),p==="repeat")for(let f=a.length;f{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var u;const l=(u=this.size)==null?void 0:u.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),[c,d]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(c,d,{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 o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const u=await super._call(l),p=[u.pixel_values.dims[0],64,64],c=(0,o.full)(p,1n);return{...u,pixel_mask:c}}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 i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[c,d,_]=l;let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(_).fill(f));let T=this.image_std;Array.isArray(T)||(T=new Array(_).fill(f));const k=f.map((w,g)=>-w/T[g]);return super.pad_image(a,l,u,{center:!0,constant_values:k,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),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"),o=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 u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,ImageFeatureExtractor:()=>T.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>f.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=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"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),c=t("./src/models/speecht5/feature_extraction_speecht5.js"),d=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),f=t("./src/models/whisper/feature_extraction_whisper.js"),T=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:c,task_prompts_with_input:d}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(c??{})),this.task_prompts_with_input=new Map(Object.entries(d??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[c,d]of this.task_prompts_with_input)if(p.includes(c)){u.push(d.replaceAll("{input}",p).replaceAll(c,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const c=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let d;switch(c){case"pure_text":d=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const _=c==="ocr"?"quad_boxes":"bboxes",f=l.matchAll(this.regexes[_]),T=[],k=[];for(const[w,g,...S]of f)T.push(g?g.trim():T.at(-1)??""),k.push(S.map((E,v)=>(Number(E)+.5)/this.size_per_bin*p[v%2]));d={labels:T,[_]:k};break;default:throw new Error(`Task "${u}" (of type "${c}") not yet implemented.`)}return{[u]:d}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=await this.image_processor(l,p),d=u?this.tokenizer(u,p):{};return{...c,...d}}}Y(i,"tokenizer_class",n.AutoTokenizer),Y(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(u,p){const d=u.dims.at(-1)-1,_=u.tolist();_.fill(!1,0,1),_.fill(!1,d);const f=p.tolist();return _.map((T,k)=>T?k:null).filter(T=>T!==null).map(T=>f[T])}class l extends s.Processor{async _call(p,c,d={}){const _=p?await this.image_processor(p,d):{};return{...c?this.tokenizer(c,d):{},..._}}post_process_grounded_object_detection(p,c,{box_threshold:d=.25,text_threshold:_=.25,target_sizes:f=null}={}){const{logits:T,pred_boxes:k}=p,w=T.dims[0];if(f!==null&&f.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=T.dims.at(1),S=T.sigmoid(),E=S.max(-1).tolist(),v=k.tolist().map(y=>y.map(C=>(0,i.center_to_corners_format)(C))),M=[];for(let y=0;yR.map((Z,H)=>Z*C[(H+1)%2])));const F=E[y],z=[],K=[],q=[];for(let R=0;R{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=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[u,p]=a.dims.slice(-2);const c=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/c),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*c),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!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 c=[],d=[],_=[];const f=[],T=[];for(const y of p){let C=await Promise.all(y.map(K=>this.preprocess(K)));f.push(...C.map(K=>K.original_size)),T.push(...C.map(K=>K.reshaped_input_size)),C.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:F}=this.max_image_size;let z;if(l??this.do_image_splitting){let K=new Array(C.length),q=new Array(C.length);z=await Promise.all(C.map(async(R,Z)=>{const H=this.get_resize_for_vision_encoder(R.pixel_values,F),J=await(0,o.interpolate_4d)(R.pixel_values,{size:[H.height,H.width]}),{frames:Q,num_splits_h:se,num_splits_w:fe}=await this.split_image(J,this.max_image_size);return K[Z]=se,q[Z]=fe,(0,o.cat)(Q,0)})),d.push(K),_.push(q)}else{const K=[F,F];z=await Promise.all(C.map(q=>(0,o.interpolate_4d)(q.pixel_values,{size:K}))),d.push(new Array(C.length).fill(0)),_.push(new Array(C.length).fill(0))}c.push((0,o.cat)(z,0))}const k=c.length,[w,g,S,E]=c[0].dims;let v,M;if(k===1)v=c[0].unsqueeze_(0),M=(0,o.full)([k,w,S,E],!0);else{const y=Math.max(...c.map(z=>z.dims.at(0)));M=(0,o.full)([k,y,S,E],!0);const C=M.data,F=y*S*E;for(let z=0;zu||_>p){f=Math.ceil(d/u),T=Math.ceil(_/p);const k=Math.ceil(d/f),w=Math.ceil(_/T);for(let E=0;E{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(c,d,_,f,T,k){let w="";for(let g=0;g`+T.repeat(c);w+=` +`}return w+=` +${f}${k}`+T.repeat(c)+`${f}`,w}function l(c,d,_,f){return`${d}${f}`+_.repeat(c)+`${d}`}function u(c,d,_,f,T,k){return c===0&&d===0?l(_,f,T,k):a(_,c,d,f,T,k)}class p extends s.Processor{constructor(){super(...arguments);Y(this,"fake_image_token","");Y(this,"image_token","");Y(this,"global_img_token","")}async _call(_,f=null,T={}){T.return_row_col_info??(T.return_row_col_info=!0);let k;f&&(k=await this.image_processor(f,T)),Array.isArray(_)||(_=[_]);const w=k.rows??[new Array(_.length).fill(0)],g=k.cols??[new Array(_.length).fill(0)],S=this.config.image_seq_len,E=[],v=[];for(let y=0;y<_.length;++y){const C=_[y],F=w[y],z=g[y];E.push((0,i.count)(C,this.image_token));const K=F.map((Z,H)=>u(Z,z[H],S,this.fake_image_token,this.image_token,this.global_img_token)),q=C.split(this.image_token);if(q.length===0)throw new Error("The image token should be present in the text.");let R=q[0];for(let Z=0;Z{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>c.DPTFeatureExtractor,DPTImageProcessor:()=>c.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>d.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>T.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>w.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>v.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>v.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>y.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>y.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>F.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>F.MobileViTImageProcessor,NougatImageProcessor:()=>z.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>R.Phi3VImageProcessor,PvtImageProcessor:()=>Z.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>J.RTDetrImageProcessor,SamImageProcessor:()=>Q.SamImageProcessor,SegformerFeatureExtractor:()=>se.SegformerFeatureExtractor,SegformerImageProcessor:()=>se.SegformerImageProcessor,SiglipImageProcessor:()=>fe.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>A.ViTFeatureExtractor,ViTImageProcessor:()=>A.ViTImageProcessor,VitMatteImageProcessor:()=>U.VitMatteImageProcessor,VitPoseImageProcessor:()=>ee.VitPoseImageProcessor,YolosFeatureExtractor:()=>_e.YolosFeatureExtractor,YolosImageProcessor:()=>_e.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=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"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),c=t("./src/models/dpt/image_processing_dpt.js"),d=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),f=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),T=t("./src/models/idefics3/image_processing_idefics3.js"),k=t("./src/models/janus/image_processing_janus.js"),w=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),v=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),y=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),F=t("./src/models/mobilevit/image_processing_mobilevit.js"),z=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),R=t("./src/models/phi3_v/image_processing_phi3_v.js"),Z=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),J=t("./src/models/rt_detr/image_processing_rt_detr.js"),Q=t("./src/models/sam/image_processing_sam.js"),se=t("./src/models/segformer/image_processing_segformer.js"),fe=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),A=t("./src/models/vit/image_processing_vit.js"),U=t("./src/models/vitmatte/image_processing_vitmatte.js"),ee=t("./src/models/vitpose/image_processing_vitpose.js"),_e=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:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(c,d){super(c,d),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(c,{images:d=null,chat_template:_="default"}={}){d?Array.isArray(d)||(d=[d]):d=await Promise.all(c.filter(z=>z.images).flatMap(z=>z.images).map(z=>l.RawImage.read(z)));const f=this.tokenizer,T=f.apply_chat_template(c,{tokenize:!1,add_generation_prompt:!0,chat_template:_}),k=z=>f.encode(z,{add_special_tokens:!1}),w=T.split(this.image_tag),g=w.length-1;if(d.length!==g)throw new Error(`Number of images provided (${d.length}) does not match number of "${this.image_tag}" image tags (${g})`);const[S,E,v]=f.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=k(w[0]),y=new Array(M.length).fill(!1);for(let z=1;z0){const z=await this.image_processor(d);return z.pixel_values.unsqueeze_(0),{...F,...z}}return F}}Y(u,"image_processor_class",o.AutoImageProcessor),Y(u,"tokenizer_class",n.AutoTokenizer),Y(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...c}=i,d=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},_=u==="bicubic"?3:2;super({...c,size:d,resample:_,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:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=l?this.tokenizer(l,p):{},d=u?await this.image_processor(u,p):{};return{...c,...d}}}Y(i,"tokenizer_class",n.AutoTokenizer),Y(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o{}},"./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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=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,c){if(!a.hasOwnProperty(c))throw new Error(`Format ${c} is not supported.`);const[d,_]=a[c],f=this[d].bind(this),[T,k]=p.dims,w=[],g=[],S=p.tolist();for(let v=0;v0?C.reduce((z,K)=>z*K,1):0;g.push(y),w.push(F)}return[f(g),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}batch_decode([p,c,d]){const[_,f]=this._decode_helper(p,"char"),[T,k]=this._decode_helper(c,"bpe"),[w,g]=this._decode_helper(d,"wp"),S=[],E=[];for(let v=0;v<_.length;++v){const[M,y]=(0,i.max)([f[v],k[v],g[v]]);S.push([_[v],T[v],w[v]][y]),E.push(M)}return{generated_text:S,scores:E,char_preds:_,bpe_preds:T,wp_preds:w}}static async from_pretrained(...p){const c=await super.from_pretrained(...p),d=await n.AutoTokenizer.from_pretrained("Xenova/gpt2"),_=await n.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return c.components={image_processor:c.image_processor,char_tokenizer:c.tokenizer,bpe_tokenizer:d,wp_tokenizer:_},c}async _call(p,c=null){const d=await this.image_processor(p);return c&&(d.labels=this.tokenizer(c).input_ids),d}}Y(l,"tokenizer_class",n.AutoTokenizer),Y(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}Y(i,"tokenizer_class",n.AutoTokenizer),Y(i,"image_processor_class",o.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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(u,p,c,d,_){return`${d.repeat(c*_)}${p}${u} +`}class l extends s.Processor{async _call(p,c=null,d={}){c||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),c=""),Array.isArray(p)||(p=[p]),Array.isArray(c)||(c=[c]);const _=this.tokenizer.bos_token,f=this.image_processor.config.image_seq_length;let T;c.some(g=>g.includes(i))?T=c.map(g=>{const S=g.replaceAll(i,i.repeat(f)),E=S.lastIndexOf(i),v=E===-1?0:E+i.length;return S.slice(0,v)+_+S.slice(v)+` +`}):(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."),T=c.map(g=>a(g,_,f,i,p.length)));const k=this.tokenizer(T,d);return{...await this.image_processor(p,d),...k}}}Y(l,"tokenizer_class",n.AutoTokenizer),Y(l,"image_processor_class",o.AutoImageProcessor),Y(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"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(d){super({...d,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=d.num_crops}calc_num_image_tokens_from_image_size(d,_){const{num_img_tokens:f}=this.config;return l((l(_/n)*l(d/n)+1)*f+1+(l(_/n)+1)*u(f))}get_resize_output_image_size(d,_){const f=this._num_crops,[T,k]=d.size;let w=T/k,g=1;for(;g*Math.ceil(g/w)<=f;)g+=1;g-=1;const S=Math.floor(g*336),E=Math.floor(S/w);return[S,E]}pad_image(d,_,f,T={}){const[k,w]=_,g=n*a(k/n),S=n*a(w/n),E=[1,1,1].map((v,M)=>(v-this.image_mean[M])/this.image_std[M]);return super.pad_image(d,_,{width:S,height:g},{center:!0,constant_values:E,...T})}async _call(d,{num_crops:_=null}={}){if(this._num_crops=_??(_=this.config.num_crops),_<4||u(_)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(d)||(d=[d]);const f=d.length,T=await Promise.all(d.map(y=>this.preprocess(y))),k=T.map(y=>y.original_size),w=T.map(y=>y.reshaped_input_size),g=[];for(const{pixel_values:y}of T){y.unsqueeze_(0);const[C,F]=y.dims.slice(-2),z=await(0,o.interpolate_4d)(y,{size:[n,n],mode:"bicubic"});if(_>0){const K=[],q=u(_),R=l(F/q),Z=l(C/q);for(let J=0;Jy.map(C=>n*a(C/n))),v=new o.Tensor("int64",E.flat(),[f,2]),M=E.map(([y,C])=>this.calc_num_image_tokens_from_image_size(C,y));return{pixel_values:S,original_sizes:k,reshaped_input_sizes:w,image_sizes:v,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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,c=null,{padding:d=!0,truncation:_=!0,num_crops:f=null}={}){Array.isArray(p)||(p=[p]);let T,k;if(c){k=await this.image_processor(c,{num_crops:f});const{num_img_tokens:w}=k,g=p.map((E,v)=>E.split(a).join(i.repeat(w[v])));T=this.tokenizer(g,{padding:d,truncation:_});const S=this.tokenizer.model.convert_tokens_to_ids([i])[0];T.input_ids.map_(E=>E==S?-E:E)}else T=this.tokenizer(p);return{...T,...k}}}Y(l,"image_processor_class",o.AutoImageProcessor),Y(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>d.PaliGemmaProcessor,Phi3VProcessor:()=>c.Phi3VProcessor,PyAnnoteProcessor:()=>_.PyAnnoteProcessor,Qwen2VLProcessor:()=>f.Qwen2VLProcessor,SamProcessor:()=>T.SamProcessor,SmolVLMProcessor:()=>k.SmolVLMProcessor,SpeechT5Processor:()=>w.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>v.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=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"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),c=t("./src/models/phi3_v/processing_phi3_v.js"),d=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/pyannote/processing_pyannote.js"),f=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),T=t("./src/models/sam/processing_sam.js"),k=t("./src/models/smolvlm/processing_smolvlm.js"),w=t("./src/models/speecht5/processing_speecht5.js"),g=t("./src/models/ultravox/processing_ultravox.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),v=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,c=[];for(const d of l.tolist()){const _=[];let f=-1;for(let T=0;T({id:T,start:k*p,end:w*p,confidence:g/(w-k)})))}return c}}},"./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"),o=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}}Y(n,"feature_extractor_class",o.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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:c}=await super._call(a,...l);let d=u;const{temporal_patch_size:_,merge_size:f,patch_size:T}=this.config;d.dims[0]===1&&(d=(0,o.cat)(Array.from({length:_},()=>d),0));const k=d.dims[0]/_,w=d.dims[1],g=Math.floor(d.dims[2]/T),S=Math.floor(d.dims[3]/T),E=d.view(k,_,w,Math.floor(g/f),f,T,Math.floor(S/f),f,T).permute(0,3,6,4,7,2,1,5,8).view(k*g*S,w*_*T*T),v=new o.Tensor("int64",[k,g,S],[1,3]);return{pixel_values:E,image_grid_thw:v,original_sizes:p,reshaped_input_sizes:c}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let c,d;if(u&&(c=await this.image_processor(u),d=c.image_grid_thw),d){let f=this.image_processor.config.merge_size**2,T=0;const k=d.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const g=Number(k[T++].reduce((S,E)=>S*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/f)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...c}}}Y(i,"image_processor_class",o.AutoImageProcessor),Y(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,u,p,c=!1){l=structuredClone(l);let d=(0,o.calculateDimensions)(l);if(d.length===3)c||(d=[1,...d]),l=[l];else if(d.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 _=0;_c!==u.dims[d]))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:u=null,input_labels:p=null,input_boxes:c=null}={}){const d=await super._call(l);if(u&&(d.input_points=this.reshape_input_points(u,d.original_sizes,d.reshaped_input_sizes)),p){if(!d.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");d.input_labels=this.add_input_labels(p,d.input_points)}return c&&(d.input_boxes=this.reshape_input_points(c,d.original_sizes,d.reshaped_input_sizes,!0)),d}async post_process_masks(l,u,p,{mask_threshold:c=0,binarize:d=!0,pad_size:_=null}={}){const f=[];_=_??this.pad_size;const T=[_.height,_.width];for(let k=0;kc&&(v[M]=1);S=new n.Tensor("bool",v,S.dims)}f.push(S)}return f}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:c=512/1500,points_per_crop:d=32,crop_n_points_downscale_factor:_=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"),o=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)}}Y(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){return l=l.map(p=>p*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:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:c=!0,return_attention_mask:d=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let _=await this._extract_fbank_features(l,this.config.max_length);if(c){const[v,M]=_.dims,y=_.data;for(let C=0;C0){const F=new Float32Array(M*(v+C));F.set(y),F.fill(this.config.padding_value,y.length);const z=v+C;_=new o.Tensor(_.type,F,[z,M]),d&&(f=new o.Tensor("int64",new BigInt64Array(z),[1,z]),f.data.fill(1n,0,v))}}const[T,k]=_.dims,w=this.config.stride;if(T%w!==0)throw new Error(`The number of frames (${T}) must be a multiple of the stride (${w}).`);const S=_.view(1,Math.floor(T/w),k*w),E={input_features:S};if(d){const v=S.dims[1],M=new BigInt64Array(v);if(f){const y=f.data;for(let C=1,F=0;C{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,u={}){const[p,c,d]=a;return super.pad_image(i,a,{width:c+(l-c%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...u})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let c={};if(u){const _=u.length,{input_features:f}=await this.feature_extractor(u,{...p,max_length:_}),T=Math.round(_/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(T/this.config.stack_factor);c.audio_token_len=[k],c.audio_values=f;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...c}}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",s.AutoFeatureExtractor),Y(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 u=await Promise.all(a.map(d=>this.preprocess(d))),p=await Promise.all(l.map(d=>this.preprocess(d,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(u.map((d,_)=>(0,o.cat)([d.pixel_values,p[_].pixel_values],0)),0),original_sizes:u.map(d=>d.original_size),reshaped_input_sizes:u.map(d=>d.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const u=i.tolist(),[p,c,d,_]=i.dims,f=[];for(let T=0;T{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((c,d)=>c+d,0)/a.length,p=a.reduce((c,d)=>c+(d-u)**2,0)/a.length;return a.map(c=>(c-u)/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 u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",s.AutoTokenizer),Y(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",s.AutoTokenizer),Y(i,"feature_extractor_class",o.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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.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 u=l.mean(1).data,p=l.data,[c,d,_]=l.dims;for(let f=0;f{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});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"]],o=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 i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[1]),o.has(a))l=a;else{const c=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(c))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,o.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,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,o.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=u.data,c=(0,n.max)(p)[0];for(let d=0;dc?(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,c)):(p=new Float32Array(c),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:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);Y(this,"return_timestamps",null);Y(this,"return_token_timestamps",null);Y(this,"num_frames",null);Y(this,"alignment_heads",null);Y(this,"task",null);Y(this,"language",null);Y(this,"no_timestamps_token_id",null);Y(this,"prompt_ids",null);Y(this,"is_multilingual",null);Y(this,"lang_to_id",null);Y(this,"task_to_id",null);Y(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Y(i,"tokenizer_class",o.AutoTokenizer),Y(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,c)=>{const d=await(0,s.createInferenceSession)(new Uint8Array(u),p);let _=Promise.resolve();return async f=>{const T=(0,s.isONNXProxy)(),k=Object.fromEntries(Object.entries(f).map(([g,S])=>[g,(T?S.clone():S).ort_tensor])),w=await(_=i?_.then(()=>d.run(k)):d.run(k));return Array.isArray(c)?c.map(g=>new o.Tensor(w[g])):new o.Tensor(w[c])}};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}}Y(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>q,AutomaticSpeechRecognitionPipeline:()=>Z,BackgroundRemovalPipeline:()=>se,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>A,FeatureExtractionPipeline:()=>z,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>Q,ImageToImagePipeline:()=>ee,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>T,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>v,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>U,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>R,ZeroShotClassificationPipeline:()=>F,ZeroShotImageClassificationPipeline:()=>fe,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>ze});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),c=t("./src/utils/image.js");async function d(pe){return Array.isArray(pe)||(pe=[pe]),await Promise.all(pe.map(W=>c.RawImage.read(W)))}async function _(pe,W){return Array.isArray(pe)||(pe=[pe]),await Promise.all(pe.map(re=>typeof re=="string"||re instanceof URL?(0,u.read_audio)(re,W):re instanceof Float64Array?new Float32Array(re):re))}function f(pe,W){W&&(pe=pe.map(Se=>Se|0));const[re,G,be,we]=pe;return{xmin:re,ymin:G,xmax:be,ymax:we}}class T extends i.Callable{constructor({task:W,model:re,tokenizer:G=null,processor:be=null}){super(),this.task=W,this.model=re,this.tokenizer=G,this.processor=be}async dispose(){await this.model.dispose()}}class k extends T{constructor(W){super(W)}async _call(W,{top_k:re=1}={}){const G=this.tokenizer(W,{padding:!0,truncation:!0}),be=await this.model(G),we=this.model.config.problem_type==="multi_label_classification"?$e=>$e.sigmoid():$e=>new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),Se=this.model.config.id2label,Ce=[];for(const $e of be.logits){const Fe=we($e),Be=await(0,p.topk)(Fe,re),He=Be[0].tolist(),ke=Be[1].tolist().map((Ve,Ze)=>({label:Se?Se[Ve]:`LABEL_${Ve}`,score:He[Ze]}));re===1?Ce.push(...ke):Ce.push(ke)}return Array.isArray(W)||re===1?Ce:Ce[0]}}class w extends T{constructor(W){super(W)}async _call(W,{ignore_labels:re=["O"]}={}){const G=Array.isArray(W),be=this.tokenizer(G?W:[W],{padding:!0,truncation:!0}),Se=(await this.model(be)).logits,Ce=this.model.config.id2label,$e=[];for(let Fe=0;FeIe==this.tokenizer.sep_token_id);$e[He].map((Ie,pt)=>Ie==1&&(pt===0||pt>ke&&Fe.findIndex(St=>St==qe[pt])===-1));const Ve=we[He].tolist(),Ze=Se[He].tolist();for(let Ie=1;Iept==qe[Ie])!==-1)&&(Ve[Ie]=-1/0,Ze[Ie]=-1/0);const nt=(0,l.softmax)(Ve).map((Ie,pt)=>[Ie,pt]),lt=(0,l.softmax)(Ze).map((Ie,pt)=>[Ie,pt]);nt[0][0]=0,lt[0][0]=0;const Ge=(0,a.product)(nt,lt).filter(Ie=>Ie[0][1]<=Ie[1][1]).map(Ie=>[Ie[0][1],Ie[1][1],Ie[0][0]*Ie[1][0]]).sort((Ie,pt)=>pt[2]-Ie[2]);for(let Ie=0;IeVe==this.tokenizer.mask_token_id);if(Fe===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Be=be[Ce][Fe],He=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Be.data),Be.dims),re),qe=He[0].tolist(),ke=He[1].tolist();we.push(ke.map((Ve,Ze)=>{const nt=$e.slice();return nt[Fe]=Ve,{score:qe[Ze],token:Number(Ve),token_str:this.tokenizer.decode([Ve]),sequence:this.tokenizer.decode(nt,{skip_special_tokens:!0})}}))}return Array.isArray(W)?we:we[0]}}class E extends T{constructor(re){super(re);Y(this,"_key","generated_text")}async _call(re,G={}){Array.isArray(re)||(re=[re]),this.model.config.prefix&&(re=re.map(Fe=>this.model.config.prefix+Fe));const be=this.model.config.task_specific_params;be&&be[this.task]&&be[this.task].prefix&&(re=re.map(Fe=>be[this.task].prefix+Fe));const we=this.tokenizer,Se={padding:!0,truncation:!0};let Ce;this instanceof M&&"_build_translation_inputs"in we?Ce=we._build_translation_inputs(re,Se,G):Ce=we(re,Se);const $e=await this.model.generate({...Ce,...G});return we.batch_decode($e,{skip_special_tokens:!0}).map(Fe=>({[this._key]:Fe}))}}class v extends E{constructor(re){super(re);Y(this,"_key","summary_text")}}class M extends E{constructor(re){super(re);Y(this,"_key","translation_text")}}function y(pe){return Array.isArray(pe)&&pe.every(W=>"role"in W&&"content"in W)}class C extends T{constructor(W){super(W)}async _call(W,re={}){let G=!1,be=!1,we;if(typeof W=="string")we=W=[W];else if(Array.isArray(W)&&W.every(ke=>typeof ke=="string"))G=!0,we=W;else{if(y(W))W=[W];else if(Array.isArray(W)&&W.every(y))G=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,we=W.map(ke=>this.tokenizer.apply_chat_template(ke,{tokenize:!1,add_generation_prompt:!0}))}const Se=re.add_special_tokens??!1,Ce=be?!1:re.return_full_text??!0;this.tokenizer.padding_side="left";const $e=this.tokenizer(we,{add_special_tokens:Se,padding:!0,truncation:!0}),Fe=await this.model.generate({...$e,...re}),Be=this.tokenizer.batch_decode(Fe,{skip_special_tokens:!0});let He;!Ce&&$e.input_ids.dims.at(-1)>0&&(He=this.tokenizer.batch_decode($e.input_ids,{skip_special_tokens:!0}).map(ke=>ke.length));const qe=Array.from({length:W.length},ke=>[]);for(let ke=0;ke[re.toLowerCase(),G])),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(W,re,{hypothesis_template:G="This example is {}.",multi_label:be=!1}={}){const we=Array.isArray(W);we||(W=[W]),Array.isArray(re)||(re=[re]);const Se=re.map(Fe=>G.replace("{}",Fe)),Ce=be||re.length===1,$e=[];for(const Fe of W){const Be=[];for(const ke of Se){const Ve=this.tokenizer(Fe,{text_pair:ke,padding:!0,truncation:!0}),Ze=await this.model(Ve);Ce?Be.push([Ze.logits.data[this.contradiction_id],Ze.logits.data[this.entailment_id]]):Be.push(Ze.logits.data[this.entailment_id])}const qe=(Ce?Be.map(ke=>(0,l.softmax)(ke)[1]):(0,l.softmax)(Be)).map((ke,Ve)=>[ke,Ve]).sort((ke,Ve)=>Ve[0]-ke[0]);$e.push({sequence:Fe,labels:qe.map(ke=>re[ke[1]]),scores:qe.map(ke=>ke[0])})}return we?$e:$e[0]}}class z extends T{constructor(W){super(W)}async _call(W,{pooling:re="none",normalize:G=!1,quantize:be=!1,precision:we="binary"}={}){const Se=this.tokenizer(W,{padding:!0,truncation:!0}),Ce=await this.model(Se);let $e=Ce.last_hidden_state??Ce.logits??Ce.token_embeddings;if(re!=="none")if(re==="mean")$e=(0,p.mean_pooling)($e,Se.attention_mask);else if(re==="cls")$e=$e.slice(null,0);else throw Error(`Pooling method '${re}' not supported.`);return G&&($e=$e.normalize(2,-1)),be&&($e=(0,p.quantize_embeddings)($e,we)),$e}}class K extends T{constructor(W){super(W)}async _call(W,{pool:re=null}={}){const G=await d(W),{pixel_values:be}=await this.processor(G),we=await this.model({pixel_values:be});let Se;if(re){if(!("pooler_output"in we))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=we.pooler_output}else Se=we.last_hidden_state??we.logits??we.image_embeds;return Se}}class q extends T{constructor(W){super(W)}async _call(W,{top_k:re=5}={}){const G=this.processor.feature_extractor.config.sampling_rate,be=await _(W,G),we=this.model.config.id2label,Se=[];for(const Ce of be){const $e=await this.processor(Ce),Be=(await this.model($e)).logits[0],He=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Be.data),Be.dims),re),qe=He[0].tolist(),Ve=He[1].tolist().map((Ze,nt)=>({label:we?we[Ze]:`LABEL_${Ze}`,score:qe[nt]}));Se.push(Ve)}return Array.isArray(W)?Se:Se[0]}}class R extends T{constructor(W){super(W)}async _call(W,re,{hypothesis_template:G="This is a sound of {}."}={}){const be=!Array.isArray(W);be&&(W=[W]);const we=re.map(Be=>G.replace("{}",Be)),Se=this.tokenizer(we,{padding:!0,truncation:!0}),Ce=this.processor.feature_extractor.config.sampling_rate,$e=await _(W,Ce),Fe=[];for(const Be of $e){const He=await this.processor(Be),qe=await this.model({...Se,...He}),ke=(0,l.softmax)(qe.logits_per_audio.data);Fe.push([...ke].map((Ve,Ze)=>({score:Ve,label:re[Ze]})))}return be?Fe[0]:Fe}}class Z extends T{constructor(W){super(W)}async _call(W,re={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(W,re);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(W,re);case"moonshine":return this._call_moonshine(W,re);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(W,re){re.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),re.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const G=!Array.isArray(W);G&&(W=[W]);const be=this.processor.feature_extractor.config.sampling_rate,we=await _(W,be),Se=[];for(const Ce of we){const $e=await this.processor(Ce),Be=(await this.model($e)).logits[0],He=[];for(const ke of Be)He.push((0,l.max)(ke.data)[1]);const qe=this.tokenizer.decode(He);Se.push({text:qe})}return G?Se[0]:Se}async _call_whisper(W,re){const G=re.return_timestamps??!1,be=re.chunk_length_s??0,we=re.force_full_sequences??!1;let Se=re.stride_length_s??null;const Ce={...re};G==="word"&&(Ce.return_token_timestamps=!0,Ce.return_timestamps=!1);const $e=!Array.isArray(W);$e&&(W=[W]);const Fe=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Be=this.processor.feature_extractor.config.hop_length,He=this.processor.feature_extractor.config.sampling_rate,qe=await _(W,He),ke=[];for(const Ve of qe){let Ze=[];if(be>0){if(Se===null)Se=be/6;else if(be<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ge=He*be,Ie=He*Se,pt=Ge-2*Ie;let St=0;for(;;){const Vt=St+Ge,Rt=Ve.subarray(St,Vt),gr=await this.processor(Rt),ir=St===0,Mt=Vt>=Ve.length;if(Ze.push({stride:[Rt.length,ir?0:Ie,Mt?0:Ie],input_features:gr.input_features,is_last:Mt}),Mt)break;St+=pt}}else Ze=[{stride:[Ve.length,0,0],input_features:(await this.processor(Ve)).input_features,is_last:!0}];for(const Ge of Ze){Ce.num_frames=Math.floor(Ge.stride[0]/Be);const Ie=await this.model.generate({inputs:Ge.input_features,...Ce});G==="word"?(Ge.tokens=Ie.sequences.tolist()[0],Ge.token_timestamps=Ie.token_timestamps.tolist()[0].map(pt=>(0,l.round)(pt,2))):Ge.tokens=Ie[0].tolist(),Ge.stride=Ge.stride.map(pt=>pt/He)}const[nt,lt]=this.tokenizer._decode_asr(Ze,{time_precision:Fe,return_timestamps:G,force_full_sequences:we});ke.push({text:nt,...lt})}return $e?ke[0]:ke}async _call_moonshine(W,re){const G=!Array.isArray(W);G&&(W=[W]);const be=this.processor.feature_extractor.config.sampling_rate,we=await _(W,be),Se=[];for(const Ce of we){const $e=await this.processor(Ce),Fe=Math.floor(Ce.length/be)*6,Be=await this.model.generate({max_new_tokens:Fe,...re,...$e}),He=this.processor.batch_decode(Be,{skip_special_tokens:!0})[0];Se.push({text:He})}return G?Se[0]:Se}}class H extends T{constructor(W){super(W)}async _call(W,re={}){const G=Array.isArray(W),be=await d(W),{pixel_values:we}=await this.processor(be),Se=[];for(const Ce of we){Ce.dims=[1,...Ce.dims];const $e=await this.model.generate({inputs:Ce,...re}),Fe=this.tokenizer.batch_decode($e,{skip_special_tokens:!0}).map(Be=>({generated_text:Be.trim()}));Se.push(Fe)}return G?Se:Se[0]}}class J extends T{constructor(W){super(W)}async _call(W,{top_k:re=5}={}){const G=await d(W),{pixel_values:be}=await this.processor(G),we=await this.model({pixel_values:be}),Se=this.model.config.id2label,Ce=[];for(const $e of we.logits){const Fe=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),re),Be=Fe[0].tolist(),qe=Fe[1].tolist().map((ke,Ve)=>({label:Se?Se[ke]:`LABEL_${ke}`,score:Be[Ve]}));Ce.push(qe)}return Array.isArray(W)?Ce:Ce[0]}}class Q extends T{constructor(W){super(W),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(W,{threshold:re=.5,mask_threshold:G=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:we=null,target_sizes:Se=null,subtask:Ce=null}={}){if(Array.isArray(W)&&W.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Fe=await d(W),Be=Fe.map(Ge=>[Ge.height,Ge.width]),He=await this.processor(Fe),{inputNames:qe,outputNames:ke}=this.model.sessions.model;if(!qe.includes("pixel_values")){if(qe.length!==1)throw Error(`Expected a single input name, but got ${qe.length} inputs: ${qe}.`);const Ge=qe[0];if(Ge in He)throw Error(`Input name ${Ge} already exists in the inputs.`);He[Ge]=He.pixel_values}const Ve=await this.model(He);let Ze=null;if(Ce!==null)Ze=this.subtasks_mapping[Ce];else if(this.processor.image_processor){for(const[Ge,Ie]of Object.entries(this.subtasks_mapping))if(Ie in this.processor.image_processor){Ze=this.processor.image_processor[Ie].bind(this.processor.image_processor),Ce=Ge;break}}const nt=this.model.config.id2label,lt=[];if(Ce)if(Ce==="panoptic"||Ce==="instance"){const Ge=Ze(Ve,re,G,be,we,Se??Be)[0],Ie=Ge.segmentation;for(const pt of Ge.segments_info){const St=new Uint8ClampedArray(Ie.data.length);for(let Rt=0;Rtgr<-1e-5||gr>1+1e-5)&&Vt.sigmoid_();const Rt=await c.RawImage.fromTensor(Vt.mul_(255).to("uint8")).resize(St[1],St[0]);lt.push({label:null,score:null,mask:Rt})}}return lt}}class se extends Q{constructor(W){super(W)}async _call(W,re={}){if(Array.isArray(W)&&W.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await d(W),we=await super._call(W,re);return be.map((Ce,$e)=>{const Fe=Ce.clone();return Fe.putAlpha(we[$e].mask),Fe})}}class fe extends T{constructor(W){super(W)}async _call(W,re,{hypothesis_template:G="This is a photo of {}"}={}){const be=Array.isArray(W),we=await d(W),Se=re.map(qe=>G.replace("{}",qe)),Ce=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:$e}=await this.processor(we),Fe=await this.model({...Ce,pixel_values:$e}),Be=this.model.config.model_type==="siglip"?qe=>qe.sigmoid().data:qe=>(0,l.softmax)(qe.data),He=[];for(const qe of Fe.logits_per_image){const Ve=[...Be(qe)].map((Ze,nt)=>({score:Ze,label:re[nt]}));Ve.sort((Ze,nt)=>nt.score-Ze.score),He.push(Ve)}return be?He:He[0]}}class ae extends T{constructor(W){super(W)}async _call(W,{threshold:re=.9,percentage:G=!1}={}){const be=Array.isArray(W);if(be&&W.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const we=await d(W),Se=G?null:we.map(ke=>[ke.height,ke.width]),{pixel_values:Ce,pixel_mask:$e}=await this.processor(we),Fe=await this.model({pixel_values:Ce,pixel_mask:$e}),Be=this.processor.image_processor.post_process_object_detection(Fe,re,Se),He=this.model.config.id2label,qe=Be.map(ke=>ke.boxes.map((Ve,Ze)=>({score:ke.scores[Ze],label:He[ke.classes[Ze]],box:f(Ve,!G)})));return be?qe:qe[0]}}class V extends T{constructor(W){super(W)}async _call(W,re,{threshold:G=.1,top_k:be=null,percentage:we=!1}={}){const Se=Array.isArray(W),Ce=await d(W),$e=this.tokenizer(re,{padding:!0,truncation:!0}),Fe=await this.processor(Ce),Be=[];for(let He=0;He({score:lt.scores[Ie],label:lt.labels[Ie],box:f(Ge,!we)}))}else{const lt=this.processor.image_processor.post_process_object_detection(Ze,G,ke,!0)[0];nt=lt.boxes.map((Ge,Ie)=>({score:lt.scores[Ie],label:re[lt.classes[Ie]],box:f(Ge,!we)}))}nt.sort((lt,Ge)=>Ge.score-lt.score),be!==null&&(nt=nt.slice(0,be)),Be.push(nt)}return Se?Be:Be[0]}}class A extends T{constructor(W){super(W)}async _call(W,re,G={}){const be=(await d(W))[0],{pixel_values:we}=await this.processor(be),Se=`${re}`,Ce=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,$e=await this.model.generate({inputs:we,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ce,...G}),Be=this.tokenizer.batch_decode($e)[0].match(/(.*?)<\/s_answer>/);let He=null;return Be&&Be.length>=2&&(He=Be[1].trim()),[{answer:He}]}}class U extends T{constructor(re){super(re);Y(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=re.vocoder??null}async _call(re,{speaker_embeddings:G=null}={}){return this.processor?this._call_text_to_spectrogram(re,{speaker_embeddings:G}):this._call_text_to_waveform(re)}async _call_text_to_waveform(re){const G=this.tokenizer(re,{padding:!0,truncation:!0}),{waveform:be}=await this.model(G),we=this.model.config.sampling_rate;return new u.RawAudio(be.data,we)}async _call_text_to_spectrogram(re,{speaker_embeddings:G}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof G=="string"||G instanceof URL)&&(G=new Float32Array(await(await fetch(G)).arrayBuffer())),G instanceof Float32Array)G=new p.Tensor("float32",G,[1,G.length]);else if(!(G instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:be}=this.tokenizer(re,{padding:!0,truncation:!0}),{waveform:we}=await this.model.generate_speech(be,G,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(we.data,Se)}}class ee extends T{constructor(W){super(W)}async _call(W){const re=await d(W),G=await this.processor(re),be=await this.model(G),we=[];for(const Se of be.reconstruction){const Ce=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");we.push(c.RawImage.fromTensor(Ce))}return we.length>1?we:we[0]}}class _e extends T{constructor(W){super(W)}async _call(W){const re=await d(W),G=await this.processor(re),{predicted_depth:be}=await this.model(G),we=[];for(let Se=0;Se1?we:we[0]}}const le=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:v,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:q,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:R,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Z,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:U,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Q,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:se,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:fe,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:A,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ee,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_e,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:z,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ye=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ze(pe,W=null,{progress_callback:re=null,config:G=null,cache_dir:be=null,local_files_only:we=!1,revision:Se="main",device:Ce=null,dtype:$e=null,subfolder:Fe="onnx",use_external_data_format:Be=null,model_file_name:He=null,session_options:qe={}}={}){pe=ye[pe]??pe;const ke=le[pe.split("_",1)[0]];if(!ke)throw Error(`Unsupported pipeline: ${pe}. Must be one of [${Object.keys(le)}]`);W||(W=ke.default.model,console.log(`No model specified. Using default model: "${W}".`));const Ve={progress_callback:re,config:G,cache_dir:be,local_files_only:we,revision:Se,device:Ce,dtype:$e,subfolder:Fe,use_external_data_format:Be,model_file_name:He,session_options:qe},Ze=new Map([["tokenizer",ke.tokenizer],["model",ke.model],["processor",ke.processor]]),nt=await Ue(Ze,W,Ve);nt.task=pe,(0,a.dispatchCallback)(re,{status:"ready",task:pe,model:W});const lt=ke.pipeline;return new lt(nt)}async function Ue(pe,W,re){const G=Object.create(null),be=[];for(const[we,Se]of pe.entries()){if(!Se)continue;let Ce;Array.isArray(Se)?Ce=new Promise(async($e,Fe)=>{var He,qe;let Be;for(const ke of Se){if(ke===null){$e(null);return}try{$e(await ke.from_pretrained(W,re));return}catch(Ve){if((He=Ve.message)!=null&&He.includes("Unsupported model type"))Be=Ve;else if((qe=Ve.message)!=null&&qe.includes("Could not locate file"))Be=Ve;else{Fe(Ve);return}}}Fe(Be)}):Ce=Se.from_pretrained(W,re),G[we]=Ce,be.push(Ce)}await Promise.all(be);for(const[we,Se]of Object.entries(G))G[we]=await Se;return G}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ft,AutoTokenizer:()=>Ds,BartTokenizer:()=>ks,BertTokenizer:()=>vt,BlenderbotSmallTokenizer:()=>Mn,BlenderbotTokenizer:()=>wn,BloomTokenizer:()=>As,CLIPTokenizer:()=>Ts,CamembertTokenizer:()=>ss,CodeGenTokenizer:()=>ls,CodeLlamaTokenizer:()=>Er,CohereTokenizer:()=>yn,ConvBertTokenizer:()=>wr,DebertaTokenizer:()=>rt,DebertaV2Tokenizer:()=>jt,DistilBertTokenizer:()=>Or,ElectraTokenizer:()=>ns,EsmTokenizer:()=>it,FalconTokenizer:()=>Ae,GPT2Tokenizer:()=>Vr,GPTNeoXTokenizer:()=>Je,GemmaTokenizer:()=>os,Grok1Tokenizer:()=>is,HerbertTokenizer:()=>Ht,LlamaTokenizer:()=>Fs,M2M100Tokenizer:()=>cr,MBart50Tokenizer:()=>vs,MBartTokenizer:()=>Qr,MPNetTokenizer:()=>Br,MarianTokenizer:()=>_n,MgpstrTokenizer:()=>vn,MobileBertTokenizer:()=>ht,NllbTokenizer:()=>as,NougatTokenizer:()=>Hs,PreTrainedTokenizer:()=>ve,Qwen2Tokenizer:()=>Nt,RoFormerTokenizer:()=>Jt,RobertaTokenizer:()=>Is,SiglipTokenizer:()=>fn,SpeechT5Tokenizer:()=>Os,SqueezeBertTokenizer:()=>ut,T5Tokenizer:()=>$s,TokenizerModel:()=>K,VitsTokenizer:()=>bn,Wav2Vec2CTCTokenizer:()=>gn,WhisperTokenizer:()=>hr,XLMRobertaTokenizer:()=>xs,XLMTokenizer:()=>ys,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function c(de,$){const j=await Promise.all([(0,n.getModelJSON)(de,"tokenizer.json",!0,$),(0,n.getModelJSON)(de,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(j[1].legacy=$.legacy),j}function d(de,$){const j=[];let X=0;for(const ie of de.matchAll($)){const ce=ie[0];X0&&j.push(ce),X=ie.index+ce.length}return X=19968&&de<=40959||de>=13312&&de<=19903||de>=131072&&de<=173791||de>=173824&&de<=177983||de>=177984&&de<=178207||de>=178208&&de<=183983||de>=63744&&de<=64255||de>=194560&&de<=195103}function E(de,$,j){const X=[];let ie=0;for(;iethis.tokens_to_ids.get(j)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(j=>this.vocab[j]??this.unk_token)}}class q extends K{constructor($){super($),this.tokens_to_ids=f($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[j,X]of this.tokens_to_ids)this.vocab[X]=j}encode($){const j=[];for(const X of $){const ie=[...X];if(ie.length>this.max_input_chars_per_word){j.push(this.unk_token);continue}let ce=!1,xe=0;const Re=[];for(;xe0&&(Ye=this.config.continuing_subword_prefix+Ye),this.tokens_to_ids.has(Ye)){We=Ye;break}--Qe}if(We===null){ce=!0;break}Re.push(We),xe=Qe}ce?j.push(this.unk_token):j.push(...Re)}return j}}class R extends K{constructor($,j){super($);const X=$.vocab.length;this.vocab=new Array(X),this.scores=new Array(X);for(let ie=0;ie[ie,ce])),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,i.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($){const j=$.chars,X=1;let ie=0;for(;ie{const de=[...Array.from({length:94},(ie,ce)=>ce+33),...Array.from({length:12},(ie,ce)=>ce+161),...Array.from({length:82},(ie,ce)=>ce+174)],$=de.slice();let j=0;for(let ie=0;ie<256;++ie)de.includes(ie)||(de.push(ie),$.push(256+j),j+=1);const X=$.map(ie=>String.fromCharCode(ie));return Object.fromEntries(de.map((ie,ce)=>[ie,X[ce]]))})(),H=(0,o.reverseDictionary)(Z);class J extends K{constructor($){super($),this.tokens_to_ids=f($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[X,ie]of this.tokens_to_ids)this.vocab[ie]=X;const j=Array.isArray($.merges[0]);this.merges=j?$.merges:$.merges.map(X=>X.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((X,ie)=>[JSON.stringify(X),ie])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe($){if($.length===0)return[];const j=this.cache.get($);if(j!==void 0)return j;const X=Array.from($);this.end_of_word_suffix&&(X[X.length-1]+=this.end_of_word_suffix);let ie=[];if(X.length>1){const ce=new l.PriorityQueue((Qe,We)=>Qe.score`<0x${Re.toString(16).toUpperCase().padStart(2,"0")}>`);xe.every(Re=>this.tokens_to_ids.has(Re))?j.push(...xe):j.push(this.unk_token)}else j.push(this.unk_token)}return j}}class Q extends K{constructor($,j){super($),this.tokens_to_ids=f(j.target_lang?$.vocab[j.target_lang]:$.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[X,ie]of this.tokens_to_ids)this.vocab[ie]=X}encode($){return $}}class se extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new pe($);case"Precompiled":return new Mt($);case"Sequence":return new Ue($);case"Replace":return new fe($);case"NFC":return new V($);case"NFD":return new A($);case"NFKC":return new U($);case"NFKD":return new ee($);case"Strip":return new _e($);case"StripAccents":return new le($);case"Lowercase":return new ye($);case"Prepend":return new ze($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class fe extends se{normalize($){const j=_(this.config.pattern);return j===null?$:$.replaceAll(j,this.config.content)}}class ae extends se{constructor(){super(...arguments);Y(this,"form")}normalize(j){return j=j.normalize(this.form),j}}class V extends ae{constructor(){super(...arguments);Y(this,"form","NFC")}}class A extends ae{constructor(){super(...arguments);Y(this,"form","NFD")}}class U extends ae{constructor(){super(...arguments);Y(this,"form","NFKC")}}class ee extends ae{constructor(){super(...arguments);Y(this,"form","NFKD")}}class _e extends se{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class le extends se{normalize($){return $=w($),$}}class ye extends se{normalize($){return $=$.toLowerCase(),$}}class ze extends se{normalize($){return $=this.config.prepend+$,$}}class Ue extends se{constructor($){super($),this.normalizers=$.normalizers.map(j=>se.fromConfig(j))}normalize($){return this.normalizers.reduce((j,X)=>X.normalize(j),$)}}class pe extends se{_tokenize_chinese_chars($){const j=[];for(let X=0;X<$.length;++X){const ie=$[X],ce=ie.charCodeAt(0);S(ce)?(j.push(" "),j.push(ie),j.push(" ")):j.push(ie)}return j.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const j=[];for(const X of $){const ie=X.charCodeAt(0);ie===0||ie===65533||this._is_control(X)||(/^\s$/.test(X)?j.push(" "):j.push(X))}return j.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class W extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new re($);case"Sequence":return new rs($);case"Whitespace":return new D($);case"WhitespaceSplit":return new oe($);case"Metaspace":return new gr($);case"ByteLevel":return new G($);case"Split":return new be($);case"Punctuation":return new we($);case"Digits":return new Se($);case"Replace":return new B($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,j){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,j){return(Array.isArray($)?$.map(X=>this.pre_tokenize_text(X,j)):this.pre_tokenize_text($,j)).flat()}_call($,j){return this.pre_tokenize($,j)}}class re extends W{constructor($){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text($,j){return $.trim().match(this.pattern)||[]}}class G extends W{constructor($){super(),this.config=$,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=Z,this.text_encoder=new TextEncoder}pre_tokenize_text($,j){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(ie=>Array.from(this.text_encoder.encode(ie),ce=>this.byte_encoder[ce]).join(""))}}class be extends W{constructor($){super(),this.config=$,this.pattern=_(this.config.pattern,this.config.invert)}pre_tokenize_text($,j){var X;return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:((X=this.config.behavior)==null?void 0:X.toLowerCase())==="removed"?$.split(this.pattern).filter(ie=>ie):d($,this.pattern)}}class we extends W{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text($,j){return $.match(this.pattern)||[]}}class Se extends W{constructor($){super(),this.config=$;const j=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(j,"gu")}pre_tokenize_text($,j){return $.match(this.pattern)||[]}}class Ce extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new Be($);case"ByteLevel":return new He($);case"RobertaProcessing":return new Fe($);case"BertProcessing":return new $e($);case"Sequence":return new qe($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...j){throw Error("post_process should be implemented in subclass.")}_call($,...j){return this.post_process($,...j)}}class $e extends Ce{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,j=null,{add_special_tokens:X=!0}={}){X&&($=(0,o.mergeArrays)([this.cls],$,[this.sep]));let ie=new Array($.length).fill(0);if(j!==null){const ce=X&&this instanceof Fe?[this.sep]:[],xe=X?[this.sep]:[];$=(0,o.mergeArrays)($,ce,j,xe),ie=(0,o.mergeArrays)(ie,new Array(j.length+ce.length+xe.length).fill(1))}return{tokens:$,token_type_ids:ie}}}class Fe extends $e{}class Be extends Ce{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,j=null,{add_special_tokens:X=!0}={}){const ie=j===null?this.single:this.pair;let ce=[],xe=[];for(const Re of ie)"SpecialToken"in Re?X&&(ce.push(Re.SpecialToken.id),xe.push(Re.SpecialToken.type_id)):"Sequence"in Re&&(Re.Sequence.id==="A"?(ce=(0,o.mergeArrays)(ce,$),xe=(0,o.mergeArrays)(xe,new Array($.length).fill(Re.Sequence.type_id))):Re.Sequence.id==="B"&&(ce=(0,o.mergeArrays)(ce,j),xe=(0,o.mergeArrays)(xe,new Array(j.length).fill(Re.Sequence.type_id))));return{tokens:ce,token_type_ids:xe}}}class He extends Ce{post_process($,j=null){return j&&($=(0,o.mergeArrays)($,j)),{tokens:$}}}class qe extends Ce{constructor($){super($),this.processors=$.processors.map(j=>Ce.fromConfig(j))}post_process($,j=null,X={}){let ie;for(const ce of this.processors)if(ce instanceof He)$=ce.post_process($).tokens,j&&(j=ce.post_process(j).tokens);else{const xe=ce.post_process($,j,X);$=xe.tokens,ie=xe.token_type_ids}return{tokens:$,token_type_ids:ie}}}class ke extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new Ge($);case"Metaspace":return new ir($);case"ByteLevel":return new Ie($);case"Replace":return new Ve($);case"ByteFallback":return new Ze($);case"Fuse":return new nt($);case"Strip":return new lt($);case"Sequence":return new St($);case"CTC":return new pt($);case"BPEDecoder":return new Vt($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class Ve extends ke{decode_chain($){const j=_(this.config.pattern);return j===null?$:$.map(X=>X.replaceAll(j,this.config.content))}}class Ze extends ke{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const j=[];let X=[];for(const ie of $){let ce=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const xe=parseInt(ie.slice(3,5),16);isNaN(xe)||(ce=xe)}if(ce!==null)X.push(ce);else{if(X.length>0){const xe=this.text_decoder.decode(Uint8Array.from(X));j.push(xe),X=[]}j.push(ie)}}if(X.length>0){const ie=this.text_decoder.decode(Uint8Array.from(X));j.push(ie),X=[]}return j}}class nt extends ke{decode_chain($){return[$.join("")]}}class lt extends ke{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(j=>{let X=0;for(let ce=0;ce(X!==0&&(j.startsWith(this.config.prefix)?j=j.replace(this.config.prefix,""):j=" "+j),this.cleanup&&(j=k(j)),j))}}class Ie extends ke{constructor($){super($),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($){const j=$.join(""),X=new Uint8Array([...j].map(ce=>this.byte_decoder[ce]));return this.text_decoder.decode(X)}decode_chain($){const j=[];let X=[];for(const ie of $)this.added_tokens.find(ce=>ce.content===ie)!==void 0?(X.length>0&&(j.push(this.convert_tokens_to_string(X)),X=[]),j.push(ie)):X.push(ie);return X.length>0&&j.push(this.convert_tokens_to_string(X)),j}}class pt extends ke{constructor($){super($),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($){if($.length===0)return"";const j=[$[0]];for(let ce=1;ce<$.length;++ce)$[ce]!==j.at(-1)&&j.push($[ce]);let ie=j.filter(ce=>ce!==this.pad_token).join("");return this.cleanup&&(ie=k(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain($){return[this.convert_tokens_to_string($)]}}class St extends ke{constructor($){super($),this.decoders=$.decoders.map(j=>ke.fromConfig(j))}decode_chain($){return this.decoders.reduce((j,X)=>X.decode_chain(j),$)}}class Vt extends ke{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((j,X)=>j.replaceAll(this.suffix,X===$.length-1?"":" "))}}class Rt extends ke{decode_chain($){let j="";for(let X=1;X<$.length;X+=2)j+=$[X];return[j]}}class gr extends W{constructor($){super(),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:j=void 0}={}){let X=$.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!X.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&j===0)&&(X=this.strRep+X),[X]}}class ir extends ke{constructor($){super($),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement}decode_chain($){const j=[];for(let X=0;X<$.length;++X){let ie=$[X].replaceAll(this.replacement," ");this.addPrefixSpace&&X==0&&ie.startsWith(" ")&&(ie=ie.substring(1)),j.push(ie)}return j}}class Mt extends se{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(X=>X.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class rs extends W{constructor($){super(),this.tokenizers=$.pretokenizers.map(j=>W.fromConfig(j))}pre_tokenize_text($,j){return this.tokenizers.reduce((X,ie)=>ie.pre_tokenize(X,j),[$])}}class D extends W{constructor($){super()}pre_tokenize_text($,j){return $.match(/\w+|[^\w\s]+/g)||[]}}class oe extends W{constructor($){super()}pre_tokenize_text($,j){return v($)}}class B extends W{constructor($){super(),this.config=$,this.pattern=_(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,j){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}const te=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function me(de,$,j,X){for(const ie of Object.keys(de)){const ce=$-de[ie].length,xe=j(ie),Re=new Array(ce).fill(xe);de[ie]=X==="right"?(0,o.mergeArrays)(de[ie],Re):(0,o.mergeArrays)(Re,de[ie])}}function Oe(de,$){for(const j of Object.keys(de))de[j].length=$}class ve extends s.Callable{constructor(j,X){super();Y(this,"return_token_type_ids",!1);Y(this,"padding_side","right");this._tokenizer_config=X,this.normalizer=se.fromConfig(j.normalizer),this.pre_tokenizer=W.fromConfig(j.pre_tokenizer),this.model=K.fromConfig(j.model,X),this.post_processor=Ce.fromConfig(j.post_processor),this.decoder=ke.fromConfig(j.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of j.added_tokens){const ce=new z(ie);this.added_tokens.push(ce),this.model.tokens_to_ids.set(ce.content,ce.id),this.model.vocab[ce.id]=ce.content,ce.special&&(this.special_tokens.push(ce.content),this.all_special_ids.push(ce.id))}if(this.additional_special_tokens=X.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_splitter=new l.DictionarySplitter(this.added_tokens.map(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),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=X.model_max_length,this.remove_space=X.remove_space,this.clean_up_tokenization_spaces=X.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=X.do_lowercase_and_remove_accent??!1,X.padding_side&&(this.padding_side=X.padding_side),this.legacy=!1,this.chat_template=X.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:ce,template:xe}of this.chat_template){if(typeof ce!="string"||typeof xe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[ce]=xe}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...j){for(const X of j){const ie=this._tokenizer_config[X];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(j,{progress_callback:X=null,config:ie=null,cache_dir:ce=null,local_files_only:xe=!1,revision:Re="main",legacy:Qe=null}={}){const We=await c(j,{progress_callback:X,config:ie,cache_dir:ce,local_files_only:xe,revision:Re,legacy:Qe});return new this(...We)}_call(j,{text_pair:X=null,add_special_tokens:ie=!0,padding:ce=!1,truncation:xe=null,max_length:Re=null,return_tensor:Qe=!0,return_token_type_ids:We=null}={}){const Ye=Array.isArray(j);let _t;if(Ye){if(j.length===0)throw Error("text array must be non-empty");if(X!==null){if(Array.isArray(X)){if(j.length!==X.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");_t=j.map((At,Yt)=>this._encode_plus(At,{text_pair:X[Yt],add_special_tokens:ie,return_token_type_ids:We}))}else _t=j.map(At=>this._encode_plus(At,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(j==null)throw Error("text may not be null or undefined");if(Array.isArray(X))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");_t=[this._encode_plus(j,{text_pair:X,add_special_tokens:ie,return_token_type_ids:We})]}if(Re===null?Re=this.model_max_length:xe===null&&(ce===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),Re=this.model_max_length):ce===!1&&(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."),xe=!0)),ce===!0&&(Re=Math.min((0,i.max)(_t.map(At=>At.input_ids.length))[0],Re??1/0)),Re=Math.min(Re,this.model_max_length??1/0),ce||xe)for(let At=0;At<_t.length;++At)_t[At].input_ids.length!==Re&&(_t[At].input_ids.length>Re?xe&&Oe(_t[At],Re):ce&&me(_t[At],Re,Yt=>Yt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ot={};if(Qe){if(!(ce&&xe)&&_t.some(Yt=>{var Ut;for(const mr of Object.keys(Yt))if(Yt[mr].length!==((Ut=_t[0][mr])==null?void 0:Ut.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 At=[_t.length,_t[0].input_ids.length];for(const Yt of Object.keys(_t[0]))Ot[Yt]=new a.Tensor("int64",BigInt64Array.from(_t.flatMap(Ut=>Ut[Yt]).map(BigInt)),At)}else{for(const At of Object.keys(_t[0]))Ot[At]=_t.map(Yt=>Yt[At]);if(!Ye)for(const At of Object.keys(Ot))Ot[At]=Ot[At][0]}return Ot}_encode_text(j){if(j===null)return null;const X=this.added_tokens_splitter.split(j);for(let ce=0;ce0&&(X[ce-1]=X[ce-1].trimEnd()),xe.rstrip&&ce{if(ce.length===0)return[];if(this.added_tokens_map.has(ce))return[ce];if(this.remove_space===!0&&(ce=ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ce=g(ce)),this.normalizer!==null&&(ce=this.normalizer(ce)),ce.length===0)return[];const Re=this.pre_tokenizer!==null?this.pre_tokenizer(ce,{section_index:xe}):[ce];return this.model(Re)})}_encode_plus(j,{text_pair:X=null,add_special_tokens:ie=!0,return_token_type_ids:ce=null}={}){const{tokens:xe,token_type_ids:Re}=this._tokenize_helper(j,{pair:X,add_special_tokens:ie}),Qe=this.model.convert_tokens_to_ids(xe),We={input_ids:Qe,attention_mask:new Array(Qe.length).fill(1)};return(ce??this.return_token_type_ids)&&Re&&(We.token_type_ids=Re),We}_tokenize_helper(j,{pair:X=null,add_special_tokens:ie=!1}={}){const ce=this._encode_text(j),xe=this._encode_text(X);return this.post_processor?this.post_processor(ce,xe,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(ce??[],xe??[])}}tokenize(j,{pair:X=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(j,{pair:X,add_special_tokens:ie}).tokens}encode(j,{text_pair:X=null,add_special_tokens:ie=!0,return_token_type_ids:ce=null}={}){return this._encode_plus(j,{text_pair:X,add_special_tokens:ie,return_token_type_ids:ce}).input_ids}batch_decode(j,X={}){return j instanceof a.Tensor&&(j=j.tolist()),j.map(ie=>this.decode(ie,X))}decode(j,X={}){if(j instanceof a.Tensor&&(j=T(j)),!Array.isArray(j)||j.length===0||!(0,o.isIntegralNumber)(j[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(j,X)}decode_single(j,{skip_special_tokens:X=!1,clean_up_tokenization_spaces:ie=null}){let ce=this.model.convert_ids_to_tokens(j);X&&(ce=ce.filter(Re=>!this.special_tokens.includes(Re)));let xe=this.decoder?this.decoder(ce):ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(xe=xe.replaceAll(this.decoder.end_of_word_suffix," "),X&&(xe=xe.trim())),(ie??this.clean_up_tokenization_spaces)&&(xe=k(xe)),xe}get_chat_template({chat_template:j=null,tools:X=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(j!==null&&Object.hasOwn(ie,j))j=ie[j];else if(j===null)if(X!==null&&"tool_use"in ie)j=ie.tool_use;else if("default"in ie)j=ie.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(ie).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:X=null,documents:ie=null,chat_template:ce=null,add_generation_prompt:xe=!1,tokenize:Re=!0,padding:Qe=!1,truncation:We=!1,max_length:Ye=null,return_tensor:_t=!0,return_dict:Ot=!1,tokenizer_kwargs:At={},...Yt}={}){if(ce=this.get_chat_template({chat_template:ce,tools:X}),typeof ce!="string")throw Error(`chat_template must be a string, but got ${typeof ce}`);let Ut=this._compiled_template_cache.get(ce);Ut===void 0&&(Ut=new u.Template(ce),this._compiled_template_cache.set(ce,Ut));const mr=Object.create(null);for(const Pr of te){const Cr=this.getToken(Pr);Cr&&(mr[Pr]=Cr)}const Mr=Ut.render({messages:j,add_generation_prompt:xe,tools:X,documents:ie,...mr,...Yt});if(Re){const Pr=this._call(Mr,{add_special_tokens:!1,padding:Qe,truncation:We,max_length:Ye,return_tensor:_t,...At});return Ot?Pr:Pr.input_ids}return Mr}}class vt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Ft extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class ht extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class ut extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class rt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class jt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Ht extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class wr extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Jt extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class Or extends ve{}class ss extends ve{}class ys extends ve{constructor(j,X){super(j,X);Y(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 ns extends ve{constructor(){super(...arguments);Y(this,"return_token_type_ids",!0)}}class $s extends ve{}class Vr extends ve{}class ks extends ve{}class Qr extends ve{constructor($,j){super($,j),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)),this.lang_to_token=X=>X}_build_translation_inputs($,j,X){return ur(this,$,j,X)}}class vs extends Qr{}class Is extends ve{}class As extends ve{}const ar="▁";class Fs extends ve{constructor(j,X){super(j,X);Y(this,"padding_side","left");this.legacy=X.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gr({replacement:ar,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 X=super._encode_text(ar+j.replaceAll(ar," "));return X.length>1&&X[0]===ar&&this.special_tokens.includes(X[1])&&(X=X.slice(1)),X}}class Er extends ve{}class xs extends ve{}class Br extends ve{}class Ae extends ve{}class Je extends ve{}class it extends ve{}class Nt extends ve{}class os extends ve{}class is extends ve{}function ur(de,$,j,X){if(!("language_codes"in de)||!Array.isArray(de.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in de)||!(de.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in de)||typeof de.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=X.src_lang,ce=X.tgt_lang;if(!de.language_codes.includes(ce))throw new Error(`Target language code "${ce}" is not valid. Must be one of: {${de.language_codes.join(", ")}}`);if(ie!==void 0){if(!de.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${de.language_codes.join(", ")}}`);for(const xe of de.post_processor.config.single)if("SpecialToken"in xe&&de.languageRegex.test(xe.SpecialToken.id)){xe.SpecialToken.id=de.lang_to_token(ie);break}}return X.forced_bos_token_id=de.model.convert_tokens_to_ids([de.lang_to_token(ce)])[0],de._call($,j)}class as extends ve{constructor($,j){super($,j),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)),this.lang_to_token=X=>X}_build_translation_inputs($,j,X){return ur(this,$,j,X)}}class cr extends ve{constructor($,j){super($,j),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)).map(X=>X.slice(2,-2)),this.lang_to_token=X=>`__${X}__`}_build_translation_inputs($,j,X){return ur(this,$,j,X)}}class hr extends ve{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:j=!1,return_language:X=!1,time_precision:ie=null,force_full_sequences:ce=!0}={}){if(ie===null)throw Error("Must specify time_precision");let xe=null;const Re=j==="word";function Qe(){return{language:xe,timestamp:[null,null],text:""}}const We=[];let Ye=Qe(),_t=0;const Ot=this.timestamp_begin,Yt=Ot+1500;let Ut=[],mr=[],Mr=!1,Pr=null;const Cr=new Set(this.all_special_ids);for(const Kt of $){const fr=Kt.tokens,Dr=Re?Kt.token_timestamps:null;let Xr=null,Jr=Ot;if("stride"in Kt){const[br,er,dr]=Kt.stride;if(_t-=er,Pr=br-dr,er&&(Jr=er/ie+Ot),dr)for(let pr=fr.length-1;pr>=0;--pr){const Ar=Number(fr[pr]);if(Ar>=Ot){if(Xr!==null&&(Ar-Ot)*ie=Ot&&er<=Yt){const dr=(er-Ot)*ie+_t,pr=(0,i.round)(dr,2);if(Xr!==null&&er>=Xr)Mr=!0;else if(Mr||Ut.length>0&&er0?(Ut.push(Ir),Re&&mr.push(Lr)):Ut.every(br=>br.length===0)&&(Ye=Qe(),Ut=[],Ir=[],mr=[],Lr=[])}if(Ut.length>0){if(ce&&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[Kt,fr]=this.findLongestCommonSequence(Ut,mr),Dr=this.decode(Kt);Ye.text=Dr,Re&&(Ye.words=this.collateWordTimestamps(Kt,fr,xe)),We.push(Ye)}let Zt=Object.create(null);const Es=We.map(Kt=>Kt.text).join("");if(j||X){for(let Kt=0;Kt0;let Re=xe?[]:null,Qe=xe?j[0]:null;for(let We=1;We<$.length;++We){const Ye=$[We];let _t=0,Ot=[ie,ie,0,0];const At=Ye.length;for(let Zt=1;Zter===Jr[dr]&&Qe[Es+dr]<=j[We][Dr+dr]).length:Ir=fr.filter((er,dr)=>er===Jr[dr]).length;const Lr=Zt/1e4,br=Ir/Zt+Lr;Ir>1&&br>_t&&(_t=br,Ot=[Es,Kt,Dr,Xr])}const[Yt,Ut,mr,Mr]=Ot,Pr=Math.floor((Ut+Yt)/2),Cr=Math.floor((Mr+mr)/2);ce.push(...X.slice(0,Pr)),X=Ye.slice(Cr),ie=X.length,xe&&(Re.push(...Qe.slice(0,Pr)),Qe=j[We].slice(Cr))}return ce.push(...X),xe?(Re.push(...Qe),[ce,Re]):[ce,[]]}collateWordTimestamps($,j,X){const[ie,ce,xe]=this.combineTokensIntoWords($,X),Re=[];for(let Qe=0;Qe=ie){const Re=((xe-ie)*X).toFixed(2);ce.push(`<|${Re}|>`),ce.push([])}else ce[ce.length-1].push(xe);return ce=ce.map(xe=>typeof xe=="string"?xe:super.decode(xe,j)),ce.join("")}splitTokensOnUnicode($){const j=this.decode($,{decode_with_timestamps:!0}),X="�",ie=[],ce=[],xe=[];let Re=[],Qe=[],We=0;for(let Ye=0;Ye<$.length;++Ye){const _t=$[Ye];Re.push(_t),Qe.push(Ye);const Ot=this.decode(Re,{decode_with_timestamps:!0});(!Ot.includes(X)||j[We+Ot.indexOf(X)]===X)&&(ie.push(Ot),ce.push(Re),xe.push(Qe),Re=[],Qe=[],We+=Ot.length)}return[ie,ce,xe]}splitTokensOnSpaces($){const[j,X,ie]=this.splitTokensOnUnicode($),ce=[],xe=[],Re=[],Qe=new RegExp(`^[${M}]$`,"gu");for(let We=0;We=this.model.tokens_to_ids.get("<|endoftext|>"),Yt=Ye.startsWith(" "),Ut=Ye.trim(),mr=Qe.test(Ut);if(At||Yt||mr||ce.length===0)ce.push(Ye),xe.push(_t),Re.push(Ot);else{const Mr=ce.length-1;ce[Mr]+=Ye,xe[Mr].push(..._t),Re[Mr].push(...Ot)}}return[ce,xe,Re]}mergePunctuations($,j,X,ie,ce){const xe=structuredClone($),Re=structuredClone(j),Qe=structuredClone(X);let We=xe.length-2,Ye=xe.length-1;for(;We>=0;)xe[We].startsWith(" ")&&ie.includes(xe[We].trim())?(xe[Ye]=xe[We]+xe[Ye],Re[Ye]=(0,o.mergeArrays)(Re[We],Re[Ye]),Qe[Ye]=(0,o.mergeArrays)(Qe[We],Qe[Ye]),xe[We]="",Re[We]=[],Qe[We]=[]):Ye=We,--We;for(We=0,Ye=1;Ye_t),Re.filter(_t=>_t.length>0),Qe.filter(_t=>_t.length>0)]}}class ls extends ve{}class Ts extends ve{}class fn extends ve{}class _n extends ve{constructor($,j){super($,j),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(X=>this.languageRegex.test(X)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[j,...X]=$.trim().split(this.languageRegex);if(X.length===0)return super._encode_text(j);if(X.length===2){const[ie,ce]=X;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(ce))}}}class gn extends ve{}class wn extends ve{}class Mn extends ve{}class Os extends ve{}class Hs extends ve{}class bn extends ve{constructor($,j){super($,j),this.decoder=new Rt({})}}class yn extends ve{}class vn extends ve{}class Ds{static async from_pretrained($,{progress_callback:j=null,config:X=null,cache_dir:ie=null,local_files_only:ce=!1,revision:xe="main",legacy:Re=null}={}){var Ot;const[Qe,We]=await c($,{progress_callback:j,config:X,cache_dir:ie,local_files_only:ce,revision:xe,legacy:Re}),Ye=((Ot=We.tokenizer_class)==null?void 0:Ot.replace(/Fast$/,""))??"PreTrainedTokenizer";let _t=this.TOKENIZER_CLASS_MAPPING[Ye];return _t||(console.warn(`Unknown tokenizer class "${Ye}", attempting to construct from base class.`),_t=ve),new _t(Qe,We)}}Y(Ds,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:$s,DistilBertTokenizer:Or,CamembertTokenizer:ss,DebertaTokenizer:rt,DebertaV2Tokenizer:jt,BertTokenizer:vt,HerbertTokenizer:Ht,ConvBertTokenizer:wr,RoFormerTokenizer:Jt,XLMTokenizer:ys,ElectraTokenizer:ns,MobileBertTokenizer:ht,SqueezeBertTokenizer:ut,AlbertTokenizer:Ft,GPT2Tokenizer:Vr,BartTokenizer:ks,MBartTokenizer:Qr,MBart50Tokenizer:vs,RobertaTokenizer:Is,WhisperTokenizer:hr,CodeGenTokenizer:ls,CLIPTokenizer:Ts,SiglipTokenizer:fn,MarianTokenizer:_n,BloomTokenizer:As,NllbTokenizer:as,M2M100Tokenizer:cr,LlamaTokenizer:Fs,CodeLlamaTokenizer:Er,XLMRobertaTokenizer:xs,MPNetTokenizer:Br,FalconTokenizer:Ae,GPTNeoXTokenizer:Je,EsmTokenizer:it,Wav2Vec2CTCTokenizer:gn,BlenderbotTokenizer:wn,BlenderbotSmallTokenizer:Mn,SpeechT5Tokenizer:Os,NougatTokenizer:Hs,VitsTokenizer:bn,Qwen2Tokenizer:Nt,GemmaTokenizer:os,Grok1Tokenizer:is,CohereTokenizer:yn,MgpstrTokenizer:vn,PreTrainedTokenizer:ve})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>d,hanning:()=>c,mel_filter_bank:()=>S,read_audio:()=>u,spectrogram:()=>C,window_function:()=>F});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(R,Z){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)(R)).arrayBuffer(),J=new AudioContext({sampleRate:Z});typeof Z>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const Q=await J.decodeAudioData(H);let se;if(Q.numberOfChannels===2){const fe=Math.sqrt(2),ae=Q.getChannelData(0),V=Q.getChannelData(1);se=new Float32Array(ae.length);for(let A=0;A2595*Math.log10(1+R/700),kaldi:R=>1127*Math.log(1+R/700),slaney:(R,Z=1e3,H=15,J=27/Math.log(6.4))=>R>=Z?H+Math.log(R/Z)*J:3*R/200};function f(R,Z="htk"){const H=_[Z];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(J=>H(J))}const T={htk:R=>700*(10**(R/2595)-1),kaldi:R=>700*(Math.exp(R/1127)-1),slaney:(R,Z=1e3,H=15,J=Math.log(6.4)/27)=>R>=H?Z*Math.exp(J*(R-H)):200*R/3};function k(R,Z="htk"){const H=T[Z];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(J=>H(J))}function w(R,Z){const H=Float64Array.from({length:Z.length-1},(fe,ae)=>Z[ae+1]-Z[ae]),J=Array.from({length:R.length},()=>new Array(Z.length));for(let fe=0;fenew Array(R.length));for(let fe=0;feR+J*se)}function S(R,Z,H,J,Q,se=null,fe="htk",ae=!1){if(se!==null&&se!=="slaney")throw new Error('norm must be one of null or "slaney"');if(R<2)throw new Error(`Require num_frequency_bins: ${R} >= 2`);if(H>J)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${J}`);const V=f(H,fe),A=f(J,fe),U=g(V,A,Z+2);let ee=k(U,fe),_e;if(ae){const ye=Q/((R-1)*2);_e=f(Float64Array.from({length:R},(ze,Ue)=>Ue*ye),fe),ee=U}else _e=g(0,Math.floor(Q/2),R);const le=w(_e,ee);if(se!==null&&se==="slaney")for(let ye=0;yeQ)throw Error(`frame_length (${H}) may not be larger than fft_length (${Q})`);if(be!==H)throw new Error(`Length of the window (${be}) must equal frame_length (${H})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(se===null&&U!==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(fe){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const nt=Math.floor((Q-1)/2)+1;R=E(R,nt,nt)}let we=Math.floor(1+Math.floor((R.length-H)/J));pe!==null&&wewe?re&&($e=W):$e=Ce=W);const Fe=new o.FFT(Q),Be=new Float64Array(Q),He=new Float64Array(Fe.outputBufferSize),qe=new Float32Array(Se*$e);for(let nt=0;nt=1;--Ie)Be[Ie]-=A*Be[Ie-1];Be[0]*=1-A}for(let Ie=0;IeMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${Z}.`)}if(H&&(fe=fe.subarray(0,R)),J===null)return fe;if(R>J)throw new Error(`Length of the window (${R}) may not be larger than frame_length (${J})`);return fe}function z(R,Z){let H=44;const J=new ArrayBuffer(H+R.length*4),Q=new DataView(J);K(Q,0,"RIFF"),Q.setUint32(4,36+R.length*4,!0),K(Q,8,"WAVE"),K(Q,12,"fmt "),Q.setUint32(16,16,!0),Q.setUint16(20,3,!0),Q.setUint16(22,1,!0),Q.setUint32(24,Z,!0),Q.setUint32(28,Z*4,!0),Q.setUint16(32,4,!0),Q.setUint16(34,32,!0),K(Q,36,"data"),Q.setUint32(40,R.length*4,!0);for(let se=0;se{let se=await Q.arrayBuffer();a.writeFileSync(J,Buffer.from(se))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Z,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>_,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>c,pick:()=>T,pop:()=>p,product:()=>d,reverseDictionary:()=>o,saveBlob:()=>f});function s(g,S){g&&g(S)}function o(g){return Object.fromEntries(Object.entries(g).map(([S,E])=>[E,S]))}function n(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(g){var S,E,v;return((v=(E=(S=g==null?void 0:g.prototype)==null?void 0:S.__proto__)==null?void 0:E.constructor)==null?void 0:v.name)==="TypedArray"}function a(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function u(g){const S=[];let E=g;for(;Array.isArray(E);)S.push(E.length),E=E[0];return S}function p(g,S,E=void 0){const v=g[S];if(v!==void 0)return delete g[S],v;if(E===void 0)throw Error(`Key ${S} does not exist in object.`);return E}function c(...g){return Array.prototype.concat.apply([],g)}function d(...g){return g.reduce((S,E)=>S.flatMap(v=>E.map(M=>[v,M])))}function _(g,S){return Math.abs((g+S)%(2*S)-S)}function f(g,S){const E=URL.createObjectURL(S),v=document.createElement("a");v.href=E,v.download=g,v.click(),v.remove(),URL.revokeObjectURL(E)}function T(g,S){return Object.assign({},...S.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function k(g){let S=0;for(const E of g)++S;return S}function w(g,S){let E=0;for(const v of g)v===S&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(c=(_,f)=>_>f,d=1/0){this._heap=[],this._comparator=c,this._maxSize=d}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...c){return this.extend(c)}extend(c){for(const d of c)if(this.size0&&this._swap(0,d),this._heap.pop(),this._siftDown(),c}replace(c){const d=this.peek();return this._heap[0]=c,this._siftDown(),d}_parent(c){return(c+1>>>1)-1}_left(c){return(c<<1)+1}_right(c){return c+1<<1}_greater(c,d){return this._comparator(this._heap[c],this._heap[d])}_swap(c,d){const _=this._heap[c];this._heap[c]=this._heap[d],this._heap[d]=_}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(c){for(;c>0&&this._greater(c,this._parent(c));)this._swap(c,this._parent(c)),c=this._parent(c)}_siftDown(){let c=0;for(;this._left(c)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const f=new a(this.bosTokenId,0,0,0,0),T=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(f.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(f)}insert(c,d,_,f){const T=this.nodes.length,k=new a(f,T,c,d,_);this.beginNodes[c].push(k),this.endNodes[c+d].push(k),this.nodes.push(k)}viterbi(){const c=this.len;let d=0;for(;d<=c;){if(this.beginNodes[d].length==0)return[];for(let w of this.beginNodes[d]){w.prev=null;let g=0,S=null;for(let E of this.endNodes[d]){const v=E.backtraceScore+w.score;(S===null||v>g)&&(S=E.clone(),g=v)}if(S!==null)w.prev=S,w.backtraceScore=g;else return[]}++d}const _=[],T=this.beginNodes[c][0].prev;if(T===null)return[];let k=T.clone();for(;k.prev!==null;)_.push(k.clone()),k=k.clone().prev.clone();return _.reverse(),_}piece(c){return this.chars.slice(c.pos,c.pos+c.length).join("")}tokens(){return this.viterbi().map(d=>this.piece(d))}tokenIds(){return this.viterbi().map(d=>d.tokenId)}}class a{constructor(c,d,_,f,T){this.tokenId=c,this.nodeId=d,this.pos=_,this.length=f,this.score=T,this.prev=null,this.backtraceScore=0}clone(){const c=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return c.prev=this.prev,c.backtraceScore=this.backtraceScore,c}}class l{constructor(c){this.trie=this._buildTrie(c)}_buildTrie(c){var _;const d=Object.create(null);for(const f of c){let T=d;for(let k=0;kf&&d.push(c.slice(f,T)),d.push(w),T+=w.length,f=T):++T}return f<_&&d.push(c.slice(f)),d}}class u{constructor(c){this.capacity=c,this.cache=new Map}get(c){if(!this.cache.has(c))return;const d=this.cache.get(c);return this.cache.delete(c),this.cache.set(c,d),d}put(c,d){this.cache.has(c)&&this.cache.delete(c),this.cache.set(c,d),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./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:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){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:()=>_,getModelFile:()=>g,getModelJSON:()=>S});var s=t("?7a2c"),o=t("?a42a"),n=t("./src/env.js"),i=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 u{constructor(y){if(this.filePath=y,this.headers=new Headers,this.exists=s.existsSync(y),this.exists){this.status=200,this.statusText="OK";let C=s.statSync(y);this.headers.set("content-length",C.size.toString()),this.updateContentType();const F=s.createReadStream(y);this.body=new ReadableStream({start(z){F.on("data",K=>z.enqueue(K)),F.on("end",()=>z.close()),F.on("error",K=>z.error(K))},cancel(){F.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const y=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[y]??"application/octet-stream")}clone(){let y=new u(this.filePath);return y.exists=this.exists,y.status=this.status,y.statusText=this.statusText,y.headers=new Headers(this.headers),y}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const y=await s.promises.readFile(this.filePath);return new Blob([y],{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(M,y=null,C=null){let F;try{F=new URL(M)}catch{return!1}return!(y&&!y.includes(F.protocol)||C&&!C.includes(F.hostname))}const c=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function d(M){return!(!c.test(M)||M.includes("..")||M.includes("--")||M.endsWith(".git")||M.endsWith(".ipynb"))}async function _(M){var y;if(n.env.useFS&&!p(M,["http:","https:","blob:"]))return new u(M instanceof URL?M.protocol==="file:"?M.pathname:M.toString():M);if(typeof process<"u"&&((y=process==null?void 0:process.release)==null?void 0:y.name)==="node"){const C=!!(js!=null&&js.TESTING_REMOTELY),F=n.env.version,z=new Headers;if(z.set("User-Agent",`transformers.js/${F}; is_ci/${C};`),p(M,["http:","https:"],["huggingface.co","hf.co"])){const q=(js==null?void 0:js.HF_TOKEN)??(js==null?void 0:js.HF_ACCESS_TOKEN);q&&z.set("Authorization",`Bearer ${q}`)}return fetch(M,{headers:z})}else return fetch(M)}const f={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 T(M,y,C){if(!C)return null;const F=f[M]??`Error (${M}) occurred while trying to load file`;throw Error(`${F}: "${y}".`)}class k{constructor(y){this.path=y}async match(y){let C=o.join(this.path,y),F=new u(C);if(F.exists)return F}async put(y,C,F=void 0){let z=o.join(this.path,y);try{const K=C.headers.get("Content-Length"),q=parseInt(K??"0");let R=0;await s.promises.mkdir(o.dirname(z),{recursive:!0});const Z=s.createWriteStream(z),H=C.body.getReader();for(;;){const{done:J,value:Q}=await H.read();if(J)break;await new Promise((fe,ae)=>{Z.write(Q,V=>{if(V){ae(V);return}fe()})}),R+=Q.length;const se=q?R/q*100:0;F==null||F({progress:se,loaded:R,total:q})}Z.close()}catch(K){try{await s.promises.unlink(z)}catch{}throw K}}}async function w(M,...y){for(let C of y)try{let F=await M.match(C);if(F)return F}catch{continue}}async function g(M,y,C=!0,F={},z=!1){if(!n.env.allowLocalModels){if(F.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,i.dispatchCallback)(F.progress_callback,{status:"initiate",name:M,file:y});let K;if(!K&&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");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(ee){console.warn("An error occurred while opening the browser cache:",ee)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new k(F.cache_dir??n.env.cacheDir)}const q=F.revision??"main",R=v(M,y),Z=d(M),H=Z?v(n.env.localModelPath,R):R,J=v(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",M).replaceAll("{revision}",encodeURIComponent(q)),y);let Q;const se=K instanceof k?q==="main"?R:v(M,q,y):J;let fe=!1,ae;K&&(ae=await w(K,H,se));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(R,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${R}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${R}.`)}else try{ae=await _(H),Q=H}catch(_e){console.warn(`Unable to load from local path "${H}": "${_e}"`)}if(ae===void 0||ae.status===404){if(F.local_files_only||!n.env.allowRemoteModels){if(C)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!Z)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${M}".`);if(ae=await _(J),ae.status!==200)return T(ae.status,J,C);Q=se}fe=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(F.progress_callback,{status:"download",name:M,file:y});let A;if(!(n.apis.IS_NODE_ENV&&z)){let ee;F.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ee=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:M,file:y,progress:100,loaded:ee.length,total:ee.length})):ee=await E(ae,_e=>{(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:M,file:y,..._e})}):ee=new Uint8Array(await ae.arrayBuffer()),A=ee}if(fe&&Q&&await K.match(Q)===void 0&&(A?await K.put(Q,new Response(A,{headers:ae.headers})).catch(ee=>{console.warn(`Unable to add response to browser cache: ${ee}.`)}):await K.put(Q,ae,F.progress_callback)),(0,i.dispatchCallback)(F.progress_callback,{status:"done",name:M,file:y}),A){if(!n.apis.IS_NODE_ENV&&z)throw new Error("Cannot return path in a browser environment.");return A}if(ae instanceof u)return ae.filePath;const U=await(K==null?void 0:K.match(Q));if(U instanceof u)return U.filePath;if(U instanceof Response)return new Uint8Array(await U.arrayBuffer());if(typeof U=="string")return U;throw new Error("Unable to get model file path or buffer.")}async function S(M,y,C=!0,F={}){const z=await g(M,y,C,F,!1);if(z===null)return{};const q=new TextDecoder("utf-8").decode(z);return JSON.parse(q)}async function E(M,y){const C=M.headers.get("Content-Length");C===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(C??"0"),z=new Uint8Array(F),K=0;const q=M.body.getReader();async function R(){const{done:Z,value:H}=await q.read();if(Z)return;const J=K+H.length;if(J>F){F=J;const se=new Uint8Array(F);se.set(z),z=se}z.set(H,K),K=J;const Q=K/F*100;return y({progress:Q,loaded:K,total:F}),R()}return await R(),z}function v(...M){return M=M.map((y,C)=>(C&&(y=y.replace(new RegExp("^/"),"")),C!==M.length-1&&(y=y.replace(new RegExp("/$"),"")),y)),M.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>f,load_image:()=>T});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const c=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(c)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async k=>{const g=(await k.metadata()).channels,{data:S,info:E}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),v=new f(new Uint8ClampedArray(S),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&v.convert(g),v};else throw new Error("Unable to load image processing library.");const d={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(w,g,S,E){this.data=w,this.width=g,this.height=S,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof f)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!c)throw new Error("fromCanvas() is only supported in browser environments.");const S=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new f(S,w.width,w.height,4)}static async fromURL(w){const g=await(0,o.getFile)(w);if(g.status!==200)throw new Error(`Unable to read image from "${w}" (${g.status} ${g.statusText})`);const S=await g.blob();return this.fromBlob(S)}static async fromBlob(w){if(c){const g=await p(w),S=l(g.width,g.height).getContext("2d");return S.drawImage(g,0,0),new this(S.getImageData(0,0,g.width,g.height).data,g.width,g.height,4)}else{const g=a(await w.arrayBuffer());return await p(g)}}static fromTensor(w,g="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(g==="CHW")w=w.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new f(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let g=0,S=0;g=0?C=S:z=-S,E>=0?F=E:K=-E,y.drawImage(M,C,F,w,g,z,K,w,g),new f(y.getImageData(0,0,w,g).data,w,g,4).convert(v)}else{let v=this.toSharp();if(S>=0&&E>=0)v=v.extract({left:Math.floor(S),top:Math.floor(E),width:w,height:g});else if(S<=0&&E<=0){const M=Math.floor(-E),y=Math.floor(-S);v=v.extend({top:M,left:y,right:w-this.width-y,bottom:g-this.height-M})}else{let M=[0,0],y=0;E<0?(M[0]=Math.floor(-E),M[1]=g-this.height-M[0]):y=Math.floor(E);let C=[0,0],F=0;S<0?(C[0]=Math.floor(-S),C[1]=w-this.width-C[0]):F=Math.floor(S),v=v.extend({top:M[0],bottom:M[1],left:C[0],right:C[1]}).extract({left:F,top:y,width:w,height:g})}return await p(v)}}async toBlob(w="image/png",g=1){if(!c)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:g})}toTensor(w="CHW"){let g=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return g}toCanvas(){if(!c)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),g=l(w.width,w.height),S=new u(w.data,w.width,w.height);return g.getContext("2d").putImageData(S,0,0),g}split(){const{data:w,width:g,height:S,channels:E}=this,v=w.constructor,M=w.length/E,y=Array.from({length:E},()=>new v(M));for(let C=0;Cnew f(C,g,S,1))}_update(w,g,S,E=null){return this.data=w,this.width=g,this.height=S,E!==null&&(this.channels=E),this}clone(){return new f(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){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(w){if(c){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const g=w.split(".").pop().toLowerCase(),S=_.get(g)??"image/png",E=await this.toBlob(S);(0,s.saveBlob)(w,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(c)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 T=f.read.bind(f)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>T,bankers_round:()=>g,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>c,medianFilter:()=>k,min:()=>p,permute_data:()=>o,round:()=>w,softmax:()=>n});function s(E,[v,M,y],[C,F],z="bilinear",K=!1){const q=F/y,R=C/M,Z=new E.constructor(C*F*v),H=M*y,J=C*F;for(let Q=0;Q=0;--K)C[K]=q,y[K]=v[M[K]],q*=y[K];const F=M.map((K,q)=>C[M.indexOf(q)]),z=new E.constructor(E.length);for(let K=0;K=0;--R)q+=Z%v[R]*F[R],Z=Math.floor(Z/v[R]);z[q]=E[K]}return[z,y]}function n(E){const v=c(E)[0],M=E.map(F=>Math.exp(F-v)),y=M.reduce((F,z)=>F+z,0);return M.map(F=>F/y)}function i(E){const v=c(E)[0];let M=0;for(let F=0;FF-v-y)}function a(E,v){let M=0;for(let y=0;yv+M*M,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let v=E[0],M=0;for(let y=1;yv&&(v=E[y],M=y);return[v,M]}function d(E){return E>0&&(E&E-1)===0}class _{constructor(v){if(this.size=v|0,this.size<=1||!d(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=v<<1,this.table=new Float64Array(this.size*2);for(let y=0;yy;y<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=v[C];return y}toComplexArray(v,M){const y=M||this.createComplexArray();for(let C=0;C>>1],y[C+1]=0;return y}transform(v,M){if(v===M)throw new Error("Input and output buffers must be different");this._transform4(v,M,1)}realTransform(v,M){if(v===M)throw new Error("Input and output buffers must be different");this._realTransform4(v,M,1)}inverseTransform(v,M){if(v===M)throw new Error("Input and output buffers must be different");this._transform4(v,M,-1);for(let y=0;y>=2;z>=2;z>>=2){K=C/z<<1;const J=K>>>2;for(q=0;q>>1,z>>>1)}else for(q=0,R=0;q>>1,z>>>1,y)}const H=this.table;for(z>>=2;z>=2;z>>=2){K=C/z<<1;const Q=K>>>1,se=Q>>>1,fe=se>>>1;for(q=0;q>>1;for(let Q=2;Q>1;++Z){const H=(Z+1-v)**2/2,J=Math.sqrt(q**2+R**2)**H,Q=H*Math.atan2(R,q),se=2*Z;F[se]=J*Math.cos(Q),F[se+1]=J*Math.sin(Q),z[se]=F[se],z[se+1]=-F[se+1]}this._slicedChirpBuffer=F.subarray(M,y),this._f=new _(C>>1),this._f.transform(this._chirpBuffer,z)}_transform(v,M,y){const C=this._buffer1,F=this._buffer2,z=this._outBuffer1,K=this._outBuffer2,q=this._chirpBuffer,R=this._slicedChirpBuffer,Z=this._a;if(y)for(let H=0;H>1,se=M[Q];C[H]=se*R[H],C[J]=se*R[J]}else for(let H=0;H=E.length&&(q=2*(E.length-1)-q),y[z++]=E[q]}y.sort(),M[F]=y[C]}return M}function w(E,v){const M=Math.pow(10,v);return Math.round(E*M)/M}function g(E){const v=Math.round(E);return Math.abs(E)%1===.5?v%2===0?v:v-1:v}function S(E){const v=E.length,M=E[0].length,y=[v+1,M+1],C=Array.from({length:y[0]},()=>Array(y[1]).fill(1/0));C[0][0]=0;const F=Array.from({length:y[0]},()=>Array(y[1]).fill(-1));for(let Z=1;Z0||K>0;)switch(q.push(z-1),R.push(K-1),F[z][K]){case 0:--z,--K;break;case 1:--z;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${z}, ${K}]. Please file a bug report.`)}return q.reverse(),R.reverse(),[q,R]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>M,full:()=>R,full_like:()=>Z,interpolate:()=>p,interpolate_4d:()=>c,layer_norm:()=>g,matmul:()=>d,mean:()=>z,mean_pooling:()=>w,ones:()=>H,ones_like:()=>J,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>fe,rfft:()=>_,slice:()=>k,stack:()=>y,std_mean:()=>F,topk:()=>f,zeros:()=>Q,zeros_like:()=>se});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=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(...A){Y(this,"ort_tensor");return(0,o.isONNXTensor)(A[0])?this.ort_tensor=A[0]:this.ort_tensor=new o.Tensor(A[0],A[1],A[2]),new Proxy(this,{get:(U,ee)=>{if(typeof ee=="string"){let _e=Number(ee);if(Number.isInteger(_e))return U._getitem(_e)}return U[ee]},set:(U,ee,_e)=>U[ee]=_e})}get dims(){return this.ort_tensor.dims}set dims(A){this.ort_tensor.dims=A}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[A,...U]=this.dims;if(U.length>0){const ee=U.reduce((_e,le)=>_e*le);for(let _e=0;_e0){const _e=ee.reduce((le,ye)=>le*ye);return this._subarray(A,_e,ee)}else return new a(this.type,[this.data[A]],ee)}indexOf(A){const U=this.data;for(let ee=0;eeG)throw new Error(`Invalid slice: ${W}`);const be=[Math.max(re,0),Math.min(G,this.dims[pe])];ee.push(be),U.push(be[1]-be[0])}else throw new Error(`Invalid slice: ${W}`)}const _e=ee.map(([pe,W])=>W-pe),le=_e.reduce((pe,W)=>pe*W),ye=this.data,ze=new ye.constructor(le),Ue=this.stride();for(let pe=0;pe=0;--re){const be=_e[re];W+=(G%be+ee[re][0])*Ue[re],G=Math.floor(G/be)}ze[pe]=ye[W]}return new a(this.type,ze,U)}permute(...A){return u(this,A)}transpose(...A){return this.permute(...A)}sum(A=null,U=!1){return this.norm(1,A,U)}norm(A="fro",U=null,ee=!1){if(A==="fro")A=2;else if(typeof A=="string")throw Error(`Unsupported norm: ${A}`);const _e=this.data,le=(pe,W)=>pe+W**A;if(U===null){const pe=_e.reduce(le,0)**(1/A);return new a(this.type,[pe],[])}const[ye,ze,Ue]=C(le,this,U,ee);if(A!==1)for(let pe=0;pe=0;--Ue){const re=this.dims[Ue];if(Ue!==U){const G=pe%re;ze+=G*W,W*=this.dims[Ue]}pe=Math.floor(pe/re)}_e[ye]/=le[ze]}return this}normalize(A=2,U=1){return this.clone().normalize_(A,U)}stride(){return K(this.dims)}squeeze(A=null){return new a(this.type,this.data,S(this.dims,A))}squeeze_(A=null){return this.dims=S(this.dims,A),this}unsqueeze(A=null){return new a(this.type,this.data,E(this.dims,A))}unsqueeze_(A=null){return this.dims=E(this.dims,A),this}flatten_(A=0,U=-1){U=(U+this.dims.length)%this.dims.length;let ee=this.dims.slice(0,A),_e=this.dims.slice(A,U+1),le=this.dims.slice(U+1);return this.dims=[...ee,_e.reduce((ye,ze)=>ye*ze,1),...le],this}flatten(A=0,U=-1){return this.clone().flatten_(A,U)}view(...A){let U=-1;for(let _e=0;_eze!==U?le*ye:le,1);A[U]=ee.length/_e}return new a(this.type,ee,A)}neg_(){const A=this.data;for(let U=0;UA?1:0;return new a("bool",U,this.dims)}lt(A){const U=new Uint8Array(this.data.length),ee=this.data;for(let _e=0;_eMath.min(ye,ze),this,A,U,1/0);return new a(ee,_e,le)}max(A=null,U=!1){if(A===null){const ye=(0,s.max)(this.data)[0];return new a(this.type,[ye],[])}const[ee,_e,le]=C((ye,ze)=>Math.max(ye,ze),this,A,U,-1/0);return new a(ee,_e,le)}argmin(A=null,U=!1){if(A!==null)throw new Error("`dim !== null` not yet implemented.");const ee=(0,s.min)(this.data)[1];return new a("int64",[BigInt(ee)],[])}argmax(A=null,U=!1){if(A!==null)throw new Error("`dim !== null` not yet implemented.");const ee=(0,s.max)(this.data)[1];return new a("int64",[BigInt(ee)],[])}to(A){if(this.type===A)return this;if(!i.hasOwnProperty(A))throw new Error(`Unsupported type: ${A}`);let U;const ee=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(A);return ee&&!_e?U=Number:!ee&&_e&&(U=BigInt),new a(A,i[A].from(this.data,U),this.dims)}}function l(V,A){const U=V.length,ee=A.reduce((le,ye)=>le*ye);if(U!==ee)throw Error(`cannot reshape array of size ${U} into shape (${A})`);let _e=V;for(let le=A.length-1;le>=0;le--)_e=_e.reduce((ye,ze)=>{let Ue=ye[ye.length-1];return Ue.lengthnew a("int64",V,[V.length]);async function k(V,A,U,ee,_e){return await(await n.TensorOpRegistry.slice)({x:V,s:T(A),e:T(U),a:T(ee),t:T(_e??new Array(ee.length).fill(1))})}function w(V,A){const U=V.data,ee=A.data,_e=[V.dims[0],V.dims[2]],le=new U.constructor(_e[0]*_e[1]),[ye,ze,Ue]=V.dims;let pe=0;for(let W=0;WU!==1):typeof A=="number"?V[A]===1&&V.splice(A,1):Array.isArray(A)&&(V=V.filter((U,ee)=>U!==1||!A.includes(ee))),V}function E(V,A){return A=v(A,V.length+1),V=V.slice(),V.splice(A,0,1),V}function v(V,A,U=null,ee=!0){if(V<-A||V>=A){if(ee)throw new Error(`IndexError: index ${V} is out of bounds for dimension${U===null?"":" "+U} with size ${A}`);return V<-A?0:A}return V<0&&(V=(V%A+A)%A),V}function M(V,A=0){A=v(A,V[0].dims.length);const U=V[0].dims.slice();U[A]=V.reduce((ye,ze)=>ye+ze.dims[A],0);const ee=U.reduce((ye,ze)=>ye*ze,1),_e=new V[0].data.constructor(ee),le=V[0].type;if(A===0){let ye=0;for(const ze of V){const Ue=ze.data;_e.set(Ue,ye),ye+=Ue.length}}else{let ye=0;for(let ze=0;ze=0;--G){const Se=pe[G];let Ce=be%Se;G===A&&(Ce+=ye),re+=Ce*we,we*=U[G],be=Math.floor(be/Se)}_e[re]=Ue[W]}ye+=pe[A]}}return new a(le,_e,U)}function y(V,A=0){return M(V.map(U=>U.unsqueeze(A)),A)}function C(V,A,U=null,ee=!1,_e=null){const le=A.data,ye=A.dims;U=v(U,ye.length);const ze=ye.slice();ze[U]=1;const Ue=new le.constructor(le.length/ye[U]);_e!==null&&Ue.fill(_e);for(let pe=0;pe=0;--re){const we=ye[re];if(re!==U){const Se=G%we;W+=Se*be,be*=ze[re]}G=Math.floor(G/we)}Ue[W]=V(Ue[W],le[pe],pe,W)}return ee||ze.splice(U,1),[A.type,Ue,ze]}function F(V,A=null,U=1,ee=!1){const _e=V.data,le=V.dims;if(A===null){const be=_e.reduce(($e,Fe)=>$e+Fe,0)/_e.length,we=Math.sqrt(_e.reduce(($e,Fe)=>$e+(Fe-be)**2,0)/(_e.length-U)),Se=new a(V.type,[be],[]);return[new a(V.type,[we],[]),Se]}A=v(A,le.length);const ye=z(V,A,ee),ze=ye.data,[Ue,pe,W]=C((G,be,we,Se)=>G+(be-ze[Se])**2,V,A,ee);for(let G=0;Gpe+W,0);return new a(V.type,[Ue/_e.length],[])}A=v(A,ee.length);const[le,ye,ze]=C((Ue,pe)=>Ue+pe,V,A,U);if(ee[A]!==1)for(let Ue=0;Ue=0;--U)A[U]=ee,ee*=V[U];return A}function q(V,A,U,ee){const _e=V.reduce((le,ye)=>le*ye,1);return new a(U,new ee(_e).fill(A),V)}function R(V,A){let U,ee;if(typeof A=="number")U="float32",ee=Float32Array;else if(typeof A=="bigint")U="int64",ee=BigInt64Array;else if(typeof A=="boolean")U="bool",ee=Uint8Array;else throw new Error(`Unsupported data type: ${typeof A}`);return q(V,A,U,ee)}function Z(V,A){return R(V.dims,A)}function H(V){return q(V,1n,"int64",BigInt64Array)}function J(V){return H(V.dims)}function Q(V){return q(V,0n,"int64",BigInt64Array)}function se(V){return Q(V.dims)}function fe(V){const A=V.reduce((U,ee)=>U*ee,1);return new a("float32",Float32Array.from({length:A},()=>Math.random()),V)}function ae(V,A){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(A))throw new Error("The precision must be either 'binary' or 'ubinary'");const U=A==="binary",ee=U?"int8":"uint8",_e=U?Int8Array:Uint8Array,le=V.data,ye=new _e(le.length/8);for(let ze=0;ze0?1:0,pe=Math.floor(ze/8),W=ze%8;ye[pe]|=Ue<<7-W,U&&W===0&&(ye[pe]-=128)}return new a(ee,ye,[V.dims[0],V.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((c,d)=>new n(c,(d+1)/(u.length+1)*p))),this.frames=u,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:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const c=[],d=document.createElement("video");if(d.crossOrigin="anonymous",d.muted=!0,typeof l=="string")d.src=l;else if(l instanceof Blob)d.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)d.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(S=>d.onloadedmetadata=S),d.seekable.start(0)===d.seekable.end(0)){const E=await(await fetch(d.src)).blob();d.src=URL.createObjectURL(E),await new Promise(v=>d.onloadedmetadata=v)}const _=d.duration;let f,T;u!=null?(f=u,T=u===1?0:_/(u-1)):(T=1/p,f=Math.floor(_/T));let k=[];for(let S=0;S{d.onseeked=y}),g.drawImage(d,0,0,w.width,w.height);const E=g.getImageData(0,0,w.width,w.height),v=new s.RawImage(E.data,w.width,w.height,4),M=new n(v,S);c.push(M)}return d.remove(),new i(c,_)}}},Ug={};function Bt(e){var r=Ug[e];if(r!==void 0)return r.exports;var t=Ug[e]={exports:{}};return Cx[e](t,t.exports,Bt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Bt.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 o=Object.create(null);Bt.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Bt.d(o,n),o}})(),Bt.d=(e,r)=>{for(var t in r)Bt.o(r,t)&&!Bt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Bt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Bt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Bt.r(m),Bt.d(m,{ASTFeatureExtractor:()=>c.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:()=>o.AutoConfig,AutoFeatureExtractor:()=>d.AutoFeatureExtractor,AutoImageProcessor:()=>T.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:()=>g.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:()=>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:()=>c.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>v.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,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,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:()=>c.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:()=>c.EncodecFeatureExtractor,EosTokenCriteria:()=>E.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:()=>u.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:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>v.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>v.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:()=>w.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:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>c.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>_.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.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:()=>v.LogitsProcessor,LogitsProcessorList:()=>v.LogitsProcessorList,LogitsWarper:()=>v.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:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>v.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>v.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:()=>c.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.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:()=>v.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>v.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:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>f.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.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:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>f.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>c.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.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:()=>w.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>f.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>v.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:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>c.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:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>c.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.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:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>v.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:()=>v.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:()=>v.TopKLogitsWarper,TopPLogitsWarper:()=>v.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.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:()=>w.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:()=>c.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>c.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>c.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>v.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:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.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=Bt("./src/env.js"),r=Bt("./src/pipelines.js"),t=Bt("./src/models.js"),s=Bt("./src/tokenizers.js"),o=Bt("./src/configs.js"),n=Bt("./src/utils/audio.js"),i=Bt("./src/utils/image.js"),a=Bt("./src/utils/video.js"),l=Bt("./src/utils/tensor.js"),u=Bt("./src/utils/maths.js"),p=Bt("./src/base/feature_extraction_utils.js"),c=Bt("./src/models/feature_extractors.js"),d=Bt("./src/models/auto/feature_extraction_auto.js"),_=Bt("./src/base/image_processors_utils.js"),f=Bt("./src/models/image_processors.js"),T=Bt("./src/models/auto/image_processing_auto.js"),k=Bt("./src/base/processing_utils.js"),w=Bt("./src/models/processors.js"),g=Bt("./src/models/auto/processing_auto.js"),S=Bt("./src/generation/streamers.js"),E=Bt("./src/generation/stopping_criteria.js"),v=Bt("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC,m.AutoModelForCausalLM,m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection;var Sx=m.AutoProcessor,$x=m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DFineForObjectDetection,m.DFineModel,m.DFinePreTrainedModel,m.DPTFeatureExtractor,m.DPTForDepthEstimation,m.DPTImageProcessor,m.DPTModel,m.DPTPreTrainedModel,m.DacDecoderModel,m.DacDecoderOutput,m.DacEncoderModel,m.DacEncoderOutput,m.DacFeatureExtractor,m.DacModel,m.DacPreTrainedModel,m.DataTypeMap,m.DebertaForMaskedLM,m.DebertaForQuestionAnswering,m.DebertaForSequenceClassification,m.DebertaForTokenClassification,m.DebertaModel,m.DebertaPreTrainedModel,m.DebertaTokenizer,m.DebertaV2ForMaskedLM,m.DebertaV2ForQuestionAnswering,m.DebertaV2ForSequenceClassification,m.DebertaV2ForTokenClassification,m.DebertaV2Model,m.DebertaV2PreTrainedModel,m.DebertaV2Tokenizer,m.DecisionTransformerModel,m.DecisionTransformerPreTrainedModel,m.DeiTFeatureExtractor,m.DeiTForImageClassification,m.DeiTImageProcessor,m.DeiTModel,m.DeiTPreTrainedModel,m.DepthAnythingForDepthEstimation,m.DepthAnythingPreTrainedModel,m.DepthEstimationPipeline,m.DepthProForDepthEstimation,m.DepthProPreTrainedModel,m.DetrFeatureExtractor,m.DetrForObjectDetection,m.DetrForSegmentation,m.DetrImageProcessor,m.DetrModel,m.DetrObjectDetectionOutput,m.DetrPreTrainedModel,m.DetrSegmentationOutput,m.Dinov2ForImageClassification,m.Dinov2Model,m.Dinov2PreTrainedModel,m.Dinov2WithRegistersForImageClassification,m.Dinov2WithRegistersModel,m.Dinov2WithRegistersPreTrainedModel,m.DistilBertForMaskedLM,m.DistilBertForQuestionAnswering,m.DistilBertForSequenceClassification,m.DistilBertForTokenClassification,m.DistilBertModel,m.DistilBertPreTrainedModel,m.DistilBertTokenizer,m.DocumentQuestionAnsweringPipeline,m.DonutFeatureExtractor,m.DonutImageProcessor,m.DonutSwinModel,m.DonutSwinPreTrainedModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline,m.InterruptableStoppingCriteria,m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.LiteWhisperForConditionalGeneration,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.PatchTSMixerForPrediction,m.PatchTSMixerModel,m.PatchTSMixerPreTrainedModel,m.PatchTSTForPrediction,m.PatchTSTModel,m.PatchTSTPreTrainedModel,m.Phi3ForCausalLM,m.Phi3Model,m.Phi3PreTrainedModel,m.Phi3VForCausalLM,m.Phi3VImageProcessor,m.Phi3VPreTrainedModel,m.Phi3VProcessor,m.PhiForCausalLM,m.PhiModel,m.PhiPreTrainedModel,m.Pipeline,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.Qwen3ForCausalLM,m.Qwen3Model,m.Qwen3PreTrainedModel,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SuppressTokensAtBeginLogitsProcessor,m.Swin2SRForImageSuperResolution,m.Swin2SRImageProcessor,m.Swin2SRModel,m.Swin2SRPreTrainedModel,m.SwinForImageClassification,m.SwinForSemanticSegmentation,m.SwinModel,m.SwinPreTrainedModel,m.T5ForConditionalGeneration,m.T5Model,m.T5PreTrainedModel,m.T5Tokenizer,m.TableTransformerForObjectDetection,m.TableTransformerModel,m.TableTransformerObjectDetectionOutput,m.TableTransformerPreTrainedModel,m.TemperatureLogitsWarper,m.Tensor,m.Text2TextGenerationPipeline,m.TextClassificationPipeline,m.TextGenerationPipeline;var kx=m.TextStreamer;m.TextToAudioPipeline,m.TokenClassificationPipeline,m.TokenClassifierOutput,m.TokenizerModel,m.TopKLogitsWarper,m.TopPLogitsWarper,m.TrOCRForCausalLM,m.TrOCRPreTrainedModel,m.TranslationPipeline,m.UltravoxModel,m.UltravoxPreTrainedModel,m.UltravoxProcessor,m.UniSpeechForCTC,m.UniSpeechForSequenceClassification,m.UniSpeechModel,m.UniSpeechPreTrainedModel,m.UniSpeechSatForAudioFrameClassification,m.UniSpeechSatForCTC,m.UniSpeechSatForSequenceClassification,m.UniSpeechSatModel,m.UniSpeechSatPreTrainedModel,m.VLChatProcessor,m.VLMImageProcessor,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor;var Ix=m.WhisperForConditionalGeneration;m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env;var Ax=m.full;m.full_like,m.getKeyValueShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data,m.pipeline,m.quantize_embeddings,m.rand,m.read_audio,m.rfft,m.round,m.slice,m.softmax,m.spectrogram,m.stack,m.std_mean,m.topk,m.window_function,m.zeros,m.zeros_like;const Fx=64;class Gn{static async getInstance(r){return this.model_id="onnx-community/whisper-large-v3-turbo",this.tokenizer??(this.tokenizer=$x.from_pretrained(this.model_id,{progress_callback:r})),this.processor??(this.processor=Sx.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=Ix.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])}}Y(Gn,"model_id",null),Y(Gn,"tokenizer"),Y(Gn,"processor"),Y(Gn,"model");async function Ox(e){const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n{i??(i=performance.now());let f;a++>0&&(f=a/(performance.now()-i)*1e3),globalThis.postMessage({status:"update",output:_,tps:f,numTokens:a})},u=new kx(s,{skip_prompt:!0,decode_kwargs:{skip_special_tokens:!0},callback_function:l}),p=await o(t),c=await n.generate({...p,max_new_tokens:Fx,language:r,streamer:u}),d=s.batch_decode(c,{skip_special_tokens:!0});globalThis.postMessage({status:"complete",output:d}),du=!1}async function Lx(){globalThis.postMessage({status:"loading",data:"Loading model..."});const[e,r,t]=await Gn.getInstance(s=>{globalThis.postMessage(s)});globalThis.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await t.generate({input_features:Ax([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":Lx();break;case"generate":Dx(t);break}})})(); diff --git a/assets/worker-i3yLSyEt.js b/assets/worker-i3yLSyEt.js deleted file mode 100644 index 1eddc558c698a2136c9b9c783945d4fa6fa8a05c..0000000000000000000000000000000000000000 --- a/assets/worker-i3yLSyEt.js +++ /dev/null @@ -1,2887 +0,0 @@ -var Xx=Object.defineProperty;var Qx=(gs,Pr,Ln)=>Pr in gs?Xx(gs,Pr,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):gs[Pr]=Ln;var te=(gs,Pr,Ln)=>Qx(gs,typeof Pr!="symbol"?Pr+"":Pr,Ln);(function(){"use strict";const gs=new Map,Pr=[],Ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=gs.get(e);if(s===void 0)gs.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 o=Pr.indexOf(e);o!==-1&&Pr.splice(o,1);for(let n=0;n{const r=gs.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}}},R0=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Pr:t;let o;const n=[],i=new Set;for(const l of s){const u=await B0(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},j0="1.21.1";let xd="warning";const Yr={wasm:{},webgl:{},webgpu:{},versions:{common:j0},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}`);xd=e}},get logLevel(){return xd}};Object.defineProperty(Yr,"logLevel",{enumerable:!0});const N0=Yr,V0=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let d=0,c=p,f=p*2,_=-1;i==="RGBA"?(d=0,c=p,f=p*2,_=p*3):i==="RGB"?(d=0,c=p,f=p*2):i==="RBG"&&(d=0,f=p,c=p*2);for(let T=0;T{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const c=4;let f=0,_=1,T=2,k=3,w=0,g=d,S=d*2,E=-1;a==="RGBA"?(w=0,g=d,S=d*2,E=d*3):a==="RGB"?(w=0,g=d,S=d*2):a==="RBG"&&(w=0,S=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{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,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let d=4,c=0,f=1,_=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(d=3,c=0,f=1,_=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,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")},u=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 d=u(p);if(d!=null){let c=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,f=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=c,a.width=f}else a.tensorFormat="RGBA",a.height=c,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,c).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const c=l();c.width=d,c.height=p;const f=u(c);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 d=u(p);if(d!=null){const c=e.height,f=e.width;return d.drawImage(e,0,0,f,c),i=d.getImageData(0,0,f,c).data,a.height=c,a.width=f,ga(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{const c=l(),f=u(c);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{c.width=_.width,c.height=_.height,f.drawImage(_,0,0,c.width,c.height);const T=f.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(ga(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ga(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},G0=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Ur({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},K0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Ur({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},H0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Ur({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},q0=(e,r,t)=>new Ur({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]]),Zo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Td=!1;const X0=()=>{if(!Td){Td=!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),Zo.set(BigInt64Array,"int64")),r&&(zn.set("uint64",BigUint64Array),Zo.set(BigUint64Array,"uint64")),s?(zn.set("float16",t),Zo.set(t,"float16")):zn.set("float16",Uint16Array)}},Q0=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Ur(e.type,e.data,r);case"cpu-pinned":return new Ur({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Ur({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Ur({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Ur({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Ur=class{constructor(r,t,s){X0();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=zn.get(o);if(!a)throw new TypeError(`unsupported type "${o}" 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(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" 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(o=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 u=zn.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)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&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=Zo.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,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 i=Q0(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return W0(r,t)}static fromTexture(r,t){return G0(r,t)}static fromGpuBuffer(r,t){return K0(r,t)}static fromMLTensor(r,t){return H0(r,t)}static fromPinnedBuffer(r,t,s){return q0(r,t,s)}toDataURL(r){return V0(this,r)}toImageData(r){return U0(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 J0(this,r)}};const Bn=Ur,Ed=(e,r)=>{(typeof Yr.trace>"u"?!Yr.wasm.trace:!Yr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Pd=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof Yr.trace>"u"?!Yr.wasm.trace:!Yr.trace)||Pd("BEGIN",e)},Ma=e=>{(typeof Yr.trace>"u"?!Yr.wasm.trace:!Yr.trace)||Pd("END",e)};var Y0=Object.freeze({__proto__:null,InferenceSession:class D0{constructor(r){this.handler=r}async run(r,t,s){wa();const o={};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 i=!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.");i=!1;for(const u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const c=t[d];(c===null||c instanceof Bn)&&(u=!0,i=!1,o[d]=c)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof Bn?l[u]=p:l[u]=new Bn(p.type,p.data,p.dims)}return Ma(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){wa();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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 d=0,c=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,d,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await R0(i),u=await a.createInferenceSessionHandler(n,l);return Ma(),new D0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Ed,TRACE_FUNC_BEGIN:wa,TRACE_FUNC_END:Ma,Tensor:Bn,env:N0,registerBackend:Ln});/*! - * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */var ba=Object.defineProperty,Z0=Object.getOwnPropertyDescriptor,ev=Object.getOwnPropertyNames,tv=Object.prototype.hasOwnProperty,rv=(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')}),Be=(e,r)=>()=>(e&&(r=e(e=0)),r),Rn=(e,r)=>{for(var t in r)ba(e,t,{get:r[t],enumerable:!0})},sv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of ev(r))!tv.call(e,o)&&o!==t&&ba(e,o,{get:()=>r[o],enumerable:!(s=Z0(r,o))||s.enumerable});return e},ao=e=>sv(ba({},"__esModule",{value:!0}),e),lo,Ds,Ys,Cd,Sd,$d=Be(()=>{lo=new Map,Ds=[],Ys=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=lo.get(e);if(s===void 0)lo.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 o=Ds.indexOf(e);o!==-1&&Ds.splice(o,1);for(let n=0;n{let r=lo.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}}},Sd=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Ds:t,o,n=[],i=new Set;for(let l of s){let u=await Cd(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),nv=Be(()=>{$d()}),kd,ov=Be(()=>{kd="1.22.0-dev.20250409-89f8206ba4"}),ya,Wr,Id=Be(()=>{ov(),ya="warning",Wr={wasm:{},webgl:{},webgpu:{},versions:{common:kd},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}`);ya=e}},get logLevel(){return ya}},Object.defineProperty(Wr,"logLevel",{enumerable:!0})}),Bt,iv=Be(()=>{Id(),Bt=Wr}),Ad,Fd,av=Be(()=>{Ad=(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 o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,d=0,c=p,f=p*2,_=-1;i==="RGBA"?(d=0,c=p,f=p*2,_=p*3):i==="RGB"?(d=0,c=p,f=p*2):i==="RBG"&&(d=0,f=p,c=p*2);for(let T=0;T{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let c=4,f=0,_=1,T=2,k=3,w=0,g=d,S=d*2,E=-1;a==="RGBA"?(w=0,g=d,S=d*2,E=d*3):a==="RGB"?(w=0,g=d,S=d*2):a==="RBG"&&(w=0,S=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{xa(),ei=(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,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),d=4,c=0,f=1,_=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(d=3,c=0,f=1,_=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,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")},u=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 d=u(p);if(d!=null){let c=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,f=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=c,a.width=f}else a.tensorFormat="RGBA",a.height=c,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,c).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let c=l();c.width=d,c.height=p;let f=u(c);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){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 d=u(p);if(d!=null){let c=e.height,f=e.width;return d.drawImage(e,0,0,f,c),i=d.getImageData(0,0,f,c).data,a.height=c,a.width=f,ei(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{let c=l(),f=u(c);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{c.width=_.width,c.height=_.height,f.drawImage(_,0,0,c.width,c.height);let T=f.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(ei(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ei(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Dd=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Or({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Ld=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Or({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},zd=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Or({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Bd=(e,r,t)=>new Or({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),Zs,uo,va,Rd,uv=Be(()=>{Zs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),uo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),va=!1,Rd=()=>{if(!va){va=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Zs.set("int64",BigInt64Array),uo.set(BigInt64Array,"int64")),r&&(Zs.set("uint64",BigUint64Array),uo.set(BigUint64Array,"uint64")),s?(Zs.set("float16",t),uo.set(t,"float16")):Zs.set("float16",Uint16Array)}}}),jd,Nd,dv=Be(()=>{xa(),jd=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Or(e.type,e.data,r);case"cpu-pinned":return new Or({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Or({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Or({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Or({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Or,xa=Be(()=>{av(),lv(),uv(),dv(),Or=class{constructor(e,r,t){Rd();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Zs.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,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.");i=r}else{let l=Zs.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"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=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)i=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",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=uo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=jd(o);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=o,this.size=n}static async fromImage(e,r){return Od(e,r)}static fromTexture(e,r){return Dd(e,r)}static fromGpuBuffer(e,r){return Ld(e,r)}static fromMLTensor(e,r){return zd(e,r)}static fromPinnedBuffer(e,r,t){return Bd(e,r,t)}toDataURL(e){return Ad(this,e)}toImageData(e){return Fd(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 Nd(this,e)}}}),Zr,Vd=Be(()=>{xa(),Zr=Or}),co,Ta,es,Gr,Ud=Be(()=>{Id(),co=(e,r)=>{(typeof Wr.trace>"u"?!Wr.wasm.trace:!Wr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ta=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Wr.trace>"u"?!Wr.wasm.trace:!Wr.trace)||Ta("BEGIN",e)},Gr=e=>{(typeof Wr.trace>"u"?!Wr.wasm.trace:!Wr.trace)||Ta("END",e)}}),Wd,cv=Be(()=>{$d(),Vd(),Ud(),Wd=class L0{constructor(r){this.handler=r}async run(r,t,s){es();let o={},n={};if(typeof r!="object"||r===null||r instanceof Zr||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Zr)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.");i=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let c=t[d];(c===null||c instanceof Zr)&&(u=!0,i=!1,o[d]=c)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof Zr?l[u]=p:l[u]=new Zr(p.type,p.data,p.dims)}return Gr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){es();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=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)i=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,d=0,c=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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,d,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Sd(i),u=await a.createInferenceSessionHandler(n,l);return Gr(),new L0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ea,pv=Be(()=>{cv(),Ea=Wd}),hv=Be(()=>{}),mv=Be(()=>{}),_v=Be(()=>{}),fv=Be(()=>{}),Gd={};Rn(Gd,{InferenceSession:()=>Ea,TRACE:()=>co,TRACE_FUNC_BEGIN:()=>es,TRACE_FUNC_END:()=>Gr,Tensor:()=>Zr,env:()=>Bt,registerBackend:()=>Ys});var ts=Be(()=>{nv(),iv(),pv(),Vd(),hv(),mv(),Ud(),_v(),fv()}),Pa=Be(()=>{}),Kd={};Rn(Kd,{default:()=>Hd});var Ca,Sa,Hd,gv=Be(()=>{var e;Cg(),en(),La(),Ca="ort-wasm-proxy-worker",Sa=((e=globalThis.self)==null?void 0:e.name)===Ca,Sa&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Ra(s.wasm).then(()=>{Yl(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;Zl(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=Mi(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;tu(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":ru(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;nu(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},iu([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":ou(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Hd=Sa?null:r=>new Worker(r??Dr,{type:"module",name:Ca})}),qd={};Rn(qd,{default:()=>Xd});var $a,ka,Xd,Qd,wv=Be(()=>{var e,r;ka=($a=self.location.href,async function(t={}){var Qo;var s,o,n=t,i=new Promise((h,x)=>{s=h,o=x}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((Qo=self.name)==null?void 0:Qo.startsWith("em-pthread"));n.mountExternalData=(h,x)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,x)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=h=>async(...x)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:x[0],errors:[]},U=await h(...x);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let ue=L.errors;if(0Oe),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=x;let I=n.Jb;n.jsepRegisterBuffer=(L,U,ue,Te)=>I.registerBuffer(L,U,ue,Te),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,U,ue)=>I.createDownloader(L,U,ue),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,U)=>{I.upload(L,U)}}else if(h==="webnn"){let I=x[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=x.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,U)=>{I.registerMLContext(L,U)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,U)=>I.createMLTensorDownloader(L,U),n.webnnRegisterMLTensor=(L,U,ue,Te)=>I.registerMLTensor(L,U,ue,Te),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,U,ue,Te,Oe,Ke)=>I.registerMLConstant(L,U,ue,Te,Oe,n.Eb,Ke),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let c=()=>{let h=(x,I,L)=>(...U)=>{let ue=Nt,Te=I==null?void 0:I();U=x(...U);let Oe=I==null?void 0:I();return Te!==Oe&&(x=Oe,L(Te),I=L=null),Nt!=ue?new Promise((Ke,Ze)=>{Rr={resolve:Ke,reject:Ze}}):U};(()=>{for(let x of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[x]=h(n[x],()=>n[x],I=>n[x]=I)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),c=void 0};n.asyncInit=()=>{c==null||c()};var f,_,T=Object.assign({},n),k=(h,x)=>{throw x},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),$a&&(w=$a),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(_=h=>{var x=new XMLHttpRequest;return x.open("GET",h,!1),x.responseType="arraybuffer",x.send(null),new Uint8Array(x.response)}),f=async h=>{if(V(h))return new Promise((I,L)=>{var U=new XMLHttpRequest;U.open("GET",h,!0),U.responseType="arraybuffer",U.onload=()=>{U.status==200||U.status==0&&U.response?I(U.response):L(U.status)},U.onerror=L,U.send(null)});var x=await fetch(h,{credentials:"same-origin"});if(x.ok)return x.arrayBuffer();throw Error(x.status+" : "+x.url)});var g=console.log.bind(console),S=console.error.bind(console),E=g,y=S;Object.assign(n,T),T=null;var M,v,C,A,B,K,G,j,ee,H,Z,X,oe,me=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function F(){return M.buffer!=A.buffer&&R(),A}function W(){return M.buffer!=A.buffer&&R(),B}function re(){return M.buffer!=A.buffer&&R(),K}function _e(){return M.buffer!=A.buffer&&R(),G}function se(){return M.buffer!=A.buffer&&R(),j}function ce(){return M.buffer!=A.buffer&&R(),ee}function $e(){return M.buffer!=A.buffer&&R(),H}function Ue(){return M.buffer!=A.buffer&&R(),oe}if(u){let h=function(x){try{var I=x.data,L=I.Bb;if(L==="load"){let U=[];self.onmessage=ue=>U.push(ue),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ue of U)h(ue);self.onmessage=h};for(let ue of I.Rb)n[ue]&&!n[ue].proxy||(n[ue]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ue,args:Te})},ue=="print"&&(E=n[ue]),ue=="printErr"&&(y=n[ue]));M=I.kc,R(),we(I.lc)}else if(L==="run"){Ir(I.Ab),Sn(I.Ab,0,0,1,0,0),ur(),ve(I.Ab),q||(Vo(),q=!0);try{js(I.fc,I.Hb)}catch(U){if(U!="unwind")throw U}}else I.target!=="setimmediate"&&(L==="checkMailbox"?q&&je():L&&(y(`worker: received unknown command ${L}`),y(I)))}catch(U){throw Uo(),U}};var we,q=!1;y=function(...x){x=x.join(" "),console.error(x)},self.alert=function(...x){postMessage({Bb:"alert",text:x.join(" "),ic:Xs()})},self.onunhandledrejection=x=>{throw x.reason||x},self.onmessage=h}function R(){var h=M.buffer;n.HEAP8=A=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=B=new Uint8Array(h),n.HEAPU16=G=new Uint16Array(h),n.HEAP32=j=new Int32Array(h),n.HEAPU32=ee=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=oe=new Float64Array(h),n.HEAP64=Z=new BigInt64Array(h),n.HEAPU64=X=new BigUint64Array(h)}function pe(){u?startWorker(n):nt.Ca()}u||(M=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R());var xe,be=0,Se=null;function Ae(){if(--be==0&&Se){var h=Se;Se=null,h()}}function Fe(h){throw y(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function ze(){return{a:{L:Y,Aa:O,b:Ns,$:us,A:ds,pa:cs,X:De,Z:Qe,qa:tt,na:Rt,ga:zr,ma:Sr,J:ps,Y:hs,V:Kr,oa:ms,W:_s,va:cn,E:pn,Q:hn,O:_n,D:gn,u:wn,r:vs,P:Mn,z:N,R:Q,ja:ie,T:He,aa:Je,M:dt,F:xt,ia:ve,sa:Pt,t:Ht,Ba:br,w:or,o:Zt,l:Ws,c:Is,n:vi,j:Ei,v:Pi,p:Ci,f:Si,s:$i,m:Eo,e:ki,k:Ii,i:Po,g:Ai,d:Co,da:Fi,ea:$o,fa:Di,ba:Tn,ca:ko,N:Io,xa:zi,ua:Ri,h:ji,C:Ao,G:Fs,ta:Bi,x:Ni,ra:pu,U:Vi,q:Li,y:hu,K:Ui,S:Fo,za:Wi,ya:Gi,ka:Lo,la:Xn,_:Xe,B:zo,I:Bo,ha:Qn,H:Ro,a:M,wa:Ie}}}var Ve={829644:(h,x,I,L,U)=>{if(n===void 0||!n.Eb)return 1;if((h=Ft(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(x=Number(x>>>0),I=Number(I>>>0),L=Number(L>>>0),x+I>h.byteLength)return 3;try{let ue=h.subarray(x,x+I);switch(U){case 0:W().set(ue,L>>>0);break;case 1:n.mc?n.mc(L,ue):n.bc(L,ue);break;default:return 4}return 0}catch{return 4}},830468:(h,x,I)=>{n.Ob(h,W().subarray(x>>>0,x+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I),!0)},830824:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,x,I)=>{n.jb("HardSigmoid",h,{alpha:x,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,x,I)=>{n.jb("Clip",h,{min:x,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,x)=>{n.jb("Elu",h,{alpha:x})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,x)=>{n.jb("LeakyRelu",h,{alpha:x})},832564:(h,x)=>{n.jb("ThresholdedRelu",h,{alpha:x})},832634:(h,x)=>{n.jb("Cast",h,{to:x})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,x,I,L,U)=>{n.jb("ReduceMean",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833403:(h,x,I,L,U)=>{n.jb("ReduceMax",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833577:(h,x,I,L,U)=>{n.jb("ReduceMin",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833751:(h,x,I,L,U)=>{n.jb("ReduceProd",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833926:(h,x,I,L,U)=>{n.jb("ReduceSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834100:(h,x,I,L,U)=>{n.jb("ReduceL1",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834273:(h,x,I,L,U)=>{n.jb("ReduceL2",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834446:(h,x,I,L,U)=>{n.jb("ReduceLogSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834623:(h,x,I,L,U)=>{n.jb("ReduceSumSquare",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834803:(h,x,I,L,U)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,x,I)=>{n.jb("Transpose",h,{perm:x?Array.from(se().subarray(Number(x)>>>0,Number(I)>>>0)):[]})},835160:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:Ft(I),format:L?"NHWC":"NCHW"})},835293:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:Ft(I),format:L?"NHWC":"NCHW"})},835426:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr,Os)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ze>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(Tt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft(Os)})},835859:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:x,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],outputShape:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},836520:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr,Os)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ze>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(Tt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft(Os)})},836953:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:x,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],outputShape:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},837614:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},837705:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},838184:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},838275:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},838754:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},838841:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},839316:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},839403:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},839878:(h,x,I,L,U)=>{n.jb("Gemm",h,{alpha:x,beta:I,transA:L,transB:U})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,x,I,L)=>{n.jb("ArgMax",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840144:(h,x,I,L)=>{n.jb("ArgMin",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840252:(h,x)=>{n.jb("Softmax",h,{axis:x})},840315:(h,x)=>{n.jb("Concat",h,{axis:x})},840375:(h,x,I,L,U)=>{n.jb("Split",h,{axis:x,numOutputs:I,splitSizes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,x)=>{n.jb("Gather",h,{axis:Number(x)})},840656:(h,x)=>{n.jb("GatherElements",h,{axis:Number(x)})},840735:(h,x)=>{n.jb("GatherND",h,{batch_dims:Number(x)})},840814:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht)=>{n.jb("Resize",h,{antialias:x,axes:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:Ft(U),cubicCoeffA:ue,excludeOutside:Te,extrapolationValue:Oe,keepAspectRatioPolicy:Ft(Ke),mode:Ft(Ze),nearestMode:Ft(ht)})},841176:(h,x,I,L,U,ue,Te)=>{n.jb("Slice",h,{starts:x?Array.from(se().subarray(Number(x)>>>0,Number(I)>>>0)):[],ends:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[],axes:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841606:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,x)=>{n.jb("Einsum",h,{equation:Ft(x)})},841854:(h,x,I,L,U)=>{n.jb("Pad",h,{mode:x,value:I,pads:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},841997:(h,x,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842166:(h,x,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842335:(h,x,I)=>{n.jb("CumSum",h,{exclusive:Number(x),reverse:Number(I)})},842432:(h,x,I)=>{n.jb("DequantizeLinear",h,{axis:x,blockSize:I})},842522:(h,x,I,L,U)=>{n.jb("GridSample",h,{align_corners:x,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842692:(h,x,I,L,U)=>{n.jb("GridSample",h,{align_corners:x,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842862:(h,x)=>{n.jb("ScatterND",h,{reduction:Ft(x)})},842947:(h,x,I,L,U,ue,Te,Oe,Ke)=>{n.jb("Attention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue,qkvHiddenSizes:Te?Array.from(se().subarray(Number(Oe)>>>0,Number(Oe)+Te>>>0)):[],pastPresentShareBuffer:!!Ke})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr,Os,Hi)=>{n.jb("Conv",h,{format:Tt?"NHWC":"NCHW",auto_pad:x,dilations:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:U,kernel_shape:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],pads:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],strides:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],w_is_const:()=>!!F()[Number(It)>>>0],activation:Ft(sr),activation_params:Os?Array.from($e().subarray(Number(Os)>>>0,Number(Hi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,x,I,L,U,ue,Te,Oe,Ke)=>{n.jb("GroupQueryAttention",h,{numHeads:x,kvNumHeads:I,scale:L,softcap:U,doRotary:ue,rotaryInterleaved:Te,smoothSoftmax:Oe,localWindowSize:Ke})},844244:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844355:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844466:(h,x,I,L,U,ue)=>{n.jb("MatMulNBits",h,{k:x,n:I,accuracyLevel:L,bits:U,blockSize:ue})},844593:(h,x,I,L,U,ue)=>{n.jb("MultiHeadAttention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue})},844752:(h,x)=>{n.jb("QuickGelu",h,{alpha:x})},844816:(h,x,I,L,U)=>{n.jb("RotaryEmbedding",h,{interleaved:!!x,numHeads:I,rotaryEmbeddingDim:L,scale:U})},844955:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845057:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845159:(h,x,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:x,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,x)=>n.ac(Number(h),Number(x),n.Fb.dc,n.Fb.errors)};function O(h,x,I){return jr(async()=>{await n.Xb(Number(h),Number(x),Number(I))})}function Y(){return typeof wasmOffsetConverter<"u"}class z{constructor(x){te(this,"name","ExitStatus");this.message=`Program terminated with exit(${x})`,this.status=x}}var J=h=>{h.terminate(),h.onmessage=()=>{}},le=[],ye=h=>{Ge.length==0&&(Ms(),ls(Ge[0]));var x=Ge.pop();if(!x)return 6;lt.push(x),Gt[h.Ab]=x,x.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return x.postMessage(I,h.Mb),0},Ee=0,ke=(h,x,...I)=>{for(var L=2*I.length,U=to(),ue=kn(8*L),Te=ue>>>3,Oe=0;Oe>>0]=Ke)}return h=Wo(h,0,L,ue,x),$n(U),h};function Ie(h){if(u)return ke(0,1,h);if(C=h,!(0{if(C=h,u)throw Re(h),"unwind";Ie(h)},Ge=[],lt=[],wt=[],Gt={},Ot=h=>{var x=h.Ab;delete Gt[x],Ge.push(h),lt.splice(lt.indexOf(h),1),h.Ab=0,Yn(x)};function ur(){wt.forEach(h=>h())}var ls=h=>new Promise(x=>{h.onmessage=U=>{var ue=(U=U.data).Bb;if(U.Gb&&U.Gb!=Xs()){var Te=Gt[U.Gb];Te?Te.postMessage(U,U.Mb):y(`Internal error! Worker sent a message "${ue}" to target pthread ${U.Gb}, but that thread no longer exists!`)}else ue==="checkMailbox"?je():ue==="spawnThread"?ye(U):ue==="cleanupThread"?Ot(Gt[U.hc]):ue==="loaded"?(h.loaded=!0,x(h)):ue==="alert"?alert(`Thread ${U.ic}: ${U.text}`):U.target==="setimmediate"?h.postMessage(U):ue==="callHandler"?n[U.Qb](...U.args):ue&&y(`worker sent an unknown command ${ue}`)},h.onerror=U=>{throw y(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:M,lc:v})});function Ms(){var h=new Worker((()=>{let x=URL;return self.location.href>"file:"&&self.location.href<"file;"?new x("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ge.push(h)}var Ir=h=>{R();var x=ce()[h+52>>>2>>>0];h=ce()[h+56>>>2>>>0],Ko(x,x-h),$n(x)},js=(h,x)=>{Ee=0,h=Ho(h,x),0>>=0);throw x>>>=0,I>>>=0,ce()[L.Ib+16>>>2>>>0]=0,ce()[L.Ib+4>>>2>>>0]=x,ce()[L.Ib+8>>>2>>>0]=I,h}function at(h,x,I,L){return u?ke(2,1,h,x,I,L):us(h,x,I,L)}function us(h,x,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var U=[];return u&&U.length===0?at(h,x>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:U},u?(h.Bb="spawnThread",postMessage(h,U),0):ye(h))}var Ar=typeof TextDecoder<"u"?new TextDecoder:void 0,bs=(h,x=0,I=NaN)=>{var L=(x>>>=0)+I;for(I=x;h[I]&&!(I>=L);)++I;if(16(U=(240&U)==224?(15&U)<<12|ue<<6|Te:(7&U)<<18|ue<<12|Te<<6|63&h[x++])?L+=String.fromCharCode(U):(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else L+=String.fromCharCode(U)}return L},Ft=(h,x)=>(h>>>=0)?bs(W(),h,x):"";function ds(h,x,I){return u?ke(3,1,h,x,I):0}function cs(h,x){if(u)return ke(4,1,h,x)}var ys=h=>{for(var x=0,I=0;I=L?x++:2047>=L?x+=2:55296<=L&&57343>=L?(x+=4,++I):x+=3}return x},Qt=(h,x,I)=>{var L=W();if(x>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&h.charCodeAt(++ue)),127>=Te){if(x>=I)break;L[x++>>>0]=Te}else{if(2047>=Te){if(x+1>=I)break;L[x++>>>0]=192|Te>>6}else{if(65535>=Te){if(x+2>=I)break;L[x++>>>0]=224|Te>>12}else{if(x+3>=I)break;L[x++>>>0]=240|Te>>18,L[x++>>>0]=128|Te>>12&63}L[x++>>>0]=128|Te>>6&63}L[x++>>>0]=128|63&Te}}L[x>>>0]=0,h=x-U}else h=0;return h};function De(h,x){if(u)return ke(5,1,h,x)}function Qe(h,x,I){if(u)return ke(6,1,h,x,I)}function tt(h,x,I){return u?ke(7,1,h,x,I):0}function Rt(h,x){if(u)return ke(8,1,h,x)}function zr(h,x,I){if(u)return ke(9,1,h,x,I)}function Sr(h,x,I,L){if(u)return ke(10,1,h,x,I,L)}function ps(h,x,I,L){if(u)return ke(11,1,h,x,I,L)}function hs(h,x,I,L){if(u)return ke(12,1,h,x,I,L)}function Kr(h){if(u)return ke(13,1,h)}function ms(h,x){if(u)return ke(14,1,h,x)}function _s(h,x,I){if(u)return ke(15,1,h,x,I)}var Hr,vr,cn=()=>Fe(""),xr=h=>{for(var x="";W()[h>>>0];)x+=Hr[W()[h++>>>0]];return x},$s={},ks={};function fr(h,x,I={}){return function(L,U,ue={}){var Te=U.name;if(!L)throw new vr(`type "${Te}" must have a positive integer typeid pointer`);if(ks.hasOwnProperty(L)){if(ue.Sb)return;throw new vr(`Cannot register type '${Te}' twice`)}ks[L]=U,$s.hasOwnProperty(L)&&(U=$s[L],delete $s[L],U.forEach(Oe=>Oe()))}(h,x,I)}var Vs=(h,x,I)=>{switch(x){case 1:return I?L=>F()[L>>>0]:L=>W()[L>>>0];case 2:return I?L=>re()[L>>>1>>>0]:L=>_e()[L>>>1>>>0];case 4:return I?L=>se()[L>>>2>>>0]:L=>ce()[L>>>2>>>0];case 8:return I?L=>Z[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${x}): ${h}`)}};function pn(h,x,I){I>>>=0,fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:L=>L,toWireType:function(L,U){if(typeof U!="bigint"&&typeof U!="number")throw U=U===null?"null":(L=typeof U)=="object"||L==="array"||L==="function"?U.toString():""+U,new TypeError(`Cannot convert "${U}" to ${this.name}`);return typeof U=="number"&&(U=BigInt(U)),U},Cb:Fr,readValueFromPointer:Vs(x,I,x.indexOf("u")==-1),Db:null})}var Fr=8;function hn(h,x,I,L){fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:function(U){return!!U},toWireType:function(U,ue){return ue?I:L},Cb:Fr,readValueFromPointer:function(U){return this.fromWireType(W()[U>>>0])},Db:null})}var qr=[],Tr=[];function Is(h){9<(h>>>=0)&&--Tr[h+1]==0&&(Tr[h]=void 0,qr.push(h))}var dr=h=>{if(!h)throw new vr("Cannot use deleted val. handle = "+h);return Tr[h]},gr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let x=qr.pop()||Tr.length;return Tr[x]=h,Tr[x+1]=1,x}};function Br(h){return this.fromWireType(ce()[h>>>2>>>0])}var mn={name:"emscripten::val",fromWireType:h=>{var x=dr(h);return Is(h),x},toWireType:(h,x)=>gr(x),Cb:Fr,readValueFromPointer:Br,Db:null};function _n(h){return fr(h>>>0,mn)}var fn=(h,x)=>{switch(x){case 4:return function(I){return this.fromWireType($e()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ue()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${x}): ${h}`)}};function gn(h,x,I){I>>>=0,fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:L=>L,toWireType:(L,U)=>U,Cb:Fr,readValueFromPointer:fn(x,I),Db:null})}function wn(h,x,I,L,U){if(h>>>=0,I>>>=0,x=xr(x>>>0),U===-1&&(U=4294967295),U=Oe=>Oe,L===0){var ue=32-8*I;U=Oe=>Oe<>>ue}var Te=x.includes("unsigned")?function(Oe,Ke){return Ke>>>0}:function(Oe,Ke){return Ke};fr(h,{name:x,fromWireType:U,toWireType:Te,Cb:Fr,readValueFromPointer:Vs(x,I,L!==0),Db:null})}function vs(h,x,I){function L(ue){var Te=ce()[ue>>>2>>>0];return ue=ce()[ue+4>>>2>>>0],new U(F().buffer,ue,Te)}var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][x];fr(h>>>=0,{name:I=xr(I>>>0),fromWireType:L,Cb:Fr,readValueFromPointer:L},{Sb:!0})}function Mn(h,x){fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:function(I){for(var L,U=ce()[I>>>2>>>0],ue=I+4,Te=ue,Oe=0;Oe<=U;++Oe){var Ke=ue+Oe;Oe!=U&&W()[Ke>>>0]!=0||(Te=Ft(Te,Ke-Te),L===void 0?L=Te:(L+="\0",L+=Te),Te=Ke+1)}return Nr(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var U=typeof L=="string";if(!(U||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new vr("Cannot pass non-string to std::string");var ue=U?ys(L):L.length,Te=Cn(4+ue+1),Oe=Te+4;if(ce()[Te>>>2>>>0]=ue,U)Qt(L,Oe,ue+1);else if(U)for(U=0;U>>0]=Ke}else for(U=0;U>>0]=L[U];return I!==null&&I.push(Nr,Te),Te},Cb:Fr,readValueFromPointer:Br,Db(I){Nr(I)}})}var Us=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,bn=(h,x)=>{for(var I=h>>1,L=I+x/2;!(I>=L)&&_e()[I>>>0];)++I;if(32<(I<<=1)-h&&Us)return Us.decode(W().slice(h,I));for(I="",L=0;!(L>=x/2);++L){var U=re()[h+2*L>>>1>>>0];if(U==0)break;I+=String.fromCharCode(U)}return I},yn=(h,x,I)=>{if(I??(I=2147483647),2>I)return 0;var L=x;I=(I-=2)<2*h.length?I/2:h.length;for(var U=0;U>>1>>>0]=ue,x+=2}return re()[x>>>1>>>0]=0,x-L},xs=h=>2*h.length,vn=(h,x)=>{for(var I=0,L="";!(I>=x/4);){var U=se()[h+4*I>>>2>>>0];if(U==0)break;++I,65536<=U?(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U)):L+=String.fromCharCode(U)}return L},he=(h,x,I)=>{if(x>>>=0,I??(I=2147483647),4>I)return 0;var L=x;I=L+I-4;for(var U=0;U=ue&&(ue=65536+((1023&ue)<<10)|1023&h.charCodeAt(++U)),se()[x>>>2>>>0]=ue,(x+=4)+4>I)break}return se()[x>>>2>>>0]=0,x-L},$=h=>{for(var x=0,I=0;I=L&&++I,x+=4}return x};function N(h,x,I){if(h>>>=0,x>>>=0,I=xr(I>>>=0),x===2)var L=bn,U=yn,ue=xs,Te=Oe=>_e()[Oe>>>1>>>0];else x===4&&(L=vn,U=he,ue=$,Te=Oe=>ce()[Oe>>>2>>>0]);fr(h,{name:I,fromWireType:Oe=>{for(var Ke,Ze=ce()[Oe>>>2>>>0],ht=Oe+4,Tt=0;Tt<=Ze;++Tt){var It=Oe+4+Tt*x;Tt!=Ze&&Te(It)!=0||(ht=L(ht,It-ht),Ke===void 0?Ke=ht:(Ke+="\0",Ke+=ht),ht=It+x)}return Nr(Oe),Ke},toWireType:(Oe,Ke)=>{if(typeof Ke!="string")throw new vr(`Cannot pass non-string to C++ string type ${I}`);var Ze=ue(Ke),ht=Cn(4+Ze+x);return ce()[ht>>>2>>>0]=Ze/x,U(Ke,ht+4,Ze+x),Oe!==null&&Oe.push(Nr,ht),ht},Cb:Fr,readValueFromPointer:Br,Db(Oe){Nr(Oe)}})}function Q(h,x){fr(h>>>=0,{Tb:!0,name:x=xr(x>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){Sn(h>>>0,!l,1,!a,131072,!1),ur()}var de=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(se(),h>>>2,h).value.then(je),h+=128,Atomics.store(se(),h>>>2,1))}var je=()=>{var h=Xs();h&&(ve(h),de(eo))};function He(h,x){(h>>>=0)==x>>>0?setTimeout(je):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=Gt[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function Je(h,x,I,L,U){for(x>>>=0,L/=2,We.length=L,I=U>>>0>>>3,U=0;U>>0];return(x?Ve[x]:jo[h])(...We)}var dt=()=>{Ee=0};function xt(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):Ot(Gt[h])}function Pt(h){}var jt=(h,x)=>{var I=ks[h];if(I===void 0)throw h=No(h),I=xr(h),Nr(h),new vr(`${x} has unknown type ${I}`);return I},kt=(h,x,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ce()[x>>>2>>>0]=gr(L)),h};function Ht(h,x,I){return x>>>=0,I>>>=0,h=dr(h>>>0),x=jt(x,"emval::as"),kt(x,I,h)}function br(h,x){return x>>>=0,h=dr(h>>>0),(x=jt(x,"emval::as")).toWireType(null,h)}var cr=h=>{try{h()}catch(x){Fe(x)}},pr=0,Nt=null,Xr=0,Dt=[],rr={},wr={},Qr=0,Rr=null,Yt=[];function jr(h){return function(x){if(!ae){if(pr===0){var I=!1,L=!1;x((U=0)=>{if(!ae&&(Xr=U,I=!0,L)){pr=2,cr(()=>Xo(Nt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),U=!1;try{var ue=function(){var Ke=se()[Nt+8>>>2>>>0];return Ke=nt[wr[Ke]],--Ee,Ke()}()}catch(Ke){ue=Ke,U=!0}var Te=!1;if(!Nt){var Oe=Rr;Oe&&(Rr=null,(U?Oe.reject:Oe.resolve)(ue),Te=!0)}if(U&&!Te)throw ue}}),L=!0,I||(pr=1,Nt=function(){var U=Cn(65548),ue=U+12;ce()[U>>>2>>>0]=ue,ce()[U+4>>>2>>>0]=ue+65536,ue=Dt[0];var Te=rr[ue];return Te===void 0&&(Te=Qr++,rr[ue]=Te,wr[Te]=ue),ue=Te,se()[U+8>>>2>>>0]=ue,U}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),cr(()=>ro(Nt)))}else pr===2?(pr=0,cr(so),Nr(Nt),Nt=null,Yt.forEach(de)):Fe(`invalid state: ${pr}`);return Xr}}(x=>{h().then(x)})}function or(h){return h>>>=0,jr(async()=>{var x=await dr(h);return gr(x)})}var Vt=[];function Zt(h,x,I,L){return I>>>=0,L>>>=0,(h=Vt[h>>>0])(null,x=dr(x>>>0),I,L)}var er={},tr=h=>{var x=er[h];return x===void 0?xr(h):x};function Ws(h,x,I,L,U){return I>>>=0,L>>>=0,U>>>=0,(h=Vt[h>>>0])(x=dr(x>>>0),x[I=tr(I)],L,U)}var xn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function vi(h){return(h>>>=0)==0?gr(xn()):(h=tr(h),gr(xn()[h]))}var xi=h=>{var x=Vt.length;return Vt.push(h),x},Ti=(h,x)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},As=(h,x)=>Object.defineProperty(x,"name",{value:h});function Ei(h,x,I){var L=(x=Ti(h,x>>>0)).shift();h--;var U=`return function (obj, func, destructorsRef, args) { -`,ue=0,Te=[];I===0&&Te.push("obj");for(var Oe=["retType"],Ke=[L],Ze=0;Zeht.name).join(", ")}) => ${L.name}>`,xi(As(I,h))}function Pi(h){return h=tr(h>>>0),gr(n[h])}function Ci(h,x){return x>>>=0,h=dr(h>>>0),x=dr(x),gr(h[x])}function Si(h){9<(h>>>=0)&&(Tr[h+1]+=1)}function $i(){return gr([])}function Eo(h){h=dr(h>>>0);for(var x=Array(h.length),I=0;I>>0))}function Ii(){return gr({})}function Po(h){for(var x=dr(h>>>=0);x.length;){var I=x.pop();x.pop()(I)}Is(h)}function Ai(h,x,I){x>>>=0,I>>>=0,h=dr(h>>>0),x=dr(x),I=dr(I),h[x]=I}function Co(h,x){return x>>>=0,h=(h=jt(h>>>0,"_emval_take_value")).readValueFromPointer(x),gr(h)}function Fi(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[x>>>2>>>0]=h.getUTCSeconds(),se()[x+4>>>2>>>0]=h.getUTCMinutes(),se()[x+8>>>2>>>0]=h.getUTCHours(),se()[x+12>>>2>>>0]=h.getUTCDate(),se()[x+16>>>2>>>0]=h.getUTCMonth(),se()[x+20>>>2>>>0]=h.getUTCFullYear()-1900,se()[x+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,se()[x+28>>>2>>>0]=h}var Kn=h=>h%4==0&&(h%100!=0||h%400==0),Oi=[0,31,60,91,121,152,182,213,244,274,305,335],So=[0,31,59,90,120,151,181,212,243,273,304,334];function $o(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[x>>>2>>>0]=h.getSeconds(),se()[x+4>>>2>>>0]=h.getMinutes(),se()[x+8>>>2>>>0]=h.getHours(),se()[x+12>>>2>>>0]=h.getDate(),se()[x+16>>>2>>>0]=h.getMonth(),se()[x+20>>>2>>>0]=h.getFullYear()-1900,se()[x+24>>>2>>>0]=h.getDay();var I=(Kn(h.getFullYear())?Oi:So)[h.getMonth()]+h.getDate()-1|0;se()[x+28>>>2>>>0]=I,se()[x+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),se()[x+32>>>2>>>0]=h}function Di(h){h>>>=0;var x=new Date(se()[h+20>>>2>>>0]+1900,se()[h+16>>>2>>>0],se()[h+12>>>2>>>0],se()[h+8>>>2>>>0],se()[h+4>>>2>>>0],se()[h>>>2>>>0],0),I=se()[h+32>>>2>>>0],L=x.getTimezoneOffset(),U=new Date(x.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(x.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ue,U);return 0>I?se()[h+32>>>2>>>0]=+(U!=ue&&Te==L):0>>2>>>0]=x.getDay(),I=(Kn(x.getFullYear())?Oi:So)[x.getMonth()]+x.getDate()-1|0,se()[h+28>>>2>>>0]=I,se()[h>>>2>>>0]=x.getSeconds(),se()[h+4>>>2>>>0]=x.getMinutes(),se()[h+8>>>2>>>0]=x.getHours(),se()[h+12>>>2>>>0]=x.getDate(),se()[h+16>>>2>>>0]=x.getMonth(),se()[h+20>>>2>>>0]=x.getYear(),h=x.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Tn(h,x,I,L,U,ue,Te){return u?ke(16,1,h,x,I,L,U,ue,Te):-52}function ko(h,x,I,L,U,ue){if(u)return ke(17,1,h,x,I,L,U,ue)}var Gs={},Li=()=>performance.timeOrigin+performance.now();function Io(h,x){if(u)return ke(18,1,h,x);if(Gs[h]&&(clearTimeout(Gs[h].id),delete Gs[h]),!x)return 0;var I=setTimeout(()=>{delete Gs[h],de(()=>Go(h,performance.timeOrigin+performance.now()))},x);return Gs[h]={id:I,qc:x},0}function zi(h,x,I,L){h>>>=0,x>>>=0,I>>>=0,L>>>=0;var U=new Date().getFullYear(),ue=new Date(U,0,1).getTimezoneOffset();U=new Date(U,6,1).getTimezoneOffset();var Te=Math.max(ue,U);ce()[h>>>2>>>0]=60*Te,se()[x>>>2>>>0]=+(ue!=U),h=(x=Oe=>{var Ke=Math.abs(Oe);return`UTC${0<=Oe?"-":"+"}${String(Math.floor(Ke/60)).padStart(2,"0")}${String(Ke%60).padStart(2,"0")}`})(ue),x=x(U),UDate.now();function Ri(h,x,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Z[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Ks=[],Hn=(h,x)=>{Ks.length=0;for(var I;I=W()[h++>>>0];){var L=I!=105;x+=(L&=I!=112)&&x%8?4:0,Ks.push(I==112?ce()[x>>>2>>>0]:I==106?Z[x>>>3]:I==105?se()[x>>>2>>>0]:Ue()[x>>>3>>>0]),x+=L?8:4}return Ks};function ji(h,x,I){return h>>>=0,x=Hn(x>>>0,I>>>0),Ve[h](...x)}function Ao(h,x,I){return h>>>=0,x=Hn(x>>>0,I>>>0),Ve[h](...x)}var Fs=()=>{};function Ni(h,x){return y(Ft(h>>>0,x>>>0))}var pu=()=>{throw Ee+=1,"unwind"};function Vi(){return 4294901760}var hu=()=>navigator.hardwareConcurrency;function Ui(){return Fe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Fo(h){h>>>=0;var x=W().length;if(h<=x||4294901760=I;I*=2){var L=x*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-M.buffer.byteLength+65535)/65536|0;try{M.grow(L),R();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1}var En=()=>(Fe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Hs={},Oo=h=>{h.forEach(x=>{En()})};function Wi(){var h=Error().stack.toString().split(` -`);return h[0]=="Error"&&h.shift(),Oo(h),Hs.Lb=En(),Hs.cc=h,Hs.Lb}function Gi(h,x,I){if(h>>>=0,x>>>=0,Hs.Lb==h)var L=Hs.cc;else(L=Error().stack.toString().split(` -`))[0]=="Error"&&L.shift(),Oo(L);for(var U=3;L[U]&&En()!=h;)++U;for(h=0;h>>2>>>0]=En();return h}var qs,qn={},Do=()=>{if(!qs){var h,x={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(h in qn)qn[h]===void 0?delete x[h]:x[h]=qn[h];var I=[];for(h in x)I.push(`${h}=${x[h]}`);qs=I}return qs};function Lo(h,x){if(u)return ke(19,1,h,x);h>>>=0,x>>>=0;var I=0;return Do().forEach((L,U)=>{var ue=x+I;for(U=ce()[h+4*U>>>2>>>0]=ue,ue=0;ue>>0]=L.charCodeAt(ue);F()[U>>>0]=0,I+=L.length+1}),0}function Xn(h,x){if(u)return ke(20,1,h,x);h>>>=0,x>>>=0;var I=Do();ce()[h>>>2>>>0]=I.length;var L=0;return I.forEach(U=>L+=U.length+1),ce()[x>>>2>>>0]=L,0}function zo(h){return u?ke(21,1,h):52}function Bo(h,x,I,L){return u?ke(22,1,h,x,I,L):52}function Qn(h,x,I,L){return u?ke(23,1,h,x,I,L):70}var Ki=[null,[],[]];function Ro(h,x,I,L){if(u)return ke(24,1,h,x,I,L);x>>>=0,I>>>=0,L>>>=0;for(var U=0,ue=0;ue>>2>>>0],Oe=ce()[x+4>>>2>>>0];x+=8;for(var Ke=0;Ke>>0],ht=Ki[h];Ze===0||Ze===10?((h===1?E:y)(bs(ht)),ht.length=0):ht.push(Ze)}U+=Oe}return ce()[L>>>2>>>0]=U,0}u||function(){for(var h=n.numThreads-1;h--;)Ms();le.unshift(()=>{be++,function(x){u?x():Promise.all(Ge.map(ls)).then(x)}(()=>Ae())})}();for(var Jn=Array(256),Pn=0;256>Pn;++Pn)Jn[Pn]=String.fromCharCode(Pn);Hr=Jn,vr=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},Tr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Tr.length/2-5-qr.length;var nt,jo=[Ie,Re,at,ds,cs,De,Qe,tt,Rt,zr,Sr,ps,hs,Kr,ms,_s,Tn,ko,Io,Lo,Xn,zo,Bo,Qn,Ro];(async function(){function h(L,U){return nt=L.exports,nt=function(){var ue=nt,Te={};for(let[Oe,Ke]of Object.entries(ue))Te[Oe]=typeof Ke=="function"?(...Ze)=>{Dt.push(Oe);try{return Ke(...Ze)}finally{ae||(Dt.pop(),Nt&&pr===1&&Dt.length===0&&(pr=0,Ee+=1,cr(qo),typeof Fibers<"u"&&Fibers.rc()))}}:Ke;return Te}(),nt=function(){var ue=nt,Te=Ke=>Ze=>Ke(Ze)>>>0,Oe=Ke=>()=>Ke()>>>0;return(ue=Object.assign({},ue)).Da=Te(ue.Da),ue.fb=Oe(ue.fb),ue.hb=Te(ue.hb),ue.tb=Te(ue.tb),ue.ub=Oe(ue.ub),ue.__cxa_get_exception_ptr=Te(ue.__cxa_get_exception_ptr),ue}(),wt.push(nt.ib),v=U,Ae(),nt}be++;var x=ze();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(x,(U,ue)=>{h(U,ue),L(U.exports)})});if(u)return new Promise(L=>{we=U=>{var ue=new WebAssembly.Instance(U,ze());L(h(ue,U))}});xe??(xe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",w):w+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href);try{var I=await async function(L){var U=xe;if(!me&&typeof WebAssembly.instantiateStreaming=="function"&&!V(U))try{var ue=fetch(U,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ue,L)}catch(Te){y(`wasm streaming compile failed: ${Te}`),y("falling back to ArrayBuffer instantiation")}return async function(Te,Oe){try{var Ke=await async function(Ze){if(!me)try{var ht=await f(Ze);return new Uint8Array(ht)}catch{}if(Ze==xe&&me)Ze=new Uint8Array(me);else{if(!_)throw"both async and sync fetching of the wasm failed";Ze=_(Ze)}return Ze}(Te);return await WebAssembly.instantiate(Ke,Oe)}catch(Ze){y(`failed to asynchronously prepare wasm: ${Ze}`),Fe(Ze)}}(U,L)}(x);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var No=h=>(No=nt.Da)(h),Vo=()=>(Vo=nt.Ea)();n._OrtInit=(h,x)=>(n._OrtInit=nt.Fa)(h,x),n._OrtGetLastError=(h,x)=>(n._OrtGetLastError=nt.Ga)(h,x),n._OrtCreateSessionOptions=(h,x,I,L,U,ue,Te,Oe,Ke,Ze)=>(n._OrtCreateSessionOptions=nt.Ha)(h,x,I,L,U,ue,Te,Oe,Ke,Ze),n._OrtAppendExecutionProvider=(h,x,I,L,U)=>(n._OrtAppendExecutionProvider=nt.Ia)(h,x,I,L,U),n._OrtAddFreeDimensionOverride=(h,x,I)=>(n._OrtAddFreeDimensionOverride=nt.Ja)(h,x,I),n._OrtAddSessionConfigEntry=(h,x,I)=>(n._OrtAddSessionConfigEntry=nt.Ka)(h,x,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=nt.La)(h),n._OrtCreateSession=(h,x,I)=>(n._OrtCreateSession=nt.Ma)(h,x,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=nt.Na)(h),n._OrtGetInputOutputCount=(h,x,I)=>(n._OrtGetInputOutputCount=nt.Oa)(h,x,I),n._OrtGetInputOutputMetadata=(h,x,I,L)=>(n._OrtGetInputOutputMetadata=nt.Pa)(h,x,I,L),n._OrtFree=h=>(n._OrtFree=nt.Qa)(h),n._OrtCreateTensor=(h,x,I,L,U,ue)=>(n._OrtCreateTensor=nt.Ra)(h,x,I,L,U,ue),n._OrtGetTensorData=(h,x,I,L,U)=>(n._OrtGetTensorData=nt.Sa)(h,x,I,L,U),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=nt.Ta)(h),n._OrtCreateRunOptions=(h,x,I,L)=>(n._OrtCreateRunOptions=nt.Ua)(h,x,I,L),n._OrtAddRunConfigEntry=(h,x,I)=>(n._OrtAddRunConfigEntry=nt.Va)(h,x,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=nt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=nt.Xa)(h),n._OrtBindInput=(h,x,I)=>(n._OrtBindInput=nt.Ya)(h,x,I),n._OrtBindOutput=(h,x,I,L)=>(n._OrtBindOutput=nt.Za)(h,x,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=nt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=nt.$a)(h),n._OrtRunWithBinding=(h,x,I,L,U)=>(n._OrtRunWithBinding=nt.ab)(h,x,I,L,U),n._OrtRun=(h,x,I,L,U,ue,Te,Oe)=>(n._OrtRun=nt.bb)(h,x,I,L,U,ue,Te,Oe),n._OrtEndProfiling=h=>(n._OrtEndProfiling=nt.cb)(h),n._JsepOutput=(h,x,I)=>(n._JsepOutput=nt.db)(h,x,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=nt.eb)(h);var Xs=()=>(Xs=nt.fb)(),Nr=n._free=h=>(Nr=n._free=nt.gb)(h),Cn=n._malloc=h=>(Cn=n._malloc=nt.hb)(h),Sn=(h,x,I,L,U,ue)=>(Sn=nt.kb)(h,x,I,L,U,ue),Uo=()=>(Uo=nt.lb)(),Wo=(h,x,I,L,U)=>(Wo=nt.mb)(h,x,I,L,U),Yn=h=>(Yn=nt.nb)(h),Zn=h=>(Zn=nt.ob)(h),Go=(h,x)=>(Go=nt.pb)(h,x),eo=()=>(eo=nt.qb)(),Ko=(h,x)=>(Ko=nt.rb)(h,x),$n=h=>($n=nt.sb)(h),kn=h=>(kn=nt.tb)(h),to=()=>(to=nt.ub)(),Ho=n.dynCall_ii=(h,x)=>(Ho=n.dynCall_ii=nt.vb)(h,x),ro=h=>(ro=nt.wb)(h),qo=()=>(qo=nt.xb)(),Xo=h=>(Xo=nt.yb)(h),so=()=>(so=nt.zb)();return n.stackSave=()=>to(),n.stackRestore=h=>$n(h),n.stackAlloc=h=>kn(h),n.setValue=function(h,x,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":F()[h>>>0]=x;break;case"i16":re()[h>>>1>>>0]=x;break;case"i32":se()[h>>>2>>>0]=x;break;case"i64":Z[h>>>3]=BigInt(x);break;case"float":$e()[h>>>2>>>0]=x;break;case"double":Ue()[h>>>3>>>0]=x;break;case"*":ce()[h>>>2>>>0]=x;break;default:Fe(`invalid type for setValue: ${I}`)}},n.getValue=function(h,x="i8"){switch(x.endsWith("*")&&(x="*"),x){case"i1":case"i8":return F()[h>>>0];case"i16":return re()[h>>>1>>>0];case"i32":return se()[h>>>2>>>0];case"i64":return Z[h>>>3];case"float":return $e()[h>>>2>>>0];case"double":return Ue()[h>>>3>>>0];case"*":return ce()[h>>>2>>>0];default:Fe(`invalid type for getValue: ${x}`)}},n.UTF8ToString=Ft,n.stringToUTF8=Qt,n.lengthBytesUTF8=ys,function h(){if(0{Pa(),Ia=typeof location>"u"?void 0:location.origin,Aa=self.location.href>"file:"&&self.location.href<"file;",Jd=()=>{{if(Aa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Ia).href}return self.location.href}},Dr=Jd(),Yd=()=>{if(Dr&&!Dr.startsWith("blob:"))return Dr.substring(0,Dr.lastIndexOf("/")+1)},ti=(e,r)=>{try{let t=r??Dr;return(t?new URL(e,t):new URL(e)).origin===Ia}catch{return!1}},Zd=(e,r)=>{let t=r??Dr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},ec=(e,r)=>`${r??"./"}${e}`,Fa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},tc=async e=>(await import(e)).default,Oa=(gv(),ao(Kd)).default,rc=async()=>{if(!Dr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ti(Dr))return[void 0,Oa()];let e=await Fa(Dr);return[e,Oa(e)]},Da=(wv(),ao(qd)).default,sc=async(e,r,t)=>{if(!e&&!r&&Da&&Dr&&ti(Dr))return[void 0,Da];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??Zd(s,r),n=t&&o&&!ti(o,r),i=n?await Fa(o):o??ec(s,r);return[n?i:void 0,await tc(i)]}}}),za,ri,po,Ba,nc,oc,ic,Ra,zt,en=Be(()=>{La(),ri=!1,po=!1,Ba=!1,nc=()=>{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}},oc=()=>{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}},ic=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ra=async e=>{if(ri)return Promise.resolve();if(po)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ba)throw new Error("previous call to 'initializeWebAssembly()' failed.");po=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ic())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!oc())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=nc();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 o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[d,c]=await sc(a,n,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(T=>{setTimeout(()=>{f=!0,T()},r)})),_.push(new Promise((T,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(u||n)w.locateFile=g=>u??n+g;else if(a&&a.indexOf("blob:")!==0)w.locateFile=g=>new URL(g,a).href;else if(d){let g=Yd();g&&(w.locateFile=S=>g+S)}c(w).then(g=>{po=!1,ri=!0,za=g,T(),d&&URL.revokeObjectURL(d)},g=>{po=!1,Ba=!0,k(g)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},zt=()=>{if(ri&&za)return za;throw new Error("WebAssembly is not initialized yet.")}}),rs,si,At,ja=Be(()=>{en(),rs=(e,r)=>{let t=zt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},si=(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(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")si(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},At=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),ac,Mv=Be(()=>{en(),ja(),ac=e=>{let r=zt(),t=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.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)o.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&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=rs(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&si(e.extra,"",new WeakSet,(i,a)=>{let l=rs(i,s),u=rs(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&At(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),lc,uc,dc,ho,cc,pc,bv=Be(()=>{en(),ja(),lc=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}`)}},uc=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},dc=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)},ho=(e,r,t,s)=>{let o=rs(r,s),n=rs(t,s);zt()._OrtAddSessionConfigEntry(e,o,n)!==0&&At(`Can't set a session config entry: ${r} - ${t}.`)},cc=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&ho(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);ho(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=rs(o,t),a=n.length,l=0,u=0;if(a>0){l=zt()._malloc(a*zt().PTR_SIZE),t.push(l),u=zt()._malloc(a*zt().PTR_SIZE),t.push(u);for(let p=0;p{let r=zt(),t=0,s=[],o=e||{};dc(o);try{let n=lc(o.graphOptimizationLevel??"all"),i=uc(o.executionMode??"sequential"),a=typeof o.logId=="string"?rs(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?rs(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&At("Can't create session options."),o.executionProviders&&await cc(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);ho(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[d,c]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof c!="number"||!Number.isInteger(c)||c<0)throw new Error(`free dimension override value must be a non-negative integer: ${c}`);let f=rs(d,s);r._OrtAddFreeDimensionOverride(t,f,c)!==0&&At(`Can't set a free dimension override: ${d} - ${c}.`)}return o.extra!==void 0&&si(o.extra,"",new WeakSet,(d,c)=>{ho(t,d,c,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),jn,Ts,tn,Na,ni,Va,Ua,Wa,ut=Be(()=>{jn=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}`)}},Ts=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}`)}},tn=(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((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},Na=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}`)}},ni=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}`)}},Va=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ua=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wa=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}`)}}}),Ga,hc=Be(()=>{Pa(),Ga=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 o=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 i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),mc,_c,fc,gc,Ka,wc,vt,Es=Be(()=>{ut(),mc=["V","I","W","E","F"],_c=(e,r)=>{console.log(`[${mc[e]},${new Date().toISOString()}]${r}`)},Ka=(e,r)=>{fc=e,gc=r},wc=(e,r)=>{let t=ni(e),s=ni(fc);t>=s&&_c(t,typeof r=="function"?r():r)},vt=(...e)=>{gc&&wc(...e)}}),Mc,Nn,Me,oi,bc,yc,vc,mt=Be(()=>{Mc=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,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=Mc.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},Me=class fa{static size(r){return fa.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}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 fa.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 fa.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+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((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},oi=class Yo{static adjustPoolAttributes(r,t,s,o,n,i){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]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,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(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ut(),Ha=(e,r)=>new(Na(r))(e)}),qa,Xa,Tc,Qa,Ec,Ja,Ya,Za,Pc,Cc,yv=Be(()=>{Es(),qa=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Xa=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Tc=1,Qa=()=>Tc++,Ec=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ja=(e,r)=>{let t=Ec.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Ya=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ja(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Xa(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):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,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},Za=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 o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",vt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Ja(o,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 a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=qa(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Xa(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Pc=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=Qa();return this.tensorTrackersById.set(e,new Za(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,o){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){vt("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 o=this.getMLContext(e),n=Qa(),i=new Ya({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new Za(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(u,1)[0];return d.sessionId=e,d}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Ya({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Cc=(...e)=>new Pc(...e)}),ii,Sc,$c,vv=Be(()=>{ut(),en(),xc(),yv(),Es(),ii=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Sc=(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((o,n)=>o===s[n]&&e[o]===r[o])},$c=class{constructor(e){this.tensorManager=Cc(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ka(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)vt("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=>Sc(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(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=ii.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=ii.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!zt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("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 Ha(t,r)}}registerMLTensor(e,r,t,s){let o=ii.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=qa(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),el=Be(()=>{}),tl,ai,li,kc,Ic,rl,sl,Ac,Fc,xv=Be(()=>{Es(),el(),tl=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]]),ai=[],li=e=>Math.ceil(Number(e)/16)*16,kc=e=>{for(let r=0;rIc++,sl=async(e,r,t,s)=>{let o=li(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),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()}},Ac=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 tl)ai.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=li(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);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,o)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),vt("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 o=li(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return vt("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=rl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),vt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),vt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=kc(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?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 i={id:rl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),vt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}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 vt("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 sl(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=tl.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&&(vt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Fc=(...e)=>new Ac(...e)}),Oc,St,Xt=Be(()=>{Oc=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}},St=e=>new Oc(e)}),Vn,ui,lr,yr,st,Kt,nl,Un,Ls,et,mo,Pe,Ye,Dc,ol,Lc,zc,ft=Be(()=>{ut(),mt(),Vn=64,ui=(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=ui(e,r);return typeof t=="string"?t:t[0]},yr=(e,r=1)=>{let t=ui(e,r);return typeof t=="string"?t:t[1]},st=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:Me.computeStrides(t)})}),r},Kt=e=>e%4===0?4:e%2===0?2:1,nl=(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})`,Ls=(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,et=(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,mo=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=ui(r,o),p=typeof u=="string"?u:u[1],d=typeof u=="string"?u:u[0],c={indices:l,value:p,storage:d,tensor:r},f=V=>typeof V=="string"?V:`${V}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},T=n?"uniforms.":"",k=`${T}${e}_shape`,w=`${T}${e}_strides`,g="";for(let V=0;V ${c.indices} { - var indices: ${c.indices}; - var current = offset; - ${g} - return indices; - }`,E=V=>(_.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),y=[];if(i>=2)for(let V=i-1;V>=0;V--)y.push(`${et(w,V,i)} * (indices[${V}])`);let M=i<2?"":` - fn i2o_${e}(indices: ${c.indices}) -> u32 { - return ${y.join("+")}; - }`,v=V=>(_.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),C=(...V)=>i===0?"0u":`${c.indices}(${V.map(f).join(",")})`,A=(V,F)=>i<2?`${V}`:`${et(V,F,i)}`,B=(V,F,W)=>i<2?`${V}=${W};`:`${et(V,F,i)}=${W};`,K={},G=(V,F)=>{_.broadcastedIndicesToOffset=!0;let W=`${F.name}broadcastedIndicesTo${e}Offset`;if(W in K)return`${W}(${V})`;let re=[];for(let _e=i-1;_e>=0;_e--){let se=F.indicesGet("outputIndices",_e+F.rank-i);re.push(`${A(w,_e)} * (${se} % ${A(k,_e)})`)}return K[W]=`fn ${W}(outputIndices: ${F.type.indices}) -> u32 { - return ${re.length>0?re.join("+"):"0u"}; - }`,`${W}(${V})`},j=(V,F)=>(()=>{if(c.storage===c.value)return`${e}[${V}]=${F};`;if(c.storage==="vec2"&&c.value==="i32")return`${e}[${V}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(c.storage==="vec2"&&c.value==="u32")return`${e}[${V}]=vec2(u32(${F}), 0u);`;if(c.storage==="u32"&&c.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),ee=V=>(()=>{if(c.storage===c.value)return`${e}[${V}]`;if(c.storage==="vec2"&&c.value==="i32")return`i32(${e}[${V}].x)`;if(c.storage==="vec2"&&c.value==="u32")return`u32(${e}[${V}].x)`;if(c.storage==="u32"&&c.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),H=i<2?"":` - fn get_${e}ByIndices(indices: ${c.indices}) -> ${p} { - return ${ee(`i2o_${e}(indices)`)}; - }`,Z=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` - fn get_${e}(${V}) -> ${p} { - return get_${e}ByIndices(${C(F)}); - }`})(),X=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let F=V.map(f).join(",");return i===0?ee("0u"):i===1?ee(F[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${F})`)},oe=V=>i<2?ee(V):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${V})`),me=i<2?"":` - fn set_${e}ByIndices(indices: ${c.indices}, value: ${p}) { - ${j(`i2o_${e}(indices)`,"value")} - }`,ae=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` - fn set_${e}(${V}, value: ${p}) { - set_${e}ByIndices(${C(F)}, value); - }`})();return{impl:()=>{let V=[],F=!1;return _.offsetToIndices&&(V.push(S),F=!0),_.indicesToOffset&&(V.push(M),F=!0),_.broadcastedIndicesToOffset&&(Object.values(K).forEach(W=>V.push(W)),F=!0),_.set&&(V.push(ae),F=!0),_.setByIndices&&(V.push(me),F=!0),_.get&&(V.push(Z),F=!0),_.getByIndices&&(V.push(H),F=!0),!n&&F&&V.unshift(`const ${k} = ${c.indices}(${t.join(",")});`,`const ${w} = ${c.indices}(${Me.computeStrides(t).join(",")});`),V.join(` -`)},type:c,offsetToIndices:E,indicesToOffset:v,broadcastedIndicesToOffset:G,indices:C,indicesGet:A,indicesSet:B,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let F=V[i];if(typeof F!="string")throw new Error("value must be string");let W=V.slice(0,i).map(f).join(",");return i===0?j("0u",F):i===1?j(W[0],F):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${W}, ${F})`)},setByOffset:j,setByIndices:(V,F)=>i<2?j(V,F):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${F});`),get:X,getByOffset:ee,getByIndices:oe,usage:s,name:e,strides:w,shape:k,rank:i}},Pe=(e,r,t,s=1)=>mo(e,r,t,"input",s),Ye=(e,r,t,s=1)=>mo(e,r,t,"output",s),Dc=(e,r,t)=>mo(e,r,t,"atomicOutput",1),ol=(e,r,t,s=1)=>mo(e,r,t,"internal",s),Lc=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=Vn){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 o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@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, - @builtin(local_invocation_id) local_id : vec3, - @builtin(local_invocation_index) local_idx : u32, - @builtin(workgroup_id) workgroup_id : vec3, - @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; - let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + - workgroup_id.y * num_workgroups[0] + workgroup_id.x; - let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) - fn main(${n}) { - ${i} - `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` -`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` - 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])}},zc=(e,r)=>new Lc(e,r)}),Bc,il,Rc,jc,Nc,Vc,Lr,Uc,Wc,zs=Be(()=>{ut(),mt(),Xt(),ft(),Bc=(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}`)},il=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Rc=(e,r)=>Me.sortBasedOnPerm(e,il(e.length,r)),jc=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { - var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=il(s,r),n=Rc(e.dims,o),i=e.dims,a=n,l=s<2||Vc(o,e.dims),u;if(l)return u=_=>{let T=Pe("input",t,i,4),k=Ye("output",t,a,4);return` - ${_.registerUniform("output_size","u32").declareVariables(T,k)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:u};let{newShape:p,newPerm:d}=Nc(e.dims,o),c=Me.areEqual(d,[2,3,1]),f=Me.areEqual(d,[3,1,2]);if(p.length===2||c||f){i=c?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return u=T=>{let k=Pe("a",t,i.length),w=Ye("output",t,a.length);return` - ${T.registerUniform("output_size","u32").declareVariables(k,w)} - var tile : array, ${_}>; - ${T.mainStart([_,_,1])} - let stride = (uniforms.output_shape[1] - 1) / ${_} + 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; - if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { - tile[local_id.y][local_id.x] = ${k.getByIndices(`${k.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; - if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { - ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} - } - }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let T=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:T},...st(i,a)]}},getShaderSource:u}}return u=_=>{let T=Pe("a",t,i.length),k=Ye("output",t,a.length);return` - ${_.registerUniform("output_size","u32").declareVariables(T,k)} - - ${jc(o,s,T,k)} - - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${k.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${k.setByOffset("global_idx",T.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...st(i,a)]}},getShaderSource:u}},Uc=(e,r)=>{Bc(e.inputs,r.perm),e.compute(Lr(e.inputs[0],r.perm))},Wc=e=>St({perm:e.perm})}),Gc,Kc,Hc,qc,Xc,Qc,Jc,Yc,Zc,ep,ss,tp,rp,sp,np,op,ip,ap,lp,up,dp,Tv=Be(()=>{ut(),mt(),ft(),ll(),zs(),Gc={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"},Kc={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"},Hc={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},qc={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Xc=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},Jc=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!Yc(e,r)){for(let s=0;st.push(s))}return t},ep=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=Me.size(n),u=Me.size(i),p=Pe("_A",t[0].dataType,a),d=Ye("output",o,n),c=64;l===1&&(c=256);let f=` - var aBestValues : array; - `,_=T=>` - ${T.registerUniform("reduceSize","u32").declareVariables(p,d)} - ${f} - fn DIV_CEIL(a : u32, b : u32) -> u32 { - return ((a - 1u) / b + 1u); - } - ${T.mainStart(c)} - - let outputIndex = global_idx / ${c}; - let offset = outputIndex * uniforms.reduceSize; - - var bestValue = f32(${Hc[s]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${c}) { - let candidate = f32(${p.getByOffset("offset + k")}); - bestValue = ${Gc[s]}; - } - aBestValues[local_idx] = bestValue; - workgroupBarrier(); - - var reduceSize = min(Length, ${c}u); - for (var currentSize = reduceSize / 2u; reduceSize > 1u; - currentSize = reduceSize / 2u) { - let interval = DIV_CEIL(reduceSize, 2u); - if (local_idx < currentSize) { - let candidate = aBestValues[local_idx + interval]; - bestValue = ${Kc[s]}; - aBestValues[local_idx] = bestValue; - } - reduceSize = interval; - workgroupBarrier(); - } - - if (local_idx == 0u) { - ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${qc[s]})`}`)}; - } - }`;return{name:e,shaderCache:{hint:`${r};${c}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},ss=(e,r,t,s)=>{let o=e.inputs.length===1?t:al(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((f,_)=>_));let i=Me.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=Zc(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Lr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=Xc(a.length,l.dims.length));let[p,d]=Qc(l.dims,a),c=p;o.keepDims&&(c=Jc(p,i)),e.compute(ep(r,o.cacheKey,[l],s,e.inputs[0].dataType,c,d),{inputs:[l]})},tp=(e,r)=>{ss(e,"ReduceMeanShared",r,"mean")},rp=(e,r)=>{ss(e,"ReduceL1Shared",r,"l1")},sp=(e,r)=>{ss(e,"ReduceL2Shared",r,"l2")},np=(e,r)=>{ss(e,"ReduceLogSumExpShared",r,"logSumExp")},op=(e,r)=>{ss(e,"ReduceMaxShared",r,"max")},ip=(e,r)=>{ss(e,"ReduceMinShared",r,"min")},ap=(e,r)=>{ss(e,"ReduceProdShared",r,"prod")},lp=(e,r)=>{ss(e,"ReduceSumShared",r,"sum")},up=(e,r)=>{ss(e,"ReduceSumSquareShared",r,"sumSquare")},dp=(e,r)=>{ss(e,"ReduceLogSumShared",r,"logSum")}}),ns,cp,di,al,os,pp,hp,mp,_p,fp,gp,wp,Mp,bp,yp,is,vp,xp,Tp,Ep,Pp,Cp,Sp,$p,kp,Ip,ll=Be(()=>{ut(),mt(),Xt(),ft(),Tv(),ns=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.")},cp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],di=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,d=Me.normalizeAxes(o,p),c=!a&&d.length===0;u.forEach((T,k)=>{c||d.indexOf(k)>=0?i&&l.push(1):l.push(T)});let f=l.length,_=Me.size(l);return{name:e,shaderCache:r,getShaderSource:T=>{let k=[],w=Pe("_A",t[0].dataType,p),g=Ye("output",n,f),S=s(w,g,d),E=S[2];for(let y=0,M=0;y=0?(i&&M++,E=`for(var j${y}: u32 = 0; j${y} < ${u[y]}; j${y}++) { - ${S[2].includes("last_index")?`let last_index = j${y};`:""} - ${w.indicesSet("input_indices",y,`j${y}`)} - ${E} - }`):(k.push(`${w.indicesSet("input_indices",y,g.indicesGet("output_indices",M))};`),M++);return` - - ${T.registerUniform("output_size","u32").declareVariables(w,g)} - - ${T.mainStart()} - ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${w.type.indices}; - let output_indices = ${g.offsetToIndices("global_idx")}; - - ${k.join(` -`)} - ${S[0]} // init ops for reduce max/min - ${S[1]} - ${E} - ${S[3]} - ${S.length===4?g.setByOffset("global_idx","value"):S.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...st(u,l)]})}},al=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),St({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},os=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:al(o,t);e.compute(di(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?cp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},pp=(e,r)=>{ns(e.inputs),os(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},hp=(e,r)=>{ns(e.inputs),os(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},mp=(e,r)=>{ns(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);"])},_p=(e,r)=>{ns(e.inputs),os(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},fp=(e,r)=>{ns(e.inputs),os(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},gp=(e,r)=>{ns(e.inputs),os(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},wp=(e,r)=>{ns(e.inputs),os(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Mp=(e,r)=>{ns(e.inputs),os(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},bp=(e,r)=>{ns(e.inputs),os(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},yp=(e,r)=>{ns(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;`,""])},is=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},vp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gp(e,r):tp(e,r)},xp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?hp(e,r):rp(e,r)},Tp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?mp(e,r):sp(e,r)},Ep=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_p(e,r):np(e,r)},Pp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?fp(e,r):op(e,r)},Cp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wp(e,r):ip(e,r)},Sp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mp(e,r):ap(e,r)},$p=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bp(e,r):lp(e,r)},kp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yp(e,r):up(e,r)},Ip=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?pp(e,r):dp(e,r)}}),ul,Ap,Fp,dl,Ev=Be(()=>{ut(),Xt(),ll(),ul=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.")},Ap=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(di("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Fp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.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); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(di("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},dl=e=>St(e)}),Op,ci,Dp,Lp,zp,_o,Bp,Rp,cl=Be(()=>{ut(),mt(),el(),ft(),Op=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&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],u=t.dims[1],p=t.dims[2];if(o.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(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=o.dims[0]/3,c=d,f=c;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");d=r.qkvHiddenSizes[0],c=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=u;if(d!==c)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+c+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let T=0;if(i){if(c!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==c/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(T=i.dims[3])}let k=_+T,w=-1,g=0;if(n)throw new Error("Mask not supported");if(i)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]!==u||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:T,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ci=(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; - let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; - total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; - var past_sequence_length: u32 = 0; - if (is_first_prompt == false) { - past_sequence_length = total_sequence_length - sequence_length; - } - `:` - ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; - let present_sequence_length = total_sequence_length; - `,Dp=(e,r,t,s,o,n,i,a)=>{let l=Kt(i?1:n),u=64,p=n/l;p{let g=Ye("x",e.dataType,e.dims,l),S=[g],E=i?Pe("seq_lens",i.dataType,i.dims):void 0;E&&S.push(E);let y=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;y&&S.push(y);let M=yr(e.dataType),v=[{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; - ${w.registerUniforms(v).declareVariables(...S)} - ${w.mainStart([u,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; - ${ci(E,y,!1)} - let local_offset = local_idx * uniforms.elements_per_thread; - let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset; - let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; - var thread_max_vector = ${_}(-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[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(); - - var max_value = f32(-3.402823e+38f); - for (var i = 0u; i < ${u}; i++) { - max_value = max(thread_max[i], max_value); - } - - var sum_vector = ${_}(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); - } - 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(); - - var sum: f32 = 0; - for (var i = 0u; i < ${u}; i++) { - sum += thread_sum[i]; - } - - if (sum == 0) { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - x[offset + i] = ${g.type.value}(${M}(1.0) / ${M}(seq_causal_length)); - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - var f32input = ${_}(x[offset + i]); - x[offset + i] = ${g.type.value}(exp(f32input - max_value) / sum); - } - } - ${i?` - 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] = ${g.type.value}(${M}(0)); - }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${f};${l}`,inputDependencies:T},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:c})}},Lp=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],d=e>1&&s,c=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,c,u,n.headSize]:void 0,_=n.nReps?n.nReps:1,T=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=Kt(n.headSize),w=n.headSize/k,g=12,S={x:Math.ceil(u/g),y:Math.ceil(n.sequenceLength/g),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:T},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:_}],y=d&&s&&Me.size(s.dims)>0,M=["type","type"];y&&M.push("type"),o&&M.push("type"),a&&M.push("type"),l&&M.push("type");let v=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&v.push({dims:f,dataType:r.dataType,gpuDataType:0});let C=A=>{let B=Pe("q",r.dataType,r.dims,k),K=Pe("key",t.dataType,t.dims,k),G=[B,K];if(y){let me=Pe("past_key",s.dataType,s.dims,k);G.push(me)}o&&G.push(Pe("attention_bias",o.dataType,o.dims));let j=a?Pe("seq_lens",a.dataType,a.dims):void 0;j&&G.push(j);let ee=l?Pe("total_sequence_length_input",l.dataType,l.dims):void 0;ee&&G.push(ee);let H=Ye("output",r.dataType,p),Z=[H];d&&Z.push(Ye("present_key",r.dataType,f,k));let X=yr(1,k),oe=[{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 = ${g}u; - - var tileQ: array<${B.type.storage}, ${g*g}>; - var tileK: array<${B.type.storage}, ${g*g}>; - ${A.registerUniforms(oe).declareVariables(...G,...Z)} - ${A.mainStart([g,g,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 batchIdx = workgroup_id.z / uniforms.num_heads; - let m = workgroup_id.y * TILE_SIZE; - let n = workgroup_id.x * TILE_SIZE; - let sequence_length = uniforms.M; - var total_sequence_length = uniforms.N; - ${ci(j,ee,!0)} - let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; - let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; - ${y&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; - let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; - ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} - var value = ${X}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { - tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; - } - if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${y&&d?` - if (n + local_id.y < past_sequence_length) { - tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { - tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; - }`:` - if (n + local_id.y < uniforms.kv_sequence_length) { - tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - }`} - ${d?`if (n + local_id.y < present_sequence_length) { - present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; - }`:""} - } - workgroupBarrier(); - - for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { - value += ${X}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); - } - - workgroupBarrier(); - } - - if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { - let headOffset = workgroup_id.z * uniforms.M * uniforms.N; - let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; - var sum: f32 = ${(()=>{switch(k){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: ${k}`)}})()}; - output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; - } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${o!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:v,dispatchGroup:S,programUniforms:E}),getShaderSource:C}},zp=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,d=e>1&&s,c=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,c,l,o.headSize]:void 0,_=[o.batchSize,o.sequenceLength,p],T=12,k={x:Math.ceil(o.vHeadSize/T),y:Math.ceil(o.sequenceLength/T),z:o.batchSize*o.numHeads},w=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:u}],g=d&&s&&Me.size(s.dims)>0,S=["type","type"];g&&S.push("type"),i&&S.push("type"),a&&S.push("type");let E=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&E.push({dims:f,dataType:r.dataType,gpuDataType:0});let y=M=>{let v=Pe("probs",r.dataType,r.dims),C=Pe("v",t.dataType,t.dims),A=[v,C];g&&A.push(Pe("past_value",s.dataType,s.dims));let B=i?Pe("seq_lens",i.dataType,i.dims):void 0;i&&A.push(B);let K=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;a&&A.push(K);let G=[Ye("output",r.dataType,_)];d&&G.push(Ye("present_value",r.dataType,f));let j=[{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 = ${T}u; - var tileQ: array<${v.type.value}, ${T*T}>; - var tileV: array<${v.type.value}, ${T*T}>; - ${M.registerUniforms(j).declareVariables(...A,...G)} - ${M.mainStart([T,T,1])} - let headIdx = workgroup_id.z % uniforms.num_heads; - let batchIdx = workgroup_id.z / uniforms.num_heads; - let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${u===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; - let m = global_id.y; - let n = global_id.x; - let sequence_length = uniforms.M; - var total_sequence_length = uniforms.K; - ${ci(B,K,!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 - ${g&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; - let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; - ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} - var value = ${v.type.storage}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (m < uniforms.M && w + local_id.x < uniforms.K) { - tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; - } - if (n < uniforms.N && w + local_id.y < uniforms.K) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${g&&d?` - if (w + local_id.y < past_sequence_length) { - tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; - } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { - tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; - } - `:` - if (w + local_id.y < uniforms.kv_sequence_length) { - tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; - }`} - ${d?` - if (w + local_id.y < present_sequence_length) { - present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; - }`:""} - } - workgroupBarrier(); - for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { - value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; - } - workgroupBarrier(); - } - - // we need to transpose output from BNSH_v to BSND_v - if (m < uniforms.M && n < uniforms.N) { - let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size - + headIdx * uniforms.N + n; - output[outputIdx] = value; - } - }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:E,dispatchGroup:k,programUniforms:w}),getShaderSource:y}},_o=(e,r,t,s,o,n,i,a,l,u,p=void 0,d=void 0)=>{let c=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=c>1?u.pastSequenceLength:0,_=f+u.kvSequenceLength,T=l&&Me.size(l.dims)>0?l:void 0,k=[r,t];c>1&&i&&Me.size(i.dims)>0&&k.push(i),T&&k.push(T),p&&k.push(p),d&&k.push(d);let w=e.compute(Lp(c,r,t,i,T,u,f,p,d),{inputs:k,outputs:c>1?[-1,1]:[-1]})[0];e.compute(Dp(w,u.batchSize,u.numHeads,f,u.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let g=[w,s];c>1&&a&&Me.size(a.dims)>0&&g.push(a),p&&g.push(p),d&&g.push(d),e.compute(zp(c,w,s,a,u,f,p,d),{inputs:g,outputs:c>1?[0,2]:[0]})},Bp=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:o},{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=d=>{let c=Ye("output_q",l[0].dataType,t),f=Ye("output_k",l[0].dataType,t),_=Ye("output_v",l[0].dataType,t),T=Pe("input",l[0].dataType,l[0].dims),k=Pe("weight",l[1].dataType,l[1].dims),w=Pe("bias",l[2].dataType,l[2].dims),g=T.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` - const TILE_SIZE = ${i}u; - var tileInput: array<${g}, ${i*i}>; - var tileWeightQ: array<${g}, ${i*i}>; - var tileWeightK: array<${g}, ${i*i}>; - var tileWeightV: array<${g}, ${i*i}>; - ${d.registerUniforms(S).declareVariables(T,k,w,c,f,_)} - ${d.mainStart([i,i,1])} - let batchIndex = workgroup_id.z / uniforms.num_heads; - let headNumber = workgroup_id.z % uniforms.num_heads; - let m = global_id.y; - let n = global_id.x; - - let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; - let biasOffsetQ = headNumber * uniforms.head_size; - let biasOffsetK = uniforms.hidden_size + biasOffsetQ; - let biasOffsetV = uniforms.hidden_size + biasOffsetK; - - var valueQ = ${g}(0); - var valueK = ${g}(0); - var valueV = ${g}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (m < uniforms.M && w + local_id.x < uniforms.K) { - tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; - } - if (n < uniforms.N && w + local_id.y < uniforms.K) { - let offset = n + (w + local_id.y) * uniforms.ldb; - tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; - tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; - tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; - } - workgroupBarrier(); - for (var k: u32 = 0u; k({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:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Rp=(e,r)=>{let t=Op(e.inputs,r),[s,o,n]=Bp(e,t);return _o(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),jp,Np,Vp,Up,Pv=Be(()=>{ts(),ut(),mt(),Xt(),ft(),jp=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.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")},Np=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?Kt(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=Me.size(n)/i,u=s,p=u?n.length:n,d=Pe("x",e[0].dataType,e[0].dims,i),c=Pe("scale",e[1].dataType,e[1].dims,a),f=Pe("bias",e[2].dataType,e[2].dims,a),_=Pe("inputMean",e[3].dataType,e[3].dims,a),T=Pe("inputVar",e[4].dataType,e[4].dims,a),k=Ye("y",e[0].dataType,p,i),w=()=>{let S="";if(s)S=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")S=` - ${k.indicesSet("outputIndices","0","0")} - let cOffset = ${k.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${c.type.indices}(0); - cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` - const epsilon = ${t}; - ${S.registerUniform("outputSize","u32").declareVariables(d,c,f,_,T,k)} - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; - ${w()} - let scale = ${c.getByOffset("cOffset")}; - let bias = ${f.getByOffset("cOffset")}; - let inputMean = ${_.getByOffset("cOffset")}; - let inputVar = ${T.getByOffset("cOffset")}; - let x = ${d.getByOffset("global_idx")}; - let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; - ${k.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...st(n)]:[{type:12,data:l}]})}},Vp=e=>St(e),Up=(e,r)=>{let{inputs:t,outputCount:s}=e,o=Vp({...r,outputCount:s});if(Bt.webgpu.validateInputContent&&jp(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Np(t,o))}}),Wp,Gp,Kp,Cv=Be(()=>{mt(),ft(),Wp=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")},Gp=e=>{let r=e[0].dims,t=e[0].dims[2],s=Me.size(r)/4,o=e[0].dataType,n=Pe("input",o,r,4),i=Pe("bias",o,[t],4),a=Pe("residual",o,r,4),l=Ye("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` - const channels = ${t}u / 4; - ${u.declareVariables(n,i,a,l)} - - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} - let value = ${n.getByOffset("global_idx")} - + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; - ${l.setByOffset("global_idx","value")} - }`}},Kp=e=>{Wp(e.inputs),e.compute(Gp(e.inputs))}}),Hp,Et,qp,Xp,Qp,Jp,Yp,Zp,eh,th,rh,sh,nh,oh,ih,ah,fo,lh,pi,uh,dh,ch,ph,hh,mh,_h,fh,gh,wh,Mh,bh,yh,vh,xh,Th,pl,Eh,hl,ml,Ph,Ch,Sh,$h,kh,Ih,_l=Be(()=>{ut(),mt(),Xt(),ft(),Hp=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Pe("inputData",t,[a],4),p=Ye("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` - ${e.registerUniforms(d).declareVariables(u,p)} - - ${n??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - - let a = ${u.getByOffset("global_idx")}; - ${p.setByOffset("global_idx",l)} - }`},Et=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(Me.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:u=>Hp(u,Me.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Me.size(u[0].dims)/64/4)},programUniforms:l})}},qp=e=>{e.compute(Et(e.inputs[0],"Abs","abs"))},Xp=e=>{e.compute(Et(e.inputs[0],"Acos","acos"))},Qp=e=>{e.compute(Et(e.inputs[0],"Acosh","acosh"))},Jp=e=>{e.compute(Et(e.inputs[0],"Asin","asin"))},Yp=e=>{e.compute(Et(e.inputs[0],"Asinh","asinh"))},Zp=e=>{e.compute(Et(e.inputs[0],"Atan","atan"))},eh=e=>{e.compute(Et(e.inputs[0],"Atanh","atanh"))},th=e=>St(e),rh=(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(Et(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},sh=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return St({min:r,max:t})},nh=(e,r)=>{let t=r||sh(e.inputs),s=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Clip",o=>`clamp(${o}, 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]})},oh=e=>{e.compute(Et(e.inputs[0],"Ceil","ceil"))},ih=e=>{e.compute(Et(e.inputs[0],"Cos","cos"))},ah=e=>{e.compute(Et(e.inputs[0],"Cosh","cosh"))},fo=e=>St(e),lh=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` - const elu_alpha_ = ${t}(${r.alpha}); - - fn elu_f32(a: ${t}) -> ${t} { - return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); - } - - fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { - return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,r.cacheKey))},pi=(e="f32")=>` -const r0: ${e} = 0.3275911; -const r1: ${e} = 0.254829592; -const r2: ${e} = -0.284496736; -const r3: ${e} = 1.421413741; -const r4: ${e} = -1.453152027; -const r5: ${e} = 1.061405429; - -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)); -}`,uh=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,pi(r)))},dh=e=>{e.compute(Et(e.inputs[0],"Exp","exp"))},ch=e=>{e.compute(Et(e.inputs[0],"Floor","floor"))},ph=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,pi(r)))},hh=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(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))},mh=e=>{e.compute(Et(e.inputs[0],"Not",r=>`!${r}`))},_h=e=>{e.compute(Et(e.inputs[0],"Neg",r=>`-${r}`))},fh=e=>{e.compute(Et(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},gh=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},wh=e=>{e.compute(Et(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Mh=e=>St(e),bh=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(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))},yh=e=>{e.compute(Et(e.inputs[0],"Sin","sin"))},vh=e=>{e.compute(Et(e.inputs[0],"Sinh","sinh"))},xh=e=>{e.compute(Et(e.inputs[0],"Sqrt","sqrt"))},Th=e=>{e.compute(Et(e.inputs[0],"Tan","tan"))},pl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Eh=e=>{e.compute(Et(e.inputs[0],"Tanh",pl))},hl=(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 ${pl("v")}; -} -`,ml=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ph=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"FastGelu",ml,hl(r),void 0,e.inputs[0].dataType))},Ch=(e,r)=>{let t=yr(e.inputs[0].dataType);return e.compute(Et(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},Sh=e=>{e.compute(Et(e.inputs[0],"Log","log"))},$h=(e,r)=>` -const alpha = vec4<${e}>(${r}); -const one = ${e}(1.0); -const zero = ${e}(0.0); - -fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { - let v = x *alpha; - var x1 : vec4<${e}>; - for (var i = 0; i < 4; i = i + 1) { - if (v[i] >= zero) { - x1[i] = one / (one + exp(-v[i])); - } else { - x1[i] = one - one / (one + exp(v[i])); - } - } - return x * x1; -} -`,kh=e=>`quick_gelu_impl(${e})`,Ih=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"QuickGelu",kh,$h(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Ah,Fh,Oh,Sv=Be(()=>{mt(),ft(),_l(),Ah=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")},Fh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Pe("input",e[0].dataType,e[0].dims,4),s=Pe("bias",e[0].dataType,[e[0].dims[2]],4),o=Ye("output",e[0].dataType,r,4),n=Me.size(r)/4,i=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; - - ${a.declareVariables(t,s,o)} - - ${pi(i)} - - ${a.mainStart()} - ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} - let biasIdx = global_idx % halfChannels; - let batchIndex = global_idx / halfChannels; - let inputOffset = biasIdx + batchIndex * halfChannels * 2; - let valueLeft = input[inputOffset] + bias[biasIdx]; - let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; - let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); - - ${o.setByOffset("global_idx","valueLeft * geluRight")} - }`}},Oh=e=>{Ah(e.inputs),e.compute(Fh(e.inputs))}}),Dh,Lh,as,zh,Bh,Rh,jh,Nh,Vh,Uh,Wh,Gh,Kh,$v=Be(()=>{ut(),mt(),ft(),Dh=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c,f;typeof a=="string"?c=f=(g,S)=>`${a}((${g}),(${S}))`:typeof a=="function"?c=f=a:(c=a.scalar,f=a.vector);let _=Ye("outputData",p,s.length,4),T=Pe("aData",l,r.length,4),k=Pe("bData",u,t.length,4),w;if(o)if(n){let g=Me.size(r)===1,S=Me.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;g||S?w=_.setByOffset("global_idx",f(g?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"),S?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` - let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; - let offsetA = ${T.broadcastedIndicesToOffset("outputIndices",_)}; - let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; - ${_.setByOffset("global_idx",f(i||E?T.getByOffset("offsetA / 4u"):`${T.type.value}(${T.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else w=_.setByOffset("global_idx",f(T.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let g=(S,E,y="")=>{let M=`aData[indexA${E}][componentA${E}]`,v=`bData[indexB${E}][componentB${E}]`;return` - let outputIndices${E} = ${_.offsetToIndices(`global_idx * 4u + ${E}u`)}; - let offsetA${E} = ${T.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; - let offsetB${E} = ${k.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; - let indexA${E} = offsetA${E} / 4u; - let indexB${E} = offsetB${E} / 4u; - let componentA${E} = offsetA${E} % 4u; - let componentB${E} = offsetB${E} % 4u; - ${S}[${E}] = ${y}(${c(M,v)}); - `};p===9?w=` - var data = vec4(0); - ${g("data",0,"u32")} - ${g("data",1,"u32")} - ${g("data",2,"u32")} - ${g("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` - ${g("outputData[global_idx]",0)} - ${g("outputData[global_idx]",1)} - ${g("outputData[global_idx]",2)} - ${g("outputData[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(T,k,_)} - - ${d??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${w} - }`},Lh=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(T=>Number(T)??1),l=s.dims.map(T=>Number(T)??1),u=!Me.areEqual(a,l),p=a,d=Me.size(a),c=!1,f=!1,_=[u];if(u){let T=Nn.calcShape(a,l,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");p=T.slice(),d=Me.size(p);let k=Me.size(a)===1,w=Me.size(l)===1,g=a.length>0&&a[a.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(w),_.push(g),_.push(S);let E=1;for(let y=1;yT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>Dh(T,a,l,p,c,u,f,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(Me.size(p)/4)},...st(a,l,p)]})}},as=(e,r,t,s,o,n)=>{e.compute(Lh(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},zh=e=>{as(e,"Add",(r,t)=>`${r}+${t}`)},Bh=e=>{as(e,"Div",(r,t)=>`${r}/${t}`)},Rh=e=>{as(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},jh=e=>{as(e,"Mul",(r,t)=>`${r}*${t}`)},Nh=e=>{let r=Pe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;as(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); - } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { - return ${r}(pow(f32(a), f32(b))); // NaN - } - return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); - } - fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { - // 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)); - } - `)},Vh=e=>{as(e,"Sub",(r,t)=>`${r}-${t}`)},Uh=e=>{as(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Wh=e=>{as(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Gh=e=>{as(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Kh=e=>{as(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Hh,qh,Xh,Qh,Jh,Yh,kv=Be(()=>{ut(),mt(),Xt(),ft(),Hh=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},qh=(e,r)=>` - fn calculateInputIndex(index: u32) -> u32 { - let sizeInConcatAxis = array(${r}); - for (var i: u32 = 0u; i < ${e}; i += 1u ) { - if (index < sizeInConcatAxis[i]) { - return i; - } - } - return ${e}u; - }`,Xh=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=Me.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:o}];for(let T=0;T`uniforms.sizeInConcatAxis${T}`).join(","),_=T=>` - - ${(()=>{T.registerUniform("outputSize","u32");for(let k=0;k(${f}); - ${c} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${Xh(i,d)} - }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:_}},Jh=(e,r)=>{let t=e.inputs,s=t[0].dims,o=Me.normalizeAxis(r.axis,s.length);Hh(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>Me.size(a.dims)>0);e.compute(Qh(i,o,n,t[0].dataType),{inputs:i})},Yh=e=>St({axis:e.axis})}),rn,sn,nn,fl,on=Be(()=>{ut(),mt(),rn=(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}`)}},sn=(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})},nn=(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"})},fl=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)||[yc,vc];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}}}),_r,Zh,gl=Be(()=>{_r=(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.`)}},Zh=e=>` - ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),em,Iv=Be(()=>{em=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)); -} -fn getOutputIndexFromCoords(coords : vec4) -> i32 { - return dot(coords, vec4( - i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); -} -`}),go,wl,Ml=Be(()=>{ut(),mt(),ft(),on(),go=(e,r,t,s,o)=>{let n=s-t;return` - ${Array.from({length:t}).map((i,a)=>` - if (${et(r.shape,a,r.rank)} != 1) { - ${r.indicesSet(e,a,et(o,a+n,s))} - } else { - ${r.indicesSet(e,a,0)} - }`).join("")} -`},wl=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],d=Kt(u),c=Kt(p),f=Kt(l),_=Me.size(t)/d/f,T=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[Me.size(k),l,u],g=[{type:12,data:_},{type:12,data:l},{type:12,data:u},{type:12,data:p}];sn(r,g),g.push(...st(k,i,a)),T&&g.push(...st(e[2].dims)),g.push(...st(w));let S=E=>{let y=ol("batch_dims",e[0].dataType,k.length),M=Pe("a",e[0].dataType,i.length,c),v=Pe("b",e[1].dataType,a.length,d),C=Ye("output",e[0].dataType,w.length,d),A=lr(C.type.tensor),B=rn(r,C.type.value,A),K=[M,v],G="";if(T){let H=o?d:1;K.push(Pe("bias",e[2].dataType,e[2].dims.length,H)),G=`${o?`value += bias[col / ${H}];`:`value += ${C.type.value}(bias[row + i]);`}`}let j=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];nn(r,j);let ee=()=>{let H=`var a_data: ${M.type.value};`;for(let Z=0;Z; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${c}) { - ${ee()} - } - for (var i = 0u; i < ${f}u; i++) { - var value = values[i]; - ${G} - ${B} - let cur_indices = ${C.type.indices}(batch, row + i, col); - let offset = ${C.indicesToOffset("cur_indices")}; - ${C.setByOffset(`offset / ${d}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${c};${f};${o}`,inputDependencies:T?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:g}),getShaderSource:S}}}),tm,rm,bl,yl,sm,vl,nm,hi,xl=Be(()=>{ut(),mt(),ft(),on(),Ml(),gl(),tm=(e,r)=>e?` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - kStart + inputRow, - globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); - `:` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - globalRow + innerRow, - kStart / innerElementSize + inputCol${r?", batchIndices":""}); - `,rm=(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]; - ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} - for (var i = 0; i < rowPerThread; i = i + 1) { - acc[i] = BCached0 * ACached0[i] + acc[i]; - acc[i] = BCached1 * ACached1[i] + acc[i]; - acc[i] = BCached2 * ACached2[i] + acc[i]; - ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} - }`:` - for (var i = 0; i < rowPerThread; i = i + 1) { - let ACached = mm_Asub[tileRow + i][k]; - acc[i] = BCached0 * ACached.x + acc[i]; - acc[i] = BCached1 * ACached.y + acc[i]; - acc[i] = BCached2 * ACached.z + acc[i]; - ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,bl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,d=o?n:l,c=p/r[0],f=n/r[1];if(!((o&&c===4&&e[1]===4||!o&&(c===3||c===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${c} and workPerThread[1] ${e[1]} must be 4. - Otherwise, innerElementSize ${c} 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/c}>, ${d}>; -var mm_Bsub: array, ${u/e[0]}>, ${n}>; - -const rowPerThread = ${e[1]}; -const colPerThread = ${e[0]}; -const innerElementSize = ${c}; -const tileInner = ${n}; - -@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let localRow = i32(localId.y); - let tileRow = localRow * rowPerThread; - let tileCol = i32(localId.x); - - let globalRow =i32(globalId.y) * rowPerThread; - let globalCol = i32(globalId.x); - let batch = ${i?"0":"i32(globalId.z)"}; - ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} - let globalRowStart = i32(workgroupId.y) * ${l}; - - let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; - - var acc: array, rowPerThread>; - - // Loop over shared dimension. - let tileRowB = localRow * ${f}; - for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let inputRow = tileRow + innerRow; - let inputCol = tileCol; - ${tm(o,s)} - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { - let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; - let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; - let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; - ${c===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - - ${rm(o,c)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},yl=(e,r)=>e?` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - kStart + inputRow, - globalRowStart + inputCol${r?", batchIndices":""}); - `:` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - globalRowStart + inputRow, - kStart + inputCol${r?", batchIndices":""}); - `,sm=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",vl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],d=o?u:n,c=o?n:u;if(!(c%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${c} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let f=c/r[1],_=d/r[0],T=n/r[1],k=l?` - let localRow = i32(localId.y); - let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${u}; - let globalColStart = i32(workgroupId.x) * ${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 inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${r[1]}) { - for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { - ${yl(o,s)} - } - } - // Load one tile of B into local memory. - for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { - for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalColStart + inputCol${s?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${t}, colPerThread>; - for (var k = 0; k < tileInner; k = k + 1) { - for (var inner = 0; inner < colPerThread; inner = inner + 1) { - BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; - } - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - acc[innerRow][innerCol] = acc[innerRow][innerCol] + - ACached * BCached[innerCol]; - } - } - } - workgroupBarrier(); - } - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let gRow = globalRowStart + localRow + innerRow * ${r[1]}; - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let gCol = globalColStart + localCol + innerCol * ${r[0]}; - mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); - } - } - `:` -let tileRow = i32(localId.y) * rowPerThread; -let tileCol = i32(localId.x) * colPerThread; - -let globalRow = i32(globalId.y) * rowPerThread; -let globalCol = i32(globalId.x) * colPerThread; -let globalRowStart = i32(workgroupId.y) * ${u}; - -let tileRowA = i32(localId.y) * ${f}; -let tileColA = i32(localId.x) * ${_}; -let tileRowB = i32(localId.y) * ${T}; -// 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 < ${f}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${yl(o,s)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${T}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol + innerCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalCol + innerCol${s?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${t}, colPerThread>; - for (var k = 0; k < tileInner; k = k + 1) { - for (var inner = 0; inner < colPerThread; inner = inner + 1) { - BCached[inner] = mm_Bsub[k][tileCol + inner]; - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${sm(o)} - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; - } - } - } - - workgroupBarrier(); -} - -for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - mm_write(batch, globalRow + innerRow, globalCol + innerCol, - acc[innerRow][innerCol]); - } -} -`;return` - var mm_Asub : array, ${c}>; - var mm_Bsub : array, ${n}>; - const rowPerThread = ${e[1]}; - const colPerThread = ${e[0]}; - const tileInner = ${n}; - -@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let batch = ${i?"0":"i32(globalId.z)"}; - ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} - let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; - - var acc : array, rowPerThread>; - ${k} - } -`},nm=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=lr(s[0].type.tensor);return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${_r(e,u)} { - var value = ${_r(e,u)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) - { - var aIndices: ${i.type.indices}; - ${go("aIndices",i,i.rank-2,n.rank,"batchIndices")} - ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} - ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} - value = ${i.getByIndices("aIndices")}; - } - return value; - } - - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${_r(e,u)} { - var value = ${_r(e,u)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) - { - var bIndices: ${a.type.indices}; - ${go("bIndices",a,a.rank-2,n.rank,"batchIndices")} - ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} - ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} - value = ${a.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${_r(e,u)}) { - let col = colIn * ${e}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { - var value = valueIn; - let coords = vec3(batch, row, colIn); - ${r?`value = value + ${o?"bias[colIn]":`${_r(e,u)}(bias[row])`};`:""} - ${t} - ${l.setByIndices("vec3(coords)","value")} - } - } - `},hi=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=Me.size(p),c=i[i.length-2],f=i[i.length-1],_=a[a.length-1],T=f%4===0&&_%4===0,k=c<=8?[4,1,1]:[4,4,1],w=[8,8,1],g=[Math.ceil(_/w[0]/k[0]),Math.ceil(c/w[1]/k[1]),Math.ceil(d/w[2]/k[2])],S=T?4:1,E=[...l,c,f/S],y=E.length,M=[...u,f,_/S],v=M.length,C=[d,c,_/S],A=[{type:6,data:c},{type:6,data:_},{type:6,data:f}];sn(r,A),A.push(...st(p,E,M));let B=["rank","rank"],K=e.length>2;K&&(A.push(...st(e[2].dims)),B.push("rank")),A.push(...st(C));let G=j=>{let ee=p.length,H=ol("batchDims",e[0].dataType,ee,1),Z=lr(e[0].dataType),X=Pe("a",e[0].dataType,y,S),oe=Pe("b",e[1].dataType,v,S),me=Ye("result",e[0].dataType,C.length,S),ae=[X,oe];if(K){let _e=o?S:1;ae.push(Pe("bias",e[2].dataType,e[2].dims.length,_e))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];nn(r,V);let F=lr(me.type.tensor),W=rn(r,me.type.value,F),re=nm(S,K,W,[H,X,oe,me],o);return` - ${j.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,me)} - ${re} - ${T?bl(k,w,Z,H):vl(k,w,Z,H)} - `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${T};${o}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:A}),getShaderSource:G}}}),om,im,Av=Be(()=>{ut(),Es(),ft(),on(),gl(),Iv(),xl(),om=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=A=>{switch(A){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${A} is not supported.`)}},d=A=>{switch(A){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 ${A} is not supported.`)}},c=e?` - let coord = vec4(batch, xRow, xCol, xCh); - `:` - let coord = vec4(batch, xCh, xRow, xCol); - `,f=e?` - let coords = vec4( - batch, - row / outWidth, - row % outWidth, - col); - `:` - let coords = vec4( - batch, - row, - col / outWidth, - col % outWidth); - `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",T=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",w=e?"col":"row",g=` - let inChannels = i32(uniforms.w_shape[2]); - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${k} / outWidth; - let outCol = ${k} % outWidth; - - let WRow = ${w} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${w} / 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 = ${w} % inChannels; - var resData = ${_r(i,u)}(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 < ${T}) { - ${c} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${p(i)} - } - return resData;`,S=e?r&&s?` - let col = colIn * ${i}; - ${g}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${g} - } - return ${_r(i,u)}(0.0);`:s&&t?` - let col = colIn * ${i}; - ${g}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${g} - } - return ${_r(i,u)}(0.0);`,E=e?s&&t?d(a):` - let col = colIn * ${a}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${d(a)} - } - return ${_r(a,u)}(0.0);`:` - let col = colIn * ${a}; - if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { - ${d(a)} - } - return ${_r(a,u)}(0.0);`,y=_r(l,u),M=_r(e?i:a,u),v=_r(e?a:i,u),C=rn(n,y,u);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { - ${e?S:E} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${v} { - ${e?E:S} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) { - let col = colIn * ${l}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) - { - var value = valueIn; - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${f} - ${Zh(o)} - ${C} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},im=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],d=t[0],c=u?t[2]:t[3],f=u?t[1]:t[2],_=u?t[3]:t[1],T=u&&(p%4===0||p%3===0)&&_%4===0,k=u?_:c*f,w=u?c*f:_,g=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil(k/g[0]/S[0]),Math.ceil(w/g[1]/S[1]),Math.ceil(d/g[2]/S[2])];vt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let y=T?u&&p%4!==0?3:4:1,M=g[1]*S[1],v=g[0]*S[0],C=Math.max(g[0]*y,g[1]),A=s%M===0,B=o%v===0,K=n%C===0,G=T?[y,4,4]:[1,1,1],j=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];sn(r,j),j.push(...st(e[0].dims,e[1].dims));let ee=["rank","rank"];i&&(j.push(...st(e[2].dims)),ee.push("rank")),j.push(...st(t));let H=Z=>{let X=[{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}];nn(r,X);let oe=T?4:1,me=lr(e[0].dataType),ae=` - fn setOutputAtIndex(flatIndex : i32, value : ${T?`vec4<${me}>`:me}) { - result[flatIndex] = ${T?`vec4<${me}>`:me}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${T?`vec4<${me}>`:me}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${T?"/ 4":""}, value); - }`,V=Pe("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=Pe("w",e[1].dataType,e[1].dims.length,oe),W=[V,F],re=Ye("result",e[0].dataType,t.length,oe);if(i){let _e=Pe("bias",e[2].dataType,e[2].dims.length,oe);W.push(_e),ae+=` - fn getBiasByOutputCoords(coords : vec4) -> ${T?`vec4<${me}>`:me} { - return bias[coords.${u?"w":"y"}${T?"/ 4":""}]; - }`}return` - ${em("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 }; - ${Z.registerUniforms(X).declareVariables(...W,re)} - ${ae} - ${om(u,A,B,K,i,r,G[0],G[1],G[2],me)} - ${T?bl(S,g,me,void 0,!u,C):vl(S,g,me,void 0,!u,C,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${T};${A};${B};${K};${M};${v};${C}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:j}),getShaderSource:H}}}),am,Tl,wo,lm,El,um,dm,cm,Fv=Be(()=>{ut(),Es(),mt(),ft(),on(),gl(),am=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,wo=(e,r)=>r<=1?e:e+(e-1)*(r-1),lm=(e,r,t,s=1)=>{let o=wo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},El=(e,r,t,s,o)=>{o==null&&(o=lm(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},um=(e,r,t,s,o,n,i,a,l,u)=>{let p,d,c,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=El([r,t,s,1],[a,l,u],1,[o,n,i],e);d=_[0],c=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((T,k,w)=>T===w[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 _=El([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);d=_[0],c=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),c=Math.ceil(t/n),f=Math.ceil(s/i);let _=(d-1)*o+a-r,T=(c-1)*n+l-t,k=(f-1)*i+u-s,w=Math.floor(_/2),g=_-w,S=Math.floor(T/2),E=T-S,y=Math.floor(k/2),M=k-y;p={top:S,bottom:E,left:y,right:M,front:w,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:c,outWidth:f}},dm=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,d;if(i==="channelsLast")[a,l,u,p,d]=e;else if(i==="channelsFirst")[a,d,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,,f,_,T]=r,[k,w,g]=Tl(t),[S,E,y]=Tl(s),M=wo(f,S),v=wo(_,E),C=wo(T,y),{padInfo:A,outDepth:B,outHeight:K,outWidth:G}=um(o,l,u,p,k,w,g,M,v,C),j=n?c*d:c,ee=[0,0,0,0,0];return i==="channelsFirst"?ee=[a,j,B,K,G]:i==="channelsLast"&&(ee=[a,B,K,G,j]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:d,outDepth:B,outHeight:K,outWidth:G,outChannels:j,padInfo:A,strideDepth:k,strideHeight:w,strideWidth:g,filterDepth:f,filterHeight:_,filterWidth:T,effectiveFilterDepth:M,effectiveFilterHeight:v,effectiveFilterWidth:C,dilationDepth:S,dilationHeight:E,dilationWidth:y,inShape:e,outShape:ee,filterShape:r}},cm=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},u=[Math.ceil(am(l.x.map(k=>t[k]))/a[0]),1,1];vt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,d=Me.size(t),c=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];sn(r,c),c.push(...st(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(c.push(...st(e[2].dims)),f.push("rank")),c.push(...st(t));let T=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];nn(r,w);let g=1,S=lr(e[0].dataType),E=Pe("x",e[0].dataType,e[0].dims.length,p),y=Pe("W",e[1].dataType,e[1].dims.length,g),M=[E,y],v=Ye("result",e[0].dataType,t.length,g),C="";if(_){let K=Pe("bias",e[2].dataType,e[2].dims.length,g);M.push(K),C+=` - fn getBiasByOutputCoords(coords : array) -> ${S} { - return bias[${i?et("coords",4,5):et("coords",1,5)}]; - }`}let A=_r(p,S),B=rn(r,A,S);return` - ${C} - fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${E.getByIndices("aIndices")}; - } - fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${y.getByIndices("aIndices")}; - } - ${k.registerUniforms(w).declareVariables(...M,v)} - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let coords = ${v.offsetToIndices("global_idx")}; - let batch = ${et("coords",0,E.rank)}; - let d2 = ${i?et("coords",E.rank-1,E.rank):et("coords",1,E.rank)}; - let xFRCCorner = vec3(${i?et("coords",1,E.rank):et("coords",2,E.rank)}, - ${i?et("coords",2,E.rank):et("coords",3,E.rank)}, - ${i?et("coords",3,E.rank):et("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; - let xFCorner = xFRCCorner.x; - let xRCorner = xFRCCorner.y; - let xCCorner = xFRCCorner.z; - let xShapeY = ${i?et("uniforms.x_shape",1,E.rank):et("uniforms.x_shape",2,E.rank)}; - let xShapeZ = ${i?et("uniforms.x_shape",2,E.rank):et("uniforms.x_shape",3,E.rank)}; - let xShapeW = ${i?et("uniforms.x_shape",3,E.rank):et("uniforms.x_shape",4,E.rank)}; - let xShapeU = ${i?et("uniforms.x_shape",4,E.rank):et("uniforms.x_shape",1,E.rank)}; - let inputDepthNearestVec4 = (xShapeU / 4) * 4; - let inputDepthVec4Remainder = xShapeU % 4; - - var value = 0.0; - for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { - let xF = xFCorner + wF * uniforms.dilations[0]; - if (xF < 0 || xF >= xShapeY) { - continue; - } - - for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { - let xR = xRCorner + wR * uniforms.dilations[1]; - if (xR < 0 || xR >= xShapeZ) { - continue; - } - - for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { - let xC = xCCorner + wC * uniforms.dilations[2]; - if (xC < 0 || xC >= xShapeW) { - continue; - } - - for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { - ${i?`let xValues = vec4( - getX(batch, xF, xR, xC, d1), - getX(batch, xF, xR, xC, d1 + 1), - getX(batch, xF, xR, xC, d1 + 2), - getX(batch, xF, xR, xC, d1 + 3)); - `:`let xValues = vec4( - getX(batch, d1, xF, xR, xC), - getX(batch, d1 + 1, xF, xR, xC), - getX(batch, d1 + 2, xF, xR, xC), - getX(batch, d1 + 3, xF, xR, xC)); - `} - let wValues = vec4( - getW(d2, d1, wF, wR, wC), - getW(d2, d1 + 1, wF, wR, wC), - getW(d2, d1 + 2, wF, wR, wC), - getW(d2, d1 + 3, wF, wR, wC)); - value += dot(xValues, wValues); - } - if (inputDepthVec4Remainder == 1) { - ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} - } else if (inputDepthVec4Remainder == 2) { - ${i?`let xValues = vec2( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); - `:`let xValues = vec2( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); - `} - let wValues = vec2( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); - value += dot(xValues, wValues); - } else if (inputDepthVec4Remainder == 3) { - ${i?`let xValues = vec3( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); - `:`let xValues = vec3( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); - `} - let wValues = vec3( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); - value += dot(xValues, wValues); - } - } - } - } - ${_?"value = value + getBiasByOutputCoords(coords)":""}; - ${B} - result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:c}),getShaderSource:T}}}),pm,hm,Ov=Be(()=>{ut(),mt(),ft(),on(),pm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,d=l&&p>=4?Kt(u):1,c=Me.size(t)/d,f=[{type:12,data:c},{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}];sn(r,f),f.push(...st(i,[a[0],a[1],a[2],a[3]/d]));let _=o?["rank","rank","rank"]:["rank","rank"];f.push(...st([t[0],t[1],t[2],t[3]/d]));let T=k=>{let w=Ye("output",e[0].dataType,t.length,d),g=lr(w.type.tensor),S=rn(r,w.type.value,g),E=Pe("x",e[0].dataType,i.length),y=Pe("w",e[1].dataType,a.length,d),M=[E,y];o&&M.push(Pe("b",e[2].dataType,e[2].dims,d));let v=[{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"}];nn(r,v);let C=l?` - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { - continue; - } - - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; - let wVal = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; - value += xVal * wVal; - } - } - } - `:` - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { - continue; - } - - let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal * wVal; - } - } - } - `;return` - ${k.registerUniforms(v).declareVariables(...M,w)} - - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let outputIndices = ${w.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 * ${d} / uniforms.output_channels_per_group; - var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; - - var value: ${w.type.value} = ${w.type.value}(0); - ${C} - ${n} - ${S} - ${w.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:f}),getShaderSource:T}},hm=(e,r,t,s)=>{let o=e.length>2,n=Kt(t[3]),i=Kt(t[2]),a=Me.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],u=[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],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];sn(r,d),d.push(...st(l,u,p));let c=(i-1)*r.strides[1]+u[1],f=_=>{let T=Ye("output",e[0].dataType,p.length,n),k=lr(T.type.tensor),w=rn(r,T.type.value,k),g=Pe("x",e[0].dataType,l.length,n),S=Pe("w",e[1].dataType,u.length,n),E=[g,S];o&&E.push(Pe("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return nn(r,M),` - ${_.registerUniforms(M).declareVariables(...E,T)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let width0 = uniforms.output_shape[3]; - let output_channel = global_idx % width0; - var index1 = global_idx / width0; - let width1 = uniforms.output_shape[2] / ${i}u; - let col = (index1 % width1) * ${i}u; - index1 = index1 / width1; - let row = index1 % uniforms.output_shape[1]; - let batch = index1 / uniforms.output_shape[1]; - - let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; - - var x_vals: array<${g.type.value}, ${c}>; - var values: array<${T.type.value}, ${i}>; - let input_channel = output_channel; - // Use constant instead of uniform can give better performance for w's height/width. - for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) { - let x_height = x_corner.x + i32(w_height); - if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { - for (var i = 0; i < ${c}; i++) { - let x_width = x_corner.y + i; - if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { - x_vals[i] = ${g.get("batch","u32(x_height)","u32(x_width)","input_channel")}; - } else { - x_vals[i] = ${g.type.value}(0); - } - } - for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { - let w_val = ${S.get("w_height","w_width","0","output_channel")}; - for (var i = 0u; i < ${i}u; i++) { - values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); - } - } - } - } - - for (var i = 0u; i < ${i}u; i++) { - var value = values[i]; - ${y} - ${w} - ${T.set("batch","row","col + i","output_channel","value")}; - } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${c};${u[0]};${u[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),mm,mi,_m,_i,Pl,Cl,fm,gm,Sl,Dv=Be(()=>{mt(),Av(),Fv(),xl(),Ov(),on(),Ml(),zs(),mm=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((c,f)=>c+(c-1)*(t[f]-1)),d=a.map((c,f)=>c+s[f]+s[f+l]).map((c,f)=>Math.floor((c-p[f]+o[f])/o[f]));return d.splice(0,0,i),d.splice(n?3:1,0,u),d},mi=[2,3,1,0],_m=(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 o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},_i=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=fl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},Cl=(e,r,t,s)=>{let o=t.format==="NHWC",n=mm(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let M=[r[0]];if(o){let v=e.kernelCustomData.wT??e.compute(Lr(r[1],mi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v),M.push(v)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(hm(M,t,n,s),{inputs:M}):e.compute(pm(M,t,n,s),{inputs:M});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],c=n[o?1:2],f=n[o?2:3],_=n[o?3:1],T=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(T||p===1&&d===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],v,C,A,B=[];if(o){let j=e.kernelCustomData.wT??e.compute(Lr(r[1],mi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j),T){let ee=a*l*u;v=r[0].reshape([1,M,ee]),C=j.reshape([1,ee,_]),A=[1,M,_]}else v=r[0].reshape([M,a*l,u]),C=j.reshape([1,u,_]),A=[M,c*f,_];B.push(v),B.push(C)}else v=r[0].reshape([M,u,a*l]),C=r[1].reshape([1,_,u]),A=[M,_,c*f],B.push(C),B.push(v);i&&B.push(r[2]);let K=A[2],G=B[0].dims[B[0].dims.length-1];K<8&&G<8?e.compute(wl(B,t,n,A,o,s),{inputs:B}):e.compute(hi(B,t,n,A,o,s),{inputs:B});return}let k=!0,w=e.kernelCustomData.wT??e.compute(Lr(r[1],mi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let g=[r[0],w];i&&g.push(r[2]);let S=o?c*f:_,E=o?_:c*f,y=p*d*u;e.compute(im(g,t,n,S,E,y,i,k,s),{inputs:g})},fm=(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 o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=_i({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);Cl(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},gm=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=_i(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=dm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(cm(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Sl=(e,r)=>{if(_m(e.inputs,r),e.inputs[0].dims.length===3)fm(e,r);else if(e.inputs[0].dims.length===5)gm(e,e.inputs,r);else{let t=_i(r,e.inputs);Cl(e,e.inputs,t)}}}),wm,Lv=Be(()=>{ut(),Es(),mt(),ft(),wm=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,u=a[3],p=n?Kt(l):1,d=n&&u===1&&l>=4,c=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-c,_=n?Kt(u):1,T=n?u===1?p:_:1,k=Me.size(o)/_,w=[Math.ceil(k/64),1,1];vt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let g=["rank","rank"],S=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],M=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],v=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],C=[{type:12,data:k},{type:12,data:S},{type:12,data:E},{type:12,data:y},{type:12,data:M},{type:6,data:v},{type:12,data:c},{type:12,data:l},{type:12,data:u},...st(e[0].dims,e[1].dims)];s&&(C.push(...st(e[2].dims)),g.push("rank")),C.push(...st(o));let A=B=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:S.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:M.length},{name:"pads",type:"i32",length:v.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],G=lr(e[0].dataType),j=n?1:2,ee=n?2:3,H=n?3:1,Z=Pe("W",e[1].dataType,e[1].dims.length,T),X=Pe("Dy",e[0].dataType,e[0].dims.length,p),oe=[X,Z];s&&oe.push(Pe("bias",e[2].dataType,[o[H]].length,_));let me=Ye("result",e[0].dataType,o.length,_),ae=()=>{let W="";if(d)p===4?W+=` - let xValue = ${X.getByOffset("x_offset")}; - let wValue = ${Z.getByOffset("w_offset")}; - dotProd = dotProd + dot(xValue, wValue); - x_offset += 1u; - w_offset += 1u;`:p===2?W+=` - dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")})); - x_offset += 2u; - w_offset += 2u;`:p===1&&(W+=` - dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}, ${X.getByOffset("x_offset + 2u")}, ${X.getByOffset("x_offset + 3u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")}, ${Z.getByOffset("w_offset + 2u")}, ${Z.getByOffset("w_offset + 3u")})); - x_offset += 4u; - w_offset += 4u;`);else if(W+=` - let xValue = ${n?X.getByOffset(`${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):X.get("batch","inputChannel","idyR","idyC")}; - `,p===1)W+=` - let w_offset = ${Z.indicesToOffset(`${Z.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; - let wValue = ${Z.getByOffset(`w_offset / ${T}`)}; - dotProd = dotProd + xValue * wValue;`;else for(let re=0;re{if(f===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let W="";if(p===1){W+="dotProd = dotProd";for(let re=0;re(i32(r), i32(c)) - uniforms.pads; - let dyRCorner = dyCorner.x; - let dyCCorner = dyCorner.y; - let groupId = d1 / uniforms.output_channels_per_group; - let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; - // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). - // ? = to be determined. : = across all values in that axis. - var dotProd = ${me.type.value}(0.0); - var wR: u32 = 0; - if (uniforms.dilations.x == 1) { - // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 - wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); - } - for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { - if (wR % uniforms.dilations.x != 0) { - continue; - } - let dyR = (${G}(dyRCorner) + ${G}(wR)) / ${G}(uniforms.strides[0]); - let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; - if (dyR < 0.0 || dyR >= ${G}(uniforms.Dy_shape[${j}]) || fract(dyR) > 0.0 || - wRPerm < 0) { - continue; - } - let idyR: u32 = u32(dyR); - var wC: u32 = 0; - if (uniforms.dilations.y == 1) { - // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 - wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); - } - for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { - if (wC % uniforms.dilations.y != 0) { - continue; - } - let dyC = (${G}(dyCCorner) + ${G}(wC)) / ${G}(uniforms.strides.y); - let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; - if (dyC < 0.0 || dyC >= ${G}(uniforms.Dy_shape[${ee}]) || - fract(dyC) > 0.0 || wCPerm < 0) { - continue; - } - let idyC: u32 = u32(dyC); - var inputChannel = groupId * uniforms.input_channels_per_group; - ${d?` - var x_offset = ${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; - var w_offset = ${Z.indicesToOffset(`${Z.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${T}; - `:""} - for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { - ${ae()} - inputChannel = inputChannel + ${d?4:p}; - } - ${V()} - wC = wC + uniforms.strides.y - 1; - } - wR = wR + uniforms.strides[0] - 1; - } - let value = dotProd${s?` + bias[d1 / ${_}]`:""}; - ${me.setByOffset("global_idx","value")}; - `;return` - ${B.registerUniforms(K).declareVariables(...oe,me)} - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${T}${_}${d}${f}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:C}),getShaderSource:A}}}),Mm,bm,ym,$l,vm,xm,kl,Tm,Em,zv=Be(()=>{Lv(),on(),zs(),Mm=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,bm=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},ym=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,d=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,c)=>d*c,1)===0){t.length=0;for(let d=2;dd+c,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let u=e.strides.slice();if(u.reduce((d,c)=>d+c,0)===0){let d=r[0].dims.length-2;u=new Array(d).fill(1)}ym(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},vm=e=>{let r=fl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},xm=(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 o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+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((i,a)=>i+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")},kl=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(Lr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(wm(n,t,s),{inputs:n})},Tm=(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 o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let u=$l({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);kl(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Em=(e,r)=>{if(xm(e.inputs,r),e.inputs[0].dims.length===3)Tm(e,r);else{let t=$l(r,e.inputs);kl(e,e.inputs,t)}}}),Pm,Cm,Sm,Bv=Be(()=>{ut(),mt(),Xt(),ft(),Pm=(e,r,t,s)=>{let o=Me.size(r),n=r.length,i=Pe("input",e,n),a=Ye("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Me.normalizeAxis(l,n),p=d=>{let c=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=et("uniforms.input_shape","uniforms.axis",n),_=s.reverse?c+(s.exclusive?" + 1":""):"0",T=s.reverse?f:c+(s.exclusive?"":" + 1");return` - ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var inputIndices = ${a.offsetToIndices("global_idx")}; - var sum = ${a.type.value}(0); - let first : i32 = ${_}; - let last : i32 = ${T}; - for (var i : i32 = first; i < last; i++) { - ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; - sum = sum + ${i.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(o/64)},programUniforms:[{type:12,data:o},{type:12,data:u},...st(r,r)]}),getShaderSource:p}},Cm=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(Pm(s,t,o,r),{inputs:[0]})},Sm=e=>{let r=e.exclusive===1,t=e.reverse===1;return St({exclusive:r,reverse:t})}}),$m,km,Im,Am,Fm,Rv=Be(()=>{ut(),mt(),Xt(),ft(),$m=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.")},km=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { - var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),c=d.dims.length,f=e.dataType,_=Pe("a",f,c),T=Ye("output",f,c),k=w=>` - ${w.registerUniform("output_size","u32").declareVariables(_,T)} - - ${km(a,c,_,T)} - - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${T.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${T.setByOffset("global_idx",_.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let g=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],S=Me.size(g),E=d.dims,y=Me.sortBasedOnPerm(E,a);return{outputs:[{dims:g,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...st(E,y)]}},getShaderSource:k}},Am=(e,r)=>{$m(e.inputs),e.compute(Im(e.inputs[0],r))},Fm=e=>St({blocksize:e.blocksize,mode:e.mode,format:e.format})}),fi,Mo,Il,Om,Dm,Lm,zm,Al,Bm,Rm,jm,jv=Be(()=>{ut(),mt(),Xt(),ft(),fi="[a-zA-Z]|\\.\\.\\.",Mo="("+fi+")+",Il="^"+Mo+"$",Om="("+Mo+",)*"+Mo,Dm="^"+Om+"$",Lm=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)}},zm=class{constructor(e,r){var o;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(Dm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(Il)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(Mo)))throw new Error("Invalid RHS");(o=s.match(RegExp(fi,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.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 o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(Il))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(fi,"g")),u=new Lm(s);return l==null||l.forEach((p,d)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let c=o-l.length+1;if(c<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+c),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",Bm=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Pe(`input${p}`,r,u)),n=Me.size(s),i=Ye("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],d="var prod = 1.0;",c="var sum = 0.0;",f="sum += prod;",_=[],T=[],k=[],w=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,y)=>{var M;if(t.rhs.symbolToIndices.has(y)){let v=(M=t.rhs.symbolToIndices.get(y))==null?void 0:M[0];v!==void 0&&t.lhs.forEach((C,A)=>{if(E.inputIndices.includes(A)){let B=C.symbolToIndices.get(y);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(K=>{p.push(`${o[A].indicesSet(`input${A}Indices`,K,i.indicesGet("outputIndices",v))}`)})}})}else t.lhs.forEach((v,C)=>{if(E.inputIndices.includes(C)){let A=v.symbolToIndices.get(y);if(A===void 0)throw new Error("Invalid symbol error");A.forEach(B=>{_.push(`${o[C].indicesSet(`input${C}Indices`,B,`${y}`)}`)}),w.push(`prod *= ${o[C].getByIndices(`input${C}Indices`)};`)}}),T.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${Al(y)}; ${y}++) {`),k.push("}")});let S=g?[...p,`let sum = ${o.map((E,y)=>E.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,c,...T,..._,d,...w,f,...k];return` - ${u.registerUniforms(a.map(E=>({name:`${Al(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} - - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${i.offsetToIndices("global_idx")}; - ${o.map((E,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` -`)} - ${S.join(` -`)}; - ${i.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(d=>t.symbolToInfo.has(d)).map(d=>{var c;return{type:12,data:((c=t.symbolToInfo.get(d))==null?void 0:c.dimValue)||0}});u.push({type:12,data:n});let p=e.map((d,c)=>[...st(d)]).reduce((d,c)=>d.concat(c),u);return p.push(...st(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Rm=(e,r)=>{let t=new zm(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(Bm(o,e.inputs[0].dataType,t,s))},jm=e=>{let r=e.equation.replace(/\s+/g,"");return St({equation:r})}}),Nm,Fl,Vm,Um,Wm,Nv=Be(()=>{ut(),mt(),ft(),Nm=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 o=0;oe.length>r.length?Fl(e,r):Fl(r,e),Um=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Vm(r,t),o=e[0].dataType,n=o===9||Me.size(r)===1,i=o===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(Me.size(s)/a),u=d=>{let c=Pe("input",o,r.length,i),f=Ye("output",o,s.length,a),_;if(o===9){let T=(k,w,g="")=>` - let outputIndices${w} = ${f.offsetToIndices(`outputOffset + ${w}u`)}; - let offset${w} = ${c.broadcastedIndicesToOffset(`outputIndices${w}`,f)}; - let index${w} = offset${w} / 4u; - let component${w} = offset${w} % 4u; - ${k}[${w}] = ${g}(${c.getByOffset(`index${w}`)}[component${w}]); - `;_=` - let outputOffset = global_idx * ${a}; - var data = vec4(0); - ${T("data",0,"u32")} - ${T("data",1,"u32")} - ${T("data",2,"u32")} - ${T("data",3,"u32")} - ${f.setByOffset("global_idx","data")} - }`}else _=` - let outputIndices = ${f.offsetToIndices(`global_idx * ${a}`)}; - let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",f)}; - let data = ${f.type.value}(${c.getByOffset(`inputOffset / ${i}`)}); - ${f.setByOffset("global_idx","data")} - }`;return` - ${d.registerUniform("vec_size","u32").declareVariables(c,f)} - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${_}`},p=[{type:12,data:l},...st(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Wm=e=>{Nm(e.inputs),e.compute(Um(e.inputs),{inputs:[0]})}}),Gm,Km,Vv=Be(()=>{ut(),mt(),ft(),_l(),Gm=e=>{let r=e[0].dataType,t=Me.size(e[0].dims),s=Me.size(e[1].dims),o=s%4===0,n=i=>{let a=Pe("x",r,[1],4),l=Pe("bias",r,[1],4),u=Ye("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` - let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; - let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,c=o?` - let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} - let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,u)} - - ${hl(yr(r))} - - ${i.mainStart(Vn)} - ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} - - let x = ${a.getByOffset("global_idx")}; - ${c} - let x_in = x + bias; - ${u.setByOffset("global_idx",ml("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Vn/4)}})}},Km=e=>{e.inputs.length<2||Me.size(e.inputs[1].dims)===0?Ph(e):e.compute(Gm(e.inputs))}}),Hm,qm,Xm,Qm,Uv=Be(()=>{ut(),mt(),Xt(),ft(),Hm=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},qm=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(Me.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...st(e[0].dims,e[1].dims,i)],d=c=>{let f=Pe("data",e[0].dataType,e[0].dims.length,l),_=Pe("inputIndices",e[1].dataType,e[1].dims.length),T=Ye("output",e[0].dataType,i.length,l),k=g=>{let S=s.length,E=`var indicesIndices${g} = ${_.type.indices}(0);`;for(let y=0;y1?`indicesIndices${g}[${y}]`:`indicesIndices${g}`} = ${i.length>1?`outputIndices${g}[uniforms.axis + ${y}]`:`outputIndices${g}`};`;E+=` - var idx${g} = ${_.getByIndices(`indicesIndices${g}`)}; - if (idx${g} < 0) { - idx${g} = idx${g} + uniforms.axisDimLimit; - } - var dataIndices${g} : ${f.type.indices}; - `;for(let y=0,M=0;y1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = u32(idx${g});`,M+=S):(E+=`${o>1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = ${i.length>1?`outputIndices${g}[${M}]`:`outputIndices${g}`};`,M++);return E},w;if(e[0].dataType===9){let g=(S,E,y="")=>` - let outputIndices${E} = ${T.offsetToIndices(`outputOffset + ${E}u`)}; - ${k(E)}; - let offset${E} = ${f.indicesToOffset(`dataIndices${E}`)}; - let index${E} = offset${E} / 4u; - let component${E} = offset${E} % 4u; - ${S}[${E}] = ${y}(${f.getByOffset(`index${E}`)}[component${E}]); - `;w=` - let outputOffset = global_idx * ${l}; - var value = vec4(0); - ${g("value",0,"u32")} - ${g("value",1,"u32")} - ${g("value",2,"u32")} - ${g("value",3,"u32")} - ${T.setByOffset("global_idx","value")} - `}else w=` - let outputIndices = ${T.offsetToIndices("global_idx")}; - ${k("")}; - let value = ${f.getByIndices("dataIndices")}; - ${T.setByOffset("global_idx","value")}; - `;return` - ${c.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,T)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${w} - }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:d}},Xm=e=>St({axis:e.axis}),Qm=(e,r)=>{let t=e.inputs;Hm(t),e.compute(qm(e.inputs,r))}}),Jm,Ym,Zm,Wv=Be(()=>{ut(),mt(),ft(),Jm=(e,r,t,s,o,n,i,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...st(r.dims,p));let d=c=>{let f=Pe("indices_data",r.dataType,r.dims.length),_=Ye("input_slice_offsets_data",12,1,1),T=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.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` - ${c.registerUniforms(k).declareVariables(...T)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let batch_idx = global_idx / uniforms.num_slices_per_batch; - let base_offset = batch_idx * uniforms.input_batch_stride; - - let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; - var relative_slice_offset = 0; - for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { - var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); - let input_dim_idx = uniforms.batch_dims + dim_idx; - if (index < 0) { - ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} - } - ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} - } - - input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); - }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},Ym=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=Me.sizeToDimension(n,n.length-1),l=Me.sizeFromDimension(s,r.batchDims+i),u=Me.sizeToDimension(s,r.batchDims),p=Me.sizeFromDimension(s,r.batchDims),d=a/u,c=new Array(i),f=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=n.slice(0,-1).concat(s.slice(T)),w=Me.size(k),g=[{type:12,data:w},{type:12,data:l},...st(t[0].dims,_.dims,k)],S=E=>{let y=Pe("data",t[0].dataType,t[0].dims.length),M=Pe("slice_offsets",12,_.dims.length),v=Ye("output",t[0].dataType,k.length);return` - ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,M,v)} - ${E.mainStart()} - ${E.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:k,dataType:o}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:g}),getShaderSource:S},{inputs:[t[0],_]})},Zm=e=>({batchDims:e.batch_dims,cacheKey:""})}),e_,t_,r_,s_,Gv=Be(()=>{ut(),mt(),Xt(),ft(),e_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Me.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.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(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.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.")}},t_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.gatherAxis,o),i=Me.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=Me.size(a),u=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...st(...e.map((f,_)=>f.dims),a)],c=f=>{let _=Pe("data",e[0].dataType,e[0].dims.length),T=Pe("inputIndices",e[1].dataType,e[1].dims.length),k=Pe("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Pe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=Ye("output",u,a.length),S=[_,T,k];w&&S.push(w);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${f.registerUniforms(E).declareVariables(...S,g)} - ${f.mainStart()} - let output_indices = ${g.offsetToIndices("global_idx")}; - var indices_indices = ${T.type.indices}(0); - ${s.length>1?` - for (var i: u32 = 0; i < ${s.length}; i++) { - let index = ${g.indicesGet("output_indices","uniforms.gather_axis + i")}; - ${T.indicesSet("indices_indices","i","index")}; - }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; - var data_indices = ${_.type.indices}(0); - for (var i: u32 = 0; i < uniforms.gather_axis; i++) { - let index = ${g.indicesGet("output_indices","i")}; - ${_.indicesSet("data_indices","i","index")}; - } - var index_from_indices = ${T.getByIndices("indices_indices")}; - if (index_from_indices < 0) { - index_from_indices += ${t[n]}; - } - ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; - for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { - let index = ${g.indicesGet("output_indices",`i + ${s.length} - 1`)}; - ${_.indicesSet("data_indices","i","index")}; - } - let data_offset = ${_.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_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]; - var scale_indices = data_indices; - let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; - ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; - var scale = ${k.getByIndices("scale_indices")}; - ${w?` - let zero_point_indices = scale_indices; - let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; - let zero_point_index = zero_point_offset % 8; - let packed_4bit_zero_points = ${w.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 = ${yr(u)}(quantized_data - zero_point) * scale; - ${g.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:c}},r_=(e,r)=>{let t=e.inputs;e_(t,r),e.compute(t_(e.inputs,r))},s_=e=>St({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),n_,o_,i_,a_,Kv=Be(()=>{ut(),mt(),Xt(),ft(),n_=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.`)},o_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=Me.normalizeAxis(r.axis,o),l=t[a],u=n.slice(0),p=Me.size(u),d=Pe("input",s,o),c=Pe("indicesInput",i,n.length),f=Ye("output",s,u.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...st(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:T=>` - ${T.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,c,f)} - ${T.mainStart()} - ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let outputIndices = ${f.offsetToIndices("global_idx")}; - - var idx = ${c.getByOffset("global_idx")}; - if (idx < 0) { - idx = idx + uniforms.axisDimLimit; - } - var inputIndices = ${d.type.indices}(outputIndices); - ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; - let value = ${d.getByIndices("inputIndices")}; - - ${f.setByOffset("global_idx","value")}; - }`}},i_=e=>St({axis:e.axis}),a_=(e,r)=>{let t=e.inputs;n_(t),e.compute(o_(e.inputs,r))}}),l_,u_,d_,c_,Hv=Be(()=>{ut(),mt(),ft(),l_=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(),[o,n,i]=bc.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,c=Me.size(a),f=[{type:12,data:d?u:c},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...st(e[2].dims)),_.push("rank")),f.push(...st(a));let T=w=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",E=Pe("a",e[0].dataType,e[0].dims),y=Pe("b",e[1].dataType,e[1].dims),M=E.type.value,v=null,C=[E,y];e.length===3&&(v=Pe("c",e[2].dataType,e[2].dims.length),C.push(v));let A=Ye("output",e[0].dataType,a.length);C.push(A);let B=[{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` - ${w.registerUniforms(B).declareVariables(...C)} - - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${M}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${g} - } - - ${S} - ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${M}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} - output[global_idx] = value; - }`},k=w=>{let g=Pe("a",e[0].dataType,e[0].dims),S=Pe("b",e[1].dataType,e[1].dims),E=null,y=[g,S];e.length===3&&(E=Pe("c",e[2].dataType,e[2].dims.length),y.push(E));let M=Ye("output",e[0].dataType,a.length);y.push(M);let v=[{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"}],C="",A="";r.transA&&r.transB?(A=` - var col = tile_row_start + local_id.x; - var row = k_start + local_id.y; - if (col < uniforms.M && row < uniforms.K) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = k_start + local_id.x; - row = tile_col_start + local_id.y; - 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); - } - `,C="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(A=` - var col = tile_row_start + local_id.x; - var row = k_start + local_id.y; - if (col < uniforms.M && row < uniforms.K) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = tile_col_start + local_id.x; - row = k_start + local_id.y; - 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); - } - `,C="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(A=` - var col = k_start + local_id.x; - var row = tile_row_start + local_id.y; - if (col < uniforms.K && row < uniforms.M) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = k_start + local_id.x; - row = tile_col_start + local_id.y; - 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); - } - `,C="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(A=` - var col = k_start + local_id.x; - var row = tile_row_start + local_id.y; - if (col < uniforms.K && row < uniforms.M) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; - } else { - tile_a[local_id.y][local_id.x] = ${g.type.value}(0); - } - - col = tile_col_start + local_id.x; - row = k_start + local_id.y; - 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); - } - `,C="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let B=r.alpha===1?"":"value *= uniforms.alpha;";return` - ${w.registerUniforms(v).declareVariables(...y)} - var tile_a: array, ${l}>; - var tile_b: array, ${l}>; - ${w.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; - var k_start = 0u; - var value = ${M.type.value}(0); - for (var t: u32 = 0u; t < num_tiles; t++) { - ${A} - k_start = k_start + ${l}; - workgroupBarrier(); - - for (var k: u32 = 0u; k < ${l}; k++) { - ${C} - } - workgroupBarrier(); - } - - ${B} - let m = tile_row_start + local_id.y; - let n = tile_col_start + local_id.x; - ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",M)}; value += ${M.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} - if (m < uniforms.M && n < uniforms.N) { - output[m * uniforms.N + n] = value; - } - }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:f}),getShaderSource:T}},d_=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},c_=(e,r)=>{l_(e.inputs),e.compute(u_(e.inputs,r))}}),ws,Ps,an,ln,p_,h_,m_,__,f_,g_,w_,M_,b_,y_,qv=Be(()=>{ut(),mt(),Xt(),ft(),[ws,Ps,an,ln]=[0,1,2,3],p_=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")},h_=` - fn gs_get_cubic_coeffs(x: f32) -> vec4 { - let cubic_alpha = -0.75f; - let x_abs = abs(x); - var coeffs: vec4; - coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); - coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); - coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); - coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); - return coeffs; - } -`,m_=e=>` - fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { - var v: vec4; - var coeffs = gs_get_cubic_coeffs(x); - for (var i = 0; i < 4; i++) { - v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; - } - coeffs = gs_get_cubic_coeffs(y); - let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); - return pixel; - } -`,__=e=>` - fn gs_denormalize(n: f32, length: i32) -> f32 { - ${e.alignCorners===0?` - // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] - return ((n + 1.0) * f32(length) - 1.0) / 2.0; - `:` - // alignCorners: true => [-1, 1] to [0, length - 1] - return (n + 1.0) / 2.0 * (f32(length - 1)); - `} - } -`,f_=e=>` - ${e.paddingMode==="reflection"?` - fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { - var dx = 0.0; - var fx = f32(x); - let range = x_max - x_min; - if (fx < x_min) { - dx = x_min - fx; - let n = u32(dx / range); - let r = dx - f32(n) * range; - if (n % 2 == 0) { - fx = x_min + r; - } else { - fx = x_max - r; - } - } else if (fx > x_max) { - dx = fx - x_max; - let n = u32(dx / range); - let r = dx - f32(n) * range; - if (n % 2 == 0) { - fx = x_max - r; - } else { - fx = x_min + r; - } - } - return u32(fx); - }`:""} -`,g_=(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); - indices[${ws}] = batch; - indices[${Ps}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` - if (r >= 0 && r < H && c >=0 && c < W) { - indices[${an}] = u32(r); - indices[${ln}] = u32(c); - } else { - return ${r}(0); - } - `;case"border":return` - indices[${an}] = u32(clamp(r, 0, H - 1)); - indices[${ln}] = u32(clamp(c, 0, W - 1)); - `;case"reflection":return` - indices[${an}] = gs_reflect(r, border[1], border[3]); - indices[${ln}] = gs_reflect(c, border[0], border[2]); - `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` - return ${e.getByIndices("indices")}; - } -`,w_=(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[${ws}], indices[${Ps}], border); - `;case"bilinear":return` - let x1 = i32(floor(x)); - let y1 = i32(floor(y)); - let x2 = x1 + 1; - let y2 = y1 + 1; - - let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ws}], indices[${Ps}], border); - let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ws}], indices[${Ps}], border); - let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ws}], indices[${Ps}], border); - let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ws}], indices[${Ps}], border); - - let dx2 = ${r}(f32(x2) - x); - let dx1 = ${r}(x - f32(x1)); - let dy2 = ${r}(f32(y2) - y); - let dy1 = ${r}(y - f32(y1)); - let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); - `;case"bicubic":return` - let x0 = i32(floor(x)) - 1; - let y0 = i32(floor(y)) - 1; - var p: mat4x4<${r}>; - for (var h = 0; h < 4; h++) { - for (var w = 0; w < 4; w++) { - p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ws}], indices[${Ps}], border); - } - } - - 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")}`,M_=(e,r)=>{let t=Pe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Pe("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]],[ws,Ps,an,ln]=[0,3,1,2]);let i=Ye("output",e[0].dataType,n.length),a=t.type.value,l=Me.size(n),u=[{type:12,data:l},...st(e[0].dims,s,n)],p=d=>` - ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} - ${h_} - ${m_(a)} - ${__(r)} - ${f_(r)} - ${g_(t,a,r)} - - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let H_in = i32(uniforms.x_shape[${an}]); - let W_in = i32(uniforms.x_shape[${ln}]); - - ${r.alignCorners===0?` - let x_min = -0.5; - let x_max = f32(W_in) - 0.5; - let y_min = -0.5; - let y_max = f32(H_in) - 0.5; - `:` - let x_min = 0.0; - let x_max = f32(W_in) - 1.0; - let y_min = 0.0; - let y_max = f32(H_in) - 1.0; - `}; - let border = vec4(x_min, y_min, x_max, y_max); - - let indices = ${i.offsetToIndices("global_idx")}; - var grid_indices = vec3(indices[${ws}], indices[${an}], indices[${ln}]); - let nxy = ${o.getByIndices("grid_indices")}; - var x = gs_denormalize(f32(nxy[0]), W_in); - var y = gs_denormalize(f32(nxy[1]), H_in); - - ${w_(i,a,r)} - }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let c=Me.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u}},getShaderSource:p}},b_=(e,r)=>{p_(e.inputs),e.compute(M_(e.inputs,r))},y_=e=>St({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Cr,v_,x_,Ol,T_,bo,E_,P_=Be(()=>{ut(),mt(),Xt(),el(),cl(),ft(),zs(),Cr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,v_=(e,r)=>{let t=e[0],s=Cr(e,1),o=Cr(e,2),n=Cr(e,3),i=Cr(e,4),a=Cr(e,5),l=Cr(e,6),u=Cr(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],d=t.dims[1],c=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,T=0,k=Math.floor(c/r.numHeads);if(l&&u&&Me.size(l.dims)&&Me.size(u.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]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],T=l.dims[2]}else if(l&&Me.size(l.dims)||u&&Me.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&Me.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)');w=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,f=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');w=3}if(n&&Me.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 g=_+f,S=0;if(i&&Me.size(i.dims)>0){S=8;let v=i.dims;throw v.length===1?v[0]===p?S=1:v[0]===3*p+2&&(S=3):v.length===2&&v[0]===p&&v[1]===g&&(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 E=!1,y=c;if(o&&Me.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(f!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(f!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],E=!0}}let M=!1;if(i&&Me.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&Me.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]!==d||a.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:g,maxSequenceLength:T,inputHiddenSize:0,hiddenSize:c,vHiddenSize:y,headSize:k,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:M,passPastInKv:E,qkvFormat:w}},x_=e=>St({...e}),Ol=St({perm:[0,2,1,3]}),T_=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=Me.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let c=Ye("qkv_with_bias",r.dataType,a),f=Pe("qkv",r.dataType,a),_=Pe("bias",t.dataType,a),T=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${d.registerUniforms(T).declareVariables(f,_,c)} - ${d.mainStart()} - ${d.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:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},bo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&Me.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=T_(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(Lr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(Lr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]},E_=(e,r)=>{let t=v_(e.inputs,r),s=e.inputs[0],o=Cr(e.inputs,1),n=Cr(e.inputs,2),i=Cr(e.inputs,3),a=Cr(e.inputs,4),l=Cr(e.inputs,5),u=Cr(e.inputs,6),p=Cr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let d=o&&n&&o.dims.length===4&&n.dims.length===4,c=bo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return _o(e,c,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let f=bo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),_=bo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);_o(e,c,f,_,a,void 0,u,p,l,t)}}),C_,S_,$_,k_,Dl,I_,A_,F_=Be(()=>{ut(),mt(),Xt(),ft(),C_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},S_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),St({numOutputs:s,axis:r.axis,splitSizes:t})},$_=e=>` -fn calculateOutputIndex(index: u32) -> u32 { - for (var i: u32 = 0u; i < ${e}u; i += 1u ) { - if (index < ${et("uniforms.size_in_split_axis","i",e)}) { - return i; - } - } - return ${e}u; -}`,k_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Me.size(t),o=e[0].dataType,n=Me.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Pe("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],d=0,c=[{type:12,data:s}];for(let _=0;_` - ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} - ${$_(l.length)} - ${k_(i)} - - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} - - var indices = ${a.offsetToIndices("global_idx")}; - var index = ${a.indicesGet("indices",n)}; - let output_number = calculateOutputIndex(index); - if (output_number != 0) { - index -= ${et("uniforms.size_in_split_axis","output_number - 1u",l.length)}; - ${a.indicesSet("indices",n,"index")}; - } - writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c})}},I_=(e,r)=>{C_(e.inputs);let t=e.inputs.length===1?r:S_(e.inputs,r);e.compute(Dl(e.inputs,t),{inputs:[0]})},A_=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 St({axis:r,numOutputs:s,splitSizes:t})}}),O_,gi,D_,L_=Be(()=>{ut(),mt(),Xt(),ft(),O_=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,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(!Me.areEqual(s.dims,[])&&!Me.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(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Me.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],p=o.dims[0],d=Me.sizeFromDimension(t.dims,1)/u,c=a===0?o.dims[1]*2:d/i;if(a>c)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(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(c/2!==o.dims[1]&&a/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},gi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=Me.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],d=o===0?p*2:u/s,c=new Array(i,l,u/d,d-p),f=Me.computeStrides(c),_=[{type:1,data:n},{type:12,data:c},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,u,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...st(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],T=k=>{let w=Pe("input",e[0].dataType,e[0].dims.length),g=Pe("position_ids",e[1].dataType,e[1].dims.length),S=Pe("cos_cache",e[2].dataType,e[2].dims.length),E=Pe("sin_cache",e[3].dataType,e[3].dims.length),y=Ye("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:c.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` - ${k.declareVariables(w,g,S,E,y)} - - ${k.mainStart(Vn)} - let half_rotary_emb_dim = uniforms.${S.name}_shape[1]; - let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; - let size = uniforms.global_shape[0] * uniforms.global_strides[0]; - ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} - - if (bsnh[3] < half_rotary_emb_dim) { - let position_ids_idx = - ${g.broadcastedIndicesToOffset("bsnh.xy",Ye("",g.type.tensor,2))}; - let position_id = - u32(${g.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 = ${w.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - - ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; - ${y.setByOffset("i","re")} - let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + - ${w.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; - ${y.setByOffset("j","im")} - } else { - let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; - ${y.setByOffset("k",w.getByOffset("k"))} - } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:St({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:T,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(c)/Vn)},programUniforms:_})}},D_=(e,r)=>{O_(e.inputs,r),e.compute(gi(e.inputs,r))}}),z_,B_,Ll,R_,j_,Xv=Be(()=>{Xt(),ut(),cl(),P_(),F_(),zs(),L_(),ft(),z_=(e,r)=>{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],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");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],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=u,c=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let T=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(T&&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(T&&k){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');c=n.dims[2]}else if(T||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=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"');d=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');d=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');d=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');w=3}let g=0,S=!1,E=r.kvNumHeads?_*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],S=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.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:u,pastSequenceLength:c,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:_,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:w}},B_=St({perm:[0,2,1,3]}),Ll=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(Lr(s,B_.perm),{inputs:[s],outputs:[-1]})[0]),s},R_=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],u=p=>{let d=Pe("seq_lens",t.dataType,t.dims),c=Pe("total_seq_lens",s.dataType,s.dims),f=Ye("pos_ids",o,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` - ${p.registerUniforms(_).declareVariables(d,c,f)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let total_sequence_length = u32(${c.getByOffset("0")}); - let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; - let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; - let batch_idx = global_idx / uniforms.sequence_length; - let sequence_idx = i32(global_idx % uniforms.sequence_length); - var pos_id: i32 = 0; - let seqlen = ${d.getByOffset("batch_idx")}; - let total_seqlen = seqlen + 1; - if (is_first_prompt) { - if (sequence_idx < total_seqlen) { - pos_id = sequence_idx; - } else { - pos_id = 1; - } - ${f.setByOffset("global_idx","pos_id")} - } else if (is_subsequent_prompt) { - let past_seqlen = total_seqlen - i32(uniforms.sequence_length); - if (past_seqlen + sequence_idx < total_seqlen) { - pos_id = past_seqlen + sequence_idx; - } else { - pos_id = 1; - } - ${f.setByOffset("global_idx","pos_id")} - } else if (global_idx < uniforms.batch_size) { - ${f.setByOffset("global_idx","seqlen")} - }; - } - `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:u}},j_=(e,r)=>{var E;let t=z_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=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,i=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,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=St({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[c,f,_]=!o&&!n?e.compute(Dl([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],T,k;if(r.doRotary){let y=e.compute(R_(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],M=e.inputs[7],v=e.inputs[8],C=St({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),A=[c,y,M,v],B=[-1];T=e.compute(gi(A,C),{inputs:A,outputs:B})[0],A.splice(0,1,f);let K=St({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(gi(A,K),{inputs:A,outputs:B})[0]}let w=bo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?T:c,void 0,0),g=Ll(e,r.doRotary?k:f,t),S=Ll(e,_,t);_o(e,w,g,S,void 0,void 0,i,a,void 0,t,l,u)}}),zl,N_,V_,U_,Qv=Be(()=>{ut(),mt(),zs(),ft(),zl=(e,r,t,s,o,n,i,a)=>{let l=Kt(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*i,c=64;d===1&&(c=256);let f=[o,i,n/l],_=[o,i,2],T=["rank","type","type"],k=[];k.push(...st(f,_));let w=g=>{let S=Pe("x",r.dataType,3,l),E=Pe("scale",t.dataType,t.dims),y=Pe("bias",s.dataType,s.dims),M=Ye("output",1,3,2),v=[S,E,y,M];return` - var workgroup_shared : array<${p}, ${c}>; - const workgroup_size = ${c}u; - ${g.declareVariables(...v)} - ${g.mainStart(c)} - let batch = workgroup_index / uniforms.x_shape[1]; - let channel = workgroup_index % uniforms.x_shape[1]; - let hight = uniforms.x_shape[2]; - // initialize workgroup memory - var sum = ${u}(0); - var squared_sum = ${u}(0); - for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${u}(${S.get("batch","channel","h")}); - sum += value; - squared_sum += value * value; - } - workgroup_shared[local_idx] = ${p}(sum, squared_sum); - workgroupBarrier(); - - for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { - if (local_idx < currSize) { - workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; - } - workgroupBarrier(); - } - if (local_idx == 0) { - let sum_final = ${Ls("workgroup_shared[0][0]",l)} / f32(hight * ${l}); - let squared_sum_final = ${Ls("workgroup_shared[0][1]",l)} / f32(hight * ${l}); - - let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); - let channel_scale = inv_std_dev * f32(scale[channel]); - 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};${c}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},N_=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=Me.sizeFromDimension(s,n),u=Kt(l),p=Me.size(o)/u,d=zl(e,r[0],r[1],r[2],i,l,a,t.epsilon),c=[i,a,l/u],f=[i,a],_=["type","none"],T=k=>{let w=Pe("x",r[0].dataType,c.length,u),g=Pe("scale_shift",1,f.length,2),S=Ye("output",r[0].dataType,c.length,u),E=[w,g,S];return` - ${k.registerUniform("output_size","u32").declareVariables(...E)} - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${S.offsetToIndices("global_idx")}; - let batch = outputIndices[0]; - let channel = outputIndices[1]; - let scale_shift = ${g.getByIndices("vec2(batch, channel)")}; - let value = ${w.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:`${u}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...st(c,f,c)]}),getShaderSource:T},{inputs:[r[0],d]})},V_=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=Me.sizeFromDimension(s,1)/i,l=Kt(i),u=Me.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],c=!1,f=[0,s.length-1];for(let w=0;ws[f[g]])),T=zl(e,_,r[1],r[2],n,a,i,t.epsilon),k=w=>{let g=lr(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,E=v=>{let C=v===0?"x":"y",A=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${A}(scale.${C}))`;case 2:return`vec2<${g}>(${A}(scale[0].${C}, scale[1].${C}))`;case 4:return`vec4<${g}>(${A}(scale[0].${C}, scale[1].${C}, scale[2].${C}, scale[3].${C}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=Pe("input",r[0].dataType,r[0].dims,l),M=Ye("output",r[0].dataType,o,l);return` - @group(0) @binding(0) var input : array<${y.type.storage}>; - @group(0) @binding(1) var scale_input : array<${S}>; - @group(0) @binding(2) var output : array<${M.type.storage}>; - struct Uniforms {H: u32, C : u32}; - @group(0) @binding(3) var uniforms: Uniforms; - - ${w.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], ${E(0)}, ${E(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],T]})},U_=(e,r)=>{r.format==="NHWC"?V_(e,e.inputs,r):N_(e,e.inputs,r)}}),W_,G_,K_,Jv=Be(()=>{ut(),mt(),ft(),W_=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},G_=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=Me.normalizeAxis(r.axis,o.length),u=Me.sizeToDimension(o,l),p=Me.sizeFromDimension(o,l),d=Me.size(n.dims),c=i?Me.size(i.dims):0;if(d!==p||i&&c!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. - Size of scale and bias (if provided) must match this. - Got scale size of ${d} and bias size of ${c}`);let f=[];for(let y=0;y1,g=t>2,S=y=>{let M=lr(e[0].dataType),v=[Pe("x",e[0].dataType,e[0].dims,_),Pe("scale",n.dataType,n.dims,_)];i&&v.push(Pe("bias",i.dataType,i.dims,_)),v.push(Ye("output",e[0].dataType,a,_)),w&&v.push(Ye("mean_data_output",1,f)),g&&v.push(Ye("inv_std_output",1,f));let C=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${y.registerUniforms(C).declareVariables(...v)} - ${y.mainStart()} - ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${nl("f32",_)}; - var mean_square_vector = ${nl("f32",_)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${Un(M,_,"x[h + offset]")}; - mean_vector += value; - mean_square_vector += value * value; - } - let mean = ${Ls("mean_vector",_)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Ls("mean_square_vector",_)} / 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]")}; - output[j + offset] = ${v[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale - ${i?`+ ${Un(M,_,"bias[j]")}`:""} - ); - } - - ${w?"mean_data_output[global_idx] = mean":""}; - ${g?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:f,dataType:1}),g&&E.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:T},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:k}),getShaderSource:S}},K_=(e,r)=>{W_(e.inputs),e.compute(G_(e.inputs,r,e.outputCount))}}),H_,q_,Yv=Be(()=>{mt(),Ml(),xl(),H_=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.")},q_=e=>{H_(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(wl(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=Me.size(e.inputs[0].dims.slice(0,-2)),i=Me.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),u=[1,n,t],p=[a,l];e.compute(hi(p,{activation:""},r,u),{inputs:p})}else e.compute(hi(e.inputs,{activation:""},r))}}}),X_,Q_,J_,Y_,Z_,Zv=Be(()=>{ut(),mt(),Xt(),ft(),X_=(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 o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!Me.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(Me.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(Me.size(l)!==u)throw new Error("zeroPoints input size error.")}},Q_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,d=Kt(r.k),c=Kt(u),f=Kt(i),_=a.concat([o,i]),T=o>1&&i/f%2===0?2:1,k=Me.size(_)/f/T,w=64,g=[],S=[l,o,n/d],E=Me.convertShape(e[1].dims).slice();E.splice(-1,1,u/c),g.push(...st(S)),g.push(...st(E)),g.push(...st(e[2].dims)),e.length===4&&g.push(...st(Me.convertShape(e[3].dims)));let y=[l,o,i/f];g.push(...st(y));let M=v=>{let C=S.length,A=Pe("a",e[0].dataType,C,d),B=Pe("b",12,E.length,c),K=Pe("scales",e[2].dataType,e[2].dims.length),G=[A,B,K],j=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;j&&G.push(j);let ee=y.length,H=Ye("output",e[0].dataType,ee,f),Z=lr(e[0].dataType),X=(()=>{switch(d){case 1:return`array<${Z}, 8>`;case 2:return`mat4x2<${Z}>`;case 4:return`mat2x4<${Z}>`;default:throw new Error(`${d}-component is not supported.`)}})(),oe=()=>{let V=` - // reuse a data - var input_offset = ${A.indicesToOffset(`${A.type.indices}(batch, row, word_offset)`)}; - var a_data: ${X}; - for (var j: u32 = 0; j < ${8/d}; j++) { - a_data[j] = ${A.getByOffset("input_offset")}; - input_offset++; - } - `;for(let F=0;F> 4) & b_mask); - b_quantized_values = ${X}(${Array.from({length:4},(W,re)=>`${Z}(b_value_lower[${re}]), ${Z}(b_value_upper[${re}])`).join(", ")}); - b_dequantized_values = ${d===1?`${X}(${Array.from({length:8},(W,re)=>`(b_quantized_values[${re}] - ${j?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${X}(${Array(8).fill(`${j?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; - workgroup_shared[local_id.x * ${T} + ${Math.floor(F/f)}]${f>1?`[${F%f}]`:""} += ${Array.from({length:8/d},(W,re)=>`${d===1?`a_data[${re}] * b_dequantized_values[${re}]`:`dot(a_data[${re}], b_dequantized_values[${re}])`}`).join(" + ")}; - `;return V},me=()=>{let V=` - var col_index = col * ${f}; - ${j?` - let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; - var zero_point_byte_count: u32; - var zero_point_word_index: u32; - var zero_point_byte_offset: u32; - let zero_point_nibble_offset: u32 = block & 0x1u; - var zero_point_bits_offset: u32; - var zero_point_word: u32;`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${Z}(8);`} - `;for(let F=0;F> 0x1u); - zero_point_word_index = zero_point_byte_count >> 0x2u; - zero_point_byte_offset = zero_point_byte_count & 0x3u; - zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point${F} = ${Z}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${f};`;for(let F=0;F; - var b_value_upper: vec4; - var b_quantized_values: ${X}; - var b_dequantized_values: ${X};`,V};return` - var workgroup_shared: array<${H.type.value}, ${T*w}>; - ${v.declareVariables(...G,H)} - ${v.mainStart([w,1,1])} - let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${T}`)}; - 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 += ${w}) { - //process one block - var word_offset: u32 = block * ${r.blockSize/d}; - ${me()} - for (var word: u32 = 0; word < ${u}; word += ${c}) { - ${ae()} - for (var i: u32 = 0; i < ${c}; i++) { - ${oe()} - word_offset += ${8/d}; - } - } - } - workgroupBarrier(); - - if (local_id.x < ${T}) { - var output_value: ${H.type.value} = ${H.type.value}(0); - var workgroup_shared_offset: u32 = local_id.x; - for (var b: u32 = 0u; b < ${w}u; b++) { - output_value += workgroup_shared[workgroup_shared_offset]; - workgroup_shared_offset += ${T}; - } - ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; - } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${c};${f};${T};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:g}),getShaderSource:M}},J_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,d=Kt(r.k),c=Kt(u),f=a.concat([o,i]),_=128,T=i%8===0?8:i%4===0?4:1,k=_/T,w=k*c*8,g=w/d,S=w/r.blockSize,E=Me.size(f)/T,y=[],M=[l,o,n/d],v=Me.convertShape(e[1].dims).slice();v.splice(-1,1,u/c),y.push(...st(M)),y.push(...st(v)),y.push(...st(e[2].dims)),e.length===4&&y.push(...st(Me.convertShape(e[3].dims)));let C=[l,o,i];y.push(...st(C));let A=B=>{let K=M.length,G=Pe("a",e[0].dataType,K,d),j=Pe("b",12,v.length,c),ee=Pe("scales",e[2].dataType,e[2].dims.length),H=[G,j,ee],Z=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;Z&&H.push(Z);let X=C.length,oe=Ye("output",e[0].dataType,X),me=lr(e[0].dataType),ae=()=>{switch(d){case 1:return` - let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); - let a_data1 = vec4<${me}>(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<${me}>(sub_a[word_offset], sub_a[word_offset + 1]); - let a_data1 = vec4<${me}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` - let a_data0 = sub_a[word_offset]; - let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` - var sub_a: array<${G.type.value}, ${g}>; - var inter_results: array, ${T}>; - ${B.declareVariables(...H,oe)} - ${B.mainStart([k,T,1])} - let output_indices = ${oe.offsetToIndices(`workgroup_index * ${T}`)}; - 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; - - // Loop over shared dimension. - for (var tile: u32 = 0; tile < num_tiles; tile += 1) { - let a_col_start = tile * ${g}; - // load one tile A data into shared memory. - for (var a_offset = local_idx; a_offset < ${g}; a_offset += ${_}) - { - let a_col = a_col_start + a_offset; - if (a_col < uniforms.a_shape[2]) - { - sub_a[a_offset] = ${G.getByIndices(`${G.type.indices}(batch, row, a_col)`)}; - } else { - sub_a[a_offset] = ${G.type.value}(0); - } - } - workgroupBarrier(); - - // each thread process one block - let b_row = col + local_id.y; - let block = tile * ${S} + local_id.x; - ${Z?` - 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); - let zero_point_word_index = zero_point_byte_count >> 0x2u; - let zero_point_byte_offset = zero_point_byte_count & 0x3u; - let zero_point_nibble_offset: u32 = block & 0x1u; - let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - let zero_point_word = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point = ${me}((zero_point_word) & 0xFu);`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${me}(8);`} - let scale = ${ee.getByOffset("b_row * n_blocks_per_col + block")}; - let b_data = ${j.getByIndices(`${j.type.indices}(b_row, block, 0)`)}; - var word_offset = local_id.x * ${r.blockSize/d}; - for (var i: u32 = 0; i < ${c}; i++) { - ${ae()} - let b_value = ${c===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<${me}>(${Array.from({length:4},(V,F)=>`${me}(b_value_lower[${F}]), ${me}(b_value_upper[${F}])`).join(", ")}); - let b_dequantized_values = (b_quantized_values - mat2x4<${me}>(${Array(8).fill("zero_point").join(",")})) * scale; - inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; - word_offset += ${8/d}; - } - workgroupBarrier(); - } - - if (local_idx < ${T}) { - var output_value: ${oe.type.value} = ${oe.type.value}(0); - for (var b = 0u; b < ${k}; b++) { - output_value += inter_results[local_idx][b]; - } - if (col + local_idx < uniforms.output_shape[2]) - { - ${oe.setByIndices(`${oe.type.indices}(batch, row, col + local_idx)`,"output_value")} - } - } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${c};${k};${T}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:E},programUniforms:y}),getShaderSource:A}},Y_=(e,r)=>{X_(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(J_(e.inputs,r)):e.compute(Q_(e.inputs,r))},Z_=e=>St(e)}),ef,tf,rf,sf,nf,of,af,lf,uf,ex=Be(()=>{ut(),mt(),ft(),ef=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].")}},tf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; - if (k < 0) { - break; - } - if (k >= i32(${et("uniforms.x_shape",o,r)})) { - break; - } - offset += k * i32(${et("uniforms.x_strides",o,r)}); - `;return` - value = ${e.type.value}(uniforms.constant_value); - for (var i = 0; i < 1; i++) { - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - } - `},rf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${et("uniforms.x_shape",o,r)}) - 1); - k = k % _2n_1; - if(k >= i32(${et("uniforms.x_shape",o,r)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${et("uniforms.x_strides",o,r)}); - `;return` - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - `},sf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${et("uniforms.x_shape",o,r)})) { - k = i32(${et("uniforms.x_shape",o,r)}) - 1; - } - offset += k * i32(${et("uniforms.x_strides",o,r)}); - `;return` - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - `},nf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` - k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; - if (k < 0) { - k += i32(${et("uniforms.x_shape",o,r)}]); - } - if (k >= i32(${et("uniforms.x_shape",o,r)})) { - k -= i32(${et("uniforms.x_shape",o,r)}); - } - offset += k * i32(${et("uniforms.x_strides",o,r)}); - `;return` - var offset = 0; - var k = 0; - ${s} - value = x[offset]; - `},of=(e,r,t)=>{switch(t.mode){case 0:return tf(e,r,t.pads.length);case 1:return rf(e,r,t.pads.length);case 2:return sf(e,r,t.pads.length);case 3:return nf(e,r,t.pads.length);default:throw new Error("Invalid mode")}},af=(e,r)=>{let t=Me.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=Me.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...st(e[0].dims,t));let a=["rank"],l=u=>{let p=Ye("output",e[0].dataType,t.length),d=Pe("x",e[0].dataType,s.length),c=d.type.value,f=of(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:i?c:"f32"}),` - ${u.registerUniforms(_).declareVariables(d,p)} - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${p.offsetToIndices("global_idx")}; - - var value = ${c}(0); - ${f} - output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(t)/64)},programUniforms:n}),getShaderSource:l}},lf=(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,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},uf=(e,r)=>{ef(e.inputs);let t=lf(e.inputs,r);e.compute(af(e.inputs,t),{inputs:[0]})}}),yo,Bl,Rl,jl,Nl,df,cf,Vl,Ul,pf,hf,Wl,mf,_f,Gl,ff,gf,wf,Mf,tx=Be(()=>{ts(),ut(),mt(),ft(),yo=e=>{if(Bt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Bl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();oi.adjustPoolAttributes(t,o,i,a,l,u);let p=oi.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let c=p.slice();return c.push(c.splice(1,1)[0]),[d,s?c:p]},Rl=(e,r)=>{let t=r.format==="NHWC",s=Me.size(e),o=Me.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{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],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let c=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],T=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];c=!!(T+k),n.push({type:12,data:f},{type:12,data:_},{type:12,data:T},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,d,c]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=Me.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.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((u,p)=>u+p);return[n,i,!!l,!1,!1]}},jl=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c=o.format==="NHWC",f=r.type.value,_=Ye("output",r.type.tensor,s);if(o.kernelShape.length<=2){let T="",k="",w="",g=t-(c?2:1);if(p?T=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${g}] < 0 || xIndices[${g}] - >= uniforms.x_shape[${g}]) { - pad++; - continue; - } - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - }`:T=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - }`,o.kernelShape.length===2){let S=t-(c?3:2);d?k=` - 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}]) { - pad += i32(uniforms.kw); - continue; - } - `:k=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; - `,w=` - } - `}return` - ${e.registerUniforms(l).declareVariables(r,_)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let indices = ${_.offsetToIndices("global_idx")}; - var xIndices = ${_.offsetToIndices("global_idx")}; - - var value = ${f}(${a}); - var pad = 0; - ${k} - ${T} - ${w} - ${i} - - output[global_idx] = value; - }`}else{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let T=o.kernelShape.length,k=o.pads.length,w="";return u?w=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - }`:w=` - } - let x_val = x[${r.indicesToOffset("xIndices")}]; - ${n} - `,` - ${e.registerUniforms(l).declareVariables(r,_)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${_.offsetToIndices("global_idx")}; - var xIndices = ${_.offsetToIndices("global_idx")}; - - var offsets: array; - - var value = ${f}(${a}); - var pad = 0; - var isPad = false; - - for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { - var offset = i; - for (var j = 0u; j < ${T-1}u; j++) { - offsets[j] = offset / ${et("uniforms.kernelStrides","j",T)}; - offset -= offsets[j] * ${et("uniforms.kernelStrides","j",T)}; - } - offsets[${T-1}] = offset; - - isPad = false; - for (var j = ${t-T}u; j < ${t}u; j++) { - xIndices[j] = indices[j] * ${et("uniforms.strides",`j - ${t-T}u`,T)} - + offsets[j - ${t-T}u] - ${et("uniforms.pads","j - 2u",k)}; - ${w} - } - ${i} - - output[global_idx] = value; - }`}},Nl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,df=e=>`${Nl(e)};${e.countIncludePad}`,cf=e=>`${Nl(e)};${e.storageOrder};${e.dilations}`,Vl=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}),Ul=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=Pe("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,c,f,_]=Rl(n,o);p.push(...st(r.dims,n));let T=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${c};${f};${_}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:k=>jl(k,i,r.dims.length,n.length,o,l,u,0,d,c,f,_)}},pf=e=>{let r=e.count_include_pad!==0,t=Vl(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:df(s)}},hf=(e,r)=>{yo(e.inputs),e.compute(Ul("AveragePool",e.inputs[0],!1,r))},Wl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},mf=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},_f=(e,r)=>{yo(e.inputs),e.compute(Ul("GlobalAveragePool",e.inputs[0],!0,r))},Gl=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=` - value = max(x_val, value); - `,a="",l=Pe("x",r.dataType,r.dims.length),u=["rank"],[p,d,c,f,_]=Rl(n,o);return p.push(...st(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${c};${f};${_}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:T=>jl(T,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,c,f,_)}},ff=(e,r)=>{yo(e.inputs),e.compute(Gl("MaxPool",e.inputs[0],!1,r))},gf=e=>{let r=e.storage_order,t=e.dilations,s=Vl(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 o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:cf(o)}},wf=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},Mf=(e,r)=>{yo(e.inputs),e.compute(Gl("GlobalMaxPool",e.inputs[0],!0,r))}}),bf,yf,vf,xf,rx=Be(()=>{ut(),mt(),Xt(),ft(),bf=(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((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&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)].")}},yf=(e,r)=>{let t=Me.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=Me.size(n),l=s===3||s===2,u=l?[Math.ceil(Me.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,c=d?l?[Math.ceil(Me.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,T=Kt(a),k=f&&(!l||T===4),w=k?T:1,g=k&&!l?T:1,S=Pe("input",l?12:s,u.length,g),E=Pe("scale",i,p.length),y=d?Pe("zero_point",l?12:s,c.length):void 0,M=Ye("output",i,n.length,w),v=[S,E];y&&v.push(y);let C=[u,p];d&&C.push(c);let A=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...st(...C,n)],B=K=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${K.registerUniforms(G).declareVariables(...v,M)} - ${K.mainStart()} - ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${M.offsetToIndices("global_idx")}; - - // Set input x - ${l?` - let input = ${S.getByOffset("global_idx / 4")}; - let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; - let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; - - // Set scale input - ${f?`let scale_value= ${E.getByOffset("0")}`:_?` - let scale_index = ${M.indicesGet("output_indices","uniforms.axis")}; - let scale_value= ${E.getByOffset("scale_index")};`:` - var scale_indices: ${E.type.indices} = output_indices; - let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; - ${E.indicesSet("scale_indices","uniforms.axis","index")}; - let scale_value= ${E.getByIndices("scale_indices")};`}; - - // Set zero-point input - ${y?f?l?` - let zero_point_input = ${y.getByOffset("0")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:_?l?` - let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; - let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; - let zero_point_vec = ${o?"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 = ${y.getByOffset("zero_point_index")};`:l?` - let zero_point_offset = ${E.indicesToOffset("scale_indices")}; - let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":S.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:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:A})}},vf=(e,r)=>{bf(e.inputs,r),e.compute(yf(e.inputs,r))},xf=e=>St({axis:e.axis,blockSize:e.blockSize})}),Tf,Ef,Pf,sx=Be(()=>{ts(),ut(),ft(),Tf=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},Ef=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...st(n)],l=u=>{let p=Ye("output",s,n.length),d=p.type.value,c=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` - ${u.registerUniforms(c).declareVariables(p)} - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},Pf=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]),Bt.webgpu.validateInputContent&&Tf(r,t,s),e.compute(Ef(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Cf,Kl,Hl,Sf,$f,kf,nx=Be(()=>{ut(),mt(),Xt(),ft(),Cf=(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 o=`{ - var oldValue = 0; - loop { - let newValueF32 =`,n=`; - let newValue = bitcast(newValueF32); - let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); - if res.exchanged { - break; - } - oldValue = res.old_value; - } - }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` - ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` - ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Kl=(e,r)=>`${e===1?` - let element_count_dim = uniforms.output_strides; - let dim_value = uniforms.output_shape;`:` - let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; - let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} - - if (index >= 0) { - if (index >= i32(dim_value)) { - index = i32(dim_value - 1); - } - } else { - if (index < -i32(dim_value)) { - index = 0; - } else { - index += i32(dim_value); - } - } - data_offset += u32((u32(index) * element_count_dim));`,Hl=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { - let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; - ${Cf(e.reduction,"output[data_offset + i]","value",r)} - }`,Sf=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(Me.size(s)/n),a=s[s.length-1],l=Me.sizeFromDimension(t,a),u=Me.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...st(e[1].dims,e[2].dims,o)],d=c=>{let f=Pe("indices",e[1].dataType,e[1].dims.length),_=Pe("updates",e[2].dataType,e[2].dims.length,n),T=r.reduction!=="none"&&r.reduction!==""?Dc("output",e[0].dataType,o.length):Ye("output",e[0].dataType,o.length,n);return` - ${c.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,T)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var hasDuplicates = false; - if (${r.reduction==="none"}) { - for (var i = 0; i < ${u}; i = i + 1) { - for (var j = i + 1; j < ${u}; j = j + 1) { - var index_i = i32(indices[i].x); - var index_j = i32(indices[j].x); - if (index_i == index_j) { - hasDuplicates = true; - break; - } - } - if (hasDuplicates) { - break; - } - } - } - - if (${r.reduction==="none"} && hasDuplicates) { - if (global_idx != 0u) { - return; - } - // Process each index-update pair individually when duplicates exist - for (var idx = 0u; idx < ${u}u; idx++) { - var data_offset = 0u; - for (var i = 0u; i < uniforms.last_index_dimension; i++) { - var index = i32(indices[idx * uniforms.last_index_dimension + i].x); - ${Kl(t.length,!1)} - } - ${Hl(r,T.type.value,!1)} - } - return; - } - - var data_offset = 0u; - var indices_start = uniforms.last_index_dimension * global_idx; - var indices_end = indices_start + uniforms.last_index_dimension; - for (var i = indices_start; i < indices_end; i++) { - var index = i32(indices[i].x); - ${Kl(t.length,!0)} - } - ${Hl(r,T.type.value,!0)} - }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},$f=e=>St({reduction:e.reduction}),kf=(e,r)=>{e.compute(Sf(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),If,Af,Ff,ql,Of,Df,Lf,zf,Bf,Rf,jf,Nf,Xl,Vf,Uf,Wf,Gf,Kf,Hf,qf,ox=Be(()=>{ut(),mt(),Xt(),ft(),If=(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")}},Af=(e,r,t)=>{r.every(o=>o>=0&&o{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((o,n)=>s[o]=e[n]),s},Ff=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].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!==u&&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");If(s,r),r.axes.length>0&&Af(s,r.axes,u).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==u&&t>=18&&o.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(o.length!==0&&o.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 o<"u"&&s.length>0&&o.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},ql=(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(). - let big = (${e}) * (${r}); - let whole = ${s}(big / (${t})); - let fract = ${s}(big % (${t})) / ${s}(${t}); - return whole + fract; -`,Of=(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 { - ${ql("xResized","lengthOriginal","lengthResized",r)} - } - `;case"pytorch_half_pixel":return`if (lengthResized > 1) { - return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; - } else { - return 0.0; - }`;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 { - ${ql("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)) / - ${r}(lengthResized - 1); - } else { - return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); - }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); - 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`)}})()+"}",Df=(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`)}})()+"}",Lf=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},zf=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},Bf=(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 o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},Rf=(e,r,t,s,o)=>` - 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++) { - var output_index = ${e.indicesGet("output_indices","i")}; - var scale = ${et("uniforms.scales","i",s)}; - var roi_low = ${et("uniforms.roi","i",o)}; - var roi_hi = ${et("uniforms.roi",`i + ${r.length}`,o)}; - if (scale == 1.0) { - original_indices[i] = ${e.type.value}(output_index); - } else { - var input_shape_i = ${et("uniforms.input_shape","i",r.length)}; - var output_shape_i = ${et("uniforms.output_shape","i",t.length)}; - original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - } - } - return original_indices; - }`,jf=(e,r,t,s,o,n,i)=>` - 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++) { - var output_index = ${r.indicesGet("output_indices","i")}; - var input_index: u32; - var scale = ${et("uniforms.scales","i",o)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${et("uniforms.roi","i",n)}; - var roi_hi = ${et("uniforms.roi",`i + ${t.length}`,n)}; - var input_shape_i = ${et("uniforms.input_shape","i",t.length)}; - var output_shape_i = ${et("uniforms.output_shape","i",s.length)}; - var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { - if (original_idx < 0) { - input_index = 0; - } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { - input_index = input_shape_i - 1; - } else { - input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); - } - } else { - input_index = u32(original_idx); - } - } - ${e.indicesSet("input_indices","i","input_index")} - } - return input_indices; - }`,Nf=(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")}; - if (input_index < 0 || input_index >= ${et("uniforms.input_shape","i",r.length)}) { - return false; - } - } - return true; - }`,Xl=(e,r,t,s)=>e.rank>s?` - ${e.indicesSet("input_indices",r,"channel")}; - ${e.indicesSet("input_indices",t,"batch")}; -`:"",Vf=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; - ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; - ${Xl(e,l,n,2)} - return ${e.getByIndices("input_indices")}; - } - - fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var row:${u} = originalIndices[${i}]; - var col:${u} = originalIndices[${a}]; - ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { - return ${o}; - }`:""}; - row = max(0, min(row, ${t[i]} - 1)); - col = max(0, min(col, ${t[a]} - 1)); - var row1: u32 = u32(row); - var col1: u32 = u32(col); - var row2: u32 = u32(row + 1); - var col2: u32 = u32(col + 1); - var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; - var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; - var x11: ${u} = getInputValue(batch, channel, row1, col1); - var x12: ${u} = getInputValue(batch, channel, row1, col2); - var x21: ${u} = getInputValue(batch, channel, row2, col1); - var x22: ${u} = getInputValue(batch, channel, row2, col2); - var dx1: ${u} = abs(row - ${u}(row1)); - var dx2: ${u} = abs(${u}(row2) - row); - var dy1: ${u} = abs(col - ${u}(col1)); - var dy2: ${u} = abs(${u}(col2) - col); - if (row1 == row2) { - dx1 = 0.5; - dx2 = 0.5; - } - if (col1 == col2) { - dy1 = 0.5; - dy2 = 0.5; - } - return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); - }`},Uf=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[d,c]=p?[0,1]:[2,3],f=e.type.value,_=T=>{let k=T===d?"row":"col";return` - fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { - var output_index = ${r.indicesGet("output_indices",T)}; - var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[T]}, - ${s[T]}, ${t[T]}, ${n[T]}, ${n[T]} + ${t.length}); - var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${a} && (originalIdx < 0 || originalIdx > (${t[T]} - 1))) { - return ${l}; - } - var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); - for (var i: i32 = -1; i < 3; i++) { - var ${k}: ${f} = originalIdx + ${f}(i); - if (${k} < 0 || ${k} >= ${t[T]}) { - ${u?`coefs[i + 1] = 0.0; - continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[T]} - 1));`}; - } - var input_indices_copy: ${e.type.indices} = input_indices; - ${e.indicesSet("input_indices_copy",T,`u32(${k})`)}; - data[i + 1] = ${T===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${_(d)}; - ${_(c)}; - fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { - var absS = abs(s); - var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); - var oneMinusAbsS: ${f} = 1.0 - absS; - var twoMinusAbsS: ${f} = 2.0 - absS; - var onePlusAbsS: ${f} = 1.0 + absS; - coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; - coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; - coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; - coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; - return coeffs; - } - - fn cubicInterpolation1D(x: array<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { - var coefsSum: ${f} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; - return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; - } - - fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${f} { - var input_indices: ${e.type.indices} = output_indices; - return colCubicInterpolation(input_indices, output_indices); - } - `},Wf=(e,r,t,s,o)=>{let[n,i,a,l,u]=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",i,`max(0, min(depth, ${t[i]} - 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))`)}; - ${Xl(e,u,n,3)} - return ${e.getByIndices("input_indices")}; - } - - fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var depth:${p} = originalIndices[${i}]; - var height:${p} = originalIndices[${a}]; - var width:${p} = originalIndices[${l}]; - ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { - return ${o}; - }`:""}; - - depth = max(0, min(depth, ${t[i]} - 1)); - height = max(0, min(height, ${t[a]} - 1)); - width = max(0, min(width, ${t[l]} - 1)); - var depth1: u32 = u32(depth); - var height1: u32 = u32(height); - var width1: u32 = u32(width); - var depth2: u32 = u32(depth + 1); - var height2: u32 = u32(height + 1); - var width2: u32 = u32(width + 1); - var channel: u32 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; - var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; - - var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); - var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); - var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); - var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); - var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); - var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); - var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); - var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); - var dx1: ${p} = abs(depth - ${p}(depth1)); - var dx2: ${p} = abs(${p}(depth2) - depth); - var dy1: ${p} = abs(height - ${p}(height1)); - var dy2: ${p} = abs(${p}(height2) - height); - var dz1: ${p} = abs(width - ${p}(width1)); - var dz2: ${p} = abs(${p}(width2) - width); - if (depth1 == depth2) { - dx1 = 0.5; - dx2 = 0.5; - } - if (height1 == height2) { - dy1 = 0.5; - dy2 = 0.5; - } - if (width1 == width2) { - dz1 = 0.5; - dz2 = 0.5; - } - 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); - }`},Gf=(e,r,t,s,o,n)=>{let i=e.dims,a=Lf(n,r.axes,i.length),l=zf(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((g,S)=>g===0?1:l[S]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=Bf(i,u,r)));let p=Ye("output",e.dataType,l.length),d=Pe("input",e.dataType,i.length),c=Me.size(l),f=i.length===l.length&&i.every((g,S)=>g===l[S]),_=r.coordinateTransformMode==="tf_crop_and_resize",T=r.extrapolationValue,k=d.type.value,w=g=>` - ${f?"":` - ${Of(r.coordinateTransformMode,k)}; - ${(()=>{switch(r.mode){case"nearest":return` - ${Nf(d,i)}; - ${Df(r.nearestMode,t,k)}; - ${jf(d,p,i,l,u.length,a.length,_)}; - `;case"linear":return` - ${Rf(p,i,l,u.length,a.length)}; - ${(()=>{if(i.length===2||i.length===4)return`${Vf(d,p,i,_,T)}`;if(i.length===3||i.length===5)return`${Wf(d,p,i,_,T)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; - `;case"cubic":return` - ${(()=>{if(i.length===2||i.length===4)return`${Uf(d,p,i,l,u,a,r.cubicCoeffA,_,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")}})()}; - `} - ${g.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} - ${g.mainStart()} - ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${f?"output[global_idx] = input[global_idx];":` - let output_indices = ${p.offsetToIndices("global_idx")}; - var input_indices: ${d.type.indices}; - ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); - if (checkInputIndices(input_indices)) { - output[global_idx] = ${d.getByIndices("input_indices")}; - } else { - output[global_idx] = ${r.extrapolationValue}; - }`;case"linear":return`output[global_idx] = ${i.length===2||i.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}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:1,data:u},{type:1,data:a},...st(i,l)]})}},Kf=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Hf=(e,r)=>{let t=[],s=[],o=[],n=Kf(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ff(e.inputs,r,n,t,s,o),e.compute(Gf(e.inputs[0],r,n,t,s,o),{inputs:[0]})},qf=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return St({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),Xf,Qf,Jf,ix=Be(()=>{ut(),mt(),ft(),Xf=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 o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)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]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Qf=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=Me.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,c=e.length>4,f=s&&t>1,_=s&&t>2,T=t>3,k=64,w=Kt(u),g=[{type:12,data:l},{type:12,data:w},{type:12,data:u},{type:1,data:r.epsilon}],S=y=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],v=[Pe("x",e[0].dataType,e[0].dims,w),Pe("skip",e[1].dataType,e[1].dims,w),Pe("gamma",e[2].dataType,e[2].dims,w)];d&&v.push(Pe("beta",e[3].dataType,e[3].dims,w)),c&&v.push(Pe("bias",e[4].dataType,e[4].dims,w)),v.push(Ye("output",e[0].dataType,a,w)),f&&v.push(Ye("mean_output",1,p)),_&&v.push(Ye("inv_std_output",1,p)),T&&v.push(Ye("input_skip_bias_sum",e[0].dataType,a,w));let C=lr(e[0].dataType),A=lr(1,w);return` - - ${y.registerUniforms(M).declareVariables(...v)} - var sum_shared : array<${A}, ${k}>; - var sum_squared_shared : array<${A}, ${k}>; - - ${y.mainStart([k,1,1])} - let ix = local_id.x; - let iy = global_id.x / ${k}; - - let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; - var stride = hidden_size_vectorized / ${k}; - let offset = ix * stride + iy * hidden_size_vectorized; - let offset1d = stride * ix; - if (ix == ${k-1}) { - stride = hidden_size_vectorized - stride * ix; - } - for (var i: u32 = 0; i < stride; i++) { - let skip_value = skip[offset + i]; - let bias_value = ${c?"bias[offset1d + i]":C+"(0.0)"}; - let input_value = x[offset + i]; - let value = input_value + skip_value + bias_value; - ${T?"input_skip_bias_sum[offset + i] = value;":""} - output[offset + i] = value; - let f32_value = ${Un(C,w,"value")}; - sum_shared[ix] += f32_value; - sum_squared_shared[ix] += f32_value * f32_value; - } - workgroupBarrier(); - - var reduce_size : u32 = ${k}; - for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { - reduce_size = curr_size + (reduce_size & 1); - if (ix < curr_size) { - sum_shared[ix] += sum_shared[ix + reduce_size]; - sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; - } - workgroupBarrier(); - } - - let sum = sum_shared[0]; - let square_sum = sum_squared_shared[0]; - let mean = ${Ls("sum",w)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Ls("square_sum",w)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); - ${f?"mean_output[global_idx] = mean;":""} - ${_?"inv_std_output[global_idx] = inv_std_dev;":""} - - for (var i: u32 = 0; i < stride; i++) { - output[offset + i] = (output[offset + i] ${o?"":`- ${C}(mean)`}) * - ${C}(inv_std_dev) * gamma[offset1d + i] - ${d?"+ beta[offset1d + i]":""}; - } - }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${T}`,inputDependencies:e.map((y,M)=>"type")},getShaderSource:S,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:g})}},Jf=(e,r)=>{Xf(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(Qf(e.inputs,r,e.outputCount,!1),{outputs:t})}}),Yf,vo,Zf,Ql,eg,tg,rg,sg,ax=Be(()=>{ut(),mt(),Xt(),ft(),Yf=(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`)})},vo=(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},Zf=(e,r)=>{if(e.length>1){let t=vo(e,1),s=vo(e,2),o=vo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),St({starts:t,ends:s,axes:o})}else return r},Ql=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},eg=(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--) { - let input_shape_i = ${et("uniforms.input_shape","i",t.length)}; - let steps_i = ${et("uniforms.steps","i",t.length)}; - let signs_i = ${et("uniforms.signs","i",t.length)}; - let starts_i = ${et("uniforms.starts","i",t.length)}; - var output_index = ${r.indicesGet("output_indices","i")}; - var input_index = output_index * steps_i + starts_i + carry; - carry = input_index / input_shape_i; - input_index = input_index % input_shape_i; - if (signs_i < 0) { - input_index = input_shape_i - input_index - 1u + starts_i; - } - ${e.indicesSet("input_indices","i","input_index")}; - } - return input_indices; - }`,tg=(e,r)=>{let t=e[0].dims,s=Me.size(t),o=r.axes.length>0?Me.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=vo(e,4);n.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((w,g)=>Ql(w,g,t,o,n)),a=r.ends.map((w,g)=>Ql(w,g,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let w=0;wMath.sign(w));n.forEach((w,g,S)=>{if(w<0){let E=(a[g]-i[g])/w,y=i[g],M=y+E*n[g];i[g]=M,a[g]=y,S[g]=-w}});let u=t.slice(0);o.forEach((w,g)=>{u[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:u,dataType:e[0].dataType},d=Ye("output",e[0].dataType,u.length),c=Pe("input",e[0].dataType,e[0].dims.length),f=Me.size(u),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],T=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:n},...st(e[0].dims,u)],k=w=>` - ${w.registerUniforms(_).declareVariables(c,d)} - ${eg(c,d,t)} - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let output_indices = ${d.offsetToIndices("global_idx")}; - let input_indices = calculateInputIndices(output_indices); - ${d.setByOffset("global_idx",c.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:T})}},rg=(e,r)=>{Yf(e.inputs,r);let t=Zf(e.inputs,r);e.compute(tg(e.inputs,t),{inputs:[0]})},sg=e=>{let r=e.starts,t=e.ends,s=e.axes;return St({starts:r,ends:t,axes:s})}}),ng,og,ig,ag,lx=Be(()=>{ut(),mt(),Xt(),zs(),ft(),ng=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},og=(e,r)=>{let t=e.inputs[0],s=t.dims,o=Me.size(s),n=s.length,i=Me.normalizeAxis(r.axis,n),a=iC),u[i]=n-1,u[n-1]=i,l=e.compute(Lr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],c=o/d,f=Kt(d),_=d/f,T=64;c===1&&(T=256);let k=(v,C)=>C===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:C===2?`max(${v}.x, ${v}.y)`:C===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,w=Pe("x",l.dataType,l.dims,f),g=Ye("result",l.dataType,l.dims,f),S=w.type.value,E=lr(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,y=v=>` - var rowMaxShared : ${S}; - var rowSumShared : ${S}; - var threadShared : array<${S}, ${T}>; - - fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} { - let index = row * row_stride + col; - return x[index]; - } - - fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) { - let index = row * row_stride + col; - result[index] = value; - } - ${v.registerUniform("packedCols","i32").declareVariables(w,g)} - ${v.mainStart(T)} - let gindex = i32(global_idx); - let lindex = i32(local_idx); - const wg = ${T}; - let row = gindex / wg; - let cols = uniforms.packedCols; - let row_stride : i32 = uniforms.packedCols; - - // find the rows max - ${E} - for (var col = lindex; col < cols; col += wg) { - let value = getValue(row, col, row_stride); - threadMax = max(threadMax, value); - } - if (lindex < cols) { - threadShared[lindex] = threadMax; - } - workgroupBarrier(); - - var reduceSize = min(cols, wg); - for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { - reduceSize = currSize + (reduceSize & 1); - if (lindex < currSize) { - threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); - } - workgroupBarrier(); - } - if (lindex == 0) { - rowMaxShared = ${S}(${k("threadShared[0]",f)}); - } - workgroupBarrier(); - - // find the rows sum - var threadSum = ${S}(0.0); - for (var col = lindex; col < cols; col += wg) { - let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); - threadSum += subExp; - } - threadShared[lindex] = threadSum; - workgroupBarrier(); - - for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { - if (lindex < currSize) { - threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; - } - workgroupBarrier(); - } - if (lindex == 0) { - rowSumShared = ${S}(${Ls("threadShared[0]",f)}); - } - workgroupBarrier(); - - // calculate final value for each element in the row - for (var col = lindex; col < cols; col += wg) { - let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; - setValue(row, col, row_stride, value); - } - }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${f};${T}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:_}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Lr(M,u),{inputs:[M]})},ig=(e,r)=>{ng(e.inputs),og(e,r)},ag=e=>St({axis:e.axis})}),Jl,lg,ug,dg,cg,ux=Be(()=>{ut(),mt(),ft(),Jl=e=>Array.from(e.getBigInt64Array(),Number),lg=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(Jl(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")},ug=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Jl(e[1]),o=ug(t,s),n=Me.size(o),i=e[0].dataType,a=Pe("input",i,t.length),l=Ye("output",i,o.length),u=p=>` - const inputShape = ${a.indices(...t)}; - ${p.registerUniform("output_size","u32").declareVariables(a,l)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${l.offsetToIndices("global_idx")}; - var input_indices: ${a.type.indices}; - for (var i = 0; i < ${t.length}; i++) { - let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; - let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; - - ${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:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...st(e[0].dims,o)]}),getShaderSource:u}},cg=e=>{lg(e.inputs),e.compute(dg(e.inputs),{inputs:[0]})}}),pg,hg,mg,dx=Be(()=>{ut(),mt(),ft(),pg=(e,r,t,s,o)=>{let n=Ye("output_data",o,t.length,4),i=Pe("a_data",r[1].dataType,r[1].dims.length,4),a=Pe("b_data",r[2].dataType,r[2].dims.length,4),l=Pe("c_data",r[0].dataType,r[0].dims.length,4),u,p=(d,c,f)=>`select(${c}, ${d}, ${f})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(c,f,_="")=>{let T=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,w=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` - let output_indices${f} = ${n.offsetToIndices(`global_idx * 4u + ${f}u`)}; - let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,n)}; - let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,n)}; - let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,n)}; - let index_a${f} = offset_a${f} / 4u; - let index_b${f} = offset_b${f} / 4u; - let index_c${f} = offset_c${f} / 4u; - let component_a${f} = offset_a${f} % 4u; - let component_b${f} = offset_b${f} % 4u; - let component_c${f} = offset_c${f} % 4u; - ${c}[${f}] = ${_}(${p(T,k,w)}); - `};o===9?u=` - var data = vec4(0); - ${d("data",0,"u32")} - ${d("data",1,"u32")} - ${d("data",2,"u32")} - ${d("data",3,"u32")} - output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` - ${d("output_data[global_idx]",0)} - ${d("output_data[global_idx]",1)} - ${d("output_data[global_idx]",2)} - ${d("output_data[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${u} - }`},hg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(Me.areEqual(r,t)&&Me.areEqual(t,s)),i=r,a=Me.size(r);if(n){let u=Nn.calcShape(Nn.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=Me.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>pg(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...st(s,r,t,i)]})}},mg=e=>{e.compute(hg(e.inputs))}}),_g,cx=Be(()=>{Ev(),cl(),Pv(),Cv(),Sv(),$v(),kv(),Dv(),zv(),Bv(),Rv(),jv(),Nv(),Vv(),Uv(),Wv(),Gv(),Kv(),Hv(),qv(),Xv(),Qv(),Jv(),Yv(),Zv(),P_(),ex(),tx(),rx(),sx(),nx(),ll(),ox(),L_(),ix(),ax(),lx(),F_(),ux(),zs(),_l(),dx(),_g=new Map([["Abs",[qp]],["Acos",[Xp]],["Acosh",[Qp]],["Add",[zh]],["ArgMax",[Fp,dl]],["ArgMin",[Ap,dl]],["Asin",[Jp]],["Asinh",[Yp]],["Atan",[Zp]],["Atanh",[eh]],["Attention",[Rp]],["AveragePool",[hf,pf]],["BatchNormalization",[Up]],["BiasAdd",[Kp]],["BiasSplitGelu",[Oh]],["Cast",[rh,th]],["Ceil",[oh]],["Clip",[nh]],["Concat",[Jh,Yh]],["Conv",[Sl,Pl]],["ConvTranspose",[Em,vm]],["Cos",[ih]],["Cosh",[ah]],["CumSum",[Cm,Sm]],["DepthToSpace",[Am,Fm]],["DequantizeLinear",[vf,xf]],["Div",[Bh]],["Einsum",[Rm,jm]],["Elu",[lh,fo]],["Equal",[Rh]],["Erf",[uh]],["Exp",[dh]],["Expand",[Wm]],["FastGelu",[Km]],["Floor",[ch]],["FusedConv",[Sl,Pl]],["Gather",[Qm,Xm]],["GatherElements",[a_,i_]],["GatherBlockQuantized",[r_,s_]],["GatherND",[Ym,Zm]],["Gelu",[ph]],["Gemm",[c_,d_]],["GlobalAveragePool",[_f,mf]],["GlobalMaxPool",[Mf,wf]],["Greater",[Uh]],["GreaterOrEqual",[Gh]],["GridSample",[b_,y_]],["GroupQueryAttention",[j_]],["HardSigmoid",[bh,Mh]],["InstanceNormalization",[U_]],["LayerNormalization",[K_]],["LeakyRelu",[hh,fo]],["Less",[Wh]],["LessOrEqual",[Kh]],["Log",[Sh]],["MatMul",[q_]],["MatMulNBits",[Y_,Z_]],["MaxPool",[ff,gf]],["Mul",[jh]],["MultiHeadAttention",[E_,x_]],["Neg",[_h]],["Not",[mh]],["Pad",[uf]],["Pow",[Nh]],["QuickGelu",[Ih,fo]],["Range",[Pf]],["Reciprocal",[fh]],["ReduceMin",[Cp]],["ReduceMean",[vp]],["ReduceMax",[Pp]],["ReduceSum",[$p]],["ReduceProd",[Sp]],["ReduceL1",[xp]],["ReduceL2",[Tp]],["ReduceLogSum",[Ip]],["ReduceLogSumExp",[Ep]],["ReduceSumSquare",[kp]],["Relu",[gh]],["Resize",[Hf,qf]],["RotaryEmbedding",[D_]],["ScatterND",[kf,$f]],["Sigmoid",[wh]],["Sin",[yh]],["Sinh",[vh]],["Slice",[rg,sg]],["SkipLayerNormalization",[Jf]],["Split",[I_,A_]],["Sqrt",[xh]],["Softmax",[ig,ag]],["Sub",[Vh]],["Tan",[Th]],["Tanh",[Eh]],["ThresholdedRelu",[Ch,fo]],["Tile",[cg]],["Transpose",[Uc,Wc]],["Where",[mg]]])}),fg,px=Be(()=>{ts(),Es(),ft(),fg=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,o){es(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.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(),Gr(e.programInfo.name)}dispose(){}build(e,r){es(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=zc(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` -`)} -${o.additionalImplementations} -${n}`,a=t.createShaderModule({code:i,label:e.name});vt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Gr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.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,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),gg={};Rn(gg,{WebGpuBackend:()=>yg});var wg,Mg,bg,yg,hx=Be(()=>{ts(),ut(),Es(),xc(),xv(),cx(),px(),wg=(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 o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${wg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},bg=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},yg=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},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new bg(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Fc(this),this.programManager=new fg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ka(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;es(),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 o=0;o"u"&&(this.queryTimeBase=f);let T=Number(f-this.queryTimeBase),k=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(T)||!Number.isSafeInteger(k))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(w=>({dims:w.dims,dataType:Ts(w.dataType)})),outputsMetadata:c.map(w=>({dims:w.dims,dataType:Ts(w.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:T,endTime:k});else{let w="";d.forEach((S,E)=>{w+=`input[${E}]: [${S.dims}] | ${Ts(S.dataType)}, `});let g="";c.forEach((S,E)=>{g+=`output[${E}]: [${S.dims}] | ${Ts(S.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${w}${g}execution time: ${k-T} ns`)}co("GPU",`${p}::${f}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),Gr()}run(e,r,t,s,o,n){es(e.name);let i=[];for(let g=0;gS):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],c=[];for(let g=0;g=n)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let S=p[g]===-1,E=p[g]===-2,y=S||E?o(a[g].dataType,a[g].dims):s(p[g],a[g].dataType,a[g].dims);if(d.push(y),y.data===0)continue;let M=this.gpuDataManager.get(y.data);if(!M)throw new Error(`no GPU data for output: ${y.data}`);if(S&&this.temporaryData.push(M),E){let v=this.kernelPersistentData.get(this.currentKernelId);v||(v=[],this.kernelPersistentData.set(this.currentKernelId,v)),v.push(M)}c.push(M)}if(i.length!==r.length||c.length!==d.length){if(c.length===0)return Gr(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(u){let g=0,S=[];u.forEach(v=>{let C=typeof v.data=="number"?[v.data]:v.data;if(C.length===0)return;let A=v.type===10?2:4,B,K;v.type===10?(K=C.length>4?16:C.length>2?8:C.length*A,B=C.length>4?16:A*C.length):(K=C.length<=2?C.length*A:16,B=16),g=Math.ceil(g/K)*K,S.push(g);let G=v.type===10?8:4;g+=C.length>4?Math.ceil(C.length/G)*B:C.length*A});let E=16;g=Math.ceil(g/E)*E;let y=new ArrayBuffer(g);u.forEach((v,C)=>{let A=S[C],B=typeof v.data=="number"?[v.data]:v.data;if(v.type===6)new Int32Array(y,A,B.length).set(B);else if(v.type===12)new Uint32Array(y,A,B.length).set(B);else if(v.type===10)new Uint16Array(y,A,B.length).set(B);else if(v.type===1)new Float32Array(y,A,B.length).set(B);else throw new Error(`Unsupported uniform type: ${Ts(v.type)}`)});let M=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,y,0,g),this.gpuDataManager.release(M.id),f={offset:0,size:g,buffer:M.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),T=_[1]===1&&_[2]===1,k=Mg(e,r,T),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(k,w),vt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),u&&w.uniformVariablesInfo){if(u.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${u.length} in program "${w.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(w,i,c,_,f),Gr(e.name),d}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 o=_g.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[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 o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),vt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}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 sl(this,e,r);return Ha(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(){vt("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(){vt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){vt("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()}}}),vg={};Rn(vg,{init:()=>Tg});var wi,xg,Tg,mx=Be(()=>{ut(),Es(),mt(),vv(),wi=class z0{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Me.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=Me.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=Me.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=Me.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Me.size(r)!==Me.size(this.dims))throw new Error("Invalid new shape");return new z0(this.module,this.dataType,this.data,r)}},xg=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,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,u)=>new wi(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=tn(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new wi(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(hx(),ao(gg)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)vt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{vt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),d)}},async(a,l,u)=>{vt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{vt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let d=new xg(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new $c(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Eg,Yl,Zl,Bs,Pg,eu,Mi,tu,ru,su,nu,ou,iu,Cg=Be(()=>{Mv(),bv(),ut(),en(),ja(),hc(),Eg=(e,r)=>{zt()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},Yl=async e=>{Eg(e.wasm.numThreads,ni(e.logLevel))},Zl=async(e,r)=>{var t,s;(s=(t=zt()).asyncInit)==null||s.call(t);{let o=(mx(),ao(vg)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.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 a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",zt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",zt(),e)}}},Bs=new Map,Pg=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&At("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},eu=(e,r)=>{let t=zt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&At("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let u=t.HEAPU32[o/4+1],p=[];for(let d=0;d{let r=zt(),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]},tu=async(e,r)=>{var d,c,f,_;let t,s,o=zt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=Mi(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await pc(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let C=[];for(let A of r.externalData){let B=typeof A=="string"?A:A.path;C.push(Ga(typeof A=="string"?A:A.data).then(K=>{o.mountExternalData(B,K)}))}await Promise.all(C)}for(let C of(r==null?void 0:r.executionProviders)??[])if((typeof C=="string"?C:C.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof C!="string"){let A=C,B=A==null?void 0:A.context,K=A==null?void 0:A.gpuDevice,G=A==null?void 0:A.deviceType,j=A==null?void 0:A.powerPreference;B?o.currentContext=B:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:G,powerPreference:j})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&At("Can't create a session."),(c=o.jsepOnCreateSession)==null||c.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[T,k]=Pg(n),w=!!(r!=null&&r.enableGraphCapture),g=[],S=[],E=[],y=[],M=[];for(let C=0;CC==="gpu-buffer"||C==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),v={handle:a,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(C=>Wa(C))}),Bs.set(n,[n,u,p,v,w,!1]),[n,g,S,E,y]}catch(T){throw u.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&At("Can't release session."),T}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&At("Can't release session options."),l.forEach(T=>o._free(T)),(_=o.unmountExternalData)==null||_.call(o)}},ru=e=>{var l,u,p;let r=zt(),t=Bs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&At("Can't release session."),Bs.delete(e)},su=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=zt(),l=a.PTR_SIZE,u=e[0],p=e[1],d=e[3],c=d,f,_;if(u==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;_=tn(jn(u),p);{let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=g(s,n,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=tn(jn(u),p);let g=a.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=g(s,w,jn(u),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let g=0;ga.setValue(k+S*l,g,l===4?"i32":"i64"));let w=a._OrtCreateTensor(jn(u),f,_,k,p.length,Wa(c));w===0&&At(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(T)}},nu=async(e,r,t,s,o,n)=>{var K,G,j,ee;let i=zt(),a=i.PTR_SIZE,l=Bs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],d=l[2],c=l[3],f=l[4],_=l[5],T=r.length,k=s.length,w=0,g=[],S=[],E=[],y=[],M=i.stackSave(),v=i.stackAlloc(T*a),C=i.stackAlloc(T*a),A=i.stackAlloc(k*a),B=i.stackAlloc(k*a);try{[w,g]=ac(n);for(let X=0;Xq*R,1);F=Ts(_e);let we=c==null?void 0:c.outputPreferredLocations[s[X]];if(F==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let q=[];for(let R=0;R0){let q=i.jsepGetBuffer;if(!q)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let R=q(W),pe=tn(_e,Ue);if(pe===void 0||!Va(F))throw new Error(`Unsupported data type: ${F}`);V=!0,Z.push([F,$e,{gpuBuffer:R,download:i.jsepCreateDownloader(R,pe,F),dispose:()=>{i._OrtReleaseTensor(oe)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&Ue>0){let q=i.webnnEnsureTensor,R=i.webnnIsInt64Supported;if(!q||!R)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(tn(_e,Ue)===void 0||!Ua(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!R(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let pe=await q(e,W,_e,$e,!1);V=!0,Z.push([F,$e,{mlTensor:pe,download:i.webnnCreateMLTensorDownloader(W,F),dispose:()=>{i.webnnReleaseTensorId(W),i._OrtReleaseTensor(oe)}},"ml-tensor"])}else{let q=Na(F),R=new q(Ue);new Uint8Array(R.buffer,R.byteOffset,R.byteLength).set(i.HEAPU8.subarray(W,W+R.byteLength)),Z.push([F,$e,R,"cpu"])}}finally{i.stackRestore(me),F==="string"&&W&&i._free(W),V||i._OrtReleaseTensor(oe),(ee=i.webnnOnRunEnd)==null||ee.call(i,u)}}return c&&!f&&(i._OrtClearBoundOutputs(c.handle)!==0&&At("Can't clear bound outputs."),Bs.set(e,[u,p,d,c,f,!1])),Z}finally{i.stackRestore(M),S.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),g.forEach(H=>i._free(H))}},ou=e=>{let r=zt(),t=Bs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&At("Can't get an profile file name."),r._OrtFree(o)},iu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Rs,kr,Wn,xo,To,bi,au,yi,un,dn,Sg,$g,kg,Ig,Ag,Fg,Og,Dg,Lg=Be(()=>{ts(),Cg(),en(),La(),Rs=()=>!!Bt.wasm.proxy&&typeof document<"u",Wn=!1,xo=!1,To=!1,yi=new Map,un=(e,r)=>{let t=yi.get(e);t?t.push(r):yi.set(e,[r])},dn=()=>{if(Wn||!xo||To||!kr)throw new Error("worker not ready")},Sg=e=>{switch(e.data.type){case"init-wasm":Wn=!1,e.data.err?(To=!0,au[1](e.data.err)):(xo=!0,au[0]()),bi&&(URL.revokeObjectURL(bi),bi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=yi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},$g=async()=>{if(!xo){if(Wn)throw new Error("multiple calls to 'initWasm()' detected.");if(To)throw new Error("previous call to 'initWasm()' failed.");if(Wn=!0,Rs())return new Promise((e,r)=>{kr==null||kr.terminate(),rc().then(([t,s])=>{try{kr=s,kr.onerror=n=>r(n),kr.onmessage=Sg,au=[e,r];let o={type:"init-wasm",in:Bt};!o.in.wasm.wasmPaths&&(t||Aa)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),kr.postMessage(o),bi=t}catch(o){r(o)}},r)});try{await Ra(Bt.wasm),await Yl(Bt),xo=!0}catch(e){throw To=!0,e}finally{Wn=!1}}},kg=async e=>{if(Rs())return dn(),new Promise((r,t)=>{un("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Bt}};kr.postMessage(s)});await Zl(Bt,e)},Ig=async e=>Rs()?(dn(),new Promise((r,t)=>{un("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};kr.postMessage(s,[e.buffer])})):Mi(e),Ag=async(e,r)=>{if(Rs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return dn(),new Promise((t,s)=>{un("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),kr.postMessage(o,n)})}else return tu(e,r)},Fg=async e=>{if(Rs())return dn(),new Promise((r,t)=>{un("release",[r,t]);let s={type:"release",in:e};kr.postMessage(s)});ru(e)},Og=async(e,r,t,s,o,n)=>{if(Rs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return dn(),new Promise((i,a)=>{un("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};kr.postMessage(u,iu(l))})}else return nu(e,r,t,s,o,n)},Dg=async e=>{if(Rs())return dn(),new Promise((r,t)=>{un("end-profiling",[r,t]);let s={type:"end-profiling",in:e};kr.postMessage(s)});ou(e)}}),lu,zg,Bg,_x=Be(()=>{ts(),Lg(),ut(),Pa(),hc(),lu=(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()}`)}},zg=e=>{switch(e[3]){case"cpu":return new Zr(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Va(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return Zr.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!Ua(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return Zr.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Bg=class{async fetchModelAndCopyToWasmMemory(e){return Ig(await Ga(e))}async loadModel(e,r){es();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Ag(t,r),Gr()}async dispose(){return Fg(this.sessionId)}async run(e,r,t){es();let s=[],o=[];Object.entries(e).forEach(d=>{let c=d[0],f=d[1],_=this.inputNames.indexOf(c);if(_===-1)throw new Error(`invalid input '${c}'`);s.push(f),o.push(_)});let n=[],i=[];Object.entries(r).forEach(d=>{let c=d[0],f=d[1],_=this.outputNames.indexOf(c);if(_===-1)throw new Error(`invalid output '${c}'`);n.push(f),i.push(_)});let a=s.map((d,c)=>lu(d,()=>`input "${this.inputNames[o[c]]}"`)),l=n.map((d,c)=>d?lu(d,()=>`output "${this.outputNames[i[c]]}"`):null),u=await Og(this.sessionId,o,a,i,l,t),p={};for(let d=0;ddu,initializeFlags:()=>uu,wasmBackend:()=>jg});var uu,du,jg,fx=Be(()=>{ts(),Lg(),_x(),uu=()=>{(typeof Bt.wasm.initTimeout!="number"||Bt.wasm.initTimeout<0)&&(Bt.wasm.initTimeout=0);let e=Bt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Bt.wasm.simd=!1),typeof Bt.wasm.proxy!="boolean"&&(Bt.wasm.proxy=!1),typeof Bt.wasm.trace!="boolean"&&(Bt.wasm.trace=!1),typeof Bt.wasm.numThreads!="number"||!Number.isInteger(Bt.wasm.numThreads)||Bt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Bt.wasm.numThreads=1;else{let r=typeof navigator>"u"?rv("node:os").cpus().length:navigator.hardwareConcurrency;Bt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},du=class{async init(e){uu(),await $g(),await kg(e)}async createInferenceSessionHandler(e,r){let t=new Bg;return await t.loadModel(e,r),t}},jg=new du});ts(),ts(),ts();var gx="1.22.0-dev.20250409-89f8206ba4",wx=Gd;{let e=(fx(),ao(Rg)).wasmBackend;Ys("webgpu",e,5),Ys("webnn",e,5),Ys("cpu",e,10),Ys("wasm",e,10)}Object.defineProperty(Bt.versions,"web",{value:gx,enumerable:!0});/** -* @license -* Copyright 2021 Google LLC. All Rights Reserved. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -* ============================================================================= -*//** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - *//** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */var Mx=Object.freeze({__proto__:null,get InferenceSession(){return Ea},get TRACE(){return co},get TRACE_FUNC_BEGIN(){return es},get TRACE_FUNC_END(){return Gr},get Tensor(){return Zr},default:wx,get env(){return Bt},get registerBackend(){return Ys}}),Cs={},bx={"onnxruntime-common":e=>{e.exports=Y0},"onnxruntime-web":e=>{e.exports=Mx},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Se,Interpreter:()=>Ae,Template:()=>Ve,parse:()=>V,tokenize:()=>d});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",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,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(O,Y){this.value=O,this.type=Y}};function i(O){return/\w/.test(O)}function a(O){return/[0-9]/.test(O)}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]],u=new Map([["n",` -`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(O,Y={}){return O.endsWith(` -`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),Y.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),Y.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function d(O,Y={}){var Ee,ke,Ie;const z=[],J=p(O,Y);let le=0;const ye=Re=>{let Xe="";for(;Re(J[le]);){if(J[le]==="\\"){if(++le,le>=J.length)throw new SyntaxError("Unexpected end of input");const Ge=J[le++],lt=u.get(Ge);if(lt===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ge}`);Xe+=lt;continue}if(Xe+=J[le++],le>=J.length)throw new SyntaxError("Unexpected end of input")}return Xe};e:for(;le0){z.push(new n(Ge,s.Text));continue}}ye(Ge=>/\s/.test(Ge));const Xe=J[le];if(Xe==="-"||Xe==="+"){const Ge=(ke=z.at(-1))==null?void 0:ke.type;if(Ge===s.Text||Ge===void 0)throw new SyntaxError(`Unexpected character: ${Xe}`);switch(Ge){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++le;const lt=ye(a);z.push(new n(`${Xe}${lt}`,lt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Ge,lt]of l)if(J.slice(le,le+Ge.length)===Ge){z.push(new n(Ge,lt)),le+=Ge.length;continue e}if(Xe==="'"||Xe==='"'){++le;const Ge=ye(lt=>lt!==Xe);z.push(new n(Ge,s.StringLiteral)),++le;continue}if(a(Xe)){const Ge=ye(a);z.push(new n(Ge,s.NumericLiteral));continue}if(i(Xe)){const Ge=ye(i),lt=Object.hasOwn(o,Ge)?o[Ge]:s.Identifier;lt===s.In&&((Ie=z.at(-1))==null?void 0:Ie.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Ge,lt));continue}throw new SyntaxError(`Unexpected character: ${Xe}`)}return z}var c=class{constructor(){te(this,"type","Statement")}},f=class extends c{constructor(Y){super();te(this,"type","Program");this.body=Y}},_=class extends c{constructor(Y,z,J){super();te(this,"type","If");this.test=Y,this.body=z,this.alternate=J}},T=class extends c{constructor(Y,z,J,le){super();te(this,"type","For");this.loopvar=Y,this.iterable=z,this.body=J,this.defaultBlock=le}},k=class extends c{constructor(Y,z,J){super();te(this,"type","Set");this.assignee=Y,this.value=z,this.body=J}},w=class extends c{constructor(Y,z,J){super();te(this,"type","Macro");this.name=Y,this.args=z,this.body=J}},g=class extends c{constructor(){super(...arguments);te(this,"type","Expression")}},S=class extends g{constructor(Y,z,J){super();te(this,"type","MemberExpression");this.object=Y,this.property=z,this.computed=J}},E=class extends g{constructor(Y,z){super();te(this,"type","CallExpression");this.callee=Y,this.args=z}},y=class extends g{constructor(Y){super();te(this,"type","Identifier");this.value=Y}},M=class extends g{constructor(Y){super();te(this,"type","Literal");this.value=Y}},v=class extends M{constructor(){super(...arguments);te(this,"type","NumericLiteral")}},C=class extends M{constructor(){super(...arguments);te(this,"type","StringLiteral")}},A=class extends M{constructor(){super(...arguments);te(this,"type","BooleanLiteral")}},B=class extends M{constructor(){super(...arguments);te(this,"type","NullLiteral")}},K=class extends M{constructor(){super(...arguments);te(this,"type","ArrayLiteral")}},G=class extends M{constructor(){super(...arguments);te(this,"type","TupleLiteral")}},j=class extends M{constructor(){super(...arguments);te(this,"type","ObjectLiteral")}},ee=class extends g{constructor(Y,z,J){super();te(this,"type","BinaryExpression");this.operator=Y,this.left=z,this.right=J}},H=class extends g{constructor(Y,z){super();te(this,"type","FilterExpression");this.operand=Y,this.filter=z}},Z=class extends g{constructor(Y,z){super();te(this,"type","SelectExpression");this.iterable=Y,this.test=z}},X=class extends g{constructor(Y,z,J){super();te(this,"type","TestExpression");this.operand=Y,this.negate=z,this.test=J}},oe=class extends g{constructor(Y,z){super();te(this,"type","UnaryExpression");this.operator=Y,this.argument=z}},me=class extends g{constructor(Y=void 0,z=void 0,J=void 0){super();te(this,"type","SliceExpression");this.start=Y,this.stop=z,this.step=J}},ae=class extends g{constructor(Y,z){super();te(this,"type","KeywordArgumentExpression");this.key=Y,this.value=z}};function V(O){const Y=new f([]);let z=0;function J(De,Qe){const tt=O[z++];if(!tt||tt.type!==De)throw new Error(`Parser Error: ${Qe}. ${tt.type} !== ${De}.`);return tt}function le(){switch(O[z].type){case s.Text:return ke();case s.OpenStatement:return Ie();case s.OpenExpression:return Re();default:throw new SyntaxError(`Unexpected token type: ${O[z].type}`)}}function ye(...De){return z+De.length<=O.length&&De.some((Qe,tt)=>Qe!==O[z+tt].type)}function Ee(...De){return z+De.length<=O.length&&De.every((Qe,tt)=>Qe===O[z+tt].type)}function ke(){return new C(J(s.Text,"Expected text token").value)}function Ie(){J(s.OpenStatement,"Expected opening statement token");let De;switch(O[z].type){case s.Set:++z,De=Xe(),J(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,De=Ge(),J(s.OpenStatement,"Expected {% token"),J(s.EndIf,"Expected endif token"),J(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,De=lt(),J(s.OpenStatement,"Expected {% token"),J(s.EndMacro,"Expected endmacro token"),J(s.CloseStatement,"Expected %} token");break;case s.For:++z,De=Gt(),J(s.OpenStatement,"Expected {% token"),J(s.EndFor,"Expected endfor token"),J(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[z].type}`)}return De}function Re(){J(s.OpenExpression,"Expected opening expression token");const De=Ot();return J(s.CloseExpression,"Expected closing expression token"),De}function Xe(){var Qe,tt;const De=Ot();if(Ee(s.Equals)){++z;const Rt=Ot();return new k(De,Rt,[])}else{const Rt=[];for(J(s.CloseStatement,"Expected %} token");!(((Qe=O[z])==null?void 0:Qe.type)===s.OpenStatement&&((tt=O[z+1])==null?void 0:tt.type)===s.EndSet);){const zr=le();Rt.push(zr)}return J(s.OpenStatement,"Expected {% token"),J(s.EndSet,"Expected endset token"),new k(De,null,Rt)}}function Ge(){var Rt,zr,Sr,ps,hs,Kr,ms,_s;const De=Ot();J(s.CloseStatement,"Expected closing statement token");const Qe=[],tt=[];for(;!(((Rt=O[z])==null?void 0:Rt.type)===s.OpenStatement&&(((zr=O[z+1])==null?void 0:zr.type)===s.ElseIf||((Sr=O[z+1])==null?void 0:Sr.type)===s.Else||((ps=O[z+1])==null?void 0:ps.type)===s.EndIf));)Qe.push(le());if(((hs=O[z])==null?void 0:hs.type)===s.OpenStatement&&((Kr=O[z+1])==null?void 0:Kr.type)!==s.EndIf)if(++z,Ee(s.ElseIf))J(s.ElseIf,"Expected elseif token"),tt.push(Ge());else for(J(s.Else,"Expected else token"),J(s.CloseStatement,"Expected closing statement token");!(((ms=O[z])==null?void 0:ms.type)===s.OpenStatement&&((_s=O[z+1])==null?void 0:_s.type)===s.EndIf);)tt.push(le());return new _(De,Qe,tt)}function lt(){const De=Qt();if(De.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Qe=us();J(s.CloseStatement,"Expected closing statement token");const tt=[];for(;ye(s.OpenStatement,s.EndMacro);)tt.push(le());return new w(De,Qe,tt)}function wt(De=!1){const Qe=De?Qt:Ot,tt=[Qe()],Rt=Ee(s.Comma);for(;Rt&&(++z,tt.push(Qe()),!!Ee(s.Comma)););return Rt?new G(tt):tt[0]}function Gt(){const De=wt(!0);if(!(De instanceof y||De instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${De.type} instead`);J(s.In,"Expected `in` keyword following loop variable");const Qe=Ot();J(s.CloseStatement,"Expected closing statement token");const tt=[];for(;ye(s.OpenStatement,s.EndFor)&&ye(s.OpenStatement,s.Else);)tt.push(le());const Rt=[];if(Ee(s.OpenStatement,s.Else))for(++z,++z,J(s.CloseStatement,"Expected closing statement token");ye(s.OpenStatement,s.EndFor);)Rt.push(le());return new T(De,Qe,tt,Rt)}function Ot(){return ur()}function ur(){const De=ls();if(Ee(s.If)){++z;const Qe=ls();if(Ee(s.Else)){++z;const tt=ls();return new _(Qe,[De],[tt])}else return new Z(De,Qe)}return De}function ls(){let De=Ms();for(;Ee(s.Or);){const Qe=O[z];++z;const tt=Ms();De=new ee(Qe,De,tt)}return De}function Ms(){let De=Ir();for(;Ee(s.And);){const Qe=O[z];++z;const tt=Ir();De=new ee(Qe,De,tt)}return De}function Ir(){let De;for(;Ee(s.Not);){const Qe=O[z];++z;const tt=Ir();De=new oe(Qe,tt)}return De??js()}function js(){let De=Ss();for(;Ee(s.ComparisonBinaryOperator)||Ee(s.In)||Ee(s.NotIn);){const Qe=O[z];++z;const tt=Ss();De=new ee(Qe,De,tt)}return De}function Ss(){let De=ds();for(;Ee(s.AdditiveBinaryOperator);){const Qe=O[z];++z;const tt=ds();De=new ee(Qe,De,tt)}return De}function Ns(){const De=Ft(Qt());return Ee(s.OpenParen)?at(De):De}function at(De){let Qe=new E(De,us());return Qe=Ft(Qe),Ee(s.OpenParen)&&(Qe=at(Qe)),Qe}function us(){J(s.OpenParen,"Expected opening parenthesis for arguments list");const De=Ar();return J(s.CloseParen,"Expected closing parenthesis for arguments list"),De}function Ar(){const De=[];for(;!Ee(s.CloseParen);){let Qe=Ot();if(Ee(s.Equals)){if(++z,!(Qe instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const tt=Ot();Qe=new ae(Qe,tt)}De.push(Qe),Ee(s.Comma)&&++z}return De}function bs(){const De=[];let Qe=!1;for(;!Ee(s.CloseSquareBracket);)Ee(s.Colon)?(De.push(void 0),++z,Qe=!0):(De.push(Ot()),Ee(s.Colon)&&(++z,Qe=!0));if(De.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Qe){if(De.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new me(...De)}return De[0]}function Ft(De){for(;Ee(s.Dot)||Ee(s.OpenSquareBracket);){const Qe=O[z];++z;let tt;const Rt=Qe.type!==s.Dot;if(Rt)tt=bs(),J(s.CloseSquareBracket,"Expected closing square bracket");else if(tt=Qt(),tt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");De=new S(De,tt,Rt)}return De}function ds(){let De=cs();for(;Ee(s.MultiplicativeBinaryOperator);){const Qe=O[z];++z;const tt=cs();De=new ee(Qe,De,tt)}return De}function cs(){let De=ys();for(;Ee(s.Is);){++z;const Qe=Ee(s.Not);Qe&&++z;let tt=Qt();if(tt instanceof A?tt=new y(tt.value.toString()):tt instanceof B&&(tt=new y("none")),!(tt instanceof y))throw new SyntaxError("Expected identifier for the test");De=new X(De,Qe,tt)}return De}function ys(){let De=Ns();for(;Ee(s.Pipe);){++z;let Qe=Qt();if(!(Qe instanceof y))throw new SyntaxError("Expected identifier for the filter");Ee(s.OpenParen)&&(Qe=at(Qe)),De=new H(De,Qe)}return De}function Qt(){const De=O[z];switch(De.type){case s.NumericLiteral:return++z,new v(Number(De.value));case s.StringLiteral:return++z,new C(De.value);case s.BooleanLiteral:return++z,new A(De.value.toLowerCase()==="true");case s.NullLiteral:return++z,new B(null);case s.Identifier:return++z,new y(De.value);case s.OpenParen:{++z;const Qe=wt();if(O[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[z].type} instead`);return++z,Qe}case s.OpenSquareBracket:{++z;const Qe=[];for(;!Ee(s.CloseSquareBracket);)Qe.push(Ot()),Ee(s.Comma)&&++z;return++z,new K(Qe)}case s.OpenCurlyBracket:{++z;const Qe=new Map;for(;!Ee(s.CloseCurlyBracket);){const tt=Ot();J(s.Colon,"Expected colon between key and value in object literal");const Rt=Ot();Qe.set(tt,Rt),Ee(s.Comma)&&++z}return++z,new j(Qe)}default:throw new SyntaxError(`Unexpected token: ${De.type}`)}}for(;z=0?(Y=(Y??(Y=0))<0?Math.max(O.length+Y,0):Math.min(Y,O.length),z=(z??(z=O.length))<0?Math.max(O.length+z,0):Math.min(z,O.length)):(Y=(Y??(Y=O.length-1))<0?Math.max(O.length+Y,-1):Math.min(Y,O.length-1),z=(z??(z=-1))<-1?Math.max(O.length+z,-1):Math.min(z,O.length-1));const ye=[];for(let Ee=Y;le*EeY.toUpperCase())}var _e=class{constructor(O=void 0){te(this,"type","RuntimeValue");te(this,"value");te(this,"builtins",new Map);this.value=O}__bool__(){return new $e(!!this.value)}},se=class extends _e{constructor(){super(...arguments);te(this,"type","NumericValue")}},ce=class extends _e{constructor(){super(...arguments);te(this,"type","StringValue");te(this,"builtins",new Map([["upper",new pe(()=>new ce(this.value.toUpperCase()))],["lower",new pe(()=>new ce(this.value.toLowerCase()))],["strip",new pe(()=>new ce(this.value.trim()))],["title",new pe(()=>new ce(re(this.value)))],["length",new se(this.value.length)],["rstrip",new pe(()=>new ce(this.value.trimEnd()))],["lstrip",new pe(()=>new ce(this.value.trimStart()))],["split",new pe(Y=>{const z=Y[0]??new xe;if(!(z instanceof ce||z instanceof xe))throw new Error("sep argument must be a string or null");const J=Y[1]??new se(-1);if(!(J instanceof se))throw new Error("maxsplit argument must be a number");let le=[];if(z instanceof xe){const ye=this.value.trimStart();for(const{0:Ee,index:ke}of ye.matchAll(/\S+/g)){if(J.value!==-1&&le.length>=J.value&&ke!==void 0){le.push(Ee+ye.slice(ke+Ee.length));break}le.push(Ee)}}else{if(z.value==="")throw new Error("empty separator");le=this.value.split(z.value),J.value!==-1&&le.length>J.value&&le.push(le.splice(J.value).join(z.value))}return new q(le.map(ye=>new ce(ye)))})]]))}},$e=class extends _e{constructor(){super(...arguments);te(this,"type","BooleanValue")}},Ue=class extends _e{constructor(){super(...arguments);te(this,"type","ObjectValue");te(this,"builtins",new Map([["get",new pe(([Y,z])=>{if(!(Y instanceof ce))throw new Error(`Object key must be a string: got ${Y.type}`);return this.value.get(Y.value)??z??new xe})],["items",new pe(()=>new q(Array.from(this.value.entries()).map(([Y,z])=>new q([new ce(Y),z]))))]]))}__bool__(){return new $e(this.value.size>0)}},we=class extends Ue{constructor(){super(...arguments);te(this,"type","KeywordArgumentsValue")}},q=class extends _e{constructor(){super(...arguments);te(this,"type","ArrayValue");te(this,"builtins",new Map([["length",new se(this.value.length)]]))}__bool__(){return new $e(this.value.length>0)}},R=class extends q{constructor(){super(...arguments);te(this,"type","TupleValue")}},pe=class extends _e{constructor(){super(...arguments);te(this,"type","FunctionValue")}},xe=class extends _e{constructor(){super(...arguments);te(this,"type","NullValue")}},be=class extends _e{constructor(){super(...arguments);te(this,"type","UndefinedValue")}},Se=class{constructor(O){te(this,"variables",new Map([["namespace",new pe(O=>{if(O.length===0)return new Ue(new Map);if(O.length!==1||!(O[0]instanceof Ue))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));te(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof pe],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toLowerCase()}],["upper",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,Y)=>O.value===Y.value],["eq",(O,Y)=>O.value===Y.value]]));this.parent=O}set(O,Y){return this.declareVariable(O,Fe(Y))}declareVariable(O,Y){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,Y),Y}setVariable(O,Y){return this.variables.set(O,Y),Y}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new be}catch{return new be}}},Ae=class{constructor(O){te(this,"global");this.global=O??new Se}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,Y){const z=this.evaluate(O.left,Y);switch(O.operator.value){case"and":return z.__bool__().value?this.evaluate(O.right,Y):z;case"or":return z.__bool__().value?z:this.evaluate(O.right,Y)}const J=this.evaluate(O.right,Y);switch(O.operator.value){case"==":return new $e(z.value==J.value);case"!=":return new $e(z.value!=J.value)}if(z instanceof be||J instanceof be)throw new Error("Cannot perform operation on undefined values");if(z instanceof xe||J instanceof xe)throw new Error("Cannot perform operation on null values");if(z instanceof se&&J instanceof se)switch(O.operator.value){case"+":return new se(z.value+J.value);case"-":return new se(z.value-J.value);case"*":return new se(z.value*J.value);case"/":return new se(z.value/J.value);case"%":return new se(z.value%J.value);case"<":return new $e(z.value":return new $e(z.value>J.value);case">=":return new $e(z.value>=J.value);case"<=":return new $e(z.value<=J.value)}else if(z instanceof q&&J instanceof q)switch(O.operator.value){case"+":return new q(z.value.concat(J.value))}else if(J instanceof q){const le=J.value.find(ye=>ye.value===z.value)!==void 0;switch(O.operator.value){case"in":return new $e(le);case"not in":return new $e(!le)}}if(z instanceof ce||J instanceof ce)switch(O.operator.value){case"+":return new ce(z.value.toString()+J.value.toString())}if(z instanceof ce&&J instanceof ce)switch(O.operator.value){case"in":return new $e(J.value.includes(z.value));case"not in":return new $e(!J.value.includes(z.value))}if(z instanceof ce&&J instanceof Ue)switch(O.operator.value){case"in":return new $e(J.value.has(z.value));case"not in":return new $e(!J.value.has(z.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${z.type} and ${J.type}`)}evaluateArguments(O,Y){const z=[],J=new Map;for(const le of O)if(le.type==="KeywordArgumentExpression"){const ye=le;J.set(ye.key.value,this.evaluate(ye.value,Y))}else{if(J.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(le,Y))}return[z,J]}evaluateFilterExpression(O,Y){const z=this.evaluate(O.operand,Y);if(O.filter.type==="Identifier"){const J=O.filter;if(J.value==="tojson")return new ce(ze(z));if(z instanceof q)switch(J.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new se(z.value.length);case"reverse":return new q(z.value.reverse());case"sort":return new q(z.value.sort((le,ye)=>{if(le.type!==ye.type)throw new Error(`Cannot compare different types: ${le.type} and ${ye.type}`);switch(le.type){case"NumericValue":return le.value-ye.value;case"StringValue":return le.value.localeCompare(ye.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));case"join":return new ce(z.value.map(le=>le.value).join(""));case"string":return new ce(ze(z));default:throw new Error(`Unknown ArrayValue filter: ${J.value}`)}else if(z instanceof ce)switch(J.value){case"length":return new se(z.value.length);case"upper":return new ce(z.value.toUpperCase());case"lower":return new ce(z.value.toLowerCase());case"title":return new ce(re(z.value));case"capitalize":return new ce(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new ce(z.value.trim());case"indent":return new ce(z.value.split(` -`).map((le,ye)=>ye===0||le.length===0?le:" "+le).join(` -`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${J.value}`)}else if(z instanceof se)switch(J.value){case"abs":return new se(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${J.value}`)}else if(z instanceof Ue)switch(J.value){case"items":return new q(Array.from(z.value.entries()).map(([le,ye])=>new q([new ce(le),ye])));case"length":return new se(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${J.value}`)}throw new Error(`Cannot apply filter "${J.value}" to type: ${z.type}`)}else if(O.filter.type==="CallExpression"){const J=O.filter;if(J.callee.type!=="Identifier")throw new Error(`Unknown filter: ${J.callee.type}`);const le=J.callee.value;if(le==="tojson"){const[,ye]=this.evaluateArguments(J.args,Y),Ee=ye.get("indent")??new xe;if(!(Ee instanceof se||Ee instanceof xe))throw new Error("If set, indent must be a number");return new ce(ze(z,Ee.value))}else if(le==="join"){let ye;if(z instanceof ce)ye=Array.from(z.value);else if(z instanceof q)ye=z.value.map(Re=>Re.value);else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`);const[Ee,ke]=this.evaluateArguments(J.args,Y),Ie=Ee.at(0)??ke.get("separator")??new ce("");if(!(Ie instanceof ce))throw new Error("separator must be a string");return new ce(ye.join(Ie.value))}if(z instanceof q){switch(le){case"selectattr":case"rejectattr":{const ye=le==="selectattr";if(z.value.some(Ge=>!(Ge instanceof Ue)))throw new Error(`\`${le}\` can only be applied to array of objects`);if(J.args.some(Ge=>Ge.type!=="StringLiteral"))throw new Error(`arguments of \`${le}\` must be strings`);const[Ee,ke,Ie]=J.args.map(Ge=>this.evaluate(Ge,Y));let Re;if(ke){const Ge=Y.tests.get(ke.value);if(!Ge)throw new Error(`Unknown test: ${ke.value}`);Re=Ge}else Re=(...Ge)=>Ge[0].__bool__().value;const Xe=z.value.filter(Ge=>{const lt=Ge.value.get(Ee.value),wt=lt?Re(lt,Ie):!1;return ye?wt:!wt});return new q(Xe)}case"map":{const[,ye]=this.evaluateArguments(J.args,Y);if(ye.has("attribute")){const Ee=ye.get("attribute");if(!(Ee instanceof ce))throw new Error("attribute must be a string");const ke=ye.get("default"),Ie=z.value.map(Re=>{if(!(Re instanceof Ue))throw new Error("items in map must be an object");return Re.value.get(Ee.value)??ke??new be});return new q(Ie)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(z instanceof ce){switch(le){case"indent":{const[ye,Ee]=this.evaluateArguments(J.args,Y),ke=ye.at(0)??Ee.get("width")??new se(4);if(!(ke instanceof se))throw new Error("width must be a number");const Ie=ye.at(1)??Ee.get("first")??new $e(!1),Re=ye.at(2)??Ee.get("blank")??new $e(!1),Xe=z.value.split(` -`),Ge=" ".repeat(ke.value),lt=Xe.map((wt,Gt)=>!Ie.value&&Gt===0||!Re.value&&wt.length===0?wt:Ge+wt);return new ce(lt.join(` -`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,Y){const z=this.evaluate(O.operand,Y),J=Y.tests.get(O.test.value);if(!J)throw new Error(`Unknown test: ${O.test.value}`);const le=J(z);return new $e(O.negate?!le:le)}evaluateUnaryExpression(O,Y){const z=this.evaluate(O.argument,Y);switch(O.operator.value){case"not":return new $e(!z.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,Y){return this.evaluateBlock(O.body,Y)}evaluateBlock(O,Y){let z="";for(const J of O){const le=this.evaluate(J,Y);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(z+=le.value)}return new ce(z)}evaluateIdentifier(O,Y){return Y.lookupVariable(O.value)}evaluateCallExpression(O,Y){const[z,J]=this.evaluateArguments(O.args,Y);J.size>0&&z.push(new we(J));const le=this.evaluate(O.callee,Y);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(z,Y)}evaluateSliceExpression(O,Y,z){if(!(O instanceof q||O instanceof ce))throw new Error("Slice object must be an array or string");const J=this.evaluate(Y.start,z),le=this.evaluate(Y.stop,z),ye=this.evaluate(Y.step,z);if(!(J instanceof se||J instanceof be))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof se||le instanceof be))throw new Error("Slice stop must be numeric or undefined");if(!(ye instanceof se||ye instanceof be))throw new Error("Slice step must be numeric or undefined");return O instanceof q?new q(W(O.value,J.value,le.value,ye.value)):new ce(W(Array.from(O.value),J.value,le.value,ye.value).join(""))}evaluateMemberExpression(O,Y){const z=this.evaluate(O.object,Y);let J;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(z,O.property,Y);J=this.evaluate(O.property,Y)}else J=new ce(O.property.value);let le;if(z instanceof Ue){if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.value.get(J.value)??z.builtins.get(J.value)}else if(z instanceof q||z instanceof ce)if(J instanceof se)le=z.value.at(J.value),z instanceof ce&&(le=new ce(z.value.at(J.value)));else if(J instanceof ce)le=z.builtins.get(J.value);else throw new Error(`Cannot access property with non-string/non-number: got ${J.type}`);else{if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.builtins.get(J.value)}return le instanceof _e?le:new be}evaluateSet(O,Y){const z=O.value?this.evaluate(O.value,Y):this.evaluateBlock(O.body,Y);if(O.assignee.type==="Identifier"){const J=O.assignee.value;Y.setVariable(J,z)}else if(O.assignee.type==="MemberExpression"){const J=O.assignee,le=this.evaluate(J.object,Y);if(!(le instanceof Ue))throw new Error("Cannot assign to member of non-object");if(J.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(J.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new xe}evaluateIf(O,Y){const z=this.evaluate(O.test,Y);return this.evaluateBlock(z.__bool__().value?O.body:O.alternate,Y)}evaluateFor(O,Y){const z=new Se(Y);let J,le;if(O.iterable.type==="SelectExpression"){const Re=O.iterable;le=this.evaluate(Re.iterable,z),J=Re.test}else le=this.evaluate(O.iterable,z);if(!(le instanceof q))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ye=[],Ee=[];for(let Re=0;Rewt.setVariable(O.loopvar.value,Ge);else if(O.loopvar.type==="TupleLiteral"){const wt=O.loopvar;if(Ge.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ge.type}`);const Gt=Ge;if(wt.value.length!==Gt.value.length)throw new Error(`Too ${wt.value.length>Gt.value.length?"few":"many"} items to unpack`);lt=Ot=>{for(let ur=0;ur0?ye[Re-1]:new be],["nextitem",Re{var Ee;const le=new Se(J);z=z.slice();let ye;((Ee=z.at(-1))==null?void 0:Ee.type)==="KeywordArgumentsValue"&&(ye=z.pop());for(let ke=0;kethis.evaluate(z,Y)));case"TupleLiteral":return new R(O.value.map(z=>this.evaluate(z,Y)));case"ObjectLiteral":{const z=new Map;for(const[J,le]of O.value){const ye=this.evaluate(J,Y);if(!(ye instanceof ce))throw new Error(`Object keys must be strings: got ${ye.type}`);z.set(ye.value,this.evaluate(le,Y))}return new Ue(z)}case"Identifier":return this.evaluateIdentifier(O,Y);case"CallExpression":return this.evaluateCallExpression(O,Y);case"MemberExpression":return this.evaluateMemberExpression(O,Y);case"UnaryExpression":return this.evaluateUnaryExpression(O,Y);case"BinaryExpression":return this.evaluateBinaryExpression(O,Y);case"FilterExpression":return this.evaluateFilterExpression(O,Y);case"TestExpression":return this.evaluateTestExpression(O,Y);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function Fe(O){switch(typeof O){case"number":return new se(O);case"string":return new ce(O);case"boolean":return new $e(O);case"undefined":return new be;case"object":return O===null?new xe:Array.isArray(O)?new q(O.map(Fe)):new Ue(new Map(Object.entries(O).map(([Y,z])=>[Y,Fe(z)])));case"function":return new pe((Y,z)=>{const J=O(...Y.map(le=>le.value))??null;return Fe(J)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function ze(O,Y,z){const J=z??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const le=Y?" ".repeat(Y):"",ye=` -`+le.repeat(J),Ee=ye+le;if(O.type==="ArrayValue"){const ke=O.value.map(Ie=>ze(Ie,Y,J+1));return Y?`[${Ee}${ke.join(`,${Ee}`)}${ye}]`:`[${ke.join(", ")}]`}else{const ke=Array.from(O.value.entries()).map(([Ie,Re])=>{const Xe=`"${Ie}": ${ze(Re,Y,J+1)}`;return Y?`${Ee}${Xe}`:Xe});return Y?`{${ke.join(",")}${ye}}`:`{${ke.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var Ve=class{constructor(O){te(this,"parsed");const Y=d(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=V(Y)}render(O){const Y=new Se;if(Y.set("false",!1),Y.set("true",!0),Y.set("raise_exception",le=>{throw new Error(le)}),Y.set("range",F),O)for(const[le,ye]of Object.entries(O))Y.set(le,ye);return new Ae(Y).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>_,isONNXProxy:()=>S,isONNXTensor:()=>w});var o=t("./src/env.js"),n=t("?2ce3"),i=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"}}),u=[];let p,d;const c=Symbol.for("onnxruntime");if(c in globalThis)d=globalThis[c];else if(o.apis.IS_NODE_ENV){switch(d=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else d=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let T=null;async function k(E,y,M){T&&await T;const v=f.create(E,y);T??(T=v);const C=await v;return C.config=M,C}function w(E){return E instanceof d.Tensor}const g=d==null?void 0:d.env;g!=null&&g.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),g.wasm.proxy=!1),g!=null&&g.webgpu&&(g.webgpu.powerPreference="high-performance");function S(){var E;return(E=g==null?void 0:g.wasm)==null?void 0:E.proxy}o.env.backends.onnx=g},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const d=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} 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:()=>E,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>c,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(y,M,v=0,C=null){const A=y/M;let B=(0,n.bankers_round)(A)*M;return C!==null&&B>C&&(B=Math.floor(A)*M),BM&&F.push(re)}else{let re=(0,n.max)(V.data)[1];if(re===j-1||(W=(0,n.softmax)(V.data),W[re]se*Z[(ce+1)%2])),X.boxes.push(_e),X.classes.push(re),X.scores.push(W[re])}}ee.push(X)}return ee}function f(y,M=null){const v=y.logits,C=v.dims[0];if(M!==null&&M.length!==C)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const A=[];for(let B=0;BZ[F]&&(Z[F]=V[F],X[F]=ae)}const oe=new Array(G.dims[0]);for(let ae=0;aeae!==void 0);A.push({segmentation:H,labels:me})}return A}function _(y,M,v,C){const A=[],B=[],K=[];for(let G=0;Gv&&(A.push(ee),B.push(X),K.push(H))}return[A,B,K]}function T(y,M,v,C=.5,A=.8){const B=[];let K=0,G=0;const j=M[v].data;for(let H=0;H=C&&++G;let ee=K>0&&G>0;return ee&&(ee=K/G>A),[ee,B]}function k(y,M,v,C,A,B=null,K=null){const[G,j]=K??y[0].dims,ee=new o.Tensor("int32",new Int32Array(G*j),[G,j]),H=[];if(K!==null)for(let ae=0;aeX[W]&&(Z[W]=ae,X[W]=F[W])}let oe=0;const me=ee.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,M)/Math.min(y,M)}`);let B=Math.round(y/v)*v,K=Math.round(M/v)*v;if(B*K>A){const G=Math.sqrt(y*M/A);B=Math.floor(y/G/v)*v,K=Math.floor(M/G/v)*v}else if(B*KB?ee=Math.floor(B*j/A):B>A&&(j=Math.floor(A*ee/B)),await M.resize(ee,j,{resample:C}))}async crop_margin(M,v=200){const C=M.clone().grayscale(),A=(0,n.min)(C.data)[0],K=(0,n.max)(C.data)[0]-A;if(K===0)return M;const G=v/255;let j=C.width,ee=C.height,H=0,Z=0;const X=C.data;for(let oe=0;oethis.preprocess(B)));return{pixel_values:(0,o.stack)(C.map(B=>B.pixel_values),0),original_sizes:C.map(B=>B.original_size),reshaped_input_sizes:C.map(B=>B.reshaped_input_size)}}static async from_pretrained(M,v){const C=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,v);return new this(C)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,u){super(),this.config=l,this.components=u}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,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}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,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,d]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(c=>c in this).map(async c=>{const f=await this[c].from_pretrained(l,u);return[c.replace(/_class$/,""),f]})).then(Object.fromEntries)]);return new this(p,d)}}te(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),te(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,d){return await(0,o.getModelJSON)(p,"config.json",!0,d)}function i(p){const d={};let c={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":c=i(p.text_config);break;case"moondream1":c=i(p.phi_config);break;case"musicgen":c=i(p.decoder);break;case"multi_modality":c=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":d.num_heads="num_attention_heads",d.num_layers="num_hidden_layers",d.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":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.hidden_size="hidden_size",d.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.dim_kv="head_dim";break;case"openelm":d.num_heads="num_kv_heads",d.num_layers="num_transformer_layers",d.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":d.num_heads="num_heads",d.num_layers="num_layers",d.hidden_size="hidden_size";break;case"bloom":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="hidden_size";break;case"mpt":d.num_heads="n_heads",d.num_layers="n_layers",d.hidden_size="d_model";break;case"exaone":d.num_heads="num_key_value_heads",d.num_layers="num_layers",d.dim_kv="head_dim",d.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":d.num_decoder_layers="num_decoder_layers",d.num_decoder_heads="num_heads",d.decoder_dim_kv="d_kv",d.num_encoder_layers="num_layers",d.num_encoder_heads="num_heads",d.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":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="d_model",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="d_model";break;case"speecht5":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="hidden_size",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="hidden_size";break;case"trocr":d.num_encoder_layers=d.num_decoder_layers="decoder_layers",d.num_encoder_heads=d.num_decoder_heads="decoder_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="d_model";break;case"musicgen_decoder":d.num_encoder_layers=d.num_decoder_layers="num_hidden_layers",d.num_encoder_heads=d.num_decoder_heads="num_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"moonshine":d.num_decoder_layers="decoder_num_hidden_layers",d.num_decoder_heads="decoder_num_key_value_heads",d.num_encoder_layers="encoder_num_hidden_layers",d.num_encoder_heads="encoder_num_key_value_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _=i(p.decoder),T="num_decoder_layers"in _,k=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return T?(k.num_decoder_layers=_.num_decoder_layers,k.num_decoder_heads=_.num_decoder_heads,k.decoder_hidden_size=_.decoder_hidden_size,k.num_encoder_layers=_.num_encoder_layers,k.num_encoder_heads=_.num_encoder_heads,k.encoder_hidden_size=_.encoder_hidden_size):(k.num_layers=_.num_layers,k.num_heads=_.num_heads,k.hidden_size=_.hidden_size),k}const f={...c,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const _ in d)f[_]=p[d[_]];return f}function a(p,{prefix:d="past_key_values",batch_size:c=1}={}){const f={},_=p.normalized_config;if(_.is_encoder_decoder&&"num_encoder_heads"in _&&"num_decoder_heads"in _){const T=_.encoder_dim_kv??_.encoder_hidden_size/_.num_encoder_heads,k=_.decoder_dim_kv??_.decoder_hidden_size/_.num_decoder_heads,w=[c,_.num_encoder_heads,0,T],g=[c,_.num_decoder_heads,0,k];for(let S=0;S<_.num_decoder_layers;++S)f[`${d}.${S}.encoder.key`]=w,f[`${d}.${S}.encoder.value`]=w,f[`${d}.${S}.decoder.key`]=g,f[`${d}.${S}.decoder.value`]=g}else{const T=_.num_heads,k=_.num_layers,w=_.dim_kv??_.hidden_size/(_.num_attention_heads??T);if(_.model_type==="falcon"){const g=[c*T,0,w];for(let S=0;S{var C,A;t.r(r),t.d(r,{apis:()=>k,env:()=>M});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((C=self.constructor)==null?void 0:C.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,c=typeof process<"u",f=c&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node",_=!v(s),T=!v(o),k=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:c,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:T}),w=_&&T;let g="./";if(w){const B=Object({url:self.location.href}).url;B?g=o.dirname(o.dirname(n.fileURLToPath(B))):typeof __dirname<"u"&&(g=o.dirname(__dirname))}const S=w?o.join(g,"/.cache/"):null,E="/models/",y=w?o.join(g,E):E,M={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:y,useFS:_,useBrowserCache:u,useFSCache:_,cacheDir:S,useCustomCache:!1,customCache:null};function v(B){return Object.keys(B).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){te(this,"max_length",20);te(this,"max_new_tokens",null);te(this,"min_length",0);te(this,"min_new_tokens",null);te(this,"early_stopping",!1);te(this,"max_time",null);te(this,"do_sample",!1);te(this,"num_beams",1);te(this,"num_beam_groups",1);te(this,"penalty_alpha",null);te(this,"use_cache",!0);te(this,"temperature",1);te(this,"top_k",50);te(this,"top_p",1);te(this,"typical_p",1);te(this,"epsilon_cutoff",0);te(this,"eta_cutoff",0);te(this,"diversity_penalty",0);te(this,"repetition_penalty",1);te(this,"encoder_repetition_penalty",1);te(this,"length_penalty",1);te(this,"no_repeat_ngram_size",0);te(this,"bad_words_ids",null);te(this,"force_words_ids",null);te(this,"renormalize_logits",!1);te(this,"constraints",null);te(this,"forced_bos_token_id",null);te(this,"forced_eos_token_id",null);te(this,"remove_invalid_values",!1);te(this,"exponential_decay_length_penalty",null);te(this,"suppress_tokens",null);te(this,"streamer",null);te(this,"begin_suppress_tokens",null);te(this,"forced_decoder_ids",null);te(this,"guidance_scale",null);te(this,"num_return_sequences",1);te(this,"output_attentions",!1);te(this,"output_hidden_states",!1);te(this,"output_scores",!1);te(this,"return_dict_in_generate",!1);te(this,"pad_token_id",null);te(this,"bos_token_id",null);te(this,"eos_token_id",null);te(this,"encoder_no_repeat_ngram_size",0);te(this,"decoder_start_token_id",null);te(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>T,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>c,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(M,v){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(M,v){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,v){let C=v;for(const A of this.processors)C=A(M,C);return C}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,v){for(let C=0;C=1&&B[B.length-1]>=this.timestamp_begin,G=B.length<2||B[B.length-2]>=this.timestamp_begin;if(K&&(G?A.subarray(this.timestamp_begin).fill(-1/0):A.subarray(0,this.eos_token_id).fill(-1/0)),M[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Z=this.timestamp_begin+this.max_initial_timestamp_index;A.subarray(Z+1).fill(-1/0)}const j=(0,o.log_softmax)(A),ee=Math.log(j.subarray(this.timestamp_begin).map(Math.exp).reduce((Z,X)=>Z+X)),H=(0,o.max)(j.subarray(0,this.timestamp_begin))[0];ee>H&&A.subarray(0,this.timestamp_begin).fill(-1/0)}return v}}class c extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const v=M.length,C=[];for(let B=0;B1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,v){if(v.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 ${v.dims[0]} for the logits and ${M.length} for the input ids.`);const C=M.length,A=v.slice([0,C],null),B=v.slice([C,v.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=M,this.filter_value=v,this.min_tokens_to_keep=C}}class E extends i{constructor(M,{filter_value:v=-1/0,min_tokens_to_keep:C=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,C),this.filter_value=v}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,c){let f=d.dims.at(-1),_=d.data;if(c===-1)_=_.slice(-f);else{let T=c*f;_=_.slice(T,T+f)}return _}randomSelect(d){let c=0;for(let _=0;_1)return new u(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const c=(0,n.max)(d.data)[1];return[[BigInt(c),0]]}}class l extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[f,_]=await(0,o.topk)(d,c),T=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(T);return[_.data[k],Math.log(T[k])]})}}class u extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[f,_]=await(0,o.topk)(d,c),T=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[_.data[w],Math.log(T[w])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,d){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 o&&(p=[p]),this.criteria.push(...p)}_call(p,d){const c=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let T=0;Td.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(c=>{const f=c.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(d){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 i{constructor(d,{skip_prompt:c=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:T=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=c,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:T,...k,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){var k;if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const c=this.next_tokens_are_prompt;if(c&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];(k=this.token_callback_function)==null||k.call(this,f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let T;c||_.endsWith(` -`)?(T=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,o.is_chinese_char)(_.charCodeAt(_.length-1))?(T=_.slice(this.print_len),this.print_len+=T.length):(T=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=T.length),this.on_finalized_text(T,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,c){var f,_;d.length>0&&((f=this.callback_function)==null||f.call(this,d)),c&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` -`))}}class u extends l{constructor(d,{skip_prompt:c=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:T=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:g=.02,skip_special_tokens:S=!0,decode_kwargs:E={}}={}){super(d,{skip_prompt:c,skip_special_tokens:S,callback_function:f,token_callback_function:_,decode_kwargs:E}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=T,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=g,this.waiting_for_timestamp=!1}put(d){var f,_;if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const c=d[0];if(c.length===1){const T=Number(c[0])-this.timestamp_begin;if(T>=0){const k=T*this.time_precision;this.waiting_for_timestamp?(f=this.on_chunk_end)==null||f.call(this,k):(_=this.on_chunk_start)==null||_.call(this,k),this.waiting_for_timestamp=!this.waiting_for_timestamp,d=[[]]}}return super.put(d)}end(){var d;super.end(),(d=this.on_finalize)==null||d.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ii,ASTModel:()=>ki,ASTPreTrainedModel:()=>Eo,AlbertForMaskedLM:()=>N,AlbertForQuestionAnswering:()=>$,AlbertForSequenceClassification:()=>he,AlbertModel:()=>vn,AlbertPreTrainedModel:()=>xs,AutoModel:()=>fd,AutoModelForAudioClassification:()=>M0,AutoModelForAudioFrameClassification:()=>y0,AutoModelForAudioTextToText:()=>k0,AutoModelForCTC:()=>w0,AutoModelForCausalLM:()=>a0,AutoModelForDepthEstimation:()=>E0,AutoModelForDocumentQuestionAnswering:()=>v0,AutoModelForImageClassification:()=>c0,AutoModelForImageFeatureExtraction:()=>S0,AutoModelForImageMatting:()=>x0,AutoModelForImageSegmentation:()=>p0,AutoModelForImageTextToText:()=>$0,AutoModelForImageToImage:()=>T0,AutoModelForMaskGeneration:()=>g0,AutoModelForMaskedLM:()=>l0,AutoModelForNormalEstimation:()=>P0,AutoModelForObjectDetection:()=>_0,AutoModelForPoseEstimation:()=>C0,AutoModelForQuestionAnswering:()=>u0,AutoModelForSemanticSegmentation:()=>h0,AutoModelForSeq2SeqLM:()=>s0,AutoModelForSequenceClassification:()=>t0,AutoModelForSpeechSeq2Seq:()=>n0,AutoModelForTextToSpectrogram:()=>o0,AutoModelForTextToWaveform:()=>i0,AutoModelForTokenClassification:()=>r0,AutoModelForUniversalSegmentation:()=>m0,AutoModelForVision2Seq:()=>d0,AutoModelForXVector:()=>b0,AutoModelForZeroShotObjectDetection:()=>f0,BartForConditionalGeneration:()=>jt,BartForSequenceClassification:()=>kt,BartModel:()=>Pt,BartPretrainedModel:()=>xt,BaseModelOutput:()=>xe,BeitForImageClassification:()=>Rw,BeitModel:()=>Bw,BeitPreTrainedModel:()=>Ou,BertForMaskedLM:()=>Ae,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Fe,BertForTokenClassification:()=>ze,BertModel:()=>Se,BertPreTrainedModel:()=>be,BlenderbotForConditionalGeneration:()=>rr,BlenderbotModel:()=>Dt,BlenderbotPreTrainedModel:()=>Xr,BlenderbotSmallForConditionalGeneration:()=>Rr,BlenderbotSmallModel:()=>Qr,BlenderbotSmallPreTrainedModel:()=>wr,BloomForCausalLM:()=>aw,BloomModel:()=>iw,BloomPreTrainedModel:()=>vu,CLIPModel:()=>Ni,CLIPPreTrainedModel:()=>Fs,CLIPSegForImageSegmentation:()=>Bo,CLIPSegModel:()=>zo,CLIPSegPreTrainedModel:()=>Xn,CLIPTextModel:()=>pu,CLIPTextModelWithProjection:()=>Vi,CLIPVisionModel:()=>hu,CLIPVisionModelWithProjection:()=>Ui,CamembertForMaskedLM:()=>Ft,CamembertForQuestionAnswering:()=>ys,CamembertForSequenceClassification:()=>ds,CamembertForTokenClassification:()=>cs,CamembertModel:()=>bs,CamembertPreTrainedModel:()=>Ar,CausalLMOutput:()=>In,CausalLMOutputWithPast:()=>Wx,ChineseCLIPModel:()=>Gi,ChineseCLIPPreTrainedModel:()=>Wi,ClapAudioModelWithProjection:()=>zb,ClapModel:()=>Db,ClapPreTrainedModel:()=>ta,ClapTextModelWithProjection:()=>Lb,CodeGenForCausalLM:()=>$n,CodeGenModel:()=>Ko,CodeGenPreTrainedModel:()=>eo,CohereForCausalLM:()=>Ug,CohereModel:()=>Vg,CoherePreTrainedModel:()=>mu,ConvBertForMaskedLM:()=>Ot,ConvBertForQuestionAnswering:()=>Ms,ConvBertForSequenceClassification:()=>ur,ConvBertForTokenClassification:()=>ls,ConvBertModel:()=>Gt,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>IM,ConvNextModel:()=>kM,ConvNextPreTrainedModel:()=>qu,ConvNextV2ForImageClassification:()=>FM,ConvNextV2Model:()=>AM,ConvNextV2PreTrainedModel:()=>Xu,DPTForDepthEstimation:()=>pM,DPTModel:()=>cM,DPTPreTrainedModel:()=>Gu,DacDecoderModel:()=>Ey,DacDecoderOutput:()=>vy,DacEncoderModel:()=>Ty,DacEncoderOutput:()=>yy,DacModel:()=>xy,DacPreTrainedModel:()=>la,DebertaForMaskedLM:()=>Qe,DebertaForQuestionAnswering:()=>zr,DebertaForSequenceClassification:()=>tt,DebertaForTokenClassification:()=>Rt,DebertaModel:()=>De,DebertaPreTrainedModel:()=>Qt,DebertaV2ForMaskedLM:()=>hs,DebertaV2ForQuestionAnswering:()=>_s,DebertaV2ForSequenceClassification:()=>Kr,DebertaV2ForTokenClassification:()=>ms,DebertaV2Model:()=>ps,DebertaV2PreTrainedModel:()=>Sr,DecisionTransformerModel:()=>ny,DecisionTransformerPreTrainedModel:()=>sy,DeiTForImageClassification:()=>tM,DeiTModel:()=>eM,DeiTPreTrainedModel:()=>Nu,DepthAnythingForDepthEstimation:()=>mM,DepthAnythingPreTrainedModel:()=>hM,DepthProForDepthEstimation:()=>MM,DepthProPreTrainedModel:()=>wM,DetrForObjectDetection:()=>Nw,DetrForSegmentation:()=>Du,DetrModel:()=>jw,DetrObjectDetectionOutput:()=>Lu,DetrPreTrainedModel:()=>qi,DetrSegmentationOutput:()=>Vw,Dinov2ForImageClassification:()=>DM,Dinov2Model:()=>OM,Dinov2PreTrainedModel:()=>Qu,Dinov2WithRegistersForImageClassification:()=>zM,Dinov2WithRegistersModel:()=>LM,Dinov2WithRegistersPreTrainedModel:()=>Ju,DistilBertForMaskedLM:()=>ks,DistilBertForQuestionAnswering:()=>$s,DistilBertForSequenceClassification:()=>cn,DistilBertForTokenClassification:()=>xr,DistilBertModel:()=>vr,DistilBertPreTrainedModel:()=>Hr,DonutSwinModel:()=>$M,DonutSwinPreTrainedModel:()=>SM,EfficientNetForImageClassification:()=>Wb,EfficientNetModel:()=>Ub,EfficientNetPreTrainedModel:()=>ad,ElectraForMaskedLM:()=>Ss,ElectraForQuestionAnswering:()=>us,ElectraForSequenceClassification:()=>Ns,ElectraForTokenClassification:()=>at,ElectraModel:()=>js,ElectraPreTrainedModel:()=>Ir,EsmForMaskedLM:()=>pn,EsmForSequenceClassification:()=>Fr,EsmForTokenClassification:()=>hn,EsmModel:()=>Vs,EsmPreTrainedModel:()=>fr,ExaoneForCausalLM:()=>L,ExaoneModel:()=>I,ExaonePreTrainedModel:()=>x,FalconForCausalLM:()=>Ob,FalconModel:()=>Fb,FalconPreTrainedModel:()=>nd,FastViTForImageClassification:()=>Cw,FastViTModel:()=>Pw,FastViTPreTrainedModel:()=>$u,Florence2ForConditionalGeneration:()=>Io,Florence2PreTrainedModel:()=>Li,GLPNForDepthEstimation:()=>CM,GLPNModel:()=>PM,GLPNPreTrainedModel:()=>Hu,GPT2LMHeadModel:()=>Ro,GPT2Model:()=>Ki,GPT2PreTrainedModel:()=>Qn,GPTBigCodeForCausalLM:()=>Go,GPTBigCodeModel:()=>Zn,GPTBigCodePreTrainedModel:()=>Yn,GPTJForCausalLM:()=>Wo,GPTJModel:()=>Uo,GPTJPreTrainedModel:()=>Sn,GPTNeoForCausalLM:()=>Vo,GPTNeoModel:()=>No,GPTNeoPreTrainedModel:()=>jo,GPTNeoXForCausalLM:()=>Cn,GPTNeoXModel:()=>Nr,GPTNeoXPreTrainedModel:()=>Xs,Gemma2ForCausalLM:()=>Hg,Gemma2Model:()=>Kg,Gemma2PreTrainedModel:()=>fu,Gemma3ForCausalLM:()=>Xg,Gemma3Model:()=>qg,Gemma3PreTrainedModel:()=>gu,GemmaForCausalLM:()=>Gg,GemmaModel:()=>Wg,GemmaPreTrainedModel:()=>_u,GlmForCausalLM:()=>h,GlmModel:()=>Qo,GlmPreTrainedModel:()=>so,GraniteForCausalLM:()=>Hi,GraniteModel:()=>Os,GranitePreTrainedModel:()=>sr,GroundingDinoForObjectDetection:()=>RM,GroundingDinoPreTrainedModel:()=>BM,GroupViTModel:()=>Ew,GroupViTPreTrainedModel:()=>Tw,HeliumForCausalLM:()=>Xo,HeliumModel:()=>qo,HeliumPreTrainedModel:()=>ro,HieraForImageClassification:()=>sM,HieraModel:()=>rM,HieraPreTrainedModel:()=>Vu,HubertForCTC:()=>_b,HubertForSequenceClassification:()=>fb,HubertModel:()=>mb,HubertPreTrainedModel:()=>kx,IJepaForImageClassification:()=>_w,IJepaModel:()=>mw,IJepaPreTrainedModel:()=>Pu,Idefics3ForConditionalGeneration:()=>Ks,Idefics3PreTrainedModel:()=>Ri,ImageMattingOutput:()=>A0,JAISLMHeadModel:()=>nt,JAISModel:()=>Pn,JAISPreTrainedModel:()=>Jn,JinaCLIPModel:()=>qn,JinaCLIPPreTrainedModel:()=>qs,JinaCLIPTextModel:()=>Do,JinaCLIPVisionModel:()=>Lo,LiteWhisperForConditionalGeneration:()=>Fi,LlamaForCausalLM:()=>Ho,LlamaModel:()=>to,LlamaPreTrainedModel:()=>kn,LlavaForConditionalGeneration:()=>Tn,LlavaOnevisionForConditionalGeneration:()=>ko,LlavaPreTrainedModel:()=>Di,LongT5ForConditionalGeneration:()=>He,LongT5Model:()=>je,LongT5PreTrainedModel:()=>ve,M2M100ForConditionalGeneration:()=>XM,M2M100Model:()=>qM,M2M100PreTrainedModel:()=>ed,MBartForCausalLM:()=>Nt,MBartForConditionalGeneration:()=>cr,MBartForSequenceClassification:()=>pr,MBartModel:()=>br,MBartPreTrainedModel:()=>Ht,MPNetForMaskedLM:()=>_n,MPNetForQuestionAnswering:()=>wn,MPNetForSequenceClassification:()=>fn,MPNetForTokenClassification:()=>gn,MPNetModel:()=>mn,MPNetPreTrainedModel:()=>Br,MT5ForConditionalGeneration:()=>dt,MT5Model:()=>Je,MT5PreTrainedModel:()=>We,MarianMTModel:()=>HM,MarianModel:()=>KM,MarianPreTrainedModel:()=>Zu,MaskFormerForInstanceSegmentation:()=>EM,MaskFormerModel:()=>TM,MaskFormerPreTrainedModel:()=>Ku,MaskedLMOutput:()=>Mr,Metric3DForDepthEstimation:()=>yM,Metric3DPreTrainedModel:()=>bM,Metric3Dv2ForDepthEstimation:()=>xM,Metric3Dv2PreTrainedModel:()=>vM,MgpstrForSceneTextRecognition:()=>uy,MgpstrModelOutput:()=>ay,MgpstrPreTrainedModel:()=>ly,MimiDecoderModel:()=>by,MimiDecoderOutput:()=>gy,MimiEncoderModel:()=>My,MimiEncoderOutput:()=>fy,MimiModel:()=>wy,MimiPreTrainedModel:()=>aa,MistralForCausalLM:()=>kb,MistralModel:()=>$b,MistralPreTrainedModel:()=>rd,MobileBertForMaskedLM:()=>Is,MobileBertForQuestionAnswering:()=>gr,MobileBertForSequenceClassification:()=>dr,MobileBertModel:()=>Tr,MobileBertPreTrainedModel:()=>qr,MobileLLMForCausalLM:()=>Te,MobileLLMModel:()=>ue,MobileLLMPreTrainedModel:()=>U,MobileNetV1ForImageClassification:()=>Kb,MobileNetV1ForSemanticSegmentation:()=>Hb,MobileNetV1Model:()=>Gb,MobileNetV1PreTrainedModel:()=>sa,MobileNetV2ForImageClassification:()=>Xb,MobileNetV2ForSemanticSegmentation:()=>Qb,MobileNetV2Model:()=>qb,MobileNetV2PreTrainedModel:()=>na,MobileNetV3ForImageClassification:()=>Yb,MobileNetV3ForSemanticSegmentation:()=>Zb,MobileNetV3Model:()=>Jb,MobileNetV3PreTrainedModel:()=>oa,MobileNetV4ForImageClassification:()=>ty,MobileNetV4ForSemanticSegmentation:()=>ry,MobileNetV4Model:()=>ey,MobileNetV4PreTrainedModel:()=>ia,MobileViTForImageClassification:()=>Iw,MobileViTModel:()=>kw,MobileViTPreTrainedModel:()=>ku,MobileViTV2ForImageClassification:()=>Fw,MobileViTV2Model:()=>Aw,MobileViTV2PreTrainedModel:()=>Iu,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>J,ModernBertForTokenClassification:()=>le,ModernBertModel:()=>Y,ModernBertPreTrainedModel:()=>O,Moondream1ForConditionalGeneration:()=>Gs,MoonshineForConditionalGeneration:()=>So,MoonshineModel:()=>Oi,MoonshinePreTrainedModel:()=>Kn,MptForCausalLM:()=>uw,MptModel:()=>lw,MptPreTrainedModel:()=>xu,MultiModalityCausalLM:()=>iy,MultiModalityPreTrainedModel:()=>oy,MusicgenForCausalLM:()=>Ox,MusicgenForConditionalGeneration:()=>ud,MusicgenModel:()=>Fx,MusicgenPreTrainedModel:()=>ld,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>ye,OPTForCausalLM:()=>cw,OPTModel:()=>dw,OPTPreTrainedModel:()=>Tu,Olmo2ForCausalLM:()=>It,Olmo2Model:()=>Tt,Olmo2PreTrainedModel:()=>ht,OlmoForCausalLM:()=>Ze,OlmoModel:()=>Ke,OlmoPreTrainedModel:()=>Oe,OpenELMForCausalLM:()=>Jg,OpenELMModel:()=>Qg,OpenELMPreTrainedModel:()=>wu,OwlViTForObjectDetection:()=>Dw,OwlViTModel:()=>Ow,OwlViTPreTrainedModel:()=>Au,Owlv2ForObjectDetection:()=>zw,Owlv2Model:()=>Lw,Owlv2PreTrainedModel:()=>Fu,PaliGemmaForConditionalGeneration:()=>Bi,PaliGemmaPreTrainedModel:()=>zi,PatchTSMixerForPrediction:()=>hy,PatchTSMixerModel:()=>py,PatchTSMixerPreTrainedModel:()=>cd,PatchTSTForPrediction:()=>cy,PatchTSTModel:()=>dy,PatchTSTPreTrainedModel:()=>dd,Phi3ForCausalLM:()=>ow,Phi3Model:()=>nw,Phi3PreTrainedModel:()=>yu,Phi3VForCausalLM:()=>Ao,Phi3VPreTrainedModel:()=>ji,PhiForCausalLM:()=>sw,PhiModel:()=>rw,PhiPreTrainedModel:()=>bu,PreTrainedModel:()=>R,PretrainedMixin:()=>Ct,PvtForImageClassification:()=>Mw,PvtModel:()=>ww,PvtPreTrainedModel:()=>Cu,PyAnnoteForAudioFrameClassification:()=>tb,PyAnnoteModel:()=>eb,PyAnnotePreTrainedModel:()=>td,QuestionAnsweringModelOutput:()=>Er,Qwen2ForCausalLM:()=>Zg,Qwen2Model:()=>Yg,Qwen2PreTrainedModel:()=>Mu,Qwen2VLForConditionalGeneration:()=>tw,Qwen2VLPreTrainedModel:()=>ew,RFDetrForObjectDetection:()=>Xw,RFDetrModel:()=>qw,RFDetrObjectDetectionOutput:()=>Qw,RFDetrPreTrainedModel:()=>Ru,RTDetrForObjectDetection:()=>Ww,RTDetrModel:()=>Uw,RTDetrObjectDetectionOutput:()=>Xi,RTDetrPreTrainedModel:()=>zu,RTDetrV2ForObjectDetection:()=>Kw,RTDetrV2Model:()=>Gw,RTDetrV2ObjectDetectionOutput:()=>Hw,RTDetrV2PreTrainedModel:()=>Bu,ResNetForImageClassification:()=>oM,ResNetModel:()=>nM,ResNetPreTrainedModel:()=>Uu,RoFormerForMaskedLM:()=>Re,RoFormerForQuestionAnswering:()=>lt,RoFormerForSequenceClassification:()=>Xe,RoFormerForTokenClassification:()=>Ge,RoFormerModel:()=>Ie,RoFormerPreTrainedModel:()=>ke,RobertaForMaskedLM:()=>or,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Vt,RobertaForTokenClassification:()=>Zt,RobertaModel:()=>jr,RobertaPreTrainedModel:()=>Yt,SamImageSegmentationOutput:()=>GM,SamModel:()=>WM,SamPreTrainedModel:()=>UM,SapiensForDepthEstimation:()=>fM,SapiensForNormalEstimation:()=>gM,SapiensForSemanticSegmentation:()=>_M,SapiensPreTrainedModel:()=>Ji,SegformerForImageClassification:()=>Rb,SegformerForSemanticSegmentation:()=>jb,SegformerModel:()=>Ax,SegformerPreTrainedModel:()=>ra,Seq2SeqLMOutput:()=>Ux,SequenceClassifierOutput:()=>_t,SiglipModel:()=>En,SiglipPreTrainedModel:()=>Fo,SiglipTextModel:()=>Hs,SiglipVisionModel:()=>Oo,SmolVLMForConditionalGeneration:()=>Hn,SnacDecoderModel:()=>Sy,SnacEncoderModel:()=>Cy,SnacModel:()=>Py,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>Tb,SpeechT5ForTextToSpeech:()=>Eb,SpeechT5HifiGan:()=>Pb,SpeechT5Model:()=>Ix,SpeechT5PreTrainedModel:()=>ea,SqueezeBertForMaskedLM:()=>Us,SqueezeBertForQuestionAnswering:()=>yn,SqueezeBertForSequenceClassification:()=>bn,SqueezeBertModel:()=>Mn,SqueezeBertPreTrainedModel:()=>vs,StableLmForCausalLM:()=>Vb,StableLmModel:()=>Nb,StableLmPreTrainedModel:()=>id,Starcoder2ForCausalLM:()=>Ab,Starcoder2Model:()=>Ib,Starcoder2PreTrainedModel:()=>sd,StyleTextToSpeech2Model:()=>xb,StyleTextToSpeech2PreTrainedModel:()=>vb,Swin2SRForImageSuperResolution:()=>dM,Swin2SRModel:()=>uM,Swin2SRPreTrainedModel:()=>Wu,SwinForImageClassification:()=>aM,SwinForSemanticSegmentation:()=>lM,SwinModel:()=>iM,SwinPreTrainedModel:()=>Qi,T5ForConditionalGeneration:()=>de,T5Model:()=>ie,T5PreTrainedModel:()=>Q,TableTransformerForObjectDetection:()=>Yw,TableTransformerModel:()=>Jw,TableTransformerObjectDetectionOutput:()=>Zw,TableTransformerPreTrainedModel:()=>ju,TokenClassifierOutput:()=>hr,TrOCRForCausalLM:()=>Sb,TrOCRPreTrainedModel:()=>Cb,UltravoxModel:()=>_y,UltravoxPreTrainedModel:()=>my,UniSpeechForCTC:()=>ob,UniSpeechForSequenceClassification:()=>ib,UniSpeechModel:()=>nb,UniSpeechPreTrainedModel:()=>Yi,UniSpeechSatForAudioFrameClassification:()=>db,UniSpeechSatForCTC:()=>lb,UniSpeechSatForSequenceClassification:()=>ub,UniSpeechSatModel:()=>ab,UniSpeechSatPreTrainedModel:()=>Jo,ViTForImageClassification:()=>hw,ViTMAEModel:()=>yw,ViTMAEPreTrainedModel:()=>bw,ViTMSNForImageClassification:()=>xw,ViTMSNModel:()=>vw,ViTMSNPreTrainedModel:()=>Su,ViTModel:()=>pw,ViTPreTrainedModel:()=>Eu,VisionEncoderDecoderModel:()=>$o,VitMatteForImageMatting:()=>$w,VitMattePreTrainedModel:()=>Sw,VitPoseForPoseEstimation:()=>gw,VitPosePreTrainedModel:()=>fw,VitsModel:()=>od,VitsModelOutput:()=>F0,VitsPreTrainedModel:()=>Bb,Wav2Vec2BertForCTC:()=>pb,Wav2Vec2BertForSequenceClassification:()=>hb,Wav2Vec2BertModel:()=>cb,Wav2Vec2BertPreTrainedModel:()=>Zi,Wav2Vec2ForAudioFrameClassification:()=>ZM,Wav2Vec2ForCTC:()=>JM,Wav2Vec2ForSequenceClassification:()=>YM,Wav2Vec2Model:()=>QM,Wav2Vec2PreTrainedModel:()=>Qs,WavLMForAudioFrameClassification:()=>yb,WavLMForCTC:()=>wb,WavLMForSequenceClassification:()=>Mb,WavLMForXVector:()=>bb,WavLMModel:()=>gb,WavLMPreTrainedModel:()=>no,WeSpeakerResNetModel:()=>sb,WeSpeakerResNetPreTrainedModel:()=>rb,WhisperForConditionalGeneration:()=>Co,WhisperModel:()=>Ai,WhisperPreTrainedModel:()=>Po,XLMForQuestionAnswering:()=>Ti,XLMForSequenceClassification:()=>vi,XLMForTokenClassification:()=>xi,XLMModel:()=>Ws,XLMPreTrainedModel:()=>tr,XLMRobertaForMaskedLM:()=>Pi,XLMRobertaForQuestionAnswering:()=>$i,XLMRobertaForSequenceClassification:()=>Ci,XLMRobertaForTokenClassification:()=>Si,XLMRobertaModel:()=>Ei,XLMRobertaPreTrainedModel:()=>As,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>I0,YolosForObjectDetection:()=>NM,YolosModel:()=>jM,YolosObjectDetectionOutput:()=>VM,YolosPreTrainedModel:()=>Yu});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),c=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),T=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),g=t("./src/models/whisper/generation_whisper.js"),S=t("./src/models/whisper/common_whisper.js");const E={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},y=new Map,M=new Map,v=new Map;async function C(b,P,D){var mr;let ne=((mr=D.config)==null?void 0:mr["transformers.js_config"])??{},ge=D.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const fe=ge??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ce=(0,o.deviceToExecutionProviders)(fe),Le=ne.device_config??{};Le.hasOwnProperty(fe)&&(ne={...ne,...Le[fe]});let Ne=D.dtype??ne.dtype;if(typeof Ne!="string"&&(Ne&&Ne.hasOwnProperty(P)?Ne=Ne[P]:(Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[fe]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${Ne}) for this device (${fe}).`))),Ne===n.DATA_TYPES.auto){let bt=ne.dtype;typeof bt!="string"&&(bt=bt==null?void 0:bt[P]),bt&&bt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(bt)?Ne=bt:Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[fe]??n.DATA_TYPES.fp32}const qe=Ne;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(qe)){if(qe===n.DATA_TYPES.fp16&&fe==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${fe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${qe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const it=ne.kv_cache_dtype,pt=it?typeof it=="string"?it:it[qe]??"float32":void 0;if(pt&&!["float32","float16"].includes(pt))throw new Error(`Invalid kv_cache_dtype: ${pt}. Should be one of: float32, float16`);const ot={dtype:qe,kv_cache_dtype:pt},Mt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[qe],ct=`${P}${Mt}.onnx`,gt=`${D.subfolder??""}/${ct}`,rt={...D.session_options};rt.executionProviders??(rt.executionProviders=Ce);const yt=ne.free_dimension_overrides;yt?rt.freeDimensionOverrides??(rt.freeDimensionOverrides=yt):fe.startsWith("webnn")&&!rt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${fe}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Lt=w.apis.IS_NODE_ENV&&w.env.useFSCache,Ut=(0,l.getModelFile)(b,gt,!0,D,Lt),Jt=D.use_external_data_format??ne.use_external_data_format;let qt=[];if(Jt){let bt;typeof Jt=="object"?Jt.hasOwnProperty(ct)?bt=Jt[ct]:Jt.hasOwnProperty(P)?bt=Jt[P]:bt=!1:bt=Jt;const ir=+bt;if(ir>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${ir}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Vr=0;Vr{const Fn=await(0,l.getModelFile)(b,$r,!0,D,Lt);Jr(Fn instanceof Uint8Array?{path:An,data:Fn}:An)}))}}else rt.externalData!==void 0&&(qt=rt.externalData.map(async bt=>{if(typeof bt.data=="string"){const ir=await(0,l.getModelFile)(b,bt.data,!0,D);return{...bt,data:ir}}return bt}));if(qt.length>0){const bt=await Promise.all(qt);w.apis.IS_NODE_ENV||(rt.externalData=bt)}if(fe==="webgpu"){const bt=(0,s.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(bt).length>0&&!(0,o.isONNXProxy)()){const ir={};for(const Vr in bt)ir[Vr]="gpu-buffer";rt.preferredOutputLocation=ir}}return{buffer_or_path:await Ut,session_options:rt,session_config:ot}}async function A(b,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:fe,session_config:Ce}=await C(b,P[ne],D),Le=await(0,o.createInferenceSession)(ge,fe,Ce);return[ne,Le]})))}async function B(b,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(b,P[ne],!1,D);return[ne,ge]})))}function K(b,P){const D=Object.create(null),ne=[];for(const Ce of b.inputNames){const Le=P[Ce];if(!(Le instanceof c.Tensor)){ne.push(Ce);continue}D[Ce]=(0,o.isONNXProxy)()?Le.clone():Le}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,fe=b.inputNames.length;if(ge>fe){let Ce=Object.keys(P).filter(Le=>!b.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${ge} > ${fe}). The following inputs will be ignored: "${Ce.join(", ")}".`)}return D}async function G(b,P){const D=K(b,P);try{const ne=Object.fromEntries(Object.entries(D).map(([fe,Ce])=>[fe,Ce.ort_tensor]));let ge=await b.run(ne);return ge=j(ge),ge}catch(ne){const ge=Object.fromEntries(Object.entries(D).map(([fe,{type:Ce,dims:Le,data:Ne}])=>[fe,{type:Ce,dims:Le,data:Ne}]));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function j(b){for(let P in b)(0,o.isONNXTensor)(b[P])?b[P]=new c.Tensor(b[P]):typeof b[P]=="object"&&j(b[P]);return b}function ee(b){if(b instanceof c.Tensor)return b;if(b.length===0)throw Error("items must be non-empty");if(Array.isArray(b[0])){if(b.some(P=>P.length!==b[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 c.Tensor("int64",BigInt64Array.from(b.flat().map(P=>BigInt(P))),[b.length,b[0].length])}else return new c.Tensor("int64",BigInt64Array.from(b.map(P=>BigInt(P))),[1,b.length])}function H(b){return new c.Tensor("bool",[b],[1])}async function Z(b,P){let{encoder_outputs:D,input_ids:ne,decoder_input_ids:ge,...fe}=P;if(!D){const Le=(0,a.pick)(P,b.sessions.model.inputNames);D=(await X(b,Le)).last_hidden_state}return fe.input_ids=ge,fe.encoder_hidden_states=D,b.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(fe.encoder_attention_mask=P.attention_mask),await me(b,fe,!0)}async function X(b,P){const D=b.sessions.model,ne=(0,a.pick)(P,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await b.encode_text({input_ids:P.input_ids})}if(D.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,c.zeros_like)(ne.input_ids)}if(D.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=ne.pixel_values.dims;ne.pixel_mask=(0,c.ones)([ge[0],ge[2],ge[3]])}return await G(D,ne)}async function oe(b,P){const D=await b.encode(P);return await b.decode(D)}async function me(b,P,D=!1){const ne=b.sessions[D?"decoder_model_merged":"model"],{past_key_values:ge,...fe}=P;if(ne.inputNames.includes("use_cache_branch")&&(fe.use_cache_branch=H(!!ge)),ne.inputNames.includes("position_ids")&&fe.attention_mask&&!fe.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(b.config.model_type)?1:0;fe.position_ids=ce(fe,ge,Le)}b.addPastKeyValues(fe,ge);const Ce=(0,a.pick)(fe,ne.inputNames);return await G(ne,Ce)}function ae({modality_token_id:b,inputs_embeds:P,modality_features:D,input_ids:ne,attention_mask:ge}){const fe=ne.tolist().map(qe=>qe.reduce((it,pt,ot)=>(pt==b&&it.push(ot),it),[])),Ce=fe.reduce((qe,it)=>qe+it.length,0),Le=D.dims[0];if(Ce!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ce}, features ${Le}`);let Ne=0;for(let qe=0;qefe.dims[1])){if(geLe==b.config.image_token_index)){const Le=b.config.num_image_tokens;if(!Le)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ne=fe.dims[1]-(ge-Le);D.input_ids=fe.slice(null,[-Ne,null]),D.attention_mask=(0,c.ones)([1,ge+Ne])}}}return D}function Ue(b,P,D,ne){return D.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...D,decoder_input_ids:ee(P)}}function we(b,...P){return b.config.is_encoder_decoder?Ue(b,...P):$e(b,...P)}function q(b,P,D,ne){const ge=!!D.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?D.input_ids=(0,c.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,c.cat)([D.input_ids,(0,c.full_like)(D.input_ids,BigInt(ne.pad_token_id))],0),D.attention_mask=(0,c.cat)([D.attention_mask,(0,c.full_like)(D.attention_mask,0n)],0))),(ge||!D.pixel_values)&&(D.pixel_values=(0,c.full)([0,0,3,384,384],1)),ge&&(D.images_seq_mask=new c.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new c.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class R extends i.Callable{constructor(D,ne,ge){super();te(this,"main_input_name","input_ids");te(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=ne,this.configs=ge;const fe=v.get(this.constructor),Ce=y.get(fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ce){case E.DecoderOnly:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=$e;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=Ue;break;case E.EncoderDecoder:this._forward=Z;break;case E.ImageTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=we;break;case E.AudioTextToText:this.can_generate=!0,this._forward=re,this._prepare_inputs_for_generation=we;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=we;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=q;break;case E.AutoEncoder:this._forward=oe;break;default:this._forward=X;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const D=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&D.push(ge.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:ne=null,config:ge=null,cache_dir:fe=null,local_files_only:Ce=!1,revision:Le="main",model_file_name:Ne=null,subfolder:qe="onnx",device:it=null,dtype:pt=null,use_external_data_format:ot=null,session_options:Mt={}}={}){let ct={progress_callback:ne,config:ge,cache_dir:fe,local_files_only:Ce,revision:Le,model_file_name:Ne,subfolder:qe,device:it,dtype:pt,use_external_data_format:ot,session_options:Mt};const gt=v.get(this),rt=y.get(gt);ge=ct.config=await s.AutoConfig.from_pretrained(D,ct);let yt;if(rt===E.DecoderOnly)yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.Seq2Seq||rt===E.Vision2Seq)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.MaskGeneration)yt=await Promise.all([A(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},ct)]);else if(rt===E.EncoderDecoder)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct)]);else if(rt===E.ImageTextToText){const Lt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(Lt.model="encoder_model"),yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(rt===E.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(rt===E.Musicgen)yt=await Promise.all([A(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.MultiModality)yt=await Promise.all([A(D,{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"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.Phi3V)yt=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.AutoEncoder)yt=await Promise.all([A(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},ct)]);else{if(rt!==E.EncoderOnly){const Lt=gt??(ge==null?void 0:ge.model_type);Lt!=="custom"&&console.warn(`Model type for '${Lt}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct)])}return new this(ge,...yt)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const ne=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&ne.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&ne.push(new p.TopPLogitsWarper(D.top_p)),ne}_get_logits_processor(D,ne,ge=null){const fe=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&fe.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&fe.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&fe.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&fe.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&fe.push(new p.MinNewTokensLengthLogitsProcessor(ne,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&fe.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&fe.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ce=ne>1||D.forced_bos_token_id===null?ne:ne+1;fe.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce))}return D.guidance_scale!==null&&D.guidance_scale>1&&fe.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),ge!==null&&fe.extend(ge),fe}_prepare_generation_config(D,ne,ge=d.GenerationConfig){const fe={...this.config};for(const Le of["decoder","generator","text_config"])Le in fe&&Object.assign(fe,fe[Le]);const Ce=new ge(fe);return Object.assign(Ce,this.generation_config??{}),D&&Object.assign(Ce,D),ne&&Object.assign(Ce,(0,a.pick)(ne,Object.getOwnPropertyNames(Ce))),Ce}_get_stopping_criteria(D,ne=null){const ge=new T.StoppingCriteriaList;return D.max_length!==null&&ge.push(new T.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&ge.push(new T.EosTokenCriteria(D.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const D=[md,_d,hd,pd],ne=v.get(this.constructor),ge=new Set,fe=this.config.model_type;for(const Le of D){const Ne=Le.get(fe);Ne&&ge.add(Ne[0])}let Ce=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ce+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ce)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:ne,model_inputs:ge,is_encoder_decoder:fe}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new c.Tensor("int64",D.flat(),[D.length,1]),fe||(ge.attention_mask=(0,c.cat)([ge.attention_mask,(0,c.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:D,bos_token_id:ne,model_kwargs:ge}){const fe=(0,a.pick)(ge,this.forward_params),Ce=this.main_input_name;if(Ce in fe){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else fe[Ce]=D;return{inputs_tensor:fe[Ce],model_inputs:fe,model_input_name:Ce}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:ne,model_input_name:ge,generation_config:fe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Le,pixel_values:Ne,attention_mask:qe,...it}=ne,pt=await this._prepare_inputs_embeds(ne);ne={...it,...(0,a.pick)(pt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ce}=await X(this,ne);if(fe.guidance_scale!==null&&fe.guidance_scale>1)Ce=(0,c.cat)([Ce,(0,c.full_like)(Ce,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,c.cat)([ne.attention_mask,(0,c.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const Le=ee(ne.decoder_input_ids).dims[0];if(Le!==Ce.dims[0]){if(Ce.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ce.dims[0]}) than the decoder inputs (${Le}).`);Ce=(0,c.cat)(Array.from({length:Le},()=>Ce),0)}}return ne.encoder_outputs=Ce,ne}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:fe,bos_token_id:Ce,generation_config:Le}){let{decoder_input_ids:Ne,...qe}=ge;if(!(Ne instanceof c.Tensor)){if(Ne)Array.isArray(Ne[0])||(Ne=Array.from({length:D},()=>Ne));else if(fe??(fe=Ce),this.config.model_type==="musicgen")Ne=Array.from({length:D*this.config.decoder.num_codebooks},()=>[fe]);else if(Array.isArray(fe)){if(fe.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${fe.length}`);Ne=fe}else Ne=Array.from({length:D},()=>[fe]);Ne=ee(Ne)}return ge.decoder_attention_mask=(0,c.ones_like)(Ne),{input_ids:Ne,model_inputs:qe}}async generate({inputs:D=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:fe=null,streamer:Ce=null,...Le}){this._validate_model_class(),ne=this._prepare_generation_config(ne,Le);let{inputs_tensor:Ne,model_inputs:qe,model_input_name:it}=this._prepare_model_inputs({inputs:D,model_kwargs:Le});const pt=this.config.is_encoder_decoder;pt&&("encoder_outputs"in qe||(qe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ne,model_inputs:qe,model_input_name:it,generation_config:ne})));let ot;pt?{input_ids:ot,model_inputs:qe}=this._prepare_decoder_input_ids_for_generation({batch_size:qe[it].dims.at(0),model_input_name:it,model_kwargs:qe,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):ot=qe[it];let Mt=ot.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=Mt+ne.max_new_tokens);const ct=this._get_logits_processor(ne,Mt,ge),gt=this._get_stopping_criteria(ne,fe),rt=qe[it].dims.at(0),yt=k.LogitsSampler.getSampler(ne),Lt=new Array(rt).fill(0),Ut=ot.tolist();Ce&&Ce.put(Ut);let Jt,qt={};for(;;){if(qe=this.prepare_inputs_for_generation(Ut,qe,ne),Jt=await this.forward(qe),ne.output_attentions&&ne.return_dict_in_generate){const $r=this.getAttentions(Jt);for(const Jr in $r)Jr in qt||(qt[Jr]=[]),qt[Jr].push($r[Jr])}const bt=Jt.logits.slice(null,-1,null),ir=ct(Ut,bt),Vr=[];for(let $r=0;$r$r))break;qe=this._update_model_kwargs_for_generation({generated_input_ids:Vr,outputs:Jt,model_inputs:qe,is_encoder_decoder:pt})}Ce&&Ce.end();const nr=this.getPastKeyValues(Jt,qe.past_key_values,!0),mr=new c.Tensor("int64",Ut.flat(),[Ut.length,Ut[0].length]);if(ne.return_dict_in_generate)return{sequences:mr,past_key_values:nr,...qt};for(const bt of Object.values(Jt))bt.location==="gpu-buffer"&&bt.dispose();return mr}getPastKeyValues(D,ne,ge=!1){const fe=Object.create(null);for(const Ce in D)if(Ce.startsWith("present")){const Le=Ce.replace("present","past_key_values"),Ne=Ce.includes("encoder");if(Ne&&ne?fe[Le]=ne[Le]:fe[Le]=D[Ce],ne&&(!Ne||ge)){const qe=ne[Le];qe.location==="gpu-buffer"&&qe.dispose()}}return fe}getAttentions(D){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const fe in D)fe.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(D[fe]));return ne}addPastKeyValues(D,ne){var ge,fe,Ce;if(ne)Object.assign(D,ne);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,Ne=((ge=Le==null?void 0:Le.config)==null?void 0:ge.kv_cache_dtype)??"float32",qe=Ne==="float16"?new c.DataTypeMap.float16:[],it=((Ce=(fe=D[this.main_input_name]??D.attention_mask)==null?void 0:fe.dims)==null?void 0:Ce[0])??1,pt=(0,s.getKeyValueShapes)(this.config,{batch_size:it});for(const ot in pt)D[ot]=new c.Tensor(Ne,qe,pt[ot])}}async encode_image({pixel_values:D}){const ne=(await G(this.sessions.vision_encoder,{pixel_values:D})).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 (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:D}){return(await G(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await G(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class pe{}class xe extends pe{constructor({last_hidden_state:P,hidden_states:D=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=D,this.attentions=ne}}class be extends R{}class Se extends be{}class Ae extends be{async _call(P){return new Mr(await super._call(P))}}class Fe extends be{async _call(P){return new _t(await super._call(P))}}class ze extends be{async _call(P){return new hr(await super._call(P))}}class Ve extends be{async _call(P){return new Er(await super._call(P))}}class O extends R{}class Y extends O{}class z extends O{async _call(P){return new Mr(await super._call(P))}}class J extends O{async _call(P){return new _t(await super._call(P))}}class le extends O{async _call(P){return new hr(await super._call(P))}}class ye extends R{}class Ee extends ye{}class ke extends R{}class Ie extends ke{}class Re extends ke{async _call(P){return new Mr(await super._call(P))}}class Xe extends ke{async _call(P){return new _t(await super._call(P))}}class Ge extends ke{async _call(P){return new hr(await super._call(P))}}class lt extends ke{async _call(P){return new Er(await super._call(P))}}class wt extends R{}class Gt extends wt{}class Ot extends wt{async _call(P){return new Mr(await super._call(P))}}class ur extends wt{async _call(P){return new _t(await super._call(P))}}class ls extends wt{async _call(P){return new hr(await super._call(P))}}class Ms extends wt{async _call(P){return new Er(await super._call(P))}}class Ir extends R{}class js extends Ir{}class Ss extends Ir{async _call(P){return new Mr(await super._call(P))}}class Ns extends Ir{async _call(P){return new _t(await super._call(P))}}class at extends Ir{async _call(P){return new hr(await super._call(P))}}class us extends Ir{async _call(P){return new Er(await super._call(P))}}class Ar extends R{}class bs extends Ar{}class Ft extends Ar{async _call(P){return new Mr(await super._call(P))}}class ds extends Ar{async _call(P){return new _t(await super._call(P))}}class cs extends Ar{async _call(P){return new hr(await super._call(P))}}class ys extends Ar{async _call(P){return new Er(await super._call(P))}}class Qt extends R{}class De extends Qt{}class Qe extends Qt{async _call(P){return new Mr(await super._call(P))}}class tt extends Qt{async _call(P){return new _t(await super._call(P))}}class Rt extends Qt{async _call(P){return new hr(await super._call(P))}}class zr extends Qt{async _call(P){return new Er(await super._call(P))}}class Sr extends R{}class ps extends Sr{}class hs extends Sr{async _call(P){return new Mr(await super._call(P))}}class Kr extends Sr{async _call(P){return new _t(await super._call(P))}}class ms extends Sr{async _call(P){return new hr(await super._call(P))}}class _s extends Sr{async _call(P){return new Er(await super._call(P))}}class Hr extends R{}class vr extends Hr{}class cn extends Hr{async _call(P){return new _t(await super._call(P))}}class xr extends Hr{async _call(P){return new hr(await super._call(P))}}class $s extends Hr{async _call(P){return new Er(await super._call(P))}}class ks extends Hr{async _call(P){return new Mr(await super._call(P))}}class fr extends R{}class Vs extends fr{}class pn extends fr{async _call(P){return new Mr(await super._call(P))}}class Fr extends fr{async _call(P){return new _t(await super._call(P))}}class hn extends fr{async _call(P){return new hr(await super._call(P))}}class qr extends R{}class Tr extends qr{}class Is extends qr{async _call(P){return new Mr(await super._call(P))}}class dr extends qr{async _call(P){return new _t(await super._call(P))}}class gr extends qr{async _call(P){return new Er(await super._call(P))}}class Br extends R{}class mn extends Br{}class _n extends Br{async _call(P){return new Mr(await super._call(P))}}class fn extends Br{async _call(P){return new _t(await super._call(P))}}class gn extends Br{async _call(P){return new hr(await super._call(P))}}class wn extends Br{async _call(P){return new Er(await super._call(P))}}class vs extends R{}class Mn extends vs{}class Us extends vs{async _call(P){return new Mr(await super._call(P))}}class bn extends vs{async _call(P){return new _t(await super._call(P))}}class yn extends vs{async _call(P){return new Er(await super._call(P))}}class xs extends R{}class vn extends xs{}class he extends xs{async _call(P){return new _t(await super._call(P))}}class $ extends xs{async _call(P){return new Er(await super._call(P))}}class N extends xs{async _call(P){return new Mr(await super._call(P))}}class Q extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ie extends Q{}class de extends Q{}class ve extends R{}class je extends ve{}class He extends ve{}class We extends R{}class Je extends We{}class dt extends We{}class xt extends R{}class Pt extends xt{}class jt extends xt{}class kt extends xt{async _call(P){return new _t(await super._call(P))}}class Ht extends R{}class br extends Ht{}class cr extends Ht{}class pr extends Ht{async _call(P){return new _t(await super._call(P))}}class Nt extends Ht{}class Xr extends R{}class Dt extends Xr{}class rr extends Xr{}class wr extends R{}class Qr extends wr{}class Rr extends wr{}class Yt extends R{}class jr extends Yt{}class or extends Yt{async _call(P){return new Mr(await super._call(P))}}class Vt extends Yt{async _call(P){return new _t(await super._call(P))}}class Zt extends Yt{async _call(P){return new hr(await super._call(P))}}class er extends Yt{async _call(P){return new Er(await super._call(P))}}class tr extends R{}class Ws extends tr{}class xn extends tr{async _call(P){return new Mr(await super._call(P))}}class vi extends tr{async _call(P){return new _t(await super._call(P))}}class xi extends tr{async _call(P){return new hr(await super._call(P))}}class Ti extends tr{async _call(P){return new Er(await super._call(P))}}class As extends R{}class Ei extends As{}class Pi extends As{async _call(P){return new Mr(await super._call(P))}}class Ci extends As{async _call(P){return new _t(await super._call(P))}}class Si extends As{async _call(P){return new hr(await super._call(P))}}class $i extends As{async _call(P){return new Er(await super._call(P))}}class Eo extends R{}class ki extends Eo{}class Ii extends Eo{}class Po extends R{constructor(){super(...arguments);te(this,"requires_attention_mask",!1);te(this,"main_input_name","input_features");te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ai extends Po{}class Co extends Po{_prepare_generation_config(P,D){return super._prepare_generation_config(P,D,g.WhisperGenerationConfig)}_retrieve_init_tokens(P){const D=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ce=`<|${(0,S.whisper_language_to_code)(ne)}|>`;D.push(P.lang_to_id[Ce]),D.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)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!P.return_timestamps&&P.no_timestamps_token_id&&D.at(-1)!==P.no_timestamps_token_id?D.push(P.no_timestamps_token_id):P.return_timestamps&&D.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(fe=>fe!=null)}async generate({inputs:P=null,generation_config:D=null,logits_processor:ne=null,stopping_criteria:ge=null,...fe}){D=this._prepare_generation_config(D,fe);const Ce=fe.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(D,Ce))),D.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce.length))),D.return_token_timestamps){if(!D.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.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Le=await super.generate({inputs:P,generation_config:D,logits_processor:ne,decoder_input_ids:Ce,...fe});return D.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,D.alignment_heads,D.num_frames)),Le}_extract_token_timestamps(P,D,ne=null,ge=.02){if(!P.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`.");ne==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 fe=this.config.median_filter_width;fe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),fe=7);const Ce=P.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(gt,rt)=>(0,c.cat)(Ce.map(yt=>yt[rt]),2)),Ne=(0,c.stack)(D.map(([gt,rt])=>{if(gt>=Le.length)throw new Error(`Layer index ${gt} is out of bounds for cross attentions (length ${Le.length}).`);return ne?Le[gt].slice(null,rt,null,[0,ne]):Le[gt].slice(null,rt)})).transpose(1,0,2,3),[qe,it]=(0,c.std_mean)(Ne,-2,0,!0),pt=Ne.clone();for(let gt=0;gtyt[mr+1]-yt[mr]),Jt=(0,a.mergeArrays)([1],Ut).map(nr=>!!nr),qt=[];for(let nr=0;nrot.findIndex(Mt=>Mt==fe)),Ne=Le.every(ot=>ot===-1),qe=Le.every(ot=>ot!==-1);if(!Ne&&!qe)throw new Error("Every input should contain either 0 or 1 image token.");if(Ne)return{inputs_embeds:P,attention_mask:ge};const it=[],pt=[];for(let ot=0;otArray.from({length:P.dims[0]},Ut=>Array.from({length:P.dims[1]},Jt=>1))),ct=D?D.tolist():[],gt=ne?ne.tolist():[];let rt=0,yt=0;for(let Lt=0;Ltot[Lt][ar]==1),qt=Ut.reduce((Wt,ar,Js)=>(ar==Ne&&Wt.push(Js),Wt),[]).map(Wt=>Ut[Wt+1]),nr=qt.filter(Wt=>Wt==Ce).length,mr=qt.filter(Wt=>Wt==Le).length;let bt=[],ir=0,Vr=nr,An=mr;for(let Wt=0;Wtfs>ir&&Dn==Ce),Js=Ut.findIndex((Dn,fs)=>fs>ir&&Dn==Le),On=Vr>0&&ar!==-1?ar:Ut.length+1,io=An>0&&Js!==-1?Js:Ut.length+1;let ha,gd,wd,Md;On0?(0,_.max)(bt.at(-1))[0]+1:0;bt.push(Array.from({length:3*yd},(Dn,fs)=>O0+fs%yd));const vd=yd+O0,_a=Gx*bd*ma,Kx=Array.from({length:_a},(Dn,fs)=>vd+Math.floor(fs/(bd*ma))),Hx=Array.from({length:_a},(Dn,fs)=>vd+Math.floor(fs/ma)%bd),qx=Array.from({length:_a},(Dn,fs)=>vd+fs%ma);bt.push([Kx,Hx,qx].flat()),ir=ha+_a}if(ir0?(0,_.max)(bt.at(-1))[0]+1:0,ar=Ut.length-ir;bt.push(Array.from({length:3*ar},(Js,On)=>Wt+On%ar))}const $r=bt.reduce((Wt,ar)=>Wt+ar.length,0),Jr=new Array($r);let da=0;for(let Wt=0;Wt<3;++Wt)for(let ar=0;arpt[rt%pt.length]),ct=Array.from({length:ot[0]},(gt,rt)=>(0,_.max)(pt.subarray(ot[1]*rt,ot[1]*(rt+1)))[0]+1n+BigInt(ot[1]));return[new c.Tensor("int64",Mt,[3,...ot]),new c.Tensor("int64",ct,[ct.length,1])]}else{const[pt,ot]=P.dims,Mt=BigInt64Array.from({length:3*pt*ot},(ct,gt)=>BigInt(Math.floor(gt%ot/pt)));return[new c.Tensor("int64",Mt,[3,...P.dims]),(0,c.zeros)([pt,1])]}}async encode_image({pixel_values:P,image_grid_thw:D}){return(await G(this.sessions.vision_encoder,{pixel_values:P,grid_thw:D})).image_features}_merge_input_ids_with_image_features(P){return V({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,D,ne){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const ge=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),fe=D.rope_deltas.map(Ce=>ge+Ce);D.position_ids=(0,c.stack)([fe,fe,fe],0)}return D}}class bu extends R{}class rw extends bu{}class sw extends bu{}class yu extends R{}class nw extends yu{}class ow extends yu{}class vu extends R{}class iw extends vu{}class aw extends vu{}class xu extends R{}class lw extends xu{}class uw extends xu{}class Tu extends R{}class dw extends Tu{}class cw extends Tu{}class Eu extends R{}class pw extends Eu{}class hw extends Eu{async _call(P){return new _t(await super._call(P))}}class Pu extends R{}class mw extends Pu{}class _w extends Pu{async _call(P){return new _t(await super._call(P))}}class fw extends R{}class gw extends fw{}class Cu extends R{}class ww extends Cu{}class Mw extends Cu{async _call(P){return new _t(await super._call(P))}}class bw extends R{}class yw extends bw{}class Su extends R{}class vw extends Su{}class xw extends Su{async _call(P){return new _t(await super._call(P))}}class Tw extends R{}class Ew extends Tw{}class $u extends R{}class Pw extends $u{}class Cw extends $u{async _call(P){return new _t(await super._call(P))}}class Sw extends R{}class $w extends Sw{async _call(P){return new A0(await super._call(P))}}class ku extends R{}class kw extends ku{}class Iw extends ku{async _call(P){return new _t(await super._call(P))}}class Iu extends R{}class Aw extends Iu{}class Fw extends Iu{async _call(P){return new _t(await super._call(P))}}class Au extends R{}class Ow extends Au{}class Dw extends Au{}class Fu extends R{}class Lw extends Fu{}class zw extends Fu{}class Ou extends R{}class Bw extends Ou{}class Rw extends Ou{async _call(P){return new _t(await super._call(P))}}class qi extends R{}class jw extends qi{}class Nw extends qi{async _call(P){return new Lu(await super._call(P))}}class Du extends qi{async _call(P){return new Vw(await super._call(P))}}class Lu extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Vw extends pe{constructor({logits:P,pred_boxes:D,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=D,this.pred_masks=ne}}class zu extends R{}class Uw extends zu{}class Ww extends zu{async _call(P){return new Xi(await super._call(P))}}class Xi extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Bu extends R{}class Gw extends Bu{}class Kw extends Bu{async _call(P){return new Hw(await super._call(P))}}class Hw extends Xi{}class Ru extends R{}class qw extends Ru{}class Xw extends Ru{async _call(P){return new Qw(await super._call(P))}}class Qw extends Xi{}class ju extends R{}class Jw extends ju{}class Yw extends ju{async _call(P){return new Zw(await super._call(P))}}class Zw extends Lu{}class Nu extends R{}class eM extends Nu{}class tM extends Nu{async _call(P){return new _t(await super._call(P))}}class Vu extends R{}class rM extends Vu{}class sM extends Vu{async _call(P){return new _t(await super._call(P))}}class Uu extends R{}class nM extends Uu{}class oM extends Uu{async _call(P){return new _t(await super._call(P))}}class Qi extends R{}class iM extends Qi{}class aM extends Qi{async _call(P){return new _t(await super._call(P))}}class lM extends Qi{}class Wu extends R{}class uM extends Wu{}class dM extends Wu{}class Gu extends R{}class cM extends Gu{}class pM extends Gu{}class hM extends R{}class mM extends hM{}class Ji extends R{}class _M extends Ji{}class fM extends Ji{}class gM extends Ji{}class wM extends R{}class MM extends wM{}class bM extends R{}class yM extends bM{}class vM extends R{}class xM extends vM{}class Ku extends R{}class TM extends Ku{}class EM extends Ku{}class Hu extends R{}class PM extends Hu{}class CM extends Hu{}class SM extends R{}class $M extends SM{}class qu extends R{}class kM extends qu{}class IM extends qu{async _call(P){return new _t(await super._call(P))}}class Xu extends R{}class AM extends Xu{}class FM extends Xu{async _call(P){return new _t(await super._call(P))}}class Qu extends R{}class OM extends Qu{}class DM extends Qu{async _call(P){return new _t(await super._call(P))}}class Ju extends R{}class LM extends Ju{}class zM extends Ju{async _call(P){return new _t(await super._call(P))}}class BM extends R{}class RM extends BM{}class Yu extends R{}class jM extends Yu{}class NM extends Yu{async _call(P){return new VM(await super._call(P))}}class VM extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class UM extends R{}class WM extends UM{async get_image_embeddings({pixel_values:P}){return await X(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((fe,Ce)=>fe*Ce,1);P.input_labels=new c.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const D={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(D.input_points=P.input_points),P.input_labels&&(D.input_labels=P.input_labels),P.input_boxes&&(D.input_boxes=P.input_boxes),await G(this.sessions.prompt_encoder_mask_decoder,D)}async _call(P){return new GM(await super._call(P))}}class GM extends pe{constructor({iou_scores:P,pred_masks:D}){super(),this.iou_scores=P,this.pred_masks=D}}class Zu extends R{}class KM extends Zu{}class HM extends Zu{}class ed extends R{}class qM extends ed{}class XM extends ed{}class Qs extends R{}class QM extends Qs{}class JM extends Qs{async _call(P){return new In(await super._call(P))}}class YM extends Qs{async _call(P){return new _t(await super._call(P))}}class ZM extends Qs{async _call(P){return new hr(await super._call(P))}}class td extends R{}class eb extends td{}class tb extends td{async _call(P){return new hr(await super._call(P))}}class rb extends R{}class sb extends rb{}class Yi extends R{}class nb extends Yi{}class ob extends Yi{async _call(P){return new In(await super._call(P))}}class ib extends Yi{async _call(P){return new _t(await super._call(P))}}class Jo extends R{}class ab extends Jo{}class lb extends Jo{async _call(P){return new In(await super._call(P))}}class ub extends Jo{async _call(P){return new _t(await super._call(P))}}class db extends Jo{async _call(P){return new hr(await super._call(P))}}class Zi extends R{}class cb extends Zi{}class pb extends Zi{async _call(P){return new In(await super._call(P))}}class hb extends Zi{async _call(P){return new _t(await super._call(P))}}class kx extends R{}class mb extends Qs{}class _b extends Qs{async _call(P){return new In(await super._call(P))}}class fb extends Qs{async _call(P){return new _t(await super._call(P))}}class no extends R{}class gb extends no{}class wb extends no{async _call(P){return new In(await super._call(P))}}class Mb extends no{async _call(P){return new _t(await super._call(P))}}class bb extends no{async _call(P){return new I0(await super._call(P))}}class yb extends no{async _call(P){return new hr(await super._call(P))}}class vb extends R{}class xb extends vb{}class ea extends R{}class Ix extends ea{}class Tb extends ea{}class Eb extends ea{async generate_speech(P,D,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:fe=20,vocoder:Ce=null}={}){const Le={input_ids:P},{encoder_outputs:Ne,encoder_attention_mask:qe}=await X(this,Le),it=Ne.dims[1]/this.config.reduction_factor,pt=Math.floor(it*fe),ot=Math.floor(it*ge),Mt=this.config.num_mel_bins;let ct=[],gt=null,rt=null,yt=0;for(;;){++yt;const Jt=H(!!rt);let qt;rt?qt=rt.output_sequence_out:qt=new c.Tensor("float32",new Float32Array(Mt),[1,1,Mt]);let nr={use_cache_branch:Jt,output_sequence:qt,encoder_attention_mask:qe,speaker_embeddings:D,encoder_hidden_states:Ne};this.addPastKeyValues(nr,gt),rt=await G(this.sessions.decoder_model_merged,nr),gt=this.getPastKeyValues(rt,gt);const{prob:mr,spectrum:bt}=rt;if(ct.push(bt),yt>=ot&&(Array.from(mr.data).filter(ir=>ir>=ne).length>0||yt>=pt))break}const Lt=(0,c.cat)(ct),{waveform:Ut}=await G(Ce.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Ut}}}class Pb extends R{constructor(){super(...arguments);te(this,"main_input_name","spectrogram")}}class Cb extends R{}class Sb extends Cb{}class rd extends R{}class $b extends rd{}class kb extends rd{}class sd extends R{}class Ib extends sd{}class Ab extends sd{}class nd extends R{}class Fb extends nd{}class Ob extends nd{}class ta extends R{}class Db extends ta{}class Lb extends ta{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"text_model"})}}class zb extends ta{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"audio_model"})}}class Bb extends R{}class od extends Bb{async _call(P){return new F0(await super._call(P))}}class ra extends R{}class Ax extends ra{}class Rb extends ra{}class jb extends ra{}class id extends R{}class Nb extends id{}class Vb extends id{}class ad extends R{}class Ub extends ad{}class Wb extends ad{async _call(P){return new _t(await super._call(P))}}class ld extends R{}class Fx extends ld{}class Ox extends ld{}class ud extends R{constructor(){super(...arguments);te(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(D){const[ne,ge]=D.dims,fe=this.config.decoder.num_codebooks,Ce=ge-fe;let Le=0;for(let it=0;it0&&Mt<=Ce&&(D.data[Le++]=D.data[it])}const Ne=Math.floor(ne/fe),qe=Le/(Ne*fe);return new c.Tensor(D.type,D.data.slice(0,Le),[Ne,fe,qe])}prepare_inputs_for_generation(D,ne,ge){let fe=structuredClone(D);for(let Le=0;Le=Ne&&(fe[Le][Ne]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(fe=fe.concat(fe)),super.prepare_inputs_for_generation(fe,ne,ge)}async generate(D){const ne=await super.generate(D),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:fe}=await G(this.sessions.encodec_decode,{audio_codes:ge});return fe}}class sa extends R{}class Gb extends sa{}class Kb extends sa{async _call(P){return new _t(await super._call(P))}}class Hb extends sa{}class na extends R{}class qb extends na{}class Xb extends na{async _call(P){return new _t(await super._call(P))}}class Qb extends na{}class oa extends R{}class Jb extends oa{}class Yb extends oa{async _call(P){return new _t(await super._call(P))}}class Zb extends oa{}class ia extends R{}class ey extends ia{}class ty extends ia{async _call(P){return new _t(await super._call(P))}}class ry extends ia{}class sy extends R{}class ny extends sy{}class oy extends R{}class iy extends oy{constructor(...D){super(...D);te(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(D){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!D.past_key_values){const qe=this.sessions.prepare_inputs_embeds,it=(0,a.pick)(D,qe.inputNames);ge=await G(qe,it)}else{const qe=this.sessions.gen_img_embeds,it=(0,a.pick)({image_ids:D.input_ids},qe.inputNames);ge=await G(qe,it)}const fe={...D,...ge},Ce=await me(this,fe),Le=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!Le)throw new Error(`Unable to find "${Le}" generation head`);const Ne=await G(Le,(0,a.pick)(Ce,Le.inputNames));return{...ge,...Ce,...Ne}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const ne=(D.inputs??D[this.main_input_name]).dims[1],fe=(await super.generate(D)).slice(null,[ne,null]),Ce=this.sessions.image_decode,{decoded_image:Le}=await G(Ce,{generated_tokens:fe}),Ne=Le.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),qe=[];for(const it of Ne){const pt=f.RawImage.fromTensor(it);qe.push(pt)}return qe}}class ay extends pe{constructor({char_logits:P,bpe_logits:D,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=D,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class ly extends R{}class uy extends ly{async _call(P){return new ay(await super._call(P))}}class dd extends R{}class dy extends dd{}class cy extends dd{}class cd extends R{}class py extends cd{}class hy extends cd{}class my extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class _y extends my{_merge_input_ids_with_audio_features(P){const D=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,D);return F({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class aa extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class fy extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class gy extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class wy extends aa{async encode(P){return new fy(await G(this.sessions.encoder_model,P))}async decode(P){return new gy(await G(this.sessions.decoder_model,P))}}class My extends aa{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class by extends aa{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class la extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class yy extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class vy extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class xy extends la{async encode(P){return new yy(await G(this.sessions.encoder_model,P))}async decode(P){return new vy(await G(this.sessions.decoder_model,P))}}class Ty extends la{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Ey extends la{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ua extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class Py extends ua{async encode(P){return await G(this.sessions.encoder_model,P)}async decode(P){return await G(this.sessions.decoder_model,P)}}class Cy extends ua{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Sy extends ua{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class Ct{static async from_pretrained(P,{progress_callback:D=null,config:ne=null,cache_dir:ge=null,local_files_only:fe=!1,revision:Ce="main",model_file_name:Le=null,subfolder:Ne="onnx",device:qe=null,dtype:it=null,use_external_data_format:pt=null,session_options:ot={}}={}){const Mt={progress_callback:D,config:ne,cache_dir:ge,local_files_only:fe,revision:Ce,model_file_name:Le,subfolder:Ne,device:qe,dtype:it,use_external_data_format:pt,session_options:ot};if(Mt.config=await s.AutoConfig.from_pretrained(P,Mt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const ct=Mt.config.model_type;for(const gt of this.MODEL_CLASS_MAPPINGS){let rt=gt.get(ct);if(!rt){for(const yt of gt.values())if(yt[0]===ct){rt=yt;break}if(!rt)continue}return await rt[1].from_pretrained(P,Mt)}if(this.BASE_IF_FAIL)return e0.has(ct)||console.warn(`Unknown model class "${ct}", attempting to construct from base class.`),await R.from_pretrained(P,Mt);throw Error(`Unsupported model type: ${ct}`)}}te(Ct,"MODEL_CLASS_MAPPINGS",null),te(Ct,"BASE_IF_FAIL",!1);const Dx=new Map([["bert",["BertModel",Se]],["modernbert",["ModernBertModel",Y]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",Ie]],["electra",["ElectraModel",js]],["esm",["EsmModel",Vs]],["convbert",["ConvBertModel",Gt]],["camembert",["CamembertModel",bs]],["deberta",["DebertaModel",De]],["deberta-v2",["DebertaV2Model",ps]],["mpnet",["MPNetModel",mn]],["albert",["AlbertModel",vn]],["distilbert",["DistilBertModel",vr]],["roberta",["RobertaModel",jr]],["xlm",["XLMModel",Ws]],["xlm-roberta",["XLMRobertaModel",Ei]],["clap",["ClapModel",Db]],["clip",["CLIPModel",Ni]],["clipseg",["CLIPSegModel",zo]],["chinese_clip",["ChineseCLIPModel",Gi]],["siglip",["SiglipModel",En]],["jina_clip",["JinaCLIPModel",qn]],["mobilebert",["MobileBertModel",Tr]],["squeezebert",["SqueezeBertModel",Mn]],["wav2vec2",["Wav2Vec2Model",QM]],["wav2vec2-bert",["Wav2Vec2BertModel",cb]],["unispeech",["UniSpeechModel",nb]],["unispeech-sat",["UniSpeechSatModel",ab]],["hubert",["HubertModel",mb]],["wavlm",["WavLMModel",gb]],["audio-spectrogram-transformer",["ASTModel",ki]],["vits",["VitsModel",od]],["pyannote",["PyAnnoteModel",eb]],["wespeaker-resnet",["WeSpeakerResNetModel",sb]],["detr",["DetrModel",jw]],["rt_detr",["RTDetrModel",Uw]],["rt_detr_v2",["RTDetrV2Model",Gw]],["rf_detr",["RFDetrModel",qw]],["table-transformer",["TableTransformerModel",Jw]],["vit",["ViTModel",pw]],["ijepa",["IJepaModel",mw]],["pvt",["PvtModel",ww]],["vit_msn",["ViTMSNModel",vw]],["vit_mae",["ViTMAEModel",yw]],["groupvit",["GroupViTModel",Ew]],["fastvit",["FastViTModel",Pw]],["mobilevit",["MobileViTModel",kw]],["mobilevitv2",["MobileViTV2Model",Aw]],["owlvit",["OwlViTModel",Ow]],["owlv2",["Owlv2Model",Lw]],["beit",["BeitModel",Bw]],["deit",["DeiTModel",eM]],["hiera",["HieraModel",rM]],["convnext",["ConvNextModel",kM]],["convnextv2",["ConvNextV2Model",AM]],["dinov2",["Dinov2Model",OM]],["dinov2_with_registers",["Dinov2WithRegistersModel",LM]],["resnet",["ResNetModel",nM]],["swin",["SwinModel",iM]],["swin2sr",["Swin2SRModel",uM]],["donut-swin",["DonutSwinModel",$M]],["yolos",["YolosModel",jM]],["dpt",["DPTModel",cM]],["glpn",["GLPNModel",PM]],["hifigan",["SpeechT5HifiGan",Pb]],["efficientnet",["EfficientNetModel",Ub]],["decision_transformer",["DecisionTransformerModel",ny]],["patchtst",["PatchTSTForPrediction",dy]],["patchtsmixer",["PatchTSMixerForPrediction",py]],["mobilenet_v1",["MobileNetV1Model",Gb]],["mobilenet_v2",["MobileNetV2Model",qb]],["mobilenet_v3",["MobileNetV3Model",Jb]],["mobilenet_v4",["MobileNetV4Model",ey]],["maskformer",["MaskFormerModel",TM]],["mgp-str",["MgpstrForSceneTextRecognition",uy]],["style_text_to_speech_2",["StyleTextToSpeech2Model",xb]]]),Lx=new Map([["t5",["T5Model",ie]],["longt5",["LongT5Model",je]],["mt5",["MT5Model",Je]],["bart",["BartModel",Pt]],["mbart",["MBartModel",br]],["marian",["MarianModel",KM]],["whisper",["WhisperModel",Ai]],["m2m_100",["M2M100Model",qM]],["blenderbot",["BlenderbotModel",Dt]],["blenderbot-small",["BlenderbotSmallModel",Qr]]]),zx=new Map([["mimi",["MimiModel",wy]],["dac",["DacModel",xy]],["snac",["SnacModel",Py]]]),Bx=new Map([["bloom",["BloomModel",iw]],["jais",["JAISModel",Pn]],["gpt2",["GPT2Model",Ki]],["gptj",["GPTJModel",Uo]],["gpt_bigcode",["GPTBigCodeModel",Zn]],["gpt_neo",["GPTNeoModel",No]],["gpt_neox",["GPTNeoXModel",Nr]],["codegen",["CodeGenModel",Ko]],["llama",["LlamaModel",to]],["exaone",["ExaoneModel",I]],["olmo",["OlmoModel",Ke]],["olmo2",["Olmo2Model",Tt]],["mobilellm",["MobileLLMModel",ue]],["granite",["GraniteModel",Os]],["cohere",["CohereModel",Vg]],["gemma",["GemmaModel",Wg]],["gemma2",["Gemma2Model",Kg]],["gemma3_text",["Gemma3Model",qg]],["helium",["HeliumModel",qo]],["glm",["GlmModel",Qo]],["openelm",["OpenELMModel",Qg]],["qwen2",["Qwen2Model",Yg]],["phi",["PhiModel",rw]],["phi3",["Phi3Model",nw]],["mpt",["MptModel",lw]],["opt",["OPTModel",dw]],["mistral",["MistralModel",$b]],["starcoder2",["Starcoder2Model",Ib]],["falcon",["FalconModel",Fb]],["stablelm",["StableLmModel",Nb]]]),pd=new Map([["speecht5",["SpeechT5ForSpeechToText",Tb]],["whisper",["WhisperForConditionalGeneration",Co]],["lite-whisper",["LiteWhisperForConditionalGeneration",Fi]],["moonshine",["MoonshineForConditionalGeneration",So]]]),$y=new Map([["speecht5",["SpeechT5ForTextToSpeech",Eb]]]),ky=new Map([["vits",["VitsModel",od]],["musicgen",["MusicgenForConditionalGeneration",ud]]]),Iy=new Map([["bert",["BertForSequenceClassification",Fe]],["modernbert",["ModernBertForSequenceClassification",J]],["roformer",["RoFormerForSequenceClassification",Xe]],["electra",["ElectraForSequenceClassification",Ns]],["esm",["EsmForSequenceClassification",Fr]],["convbert",["ConvBertForSequenceClassification",ur]],["camembert",["CamembertForSequenceClassification",ds]],["deberta",["DebertaForSequenceClassification",tt]],["deberta-v2",["DebertaV2ForSequenceClassification",Kr]],["mpnet",["MPNetForSequenceClassification",fn]],["albert",["AlbertForSequenceClassification",he]],["distilbert",["DistilBertForSequenceClassification",cn]],["roberta",["RobertaForSequenceClassification",Vt]],["xlm",["XLMForSequenceClassification",vi]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ci]],["bart",["BartForSequenceClassification",kt]],["mbart",["MBartForSequenceClassification",pr]],["mobilebert",["MobileBertForSequenceClassification",dr]],["squeezebert",["SqueezeBertForSequenceClassification",bn]]]),Ay=new Map([["bert",["BertForTokenClassification",ze]],["modernbert",["ModernBertForTokenClassification",le]],["roformer",["RoFormerForTokenClassification",Ge]],["electra",["ElectraForTokenClassification",at]],["esm",["EsmForTokenClassification",hn]],["convbert",["ConvBertForTokenClassification",ls]],["camembert",["CamembertForTokenClassification",cs]],["deberta",["DebertaForTokenClassification",Rt]],["deberta-v2",["DebertaV2ForTokenClassification",ms]],["mpnet",["MPNetForTokenClassification",gn]],["distilbert",["DistilBertForTokenClassification",xr]],["roberta",["RobertaForTokenClassification",Zt]],["xlm",["XLMForTokenClassification",xi]],["xlm-roberta",["XLMRobertaForTokenClassification",Si]]]),hd=new Map([["t5",["T5ForConditionalGeneration",de]],["longt5",["LongT5ForConditionalGeneration",He]],["mt5",["MT5ForConditionalGeneration",dt]],["bart",["BartForConditionalGeneration",jt]],["mbart",["MBartForConditionalGeneration",cr]],["marian",["MarianMTModel",HM]],["m2m_100",["M2M100ForConditionalGeneration",XM]],["blenderbot",["BlenderbotForConditionalGeneration",rr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Rr]]]),md=new Map([["bloom",["BloomForCausalLM",aw]],["gpt2",["GPT2LMHeadModel",Ro]],["jais",["JAISLMHeadModel",nt]],["gptj",["GPTJForCausalLM",Wo]],["gpt_bigcode",["GPTBigCodeForCausalLM",Go]],["gpt_neo",["GPTNeoForCausalLM",Vo]],["gpt_neox",["GPTNeoXForCausalLM",Cn]],["codegen",["CodeGenForCausalLM",$n]],["llama",["LlamaForCausalLM",Ho]],["exaone",["ExaoneForCausalLM",L]],["olmo",["OlmoForCausalLM",Ze]],["olmo2",["Olmo2ForCausalLM",It]],["mobilellm",["MobileLLMForCausalLM",Te]],["granite",["GraniteForCausalLM",Hi]],["cohere",["CohereForCausalLM",Ug]],["gemma",["GemmaForCausalLM",Gg]],["gemma2",["Gemma2ForCausalLM",Hg]],["gemma3_text",["Gemma3ForCausalLM",Xg]],["helium",["HeliumForCausalLM",Xo]],["glm",["GlmForCausalLM",h]],["openelm",["OpenELMForCausalLM",Jg]],["qwen2",["Qwen2ForCausalLM",Zg]],["phi",["PhiForCausalLM",sw]],["phi3",["Phi3ForCausalLM",ow]],["mpt",["MptForCausalLM",uw]],["opt",["OPTForCausalLM",cw]],["mbart",["MBartForCausalLM",Nt]],["mistral",["MistralForCausalLM",kb]],["starcoder2",["Starcoder2ForCausalLM",Ab]],["falcon",["FalconForCausalLM",Ob]],["trocr",["TrOCRForCausalLM",Sb]],["stablelm",["StableLmForCausalLM",Vb]],["phi3_v",["Phi3VForCausalLM",Ao]]]),Rx=new Map([["multi_modality",["MultiModalityCausalLM",iy]]]),Fy=new Map([["bert",["BertForMaskedLM",Ae]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",Re]],["electra",["ElectraForMaskedLM",Ss]],["esm",["EsmForMaskedLM",pn]],["convbert",["ConvBertForMaskedLM",Ot]],["camembert",["CamembertForMaskedLM",Ft]],["deberta",["DebertaForMaskedLM",Qe]],["deberta-v2",["DebertaV2ForMaskedLM",hs]],["mpnet",["MPNetForMaskedLM",_n]],["albert",["AlbertForMaskedLM",N]],["distilbert",["DistilBertForMaskedLM",ks]],["roberta",["RobertaForMaskedLM",or]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",Pi]],["mobilebert",["MobileBertForMaskedLM",Is]],["squeezebert",["SqueezeBertForMaskedLM",Us]]]),Oy=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",lt]],["electra",["ElectraForQuestionAnswering",us]],["convbert",["ConvBertForQuestionAnswering",Ms]],["camembert",["CamembertForQuestionAnswering",ys]],["deberta",["DebertaForQuestionAnswering",zr]],["deberta-v2",["DebertaV2ForQuestionAnswering",_s]],["mpnet",["MPNetForQuestionAnswering",wn]],["albert",["AlbertForQuestionAnswering",$]],["distilbert",["DistilBertForQuestionAnswering",$s]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",Ti]],["xlm-roberta",["XLMRobertaForQuestionAnswering",$i]],["mobilebert",["MobileBertForQuestionAnswering",gr]],["squeezebert",["SqueezeBertForQuestionAnswering",yn]]]),_d=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]],["idefics3",["Idefics3ForConditionalGeneration",Ks]],["smolvlm",["SmolVLMForConditionalGeneration",Hn]]]),Dy=new Map([["llava",["LlavaForConditionalGeneration",Tn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",ko]],["moondream1",["Moondream1ForConditionalGeneration",Gs]],["florence2",["Florence2ForConditionalGeneration",Io]],["qwen2-vl",["Qwen2VLForConditionalGeneration",tw]],["idefics3",["Idefics3ForConditionalGeneration",Ks]],["smolvlm",["SmolVLMForConditionalGeneration",Hn]],["paligemma",["PaliGemmaForConditionalGeneration",Bi]]]),Ly=new Map([["ultravox",["UltravoxModel",_y]]]),jx=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]]]),zy=new Map([["vit",["ViTForImageClassification",hw]],["ijepa",["IJepaForImageClassification",_w]],["pvt",["PvtForImageClassification",Mw]],["vit_msn",["ViTMSNForImageClassification",xw]],["fastvit",["FastViTForImageClassification",Cw]],["mobilevit",["MobileViTForImageClassification",Iw]],["mobilevitv2",["MobileViTV2ForImageClassification",Fw]],["beit",["BeitForImageClassification",Rw]],["deit",["DeiTForImageClassification",tM]],["hiera",["HieraForImageClassification",sM]],["convnext",["ConvNextForImageClassification",IM]],["convnextv2",["ConvNextV2ForImageClassification",FM]],["dinov2",["Dinov2ForImageClassification",DM]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",zM]],["resnet",["ResNetForImageClassification",oM]],["swin",["SwinForImageClassification",aM]],["segformer",["SegformerForImageClassification",Rb]],["efficientnet",["EfficientNetForImageClassification",Wb]],["mobilenet_v1",["MobileNetV1ForImageClassification",Kb]],["mobilenet_v2",["MobileNetV2ForImageClassification",Xb]],["mobilenet_v3",["MobileNetV3ForImageClassification",Yb]],["mobilenet_v4",["MobileNetV4ForImageClassification",ty]]]),By=new Map([["detr",["DetrForObjectDetection",Nw]],["rt_detr",["RTDetrForObjectDetection",Ww]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Kw]],["rf_detr",["RFDetrForObjectDetection",Xw]],["table-transformer",["TableTransformerForObjectDetection",Yw]],["yolos",["YolosForObjectDetection",NM]]]),Ry=new Map([["owlvit",["OwlViTForObjectDetection",Dw]],["owlv2",["Owlv2ForObjectDetection",zw]],["grounding-dino",["GroundingDinoForObjectDetection",RM]]]),oo=new Map([["detr",["DetrForSegmentation",Du]],["clipseg",["CLIPSegForImageSegmentation",Bo]]]),jy=new Map([["segformer",["SegformerForSemanticSegmentation",jb]],["sapiens",["SapiensForSemanticSegmentation",_M]],["swin",["SwinForSemanticSegmentation",lM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Hb]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Qb]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Zb]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",ry]]]),Ny=new Map([["detr",["DetrForSegmentation",Du]],["maskformer",["MaskFormerForInstanceSegmentation",EM]]]),Vy=new Map([["sam",["SamModel",WM]]]),Uy=new Map([["wav2vec2",["Wav2Vec2ForCTC",JM]],["wav2vec2-bert",["Wav2Vec2BertForCTC",pb]],["unispeech",["UniSpeechForCTC",ob]],["unispeech-sat",["UniSpeechSatForCTC",lb]],["wavlm",["WavLMForCTC",wb]],["hubert",["HubertForCTC",_b]]]),Wy=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",YM]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",hb]],["unispeech",["UniSpeechForSequenceClassification",ib]],["unispeech-sat",["UniSpeechSatForSequenceClassification",ub]],["wavlm",["WavLMForSequenceClassification",Mb]],["hubert",["HubertForSequenceClassification",fb]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ii]]]),Gy=new Map([["wavlm",["WavLMForXVector",bb]]]),Ky=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",db]],["wavlm",["WavLMForAudioFrameClassification",yb]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ZM]],["pyannote",["PyAnnoteForAudioFrameClassification",tb]]]),Hy=new Map([["vitmatte",["VitMatteForImageMatting",$w]]]),Nx=new Map([["patchtst",["PatchTSTForPrediction",cy]],["patchtsmixer",["PatchTSMixerForPrediction",hy]]]),qy=new Map([["swin2sr",["Swin2SRForImageSuperResolution",dM]]]),Xy=new Map([["dpt",["DPTForDepthEstimation",pM]],["depth_anything",["DepthAnythingForDepthEstimation",mM]],["glpn",["GLPNForDepthEstimation",CM]],["sapiens",["SapiensForDepthEstimation",fM]],["depth_pro",["DepthProForDepthEstimation",MM]],["metric3d",["Metric3DForDepthEstimation",yM]],["metric3dv2",["Metric3Dv2ForDepthEstimation",xM]]]),Qy=new Map([["sapiens",["SapiensForNormalEstimation",gM]]]),Jy=new Map([["vitpose",["VitPoseForPoseEstimation",gw]]]),Yy=new Map([["clip",["CLIPVisionModelWithProjection",Ui]],["siglip",["SiglipVisionModel",Oo]],["jina_clip",["JinaCLIPVisionModel",Lo]]]),Zy=[[Dx,E.EncoderOnly],[Lx,E.EncoderDecoder],[Bx,E.DecoderOnly],[zx,E.AutoEncoder],[Iy,E.EncoderOnly],[Ay,E.EncoderOnly],[hd,E.Seq2Seq],[pd,E.Seq2Seq],[md,E.DecoderOnly],[Rx,E.MultiModality],[Fy,E.EncoderOnly],[Oy,E.EncoderOnly],[_d,E.Vision2Seq],[Dy,E.ImageTextToText],[Ly,E.AudioTextToText],[zy,E.EncoderOnly],[oo,E.EncoderOnly],[Ny,E.EncoderOnly],[jy,E.EncoderOnly],[Hy,E.EncoderOnly],[Nx,E.EncoderOnly],[qy,E.EncoderOnly],[Xy,E.EncoderOnly],[Qy,E.EncoderOnly],[Jy,E.EncoderOnly],[By,E.EncoderOnly],[Ry,E.EncoderOnly],[Vy,E.MaskGeneration],[Uy,E.EncoderOnly],[Wy,E.EncoderOnly],[$y,E.Seq2Seq],[ky,E.EncoderOnly],[Gy,E.EncoderOnly],[Ky,E.EncoderOnly],[Yy,E.EncoderOnly]];for(const[b,P]of Zy)for(const[D,ne]of b.values())y.set(D,P),v.set(ne,D),M.set(D,ne);const Vx=[["MusicgenForConditionalGeneration",ud,E.Musicgen],["Phi3VForCausalLM",Ao,E.Phi3V],["CLIPTextModelWithProjection",Vi,E.EncoderOnly],["SiglipTextModel",Hs,E.EncoderOnly],["JinaCLIPTextModel",Do,E.EncoderOnly],["ClapTextModelWithProjection",Lb,E.EncoderOnly],["ClapAudioModelWithProjection",zb,E.EncoderOnly],["DacEncoderModel",Ty,E.EncoderOnly],["DacDecoderModel",Ey,E.EncoderOnly],["MimiEncoderModel",My,E.EncoderOnly],["MimiDecoderModel",by,E.EncoderOnly],["SnacEncoderModel",Cy,E.EncoderOnly],["SnacDecoderModel",Sy,E.EncoderOnly]];for(const[b,P,D]of Vx)y.set(b,D),v.set(P,b),M.set(b,P);const e0=new Map([["modnet",oo],["birefnet",oo],["isnet",oo],["ben",oo]]);for(const[b,P]of e0.entries())P.set(b,["PreTrainedModel",R]),y.set(b,E.EncoderOnly),v.set(R,b),M.set(b,R);class fd extends Ct{}te(fd,"MODEL_CLASS_MAPPINGS",Zy.map(P=>P[0])),te(fd,"BASE_IF_FAIL",!0);class t0 extends Ct{}te(t0,"MODEL_CLASS_MAPPINGS",[Iy]);class r0 extends Ct{}te(r0,"MODEL_CLASS_MAPPINGS",[Ay]);class s0 extends Ct{}te(s0,"MODEL_CLASS_MAPPINGS",[hd]);class n0 extends Ct{}te(n0,"MODEL_CLASS_MAPPINGS",[pd]);class o0 extends Ct{}te(o0,"MODEL_CLASS_MAPPINGS",[$y]);class i0 extends Ct{}te(i0,"MODEL_CLASS_MAPPINGS",[ky]);class a0 extends Ct{}te(a0,"MODEL_CLASS_MAPPINGS",[md]);class l0 extends Ct{}te(l0,"MODEL_CLASS_MAPPINGS",[Fy]);class u0 extends Ct{}te(u0,"MODEL_CLASS_MAPPINGS",[Oy]);class d0 extends Ct{}te(d0,"MODEL_CLASS_MAPPINGS",[_d]);class c0 extends Ct{}te(c0,"MODEL_CLASS_MAPPINGS",[zy]);class p0 extends Ct{}te(p0,"MODEL_CLASS_MAPPINGS",[oo]);class h0 extends Ct{}te(h0,"MODEL_CLASS_MAPPINGS",[jy]);class m0 extends Ct{}te(m0,"MODEL_CLASS_MAPPINGS",[Ny]);class _0 extends Ct{}te(_0,"MODEL_CLASS_MAPPINGS",[By]);class f0 extends Ct{}te(f0,"MODEL_CLASS_MAPPINGS",[Ry]);class g0 extends Ct{}te(g0,"MODEL_CLASS_MAPPINGS",[Vy]);class w0 extends Ct{}te(w0,"MODEL_CLASS_MAPPINGS",[Uy]);class M0 extends Ct{}te(M0,"MODEL_CLASS_MAPPINGS",[Wy]);class b0 extends Ct{}te(b0,"MODEL_CLASS_MAPPINGS",[Gy]);class y0 extends Ct{}te(y0,"MODEL_CLASS_MAPPINGS",[Ky]);class v0 extends Ct{}te(v0,"MODEL_CLASS_MAPPINGS",[jx]);class x0 extends Ct{}te(x0,"MODEL_CLASS_MAPPINGS",[Hy]);class T0 extends Ct{}te(T0,"MODEL_CLASS_MAPPINGS",[qy]);class E0 extends Ct{}te(E0,"MODEL_CLASS_MAPPINGS",[Xy]);class P0 extends Ct{}te(P0,"MODEL_CLASS_MAPPINGS",[Qy]);class C0 extends Ct{}te(C0,"MODEL_CLASS_MAPPINGS",[Jy]);class S0 extends Ct{}te(S0,"MODEL_CLASS_MAPPINGS",[Yy]);class $0 extends Ct{}te($0,"MODEL_CLASS_MAPPINGS",[Dy]);class k0 extends Ct{}te(k0,"MODEL_CLASS_MAPPINGS",[Ly]);class Ux extends pe{constructor({logits:P,past_key_values:D,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:fe=null}){super(),this.logits=P,this.past_key_values=D,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=fe}}class _t extends pe{constructor({logits:P,...D}){super(),this.logits=P;const ne=Object.values(D);ne.length>0&&(this.attentions=ne)}}class I0 extends pe{constructor({logits:P,embeddings:D}){super(),this.logits=P,this.embeddings=D}}class hr extends pe{constructor({logits:P}){super(),this.logits=P}}class Mr extends pe{constructor({logits:P}){super(),this.logits=P}}class Er extends pe{constructor({start_logits:P,end_logits:D}){super(),this.start_logits=P,this.end_logits=D}}class In extends pe{constructor({logits:P}){super(),this.logits=P}}class Wx extends pe{constructor({logits:P,past_key_values:D}){super(),this.logits=P,this.past_key_values=D}}class A0 extends pe{constructor({alphas:P}){super(),this.alphas=P}}class F0 extends pe{constructor({waveform:P,spectrogram:D}){super(),this.waveform=P,this.spectrogram=D}}},"./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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.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,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const u=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),d=p.feature_extractor_type,c=n[d];if(!c)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new c(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"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const d=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),c=d.image_processor_type??d.feature_extractor_type;let f=i[c];return f||(c!==void 0&&console.warn(`Image processor type '${c}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=n.ImageProcessor),new f(d)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class u{static async from_pretrained(d,c={}){const f=await(0,o.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,c),{image_processor_type:_,feature_extractor_type:T,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,c);if(!_&&!T)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const S=a[_];if(!S)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new S(f)}if(T){const S=a[T];if(S)w.image_processor=new S(f);else{const E=l[T];if(!E)throw new Error(`Unknown feature_extractor_type: '${T}'.`);w.feature_extractor=new E(f)}}const g={};return new n.Processor(g,w)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.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,o.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,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let d;const c=a.length-l;if(c>0)if(u==="rand_trunc"){const f=Math.floor(Math.random()*(c+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(c<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var u;const l=(u=this.size)==null?void 0:u.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),[d,c]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(d,c,{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 o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const u=await super._call(l),p=[u.pixel_values.dims[0],64,64],d=(0,o.full)(p,1n);return{...u,pixel_mask:d}}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 i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[d,c,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let T=this.image_std;Array.isArray(T)||(T=new Array(f).fill(_));const k=_.map((w,g)=>-w/T[g]);return super.pad_image(a,l,u,{center:!0,constant_values:k,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),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"),o=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 u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,ImageFeatureExtractor:()=>T.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>c.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>f.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>_.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=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"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),d=t("./src/models/speecht5/feature_extraction_speecht5.js"),c=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),f=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),_=t("./src/models/whisper/feature_extraction_whisper.js"),T=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:d,task_prompts_with_input:c}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(d??{})),this.task_prompts_with_input=new Map(Object.entries(c??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[d,c]of this.task_prompts_with_input)if(p.includes(d)){u.push(c.replaceAll("{input}",p).replaceAll(d,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const d=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let c;switch(d){case"pure_text":c=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),T=[],k=[];for(const[w,g,...S]of _)T.push(g?g.trim():T.at(-1)??""),k.push(S.map((E,y)=>(Number(E)+.5)/this.size_per_bin*p[y%2]));c={labels:T,[f]:k};break;default:throw new Error(`Task "${u}" (of type "${d}") not yet implemented.`)}return{[u]:c}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),c=u?this.tokenizer(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(u,p){const c=u.dims.at(-1)-1,f=u.tolist();f.fill(!1,0,1),f.fill(!1,c);const _=p.tolist();return f.map((T,k)=>T?k:null).filter(T=>T!==null).map(T=>_[T])}class l extends s.Processor{async _call(p,d,c={}){const f=p?await this.image_processor(p,c):{};return{...d?this.tokenizer(d,c):{},...f}}post_process_grounded_object_detection(p,d,{box_threshold:c=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:T,pred_boxes:k}=p,w=T.dims[0];if(_!==null&&_.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=T.dims.at(1),S=T.sigmoid(),E=S.max(-1).tolist(),y=k.tolist().map(v=>v.map(C=>(0,i.center_to_corners_format)(C))),M=[];for(let v=0;vj.map((ee,H)=>ee*C[(H+1)%2])));const A=E[v],B=[],K=[],G=[];for(let j=0;j{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=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[u,p]=a.dims.slice(-2);const d=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/d),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*d),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!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 d=[],c=[],f=[];const _=[],T=[];for(const v of p){let C=await Promise.all(v.map(K=>this.preprocess(K)));_.push(...C.map(K=>K.original_size)),T.push(...C.map(K=>K.reshaped_input_size)),C.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:A}=this.max_image_size;let B;if(l??this.do_image_splitting){let K=new Array(C.length),G=new Array(C.length);B=await Promise.all(C.map(async(j,ee)=>{const H=this.get_resize_for_vision_encoder(j.pixel_values,A),Z=await(0,o.interpolate_4d)(j.pixel_values,{size:[H.height,H.width]}),{frames:X,num_splits_h:oe,num_splits_w:me}=await this.split_image(Z,this.max_image_size);return K[ee]=oe,G[ee]=me,(0,o.cat)(X,0)})),c.push(K),f.push(G)}else{const K=[A,A];B=await Promise.all(C.map(G=>(0,o.interpolate_4d)(G.pixel_values,{size:K}))),c.push(new Array(C.length).fill(0)),f.push(new Array(C.length).fill(0))}d.push((0,o.cat)(B,0))}const k=d.length,[w,g,S,E]=d[0].dims;let y,M;if(k===1)y=d[0].unsqueeze_(0),M=(0,o.full)([k,w,S,E],!0);else{const v=Math.max(...d.map(B=>B.dims.at(0)));M=(0,o.full)([k,v,S,E],!0);const C=M.data,A=v*S*E;for(let B=0;Bu||f>p){_=Math.ceil(c/u),T=Math.ceil(f/p);const k=Math.ceil(c/_),w=Math.ceil(f/T);for(let E=0;E<_;++E)for(let y=0;y{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,c,f,_,T,k){let w="";for(let g=0;g`+T.repeat(d);w+=` -`}return w+=` -${_}${k}`+T.repeat(d)+`${_}`,w}function l(d,c,f,_){return`${c}${_}`+f.repeat(d)+`${c}`}function u(d,c,f,_,T,k){return d===0&&c===0?l(f,_,T,k):a(f,d,c,_,T,k)}class p extends s.Processor{constructor(){super(...arguments);te(this,"fake_image_token","");te(this,"image_token","");te(this,"global_img_token","")}async _call(f,_=null,T={}){T.return_row_col_info??(T.return_row_col_info=!0);let k;_&&(k=await this.image_processor(_,T)),Array.isArray(f)||(f=[f]);const w=k.rows??[new Array(f.length).fill(0)],g=k.cols??[new Array(f.length).fill(0)],S=this.config.image_seq_len,E=[],y=[];for(let v=0;vu(ee,B[H],S,this.fake_image_token,this.image_token,this.global_img_token)),G=C.split(this.image_token);if(G.length===0)throw new Error("The image token should be present in the text.");let j=G[0];for(let ee=0;ee{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTImageProcessor:()=>d.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>c.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>T.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>w.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>v.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>v.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>A.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>A.MobileViTImageProcessor,NougatImageProcessor:()=>B.NougatImageProcessor,OwlViTFeatureExtractor:()=>G.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>G.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>j.Phi3VImageProcessor,PvtImageProcessor:()=>ee.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Z.RTDetrImageProcessor,SamImageProcessor:()=>X.SamImageProcessor,SegformerFeatureExtractor:()=>oe.SegformerFeatureExtractor,SegformerImageProcessor:()=>oe.SegformerImageProcessor,SiglipImageProcessor:()=>me.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>W.VitMatteImageProcessor,VitPoseImageProcessor:()=>re.VitPoseImageProcessor,YolosFeatureExtractor:()=>_e.YolosFeatureExtractor,YolosImageProcessor:()=>_e.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=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"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),d=t("./src/models/dpt/image_processing_dpt.js"),c=t("./src/models/efficientnet/image_processing_efficientnet.js"),f=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),T=t("./src/models/idefics3/image_processing_idefics3.js"),k=t("./src/models/janus/image_processing_janus.js"),w=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),v=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),A=t("./src/models/mobilevit/image_processing_mobilevit.js"),B=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),G=t("./src/models/owlvit/image_processing_owlvit.js"),j=t("./src/models/phi3_v/image_processing_phi3_v.js"),ee=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Z=t("./src/models/rt_detr/image_processing_rt_detr.js"),X=t("./src/models/sam/image_processing_sam.js"),oe=t("./src/models/segformer/image_processing_segformer.js"),me=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),W=t("./src/models/vitmatte/image_processing_vitmatte.js"),re=t("./src/models/vitpose/image_processing_vitpose.js"),_e=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:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(d,c){super(d,c),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(d,{images:c=null,chat_template:f="default"}={}){c?Array.isArray(c)||(c=[c]):c=await Promise.all(d.filter(B=>B.images).flatMap(B=>B.images).map(B=>l.RawImage.read(B)));const _=this.tokenizer,T=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=B=>_.encode(B,{add_special_tokens:!1}),w=T.split(this.image_tag),g=w.length-1;if(c.length!==g)throw new Error(`Number of images provided (${c.length}) does not match number of "${this.image_tag}" image tags (${g})`);const[S,E,y]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=k(w[0]),v=new Array(M.length).fill(!1);for(let B=1;B0){const B=await this.image_processor(c);return B.pixel_values.unsqueeze_(0),{...A,...B}}return A}}te(u,"image_processor_class",o.AutoImageProcessor),te(u,"tokenizer_class",n.AutoTokenizer),te(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...d}=i,c=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=u==="bicubic"?3:2;super({...d,size:c,resample:f,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:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},c=u?await this.image_processor(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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 o{}},"./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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=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,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[c,f]=a[d],_=this[c].bind(this),[T,k]=p.dims,w=[],g=[],S=p.tolist();for(let y=0;y0?C.reduce((B,K)=>B*K,1):0;g.push(v),w.push(A)}return[_(g),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,c]){const[f,_]=this._decode_helper(p,"char"),[T,k]=this._decode_helper(d,"bpe"),[w,g]=this._decode_helper(c,"wp"),S=[],E=[];for(let y=0;y{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(u,p,d,c,f){return`${c.repeat(d*f)}${p}${u} -`}class l extends s.Processor{async _call(p,d=null,c={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let T;d.some(g=>g.includes(i))?T=d.map(g=>{const S=g.replaceAll(i,i.repeat(_)),E=S.lastIndexOf(i),y=E===-1?0:E+i.length;return S.slice(0,y)+f+S.slice(y)+` -`}):(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."),T=d.map(g=>a(g,f,_,i,p.length)));const k=this.tokenizer(T,c);return{...await this.image_processor(p,c),...k}}}te(l,"tokenizer_class",n.AutoTokenizer),te(l,"image_processor_class",o.AutoImageProcessor),te(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"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(c){super({...c,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=c.num_crops}calc_num_image_tokens_from_image_size(c,f){const{num_img_tokens:_}=this.config;return l((l(f/n)*l(c/n)+1)*_+1+(l(f/n)+1)*u(_))}get_resize_output_image_size(c,f){const _=this._num_crops,[T,k]=c.size;let w=T/k,g=1;for(;g*Math.ceil(g/w)<=_;)g+=1;g-=1;const S=Math.floor(g*336),E=Math.floor(S/w);return[S,E]}pad_image(c,f,_,T={}){const[k,w]=f,g=n*a(k/n),S=n*a(w/n),E=[1,1,1].map((y,M)=>(y-this.image_mean[M])/this.image_std[M]);return super.pad_image(c,f,{width:S,height:g},{center:!0,constant_values:E,...T})}async _call(c,{num_crops:f=null}={}){if(this._num_crops=f??(f=this.config.num_crops),f<4||u(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(c)||(c=[c]);const _=c.length,T=await Promise.all(c.map(v=>this.preprocess(v))),k=T.map(v=>v.original_size),w=T.map(v=>v.reshaped_input_size),g=[];for(const{pixel_values:v}of T){v.unsqueeze_(0);const[C,A]=v.dims.slice(-2),B=await(0,o.interpolate_4d)(v,{size:[n,n],mode:"bicubic"});if(f>0){const K=[],G=u(f),j=l(A/G),ee=l(C/G);for(let Z=0;Zv.map(C=>n*a(C/n))),y=new o.Tensor("int64",E.flat(),[_,2]),M=E.map(([v,C])=>this.calc_num_image_tokens_from_image_size(C,v));return{pixel_values:S,original_sizes:k,reshaped_input_sizes:w,image_sizes:y,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"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,d=null,{padding:c=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let T,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:w}=k,g=p.map((E,y)=>E.split(a).join(i.repeat(w[y])));T=this.tokenizer(g,{padding:c,truncation:f});const S=this.tokenizer.model.convert_tokens_to_ids([i])[0];T.input_ids.map_(E=>E==S?-E:E)}else T=this.tokenizer(p);return{...T,...k}}}te(l,"image_processor_class",o.AutoImageProcessor),te(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>c.PaliGemmaProcessor,Phi3VProcessor:()=>d.Phi3VProcessor,PyAnnoteProcessor:()=>f.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>T.SamProcessor,SmolVLMProcessor:()=>k.SmolVLMProcessor,SpeechT5Processor:()=>w.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>y.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=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"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),d=t("./src/models/phi3_v/processing_phi3_v.js"),c=t("./src/models/paligemma/processing_paligemma.js"),f=t("./src/models/pyannote/processing_pyannote.js"),_=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),T=t("./src/models/sam/processing_sam.js"),k=t("./src/models/smolvlm/processing_smolvlm.js"),w=t("./src/models/speecht5/processing_speecht5.js"),g=t("./src/models/ultravox/processing_ultravox.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),y=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,d=[];for(const c of l.tolist()){const f=[];let _=-1;for(let T=0;T({id:T,start:k*p,end:w*p,confidence:g/(w-k)})))}return d}}},"./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"),o=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}}te(n,"feature_extractor_class",o.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"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let c=u;const{temporal_patch_size:f,merge_size:_,patch_size:T}=this.config;c.dims[0]===1&&(c=(0,o.cat)(Array.from({length:f},()=>c),0));const k=c.dims[0]/f,w=c.dims[1],g=Math.floor(c.dims[2]/T),S=Math.floor(c.dims[3]/T),E=c.view(k,f,w,Math.floor(g/_),_,T,Math.floor(S/_),_,T).permute(0,3,6,4,7,2,1,5,8).view(k*g*S,w*f*T*T),y=new o.Tensor("int64",[k,g,S],[1,3]);return{pixel_values:E,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:d}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let d,c;if(u&&(d=await this.image_processor(u),c=d.image_grid_thw),c){let _=this.image_processor.config.merge_size**2,T=0;const k=c.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const g=Number(k[T++].reduce((S,E)=>S*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/_)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}te(i,"image_processor_class",o.AutoImageProcessor),te(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,u,p,d=!1){l=structuredClone(l);let c=(0,o.calculateDimensions)(l);if(c.length===3)d||(c=[1,...c]),l=[l];else if(c.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 f=0;fd!==u.dims[c]))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:u=null,input_labels:p=null,input_boxes:d=null}={}){const c=await super._call(l);if(u&&(c.input_points=this.reshape_input_points(u,c.original_sizes,c.reshaped_input_sizes)),p){if(!c.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");c.input_labels=this.add_input_labels(p,c.input_points)}return d&&(c.input_boxes=this.reshape_input_points(d,c.original_sizes,c.reshaped_input_sizes,!0)),c}async post_process_masks(l,u,p,{mask_threshold:d=0,binarize:c=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size;const T=[f.height,f.width];for(let k=0;kd&&(y[M]=1);S=new n.Tensor("bool",y,S.dims)}_.push(S)}return _}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:c=32,crop_n_points_downscale_factor:f=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"),o=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)}}te(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){return l=l.map(p=>p*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:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:c=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[y,M]=f.dims,v=f.data;for(let C=0;C0){const A=new Float32Array(M*(y+C));A.set(v),A.fill(this.config.padding_value,v.length);const B=y+C;f=new o.Tensor(f.type,A,[B,M]),c&&(_=new o.Tensor("int64",new BigInt64Array(B),[1,B]),_.data.fill(1n,0,y))}}const[T,k]=f.dims,w=this.config.stride;if(T%w!==0)throw new Error(`The number of frames (${T}) must be a multiple of the stride (${w}).`);const S=f.view(1,Math.floor(T/w),k*w),E={input_features:S};if(c){const y=S.dims[1],M=new BigInt64Array(y);if(_){const v=_.data;for(let C=1,A=0;C{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o 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:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,u={}){const[p,d,c]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...u})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(u){const f=u.length,{input_features:_}=await this.feature_extractor(u,{...p,max_length:f}),T=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(T/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor),te(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./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"),o=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 u=await Promise.all(a.map(c=>this.preprocess(c))),p=await Promise.all(l.map(c=>this.preprocess(c,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(u.map((c,f)=>(0,o.cat)([c.pixel_values,p[f].pixel_values],0)),0),original_sizes:u.map(c=>c.original_size),reshaped_input_sizes:u.map(c=>c.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const u=i.tolist(),[p,d,c,f]=i.dims,_=[];for(let T=0;T{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((d,c)=>d+c,0)/a.length,p=a.reduce((d,c)=>d+(c-u)**2,0)/a.length;return a.map(d=>(d-u)/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 u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",s.AutoTokenizer),te(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",s.AutoTokenizer),te(i,"feature_extractor_class",o.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 o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.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 u=l.mean(1).data,p=l.data,[d,c,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});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"]],o=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 i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[1]),o.has(a))l=a;else{const d=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,o.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,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,o.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=u.data,d=(0,n.max)(p)[0];for(let c=0;cd?(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,d)):(p=new Float32Array(d),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:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);te(this,"return_timestamps",null);te(this,"return_token_timestamps",null);te(this,"num_frames",null);te(this,"alignment_heads",null);te(this,"task",null);te(this,"language",null);te(this,"no_timestamps_token_id",null);te(this,"prompt_ids",null);te(this,"is_multilingual",null);te(this,"lang_to_id",null);te(this,"task_to_id",null);te(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,d)=>{const c=await(0,s.createInferenceSession)(new Uint8Array(u),p);let f=Promise.resolve();return async _=>{const T=(0,s.isONNXProxy)(),k=Object.fromEntries(Object.entries(_).map(([g,S])=>[g,(T?S.clone():S).ort_tensor])),w=await(f=i?f.then(()=>c.run(k)):c.run(k));return Array.isArray(d)?d.map(g=>new o.Tensor(w[g])):new o.Tensor(w[d])}};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}}te(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>G,AutomaticSpeechRecognitionPipeline:()=>ee,BackgroundRemovalPipeline:()=>oe,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>B,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>Z,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>X,ImageToImagePipeline:()=>re,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>T,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>W,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>j,ZeroShotClassificationPipeline:()=>A,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>$e});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function c(we){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(q=>d.RawImage.read(q)))}async function f(we,q){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(R=>typeof R=="string"||R instanceof URL?(0,u.read_audio)(R,q):R instanceof Float64Array?new Float32Array(R):R))}function _(we,q){q&&(we=we.map(Se=>Se|0));const[R,pe,xe,be]=we;return{xmin:R,ymin:pe,xmax:xe,ymax:be}}class T extends i.Callable{constructor({task:q,model:R,tokenizer:pe=null,processor:xe=null}){super(),this.task=q,this.model=R,this.tokenizer=pe,this.processor=xe}async dispose(){await this.model.dispose()}}class k extends T{constructor(q){super(q)}async _call(q,{top_k:R=1}={}){const pe=this.tokenizer(q,{padding:!0,truncation:!0}),xe=await this.model(pe),be=this.model.config.problem_type==="multi_label_classification"?Fe=>Fe.sigmoid():Fe=>new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),Se=this.model.config.id2label,Ae=[];for(const Fe of xe.logits){const ze=be(Fe),Ve=await(0,p.topk)(ze,R),O=Ve[0].tolist(),z=Ve[1].tolist().map((J,le)=>({label:Se?Se[J]:`LABEL_${J}`,score:O[le]}));R===1?Ae.push(...z):Ae.push(z)}return Array.isArray(q)||R===1?Ae:Ae[0]}}class w extends T{constructor(q){super(q)}async _call(q,{ignore_labels:R=["O"]}={}){const pe=Array.isArray(q),xe=this.tokenizer(pe?q:[q],{padding:!0,truncation:!0}),Se=(await this.model(xe)).logits,Ae=this.model.config.id2label,Fe=[];for(let ze=0;zeIe==this.tokenizer.sep_token_id);Fe[O].map((Ie,Re)=>Ie==1&&(Re===0||Re>z&&ze.findIndex(Xe=>Xe==Y[Re])===-1));const J=be[O].tolist(),le=Se[O].tolist();for(let Ie=1;IeRe==Y[Ie])!==-1)&&(J[Ie]=-1/0,le[Ie]=-1/0);const ye=(0,l.softmax)(J).map((Ie,Re)=>[Ie,Re]),Ee=(0,l.softmax)(le).map((Ie,Re)=>[Ie,Re]);ye[0][0]=0,Ee[0][0]=0;const ke=(0,a.product)(ye,Ee).filter(Ie=>Ie[0][1]<=Ie[1][1]).map(Ie=>[Ie[0][1],Ie[1][1],Ie[0][0]*Ie[1][0]]).sort((Ie,Re)=>Re[2]-Ie[2]);for(let Ie=0;IeJ==this.tokenizer.mask_token_id);if(ze===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=xe[Ae][ze],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),z=O[1].tolist();be.push(z.map((J,le)=>{const ye=Fe.slice();return ye[ze]=J,{score:Y[le],token:Number(J),token_str:this.tokenizer.decode([J]),sequence:this.tokenizer.decode(ye,{skip_special_tokens:!0})}}))}return Array.isArray(q)?be:be[0]}}class E extends T{constructor(R){super(R);te(this,"_key","generated_text")}async _call(R,pe={}){Array.isArray(R)||(R=[R]),this.model.config.prefix&&(R=R.map(ze=>this.model.config.prefix+ze));const xe=this.model.config.task_specific_params;xe&&xe[this.task]&&xe[this.task].prefix&&(R=R.map(ze=>xe[this.task].prefix+ze));const be=this.tokenizer,Se={padding:!0,truncation:!0};let Ae;this instanceof M&&"_build_translation_inputs"in be?Ae=be._build_translation_inputs(R,Se,pe):Ae=be(R,Se);const Fe=await this.model.generate({...Ae,...pe});return be.batch_decode(Fe,{skip_special_tokens:!0}).map(ze=>({[this._key]:ze}))}}class y extends E{constructor(R){super(R);te(this,"_key","summary_text")}}class M extends E{constructor(R){super(R);te(this,"_key","translation_text")}}function v(we){return Array.isArray(we)&&we.every(q=>"role"in q&&"content"in q)}class C extends T{constructor(q){super(q)}async _call(q,R={}){let pe=!1,xe=!1,be;if(typeof q=="string")be=q=[q];else if(Array.isArray(q)&&q.every(z=>typeof z=="string"))pe=!0,be=q;else{if(v(q))q=[q];else if(Array.isArray(q)&&q.every(v))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");xe=!0,be=q.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Se=R.add_special_tokens??!1,Ae=xe?!1:R.return_full_text??!0;this.tokenizer.padding_side="left";const Fe=this.tokenizer(be,{add_special_tokens:Se,padding:!0,truncation:!0}),ze=await this.model.generate({...Fe,...R}),Ve=this.tokenizer.batch_decode(ze,{skip_special_tokens:!0});let O;!Ae&&Fe.input_ids.dims.at(-1)>0&&(O=this.tokenizer.batch_decode(Fe.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Y=Array.from({length:q.length},z=>[]);for(let z=0;z[R.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(q,R,{hypothesis_template:pe="This example is {}.",multi_label:xe=!1}={}){const be=Array.isArray(q);be||(q=[q]),Array.isArray(R)||(R=[R]);const Se=R.map(ze=>pe.replace("{}",ze)),Ae=xe||R.length===1,Fe=[];for(const ze of q){const Ve=[];for(const z of Se){const J=this.tokenizer(ze,{text_pair:z,padding:!0,truncation:!0}),le=await this.model(J);Ae?Ve.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):Ve.push(le.logits.data[this.entailment_id])}const Y=(Ae?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,J)=>[z,J]).sort((z,J)=>J[0]-z[0]);Fe.push({sequence:ze,labels:Y.map(z=>R[z[1]]),scores:Y.map(z=>z[0])})}return be?Fe:Fe[0]}}class B extends T{constructor(q){super(q)}async _call(q,{pooling:R="none",normalize:pe=!1,quantize:xe=!1,precision:be="binary"}={}){const Se=this.tokenizer(q,{padding:!0,truncation:!0}),Ae=await this.model(Se);let Fe=Ae.last_hidden_state??Ae.logits??Ae.token_embeddings;if(R!=="none")if(R==="mean")Fe=(0,p.mean_pooling)(Fe,Se.attention_mask);else if(R==="cls")Fe=Fe.slice(null,0);else throw Error(`Pooling method '${R}' not supported.`);return pe&&(Fe=Fe.normalize(2,-1)),xe&&(Fe=(0,p.quantize_embeddings)(Fe,be)),Fe}}class K extends T{constructor(q){super(q)}async _call(q,{pool:R=null}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),be=await this.model({pixel_values:xe});let Se;if(R){if(!("pooler_output"in be))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=be.pooler_output}else Se=be.last_hidden_state??be.logits??be.image_embeds;return Se}}class G extends T{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,xe=await f(q,pe),be=this.model.config.id2label,Se=[];for(const Ae of xe){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),J=O[1].tolist().map((le,ye)=>({label:be?be[le]:`LABEL_${le}`,score:Y[ye]}));Se.push(J)}return Array.isArray(q)?Se:Se[0]}}class j extends T{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a sound of {}."}={}){const xe=!Array.isArray(q);xe&&(q=[q]);const be=R.map(Ve=>pe.replace("{}",Ve)),Se=this.tokenizer(be,{padding:!0,truncation:!0}),Ae=this.processor.feature_extractor.config.sampling_rate,Fe=await f(q,Ae),ze=[];for(const Ve of Fe){const O=await this.processor(Ve),Y=await this.model({...Se,...O}),z=(0,l.softmax)(Y.logits_per_audio.data);ze.push([...z].map((J,le)=>({score:J,label:R[le]})))}return xe?ze[0]:ze}}class ee extends T{constructor(q){super(q)}async _call(q,R={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(q,R);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(q,R);case"moonshine":return this._call_moonshine(q,R);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(q,R){R.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),R.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,be=await f(q,xe),Se=[];for(const Ae of be){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=[];for(const z of Ve)O.push((0,l.max)(z.data)[1]);const Y=this.tokenizer.decode(O);Se.push({text:Y})}return pe?Se[0]:Se}async _call_whisper(q,R){const pe=R.return_timestamps??!1,xe=R.chunk_length_s??0,be=R.force_full_sequences??!1;let Se=R.stride_length_s??null;const Ae={...R};pe==="word"&&(Ae.return_token_timestamps=!0,Ae.return_timestamps=!1);const Fe=!Array.isArray(q);Fe&&(q=[q]);const ze=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,O=this.processor.feature_extractor.config.sampling_rate,Y=await f(q,O),z=[];for(const J of Y){let le=[];if(xe>0){if(Se===null)Se=xe/6;else if(xe<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ke=O*xe,Ie=O*Se,Re=ke-2*Ie;let Xe=0;for(;;){const Ge=Xe+ke,lt=J.subarray(Xe,Ge),wt=await this.processor(lt),Gt=Xe===0,Ot=Ge>=J.length;if(le.push({stride:[lt.length,Gt?0:Ie,Ot?0:Ie],input_features:wt.input_features,is_last:Ot}),Ot)break;Xe+=Re}}else le=[{stride:[J.length,0,0],input_features:(await this.processor(J)).input_features,is_last:!0}];for(const ke of le){Ae.num_frames=Math.floor(ke.stride[0]/Ve);const Ie=await this.model.generate({inputs:ke.input_features,...Ae});pe==="word"?(ke.tokens=Ie.sequences.tolist()[0],ke.token_timestamps=Ie.token_timestamps.tolist()[0].map(Re=>(0,l.round)(Re,2))):ke.tokens=Ie[0].tolist(),ke.stride=ke.stride.map(Re=>Re/O)}const[ye,Ee]=this.tokenizer._decode_asr(le,{time_precision:ze,return_timestamps:pe,force_full_sequences:be});z.push({text:ye,...Ee})}return Fe?z[0]:z}async _call_moonshine(q,R){const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,be=await f(q,xe),Se=[];for(const Ae of be){const Fe=await this.processor(Ae),ze=Math.floor(Ae.length/xe)*6,Ve=await this.model.generate({max_new_tokens:ze,...R,...Fe}),O=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Se.push({text:O})}return pe?Se[0]:Se}}class H extends T{constructor(q){super(q)}async _call(q,R={}){const pe=Array.isArray(q),xe=await c(q),{pixel_values:be}=await this.processor(xe),Se=[];for(const Ae of be){Ae.dims=[1,...Ae.dims];const Fe=await this.model.generate({inputs:Ae,...R}),ze=this.tokenizer.batch_decode(Fe,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Se.push(ze)}return pe?Se:Se[0]}}class Z extends T{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),be=await this.model({pixel_values:xe}),Se=this.model.config.id2label,Ae=[];for(const Fe of be.logits){const ze=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),R),Ve=ze[0].tolist(),Y=ze[1].tolist().map((z,J)=>({label:Se?Se[z]:`LABEL_${z}`,score:Ve[J]}));Ae.push(Y)}return Array.isArray(q)?Ae:Ae[0]}}class X extends T{constructor(q){super(q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(q,{threshold:R=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:xe=.8,label_ids_to_fuse:be=null,target_sizes:Se=null,subtask:Ae=null}={}){if(Array.isArray(q)&&q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ze=await c(q),Ve=ze.map(ke=>[ke.height,ke.width]),O=await this.processor(ze),{inputNames:Y,outputNames:z}=this.model.sessions.model;if(!Y.includes("pixel_values")){if(Y.length!==1)throw Error(`Expected a single input name, but got ${Y.length} inputs: ${Y}.`);const ke=Y[0];if(ke in O)throw Error(`Input name ${ke} already exists in the inputs.`);O[ke]=O.pixel_values}const J=await this.model(O);let le=null;if(Ae!==null)le=this.subtasks_mapping[Ae];else if(this.processor.image_processor){for(const[ke,Ie]of Object.entries(this.subtasks_mapping))if(Ie in this.processor.image_processor){le=this.processor.image_processor[Ie].bind(this.processor.image_processor),Ae=ke;break}}const ye=this.model.config.id2label,Ee=[];if(Ae)if(Ae==="panoptic"||Ae==="instance"){const ke=le(J,R,pe,xe,be,Se??Ve)[0],Ie=ke.segmentation;for(const Re of ke.segments_info){const Xe=new Uint8ClampedArray(Ie.data.length);for(let lt=0;ltwt<-1e-5||wt>1+1e-5)&&Ge.sigmoid_();const lt=await d.RawImage.fromTensor(Ge.mul_(255).to("uint8")).resize(Xe[1],Xe[0]);Ee.push({label:null,score:null,mask:lt})}}return Ee}}class oe extends X{constructor(q){super(q)}async _call(q,R={}){if(Array.isArray(q)&&q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const xe=await c(q),be=await super._call(q,R);return xe.map((Ae,Fe)=>{const ze=Ae.clone();return ze.putAlpha(be[Fe].mask),ze})}}class me extends T{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a photo of {}"}={}){const xe=Array.isArray(q),be=await c(q),Se=R.map(Y=>pe.replace("{}",Y)),Ae=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Fe}=await this.processor(be),ze=await this.model({...Ae,pixel_values:Fe}),Ve=this.model.config.model_type==="siglip"?Y=>Y.sigmoid().data:Y=>(0,l.softmax)(Y.data),O=[];for(const Y of ze.logits_per_image){const J=[...Ve(Y)].map((le,ye)=>({score:le,label:R[ye]}));J.sort((le,ye)=>ye.score-le.score),O.push(J)}return xe?O:O[0]}}class ae extends T{constructor(q){super(q)}async _call(q,{threshold:R=.9,percentage:pe=!1}={}){const xe=Array.isArray(q);if(xe&&q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const be=await c(q),Se=pe?null:be.map(z=>[z.height,z.width]),{pixel_values:Ae,pixel_mask:Fe}=await this.processor(be),ze=await this.model({pixel_values:Ae,pixel_mask:Fe}),Ve=this.processor.image_processor.post_process_object_detection(ze,R,Se),O=this.model.config.id2label,Y=Ve.map(z=>z.boxes.map((J,le)=>({score:z.scores[le],label:O[z.classes[le]],box:_(J,!pe)})));return xe?Y:Y[0]}}class V extends T{constructor(q){super(q)}async _call(q,R,{threshold:pe=.1,top_k:xe=null,percentage:be=!1}={}){const Se=Array.isArray(q),Ae=await c(q),Fe=this.tokenizer(R,{padding:!0,truncation:!0}),ze=await this.processor(Ae),Ve=[];for(let O=0;O({score:Ee.scores[Ie],label:Ee.labels[Ie],box:_(ke,!be)}))}else{const Ee=this.processor.image_processor.post_process_object_detection(le,pe,z,!0)[0];ye=Ee.boxes.map((ke,Ie)=>({score:Ee.scores[Ie],label:R[Ee.classes[Ie]],box:_(ke,!be)}))}ye.sort((Ee,ke)=>ke.score-Ee.score),xe!==null&&(ye=ye.slice(0,xe)),Ve.push(ye)}return Se?Ve:Ve[0]}}class F extends T{constructor(q){super(q)}async _call(q,R,pe={}){const xe=(await c(q))[0],{pixel_values:be}=await this.processor(xe),Se=`${R}`,Ae=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Fe=await this.model.generate({inputs:be,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ae,...pe}),Ve=this.tokenizer.batch_decode(Fe)[0].match(/(.*?)<\/s_answer>/);let O=null;return Ve&&Ve.length>=2&&(O=Ve[1].trim()),[{answer:O}]}}class W extends T{constructor(R){super(R);te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=R.vocoder??null}async _call(R,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(R,{speaker_embeddings:pe}):this._call_text_to_waveform(R)}async _call_text_to_waveform(R){const pe=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:xe}=await this.model(pe),be=this.model.config.sampling_rate;return new u.RawAudio(xe.data,be)}async _call_text_to_spectrogram(R,{speaker_embeddings:pe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.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:xe}=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:be}=await this.model.generate_speech(xe,pe,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(be.data,Se)}}class re extends T{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),xe=await this.model(pe),be=[];for(const Se of xe.reconstruction){const Ae=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");be.push(d.RawImage.fromTensor(Ae))}return be.length>1?be:be[0]}}class _e extends T{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),{predicted_depth:xe}=await this.model(pe),be=[];for(let Se=0;Se1?be:be[0]}}const se=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:G,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:j,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:ee,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:W,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Z,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:X,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:oe,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:me,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:re,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_e,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:B,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ce=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $e(we,q=null,{progress_callback:R=null,config:pe=null,cache_dir:xe=null,local_files_only:be=!1,revision:Se="main",device:Ae=null,dtype:Fe=null,subfolder:ze="onnx",use_external_data_format:Ve=null,model_file_name:O=null,session_options:Y={}}={}){we=ce[we]??we;const z=se[we.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${we}. Must be one of [${Object.keys(se)}]`);q||(q=z.default.model,console.log(`No model specified. Using default model: "${q}".`));const J={progress_callback:R,config:pe,cache_dir:xe,local_files_only:be,revision:Se,device:Ae,dtype:Fe,subfolder:ze,use_external_data_format:Ve,model_file_name:O,session_options:Y},le=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),ye=await Ue(le,q,J);ye.task=we,(0,a.dispatchCallback)(R,{status:"ready",task:we,model:q});const Ee=z.pipeline;return new Ee(ye)}async function Ue(we,q,R){const pe=Object.create(null),xe=[];for(const[be,Se]of we.entries()){if(!Se)continue;let Ae;Array.isArray(Se)?Ae=new Promise(async(Fe,ze)=>{var O,Y;let Ve;for(const z of Se){if(z===null){Fe(null);return}try{Fe(await z.from_pretrained(q,R));return}catch(J){if((O=J.message)!=null&&O.includes("Unsupported model type"))Ve=J;else if((Y=J.message)!=null&&Y.includes("Could not locate file"))Ve=J;else{ze(J);return}}}ze(Ve)}):Ae=Se.from_pretrained(q,R),pe[be]=Ae,xe.push(Ae)}await Promise.all(xe);for(const[be,Se]of Object.entries(pe))pe[be]=await Se;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ar,AutoTokenizer:()=>vn,BartTokenizer:()=>hs,BertTokenizer:()=>us,BlenderbotSmallTokenizer:()=>vs,BlenderbotTokenizer:()=>wn,BloomTokenizer:()=>Hr,CLIPTokenizer:()=>mn,CamembertTokenizer:()=>tt,CodeGenTokenizer:()=>Br,CodeLlamaTokenizer:()=>xr,CohereTokenizer:()=>yn,ConvBertTokenizer:()=>Qt,DebertaTokenizer:()=>ds,DebertaV2Tokenizer:()=>cs,DistilBertTokenizer:()=>Qe,ElectraTokenizer:()=>zr,EsmTokenizer:()=>pn,FalconTokenizer:()=>fr,GPT2Tokenizer:()=>ps,GPTNeoXTokenizer:()=>Vs,GemmaTokenizer:()=>hn,Grok1Tokenizer:()=>qr,HerbertTokenizer:()=>ys,LlamaTokenizer:()=>cn,M2M100Tokenizer:()=>dr,MBart50Tokenizer:()=>ms,MBartTokenizer:()=>Kr,MPNetTokenizer:()=>ks,MarianTokenizer:()=>fn,MgpstrTokenizer:()=>xs,MobileBertTokenizer:()=>bs,NllbTokenizer:()=>Is,NougatTokenizer:()=>Us,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Fr,RoFormerTokenizer:()=>De,RobertaTokenizer:()=>_s,SiglipTokenizer:()=>_n,SpeechT5Tokenizer:()=>Mn,SqueezeBertTokenizer:()=>Ft,T5Tokenizer:()=>Sr,TokenizerModel:()=>K,VitsTokenizer:()=>bn,Wav2Vec2CTCTokenizer:()=>gn,WhisperTokenizer:()=>gr,XLMRobertaTokenizer:()=>$s,XLMTokenizer:()=>Rt,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(he,$){const N=await Promise.all([(0,n.getModelJSON)(he,"tokenizer.json",!0,$),(0,n.getModelJSON)(he,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(N[1].legacy=$.legacy),N}function c(he,$){const N=[];let Q=0;for(const ie of he.matchAll($)){const de=ie[0];Q0&&N.push(de),Q=ie.index+de.length}return Q=19968&&he<=40959||he>=13312&&he<=19903||he>=131072&&he<=173791||he>=173824&&he<=177983||he>=177984&&he<=178207||he>=178208&&he<=183983||he>=63744&&he<=64255||he>=194560&&he<=195103}function E(he,$,N){const Q=[];let ie=0;for(;iethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(N=>this.vocab[N]??this.unk_token)}}class G extends K{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,Q]of this.tokens_to_ids)this.vocab[Q]=N}encode($){const N=[];for(const Q of $){const ie=[...Q];if(ie.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let de=!1,ve=0;const je=[];for(;ve0&&(Je=this.config.continuing_subword_prefix+Je),this.tokens_to_ids.has(Je)){We=Je;break}--He}if(We===null){de=!0;break}je.push(We),ve=He}de?N.push(this.unk_token):N.push(...je)}return N}}class j extends K{constructor($,N){super($);const Q=$.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let ie=0;ie[ie,de])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.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,i.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($){const N=$.chars,Q=1;let ie=0;for(;ie{const he=[...Array.from({length:94},(ie,de)=>de+33),...Array.from({length:12},(ie,de)=>de+161),...Array.from({length:82},(ie,de)=>de+174)],$=he.slice();let N=0;for(let ie=0;ie<256;++ie)he.includes(ie)||(he.push(ie),$.push(256+N),N+=1);const Q=$.map(ie=>String.fromCharCode(ie));return Object.fromEntries(he.map((ie,de)=>[ie,Q[de]]))})(),H=(0,o.reverseDictionary)(ee);class Z extends K{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q;const N=Array.isArray($.merges[0]);this.merges=N?$.merges:$.merges.map(Q=>Q.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Q,ie)=>[JSON.stringify(Q),ie])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe($){if($.length===0)return[];const N=this.cache.get($);if(N!==void 0)return N;const Q=Array.from($);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let ie=[];if(Q.length>1){const de=new l.PriorityQueue((He,We)=>He.score`<0x${je.toString(16).toUpperCase().padStart(2,"0")}>`);ve.every(je=>this.tokens_to_ids.has(je))?N.push(...ve):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class X extends K{constructor($,N){super($),this.tokens_to_ids=_(N.target_lang?$.vocab[N.target_lang]:$.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.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[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q}encode($){return $}}class oe extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new we($);case"Precompiled":return new Ot($);case"Sequence":return new Ue($);case"Replace":return new me($);case"NFC":return new V($);case"NFD":return new F($);case"NFKC":return new W($);case"NFKD":return new re($);case"Strip":return new _e($);case"StripAccents":return new se($);case"Lowercase":return new ce($);case"Prepend":return new $e($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class me extends oe{normalize($){const N=f(this.config.pattern);return N===null?$:$.replaceAll(N,this.config.content)}}class ae extends oe{constructor(){super(...arguments);te(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class V extends ae{constructor(){super(...arguments);te(this,"form","NFC")}}class F extends ae{constructor(){super(...arguments);te(this,"form","NFD")}}class W extends ae{constructor(){super(...arguments);te(this,"form","NFKC")}}class re extends ae{constructor(){super(...arguments);te(this,"form","NFKD")}}class _e extends oe{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class se extends oe{normalize($){return $=w($),$}}class ce extends oe{normalize($){return $=$.toLowerCase(),$}}class $e extends oe{normalize($){return $=this.config.prepend+$,$}}class Ue extends oe{constructor($){super($),this.normalizers=$.normalizers.map(N=>oe.fromConfig(N))}normalize($){return this.normalizers.reduce((N,Q)=>Q.normalize(N),$)}}class we extends oe{_tokenize_chinese_chars($){const N=[];for(let Q=0;Q<$.length;++Q){const ie=$[Q],de=ie.charCodeAt(0);S(de)?(N.push(" "),N.push(ie),N.push(" ")):N.push(ie)}return N.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` -`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const N=[];for(const Q of $){const ie=Q.charCodeAt(0);ie===0||ie===65533||this._is_control(Q)||(/^\s$/.test(Q)?N.push(" "):N.push(Q))}return N.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new R($);case"Sequence":return new ur($);case"Whitespace":return new ls($);case"WhitespaceSplit":return new Ms($);case"Metaspace":return new wt($);case"ByteLevel":return new pe($);case"Split":return new xe($);case"Punctuation":return new be($);case"Digits":return new Se($);case"Replace":return new Ir($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,N){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,N){return(Array.isArray($)?$.map(Q=>this.pre_tokenize_text(Q,N)):this.pre_tokenize_text($,N)).flat()}_call($,N){return this.pre_tokenize($,N)}}class R extends q{constructor($){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text($,N){return $.trim().match(this.pattern)||[]}}class pe extends q{constructor($){super(),this.config=$,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=ee,this.text_encoder=new TextEncoder}pre_tokenize_text($,N){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(ie=>Array.from(this.text_encoder.encode(ie),de=>this.byte_encoder[de]).join(""))}}class xe extends q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text($,N){var Q;return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:((Q=this.config.behavior)==null?void 0:Q.toLowerCase())==="removed"?$.split(this.pattern).filter(ie=>ie):c($,this.pattern)}}class be extends q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text($,N){return $.match(this.pattern)||[]}}class Se extends q{constructor($){super(),this.config=$;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text($,N){return $.match(this.pattern)||[]}}class Ae extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new Ve($);case"ByteLevel":return new O($);case"RobertaProcessing":return new ze($);case"BertProcessing":return new Fe($);case"Sequence":return new Y($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...N){throw Error("post_process should be implemented in subclass.")}_call($,...N){return this.post_process($,...N)}}class Fe extends Ae{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,N=null,{add_special_tokens:Q=!0}={}){Q&&($=(0,o.mergeArrays)([this.cls],$,[this.sep]));let ie=new Array($.length).fill(0);if(N!==null){const de=Q&&this instanceof ze?[this.sep]:[],ve=Q?[this.sep]:[];$=(0,o.mergeArrays)($,de,N,ve),ie=(0,o.mergeArrays)(ie,new Array(N.length+de.length+ve.length).fill(1))}return{tokens:$,token_type_ids:ie}}}class ze extends Fe{}class Ve extends Ae{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,N=null,{add_special_tokens:Q=!0}={}){const ie=N===null?this.single:this.pair;let de=[],ve=[];for(const je of ie)"SpecialToken"in je?Q&&(de.push(je.SpecialToken.id),ve.push(je.SpecialToken.type_id)):"Sequence"in je&&(je.Sequence.id==="A"?(de=(0,o.mergeArrays)(de,$),ve=(0,o.mergeArrays)(ve,new Array($.length).fill(je.Sequence.type_id))):je.Sequence.id==="B"&&(de=(0,o.mergeArrays)(de,N),ve=(0,o.mergeArrays)(ve,new Array(N.length).fill(je.Sequence.type_id))));return{tokens:de,token_type_ids:ve}}}class O extends Ae{post_process($,N=null){return N&&($=(0,o.mergeArrays)($,N)),{tokens:$}}}class Y extends Ae{constructor($){super($),this.processors=$.processors.map(N=>Ae.fromConfig(N))}post_process($,N=null,Q={}){let ie;for(const de of this.processors)if(de instanceof O)$=de.post_process($).tokens,N&&(N=de.post_process(N).tokens);else{const ve=de.post_process($,N,Q);$=ve.tokens,ie=ve.token_type_ids}return{tokens:$,token_type_ids:ie}}}class z extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new ke($);case"Metaspace":return new Gt($);case"ByteLevel":return new Ie($);case"Replace":return new J($);case"ByteFallback":return new le($);case"Fuse":return new ye($);case"Strip":return new Ee($);case"Sequence":return new Xe($);case"CTC":return new Re($);case"BPEDecoder":return new Ge($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class J extends z{decode_chain($){const N=f(this.config.pattern);return N===null?$:$.map(Q=>Q.replaceAll(N,this.config.content))}}class le extends z{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const N=[];let Q=[];for(const ie of $){let de=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const ve=parseInt(ie.slice(3,5),16);isNaN(ve)||(de=ve)}if(de!==null)Q.push(de);else{if(Q.length>0){const ve=this.text_decoder.decode(Uint8Array.from(Q));N.push(ve),Q=[]}N.push(ie)}}if(Q.length>0){const ie=this.text_decoder.decode(Uint8Array.from(Q));N.push(ie),Q=[]}return N}}class ye extends z{decode_chain($){return[$.join("")]}}class Ee extends z{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(N=>{let Q=0;for(let de=0;de(Q!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=k(N)),N))}}class Ie extends z{constructor($){super($),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($){const N=$.join(""),Q=new Uint8Array([...N].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Q)}decode_chain($){const N=[];let Q=[];for(const ie of $)this.added_tokens.find(de=>de.content===ie)!==void 0?(Q.length>0&&(N.push(this.convert_tokens_to_string(Q)),Q=[]),N.push(ie)):Q.push(ie);return Q.length>0&&N.push(this.convert_tokens_to_string(Q)),N}}class Re extends z{constructor($){super($),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($){if($.length===0)return"";const N=[$[0]];for(let de=1;de<$.length;++de)$[de]!==N.at(-1)&&N.push($[de]);let ie=N.filter(de=>de!==this.pad_token).join("");return this.cleanup&&(ie=k(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain($){return[this.convert_tokens_to_string($)]}}class Xe extends z{constructor($){super($),this.decoders=$.decoders.map(N=>z.fromConfig(N))}decode_chain($){return this.decoders.reduce((N,Q)=>Q.decode_chain(N),$)}}class Ge extends z{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((N,Q)=>N.replaceAll(this.suffix,Q===$.length-1?"":" "))}}class lt extends z{decode_chain($){let N="";for(let Q=1;Q<$.length;Q+=2)N+=$[Q];return[N]}}class wt extends q{constructor($){super(),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:N=void 0}={}){let Q=$.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Q.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&N===0)&&(Q=this.strRep+Q),[Q]}}class Gt extends z{constructor($){super($),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement}decode_chain($){const N=[];for(let Q=0;Q<$.length;++Q){let ie=$[Q].replaceAll(this.replacement," ");this.addPrefixSpace&&Q==0&&ie.startsWith(" ")&&(ie=ie.substring(1)),N.push(ie)}return N}}class Ot extends oe{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(Q=>Q.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class ur extends q{constructor($){super(),this.tokenizers=$.pretokenizers.map(N=>q.fromConfig(N))}pre_tokenize_text($,N){return this.tokenizers.reduce((Q,ie)=>ie.pre_tokenize(Q,N),[$])}}class ls extends q{constructor($){super()}pre_tokenize_text($,N){return $.match(/\w+|[^\w\s]+/g)||[]}}class Ms extends q{constructor($){super()}pre_tokenize_text($,N){return y($)}}class Ir extends q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,N){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}const js=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ss(he,$,N,Q){for(const ie of Object.keys(he)){const de=$-he[ie].length,ve=N(ie),je=new Array(de).fill(ve);he[ie]=Q==="right"?(0,o.mergeArrays)(he[ie],je):(0,o.mergeArrays)(je,he[ie])}}function Ns(he,$){for(const N of Object.keys(he))he[N].length=$}class at extends s.Callable{constructor(N,Q){super();te(this,"return_token_type_ids",!1);te(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=oe.fromConfig(N.normalizer),this.pre_tokenizer=q.fromConfig(N.pre_tokenizer),this.model=K.fromConfig(N.model,Q),this.post_processor=Ae.fromConfig(N.post_processor),this.decoder=z.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of N.added_tokens){const de=new B(ie);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Q.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_splitter=new l.DictionarySplitter(this.added_tokens.map(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),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=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:de,template:ve}of this.chat_template){if(typeof de!="string"||typeof ve!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[de]=ve}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...N){for(const Q of N){const ie=this._tokenizer_config[Q];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(N,{progress_callback:Q=null,config:ie=null,cache_dir:de=null,local_files_only:ve=!1,revision:je="main",legacy:He=null}={}){const We=await d(N,{progress_callback:Q,config:ie,cache_dir:de,local_files_only:ve,revision:je,legacy:He});return new this(...We)}_call(N,{text_pair:Q=null,add_special_tokens:ie=!0,padding:de=!1,truncation:ve=null,max_length:je=null,return_tensor:He=!0,return_token_type_ids:We=null}={}){const Je=Array.isArray(N);let dt;if(Je){if(N.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(N.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");dt=N.map((Pt,jt)=>this._encode_plus(Pt,{text_pair:Q[jt],add_special_tokens:ie,return_token_type_ids:We}))}else dt=N.map(Pt=>this._encode_plus(Pt,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");dt=[this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:We})]}if(je===null?de==="max_length"?je=this.model_max_length:je=(0,i.max)(dt.map(Pt=>Pt.input_ids.length))[0]:ve||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."),je=Math.min(je,this.model_max_length??1/0),de||ve)for(let Pt=0;Ptje?ve&&Ns(dt[Pt],je):de&&Ss(dt[Pt],je,jt=>jt==="input_ids"?this.pad_token_id:0,this.padding_side));const xt={};if(He){if(!(de&&ve)&&dt.some(jt=>{var kt;for(const Ht of Object.keys(jt))if(jt[Ht].length!==((kt=dt[0][Ht])==null?void 0:kt.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 Pt=[dt.length,dt[0].input_ids.length];for(const jt of Object.keys(dt[0]))xt[jt]=new a.Tensor("int64",BigInt64Array.from(dt.flatMap(kt=>kt[jt]).map(BigInt)),Pt)}else{for(const Pt of Object.keys(dt[0]))xt[Pt]=dt.map(jt=>jt[Pt]);if(!Je)for(const Pt of Object.keys(xt))xt[Pt]=xt[Pt][0]}return xt}_encode_text(N){if(N===null)return null;const Q=this.added_tokens_splitter.split(N);for(let de=0;de0&&(Q[de-1]=Q[de-1].trimEnd()),ve.rstrip&&de{if(de.length===0)return[];if(this.added_tokens_map.has(de))return[de];if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=g(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const je=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:ve}):[de];return this.model(je)})}_encode_plus(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){const{tokens:ve,token_type_ids:je}=this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}),He=this.model.convert_tokens_to_ids(ve),We={input_ids:He,attention_mask:new Array(He.length).fill(1)};return(de??this.return_token_type_ids)&&je&&(We.token_type_ids=je),We}_tokenize_helper(N,{pair:Q=null,add_special_tokens:ie=!1}={}){const de=this._encode_text(N),ve=this._encode_text(Q);return this.post_processor?this.post_processor(de,ve,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(de??[],ve??[])}}tokenize(N,{pair:Q=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}).tokens}encode(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){return this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:de}).input_ids}batch_decode(N,Q={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(ie=>this.decode(ie,Q))}decode(N,Q={}){if(N instanceof a.Tensor&&(N=T(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,Q)}decode_single(N,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:ie=null}){let de=this.model.convert_ids_to_tokens(N);Q&&(de=de.filter(je=>!this.special_tokens.includes(je)));let ve=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ve=ve.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(ve=ve.trim())),(ie??this.clean_up_tokenization_spaces)&&(ve=k(ve)),ve}get_chat_template({chat_template:N=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(N!==null&&Object.hasOwn(ie,N))N=ie[N];else if(N===null)if(Q!==null&&"tool_use"in ie)N=ie.tool_use;else if("default"in ie)N=ie.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(ie).sort()}.`)}else if(N===null)if(this.chat_template)N=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 N}apply_chat_template(N,{tools:Q=null,documents:ie=null,chat_template:de=null,add_generation_prompt:ve=!1,tokenize:je=!0,padding:He=!1,truncation:We=!1,max_length:Je=null,return_tensor:dt=!0,return_dict:xt=!1,tokenizer_kwargs:Pt={},...jt}={}){if(de=this.get_chat_template({chat_template:de,tools:Q}),typeof de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let kt=this._compiled_template_cache.get(de);kt===void 0&&(kt=new u.Template(de),this._compiled_template_cache.set(de,kt));const Ht=Object.create(null);for(const cr of js){const pr=this.getToken(cr);pr&&(Ht[cr]=pr)}const br=kt.render({messages:N,add_generation_prompt:ve,tools:Q,documents:ie,...Ht,...jt});if(je){const cr=this._call(br,{add_special_tokens:!1,padding:He,truncation:We,max_length:Je,return_tensor:dt,...Pt});return xt?cr:cr.input_ids}return br}}class us extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ar extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class bs extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ft extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ds extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class cs extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ys extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Qt extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class De extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Qe extends at{}class tt extends at{}class Rt extends at{constructor(N,Q){super(N,Q);te(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 zr extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Sr extends at{}class ps extends at{}class hs extends at{}class Kr extends at{constructor($,N){super($,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs($,N,Q){return Tr(this,$,N,Q)}}class ms extends Kr{}class _s extends at{}class Hr extends at{}const vr="▁";class cn extends at{constructor(N,Q){super(N,Q);te(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new wt({replacement:vr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let Q=super._encode_text(vr+N.replaceAll(vr," "));return Q.length>1&&Q[0]===vr&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class xr extends at{}class $s extends at{}class ks extends at{}class fr extends at{}class Vs extends at{}class pn extends at{}class Fr extends at{}class hn extends at{}class qr extends at{}function Tr(he,$,N,Q){if(!("language_codes"in he)||!Array.isArray(he.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in he)||!(he.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in he)||typeof he.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=Q.src_lang,de=Q.tgt_lang;if(!he.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);if(ie!==void 0){if(!he.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);for(const ve of he.post_processor.config.single)if("SpecialToken"in ve&&he.languageRegex.test(ve.SpecialToken.id)){ve.SpecialToken.id=he.lang_to_token(ie);break}}return Q.forced_bos_token_id=he.model.convert_tokens_to_ids([he.lang_to_token(de)])[0],he._call($,N)}class Is extends at{constructor($,N){super($,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs($,N,Q){return Tr(this,$,N,Q)}}class dr extends at{constructor($,N){super($,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs($,N,Q){return Tr(this,$,N,Q)}}class gr extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:N=!1,return_language:Q=!1,time_precision:ie=null,force_full_sequences:de=!0}={}){if(ie===null)throw Error("Must specify time_precision");let ve=null;const je=N==="word";function He(){return{language:ve,timestamp:[null,null],text:""}}const We=[];let Je=He(),dt=0;const xt=this.timestamp_begin,jt=xt+1500;let kt=[],Ht=[],br=!1,cr=null;const pr=new Set(this.all_special_ids);for(const Dt of $){const rr=Dt.tokens,wr=je?Dt.token_timestamps:null;let Qr=null,Rr=xt;if("stride"in Dt){const[or,Vt,Zt]=Dt.stride;if(dt-=Vt,cr=or-Zt,Vt&&(Rr=Vt/ie+xt),Zt)for(let er=rr.length-1;er>=0;--er){const tr=Number(rr[er]);if(tr>=xt){if(Qr!==null&&(tr-xt)*ie=xt&&Vt<=jt){const Zt=(Vt-xt)*ie+dt,er=(0,i.round)(Zt,2);if(Qr!==null&&Vt>=Qr)br=!0;else if(br||kt.length>0&&Vt0?(kt.push(Yt),je&&Ht.push(jr)):kt.every(or=>or.length===0)&&(Je=He(),kt=[],Yt=[],Ht=[],jr=[])}if(kt.length>0){if(de&&N)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[Dt,rr]=this.findLongestCommonSequence(kt,Ht),wr=this.decode(Dt);Je.text=wr,je&&(Je.words=this.collateWordTimestamps(Dt,rr,ve)),We.push(Je)}let Nt=Object.create(null);const Xr=We.map(Dt=>Dt.text).join("");if(N||Q){for(let Dt=0;Dt0;let je=ve?[]:null,He=ve?N[0]:null;for(let We=1;We<$.length;++We){const Je=$[We];let dt=0,xt=[ie,ie,0,0];const Pt=Je.length;for(let Nt=1;NtVt===Rr[Zt]&&He[Xr+Zt]<=N[We][wr+Zt]).length:Yt=rr.filter((Vt,Zt)=>Vt===Rr[Zt]).length;const jr=Nt/1e4,or=Yt/Nt+jr;Yt>1&&or>dt&&(dt=or,xt=[Xr,Dt,wr,Qr])}const[jt,kt,Ht,br]=xt,cr=Math.floor((kt+jt)/2),pr=Math.floor((br+Ht)/2);de.push(...Q.slice(0,cr)),Q=Je.slice(pr),ie=Q.length,ve&&(je.push(...He.slice(0,cr)),He=N[We].slice(pr))}return de.push(...Q),ve?(je.push(...He),[de,je]):[de,[]]}collateWordTimestamps($,N,Q){const[ie,de,ve]=this.combineTokensIntoWords($,Q),je=[];for(let He=0;He=ie){const je=((ve-ie)*Q).toFixed(2);de.push(`<|${je}|>`),de.push([])}else de[de.length-1].push(ve);return de=de.map(ve=>typeof ve=="string"?ve:super.decode(ve,N)),de.join("")}splitTokensOnUnicode($){const N=this.decode($,{decode_with_timestamps:!0}),Q="�",ie=[],de=[],ve=[];let je=[],He=[],We=0;for(let Je=0;Je<$.length;++Je){const dt=$[Je];je.push(dt),He.push(Je);const xt=this.decode(je,{decode_with_timestamps:!0});(!xt.includes(Q)||N[We+xt.indexOf(Q)]===Q)&&(ie.push(xt),de.push(je),ve.push(He),je=[],He=[],We+=xt.length)}return[ie,de,ve]}splitTokensOnSpaces($){const[N,Q,ie]=this.splitTokensOnUnicode($),de=[],ve=[],je=[],He=new RegExp(`^[${M}]$`,"gu");for(let We=0;We=this.model.tokens_to_ids.get("<|endoftext|>"),jt=Je.startsWith(" "),kt=Je.trim(),Ht=He.test(kt);if(Pt||jt||Ht||de.length===0)de.push(Je),ve.push(dt),je.push(xt);else{const br=de.length-1;de[br]+=Je,ve[br].push(...dt),je[br].push(...xt)}}return[de,ve,je]}mergePunctuations($,N,Q,ie,de){const ve=structuredClone($),je=structuredClone(N),He=structuredClone(Q);let We=ve.length-2,Je=ve.length-1;for(;We>=0;)ve[We].startsWith(" ")&&ie.includes(ve[We].trim())?(ve[Je]=ve[We]+ve[Je],je[Je]=(0,o.mergeArrays)(je[We],je[Je]),He[Je]=(0,o.mergeArrays)(He[We],He[Je]),ve[We]="",je[We]=[],He[We]=[]):Je=We,--We;for(We=0,Je=1;Jedt),je.filter(dt=>dt.length>0),He.filter(dt=>dt.length>0)]}}class Br extends at{}class mn extends at{}class _n extends at{}class fn extends at{constructor($,N){super($,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[N,...Q]=$.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(N);if(Q.length===2){const[ie,de]=Q;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(de))}}}class gn extends at{}class wn extends at{}class vs extends at{}class Mn extends at{}class Us extends at{}class bn extends at{constructor($,N){super($,N),this.decoder=new lt({})}}class yn extends at{}class xs extends at{}class vn{static async from_pretrained($,{progress_callback:N=null,config:Q=null,cache_dir:ie=null,local_files_only:de=!1,revision:ve="main",legacy:je=null}={}){var xt;const[He,We]=await d($,{progress_callback:N,config:Q,cache_dir:ie,local_files_only:de,revision:ve,legacy:je}),Je=((xt=We.tokenizer_class)==null?void 0:xt.replace(/Fast$/,""))??"PreTrainedTokenizer";let dt=this.TOKENIZER_CLASS_MAPPING[Je];return dt||(console.warn(`Unknown tokenizer class "${Je}", attempting to construct from base class.`),dt=at),new dt(He,We)}}te(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Sr,DistilBertTokenizer:Qe,CamembertTokenizer:tt,DebertaTokenizer:ds,DebertaV2Tokenizer:cs,BertTokenizer:us,HerbertTokenizer:ys,ConvBertTokenizer:Qt,RoFormerTokenizer:De,XLMTokenizer:Rt,ElectraTokenizer:zr,MobileBertTokenizer:bs,SqueezeBertTokenizer:Ft,AlbertTokenizer:Ar,GPT2Tokenizer:ps,BartTokenizer:hs,MBartTokenizer:Kr,MBart50Tokenizer:ms,RobertaTokenizer:_s,WhisperTokenizer:gr,CodeGenTokenizer:Br,CLIPTokenizer:mn,SiglipTokenizer:_n,MarianTokenizer:fn,BloomTokenizer:Hr,NllbTokenizer:Is,M2M100Tokenizer:dr,LlamaTokenizer:cn,CodeLlamaTokenizer:xr,XLMRobertaTokenizer:$s,MPNetTokenizer:ks,FalconTokenizer:fr,GPTNeoXTokenizer:Vs,EsmTokenizer:pn,Wav2Vec2CTCTokenizer:gn,BlenderbotTokenizer:wn,BlenderbotSmallTokenizer:vs,SpeechT5Tokenizer:Mn,NougatTokenizer:Us,VitsTokenizer:bn,Qwen2Tokenizer:Fr,GemmaTokenizer:hn,Grok1Tokenizer:qr,CohereTokenizer:yn,MgpstrTokenizer:xs,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>G,hamming:()=>c,hanning:()=>d,mel_filter_bank:()=>S,read_audio:()=>u,spectrogram:()=>C,window_function:()=>A});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(j,ee){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)(j)).arrayBuffer(),Z=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${Z.sampleRate}Hz.`);const X=await Z.decodeAudioData(H);let oe;if(X.numberOfChannels===2){const me=Math.sqrt(2),ae=X.getChannelData(0),V=X.getChannelData(1);oe=new Float32Array(ae.length);for(let F=0;F2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,ee=1e3,H=15,Z=27/Math.log(6.4))=>j>=ee?H+Math.log(j/ee)*Z:3*j/200};function _(j,ee="htk"){const H=f[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}const T={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,ee=1e3,H=15,Z=Math.log(6.4)/27)=>j>=H?ee*Math.exp(Z*(j-H)):200*j/3};function k(j,ee="htk"){const H=T[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}function w(j,ee){const H=Float64Array.from({length:ee.length-1},(me,ae)=>ee[ae+1]-ee[ae]),Z=Array.from({length:j.length},()=>new Array(ee.length));for(let me=0;menew Array(j.length));for(let me=0;mej+Z*oe)}function S(j,ee,H,Z,X,oe=null,me="htk",ae=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(j<2)throw new Error(`Require num_frequency_bins: ${j} >= 2`);if(H>Z)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${Z}`);const V=_(H,me),F=_(Z,me),W=g(V,F,ee+2);let re=k(W,me),_e;if(ae){const ce=X/((j-1)*2);_e=_(Float64Array.from({length:j},($e,Ue)=>Ue*ce),me),re=W}else _e=g(0,Math.floor(X/2),j);const se=w(_e,re);if(oe!==null&&oe==="slaney")for(let ce=0;ceX)throw Error(`frame_length (${H}) may not be larger than fft_length (${X})`);if(xe!==H)throw new Error(`Length of the window (${xe}) must equal frame_length (${H})`);if(Z<=0)throw new Error("hop_length must be greater than zero");if(oe===null&&W!==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(me){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const ye=Math.floor((X-1)/2)+1;j=E(j,ye,ye)}let be=Math.floor(1+Math.floor((j.length-H)/Z));we!==null&&bebe?R&&(Fe=q):Fe=Ae=q);const ze=new o.FFT(X),Ve=new Float64Array(X),O=new Float64Array(ze.outputBufferSize),Y=new Float32Array(Se*Fe);for(let ye=0;ye=1;--Ie)Ve[Ie]-=F*Ve[Ie-1];Ve[0]*=1-F}for(let Ie=0;IeMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(H&&(me=me.subarray(0,j)),Z===null)return me;if(j>Z)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${Z})`);return me}function B(j,ee){let H=44;const Z=new ArrayBuffer(H+j.length*4),X=new DataView(Z);K(X,0,"RIFF"),X.setUint32(4,36+j.length*4,!0),K(X,8,"WAVE"),K(X,12,"fmt "),X.setUint32(16,16,!0),X.setUint16(20,3,!0),X.setUint16(22,1,!0),X.setUint32(24,ee,!0),X.setUint32(28,ee*4,!0),X.setUint16(32,4,!0),X.setUint16(34,32,!0),K(X,36,"data"),X.setUint32(40,j.length*4,!0);for(let oe=0;oe{let oe=await X.arrayBuffer();a.writeFileSync(Z,Buffer.from(oe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(ee,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>f,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>T,pop:()=>p,product:()=>c,reverseDictionary:()=>o,saveBlob:()=>_});function s(g,S){g&&g(S)}function o(g){return Object.fromEntries(Object.entries(g).map(([S,E])=>[E,S]))}function n(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(g){var S,E,y;return((y=(E=(S=g==null?void 0:g.prototype)==null?void 0:S.__proto__)==null?void 0:E.constructor)==null?void 0:y.name)==="TypedArray"}function a(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function u(g){const S=[];let E=g;for(;Array.isArray(E);)S.push(E.length),E=E[0];return S}function p(g,S,E=void 0){const y=g[S];if(y!==void 0)return delete g[S],y;if(E===void 0)throw Error(`Key ${S} does not exist in object.`);return E}function d(...g){return Array.prototype.concat.apply([],g)}function c(...g){return g.reduce((S,E)=>S.flatMap(y=>E.map(M=>[y,M])))}function f(g,S){return Math.abs((g+S)%(2*S)-S)}function _(g,S){const E=URL.createObjectURL(S),y=document.createElement("a");y.href=E,y.download=g,y.click(),y.remove(),URL.revokeObjectURL(E)}function T(g,S){return Object.assign({},...S.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function k(g){let S=0;for(const E of g)++S;return S}function w(g,S){let E=0;for(const y of g)y===S&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,c=1/0){this._heap=[],this._comparator=d,this._maxSize=c}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 c of d)if(this.size0&&this._swap(0,c),this._heap.pop(),this._siftDown(),d}replace(d){const c=this.peek();return this._heap[0]=d,this._siftDown(),c}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,c){return this._comparator(this._heap[d],this._heap[c])}_swap(d,c){const f=this._heap[d];this._heap[d]=this._heap[c],this._heap[c]=f}_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 _=new a(this.bosTokenId,0,0,0,0),T=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(_)}insert(d,c,f,_){const T=this.nodes.length,k=new a(_,T,d,c,f);this.beginNodes[d].push(k),this.endNodes[d+c].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let c=0;for(;c<=d;){if(this.beginNodes[c].length==0)return[];for(let w of this.beginNodes[c]){w.prev=null;let g=0,S=null;for(let E of this.endNodes[c]){const y=E.backtraceScore+w.score;(S===null||y>g)&&(S=E.clone(),g=y)}if(S!==null)w.prev=S,w.backtraceScore=g;else return[]}++c}const f=[],T=this.beginNodes[d][0].prev;if(T===null)return[];let k=T.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(c=>this.piece(c))}tokenIds(){return this.viterbi().map(c=>c.tokenId)}}class a{constructor(d,c,f,_,T){this.tokenId=d,this.nodeId=c,this.pos=f,this.length=_,this.score=T,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}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){var f;const c=Object.create(null);for(const _ of d){let T=c;for(let k=0;k<_.length;++k)T=T[f=_[k]]??(T[f]=Object.create(null));T.end=_}return c}split(d){const c=[],f=d.length;let _=0,T=0;for(;T_&&c.push(d.slice(_,T)),c.push(w),T+=w.length,_=T):++T}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./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:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){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:()=>f,getModelFile:()=>g,getModelJSON:()=>S});var s=t("?7a2c"),o=t("?a42a"),n=t("./src/env.js"),i=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 u{constructor(v){if(this.filePath=v,this.headers=new Headers,this.exists=s.existsSync(v),this.exists){this.status=200,this.statusText="OK";let C=s.statSync(v);this.headers.set("content-length",C.size.toString()),this.updateContentType();const A=s.createReadStream(v);this.body=new ReadableStream({start(B){A.on("data",K=>B.enqueue(K)),A.on("end",()=>B.close()),A.on("error",K=>B.error(K))},cancel(){A.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const v=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[v]??"application/octet-stream")}clone(){let v=new u(this.filePath);return v.exists=this.exists,v.status=this.status,v.statusText=this.statusText,v.headers=new Headers(this.headers),v}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const v=await s.promises.readFile(this.filePath);return new Blob([v],{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(M,v=null,C=null){let A;try{A=new URL(M)}catch{return!1}return!(v&&!v.includes(A.protocol)||C&&!C.includes(A.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function c(M){return!(!d.test(M)||M.includes("..")||M.includes("--")||M.endsWith(".git")||M.endsWith(".ipynb"))}async function f(M){var v;if(n.env.useFS&&!p(M,["http:","https:","blob:"]))return new u(M.toString());if(typeof process<"u"&&((v=process==null?void 0:process.release)==null?void 0:v.name)==="node"){const C=!!(Cs!=null&&Cs.TESTING_REMOTELY),A=n.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${A}; is_ci/${C};`),p(M,["http:","https:"],["huggingface.co","hf.co"])){const G=(Cs==null?void 0:Cs.HF_TOKEN)??(Cs==null?void 0:Cs.HF_ACCESS_TOKEN);G&&B.set("Authorization",`Bearer ${G}`)}return fetch(M,{headers:B})}else return fetch(M)}const _={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 T(M,v,C){if(!C)return null;const A=_[M]??`Error (${M}) occurred while trying to load file`;throw Error(`${A}: "${v}".`)}class k{constructor(v){this.path=v}async match(v){let C=o.join(this.path,v),A=new u(C);if(A.exists)return A}async put(v,C,A=void 0){let B=o.join(this.path,v);try{const K=C.headers.get("Content-Length"),G=parseInt(K??"0");let j=0;await s.promises.mkdir(o.dirname(B),{recursive:!0});const ee=s.createWriteStream(B),H=C.body.getReader();for(;;){const{done:Z,value:X}=await H.read();if(Z)break;await new Promise((me,ae)=>{ee.write(X,V=>{if(V){ae(V);return}me()})}),j+=X.length;const oe=G?j/G*100:0;A==null||A({progress:oe,loaded:j,total:G})}ee.close()}catch(K){try{await s.promises.unlink(B)}catch{}throw K}}}async function w(M,...v){for(let C of v)try{let A=await M.match(C);if(A)return A}catch{continue}}async function g(M,v,C=!0,A={},B=!1){if(!n.env.allowLocalModels){if(A.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,i.dispatchCallback)(A.progress_callback,{status:"initiate",name:M,file:v});let K;if(!K&&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");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(re){console.warn("An error occurred while opening the browser cache:",re)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new k(A.cache_dir??n.env.cacheDir)}const G=A.revision??"main",j=y(M,v),ee=c(M),H=ee?y(n.env.localModelPath,j):j,Z=y(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",M).replaceAll("{revision}",encodeURIComponent(G)),v);let X;const oe=K instanceof k?G==="main"?j:y(M,G,v):Z;let me=!1,ae;K&&(ae=await w(K,H,oe));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(j,["http:","https:"])){if(A.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${j}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${j}.`)}else try{ae=await f(H),X=H}catch(_e){console.warn(`Unable to load from local path "${H}": "${_e}"`)}if(ae===void 0||ae.status===404){if(A.local_files_only||!n.env.allowRemoteModels){if(C)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!ee)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${M}".`);if(ae=await f(Z),ae.status!==200)return T(ae.status,Z,C);X=oe}me=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(A.progress_callback,{status:"download",name:M,file:v});let F;if(!(n.apis.IS_NODE_ENV&&B)){let re;A.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(re=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:M,file:v,progress:100,loaded:re.length,total:re.length})):re=await E(ae,_e=>{(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:M,file:v,..._e})}):re=new Uint8Array(await ae.arrayBuffer()),F=re}if(me&&X&&await K.match(X)===void 0&&(F?await K.put(X,new Response(F,{headers:ae.headers})).catch(re=>{console.warn(`Unable to add response to browser cache: ${re}.`)}):await K.put(X,ae,A.progress_callback)),(0,i.dispatchCallback)(A.progress_callback,{status:"done",name:M,file:v}),F){if(!n.apis.IS_NODE_ENV&&B)throw new Error("Cannot return path in a browser environment.");return F}if(ae instanceof u)return ae.filePath;const W=await(K==null?void 0:K.match(X));if(W instanceof u)return W.filePath;if(W instanceof Response)return new Uint8Array(await W.arrayBuffer());if(typeof W=="string")return W;throw new Error("Unable to get model file path or buffer.")}async function S(M,v,C=!0,A={}){const B=await g(M,v,C,A,!1);if(B===null)return{};const G=new TextDecoder("utf-8").decode(B);return JSON.parse(G)}async function E(M,v){const C=M.headers.get("Content-Length");C===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let A=parseInt(C??"0"),B=new Uint8Array(A),K=0;const G=M.body.getReader();async function j(){const{done:ee,value:H}=await G.read();if(ee)return;const Z=K+H.length;if(Z>A){A=Z;const oe=new Uint8Array(A);oe.set(B),B=oe}B.set(H,K),K=Z;const X=K/A*100;return v({progress:X,loaded:K,total:A}),j()}return await j(),B}function y(...M){return M=M.map((v,C)=>(C&&(v=v.replace(new RegExp("^/"),"")),C!==M.length-1&&(v=v.replace(new RegExp("/$"),"")),v)),M.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>T});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const d=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(d)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async k=>{const g=(await k.metadata()).channels,{data:S,info:E}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),y=new _(new Uint8ClampedArray(S),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&y.convert(g),y};else throw new Error("Unable to load image processing library.");const c={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(w,g,S,E){this.data=w,this.width=g,this.height=S,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const S=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _(S,w.width,w.height,4)}static async fromURL(w){const g=await(0,o.getFile)(w);if(g.status!==200)throw new Error(`Unable to read image from "${w}" (${g.status} ${g.statusText})`);const S=await g.blob();return this.fromBlob(S)}static async fromBlob(w){if(d){const g=await p(w),S=l(g.width,g.height).getContext("2d");return S.drawImage(g,0,0),new this(S.getImageData(0,0,g.width,g.height).data,g.width,g.height,4)}else{const g=a(await w.arrayBuffer());return await p(g)}}static fromTensor(w,g="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(g==="CHW")w=w.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let g=0,S=0;g=0?C=S:B=-S,E>=0?A=E:K=-E,v.drawImage(M,C,A,w,g,B,K,w,g),new _(v.getImageData(0,0,w,g).data,w,g,4).convert(y)}else{let y=this.toSharp();if(S>=0&&E>=0)y=y.extract({left:Math.floor(S),top:Math.floor(E),width:w,height:g});else if(S<=0&&E<=0){const M=Math.floor(-E),v=Math.floor(-S);y=y.extend({top:M,left:v,right:w-this.width-v,bottom:g-this.height-M})}else{let M=[0,0],v=0;E<0?(M[0]=Math.floor(-E),M[1]=g-this.height-M[0]):v=Math.floor(E);let C=[0,0],A=0;S<0?(C[0]=Math.floor(-S),C[1]=w-this.width-C[0]):A=Math.floor(S),y=y.extend({top:M[0],bottom:M[1],left:C[0],right:C[1]}).extract({left:A,top:v,width:w,height:g})}return await p(y)}}async toBlob(w="image/png",g=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:g})}toTensor(w="CHW"){let g=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return g}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),g=l(w.width,w.height),S=new u(w.data,w.width,w.height);return g.getContext("2d").putImageData(S,0,0),g}split(){const{data:w,width:g,height:S,channels:E}=this,y=w.constructor,M=w.length/E,v=Array.from({length:E},()=>new y(M));for(let C=0;Cnew _(C,g,S,1))}_update(w,g,S,E=null){return this.data=w,this.width=g,this.height=S,E!==null&&(this.channels=E),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){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(w){if(d){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const g=w.split(".").pop().toLowerCase(),S=f.get(g)??"image/png",E=await this.toBlob(S);(0,s.saveBlob)(w,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)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 T=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>T,bankers_round:()=>g,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>o,round:()=>w,softmax:()=>n});function s(E,[y,M,v],[C,A],B="bilinear",K=!1){const G=A/v,j=C/M,ee=new E.constructor(C*A*y),H=M*v,Z=C*A;for(let X=0;X=0;--K)C[K]=G,v[K]=y[M[K]],G*=v[K];const A=M.map((K,G)=>C[M.indexOf(G)]),B=new E.constructor(E.length);for(let K=0;K=0;--j)G+=ee%y[j]*A[j],ee=Math.floor(ee/y[j]);B[G]=E[K]}return[B,v]}function n(E){const y=d(E)[0],M=E.map(A=>Math.exp(A-y)),v=M.reduce((A,B)=>A+B,0);return M.map(A=>A/v)}function i(E){const y=d(E)[0];let M=0;for(let A=0;AA-y-v)}function a(E,y){let M=0;for(let v=0;vy+M*M,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let y=E[0],M=0;for(let v=1;vy&&(y=E[v],M=v);return[y,M]}function c(E){return E>0&&(E&E-1)===0}class f{constructor(y){if(this.size=y|0,this.size<=1||!c(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let v=0;vv;v<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=y[C];return v}toComplexArray(y,M){const v=M||this.createComplexArray();for(let C=0;C>>1],v[C+1]=0;return v}transform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._transform4(y,M,1)}realTransform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._realTransform4(y,M,1)}inverseTransform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._transform4(y,M,-1);for(let v=0;v>=2;B>=2;B>>=2){K=C/B<<1;const Z=K>>>2;for(G=0;G>>1,B>>>1)}else for(G=0,j=0;G>>1,B>>>1,v)}const H=this.table;for(B>>=2;B>=2;B>>=2){K=C/B<<1;const X=K>>>1,oe=X>>>1,me=oe>>>1;for(G=0;G>>1;for(let X=2;X>1;++ee){const H=(ee+1-y)**2/2,Z=Math.sqrt(G**2+j**2)**H,X=H*Math.atan2(j,G),oe=2*ee;A[oe]=Z*Math.cos(X),A[oe+1]=Z*Math.sin(X),B[oe]=A[oe],B[oe+1]=-A[oe+1]}this._slicedChirpBuffer=A.subarray(M,v),this._f=new f(C>>1),this._f.transform(this._chirpBuffer,B)}_transform(y,M,v){const C=this._buffer1,A=this._buffer2,B=this._outBuffer1,K=this._outBuffer2,G=this._chirpBuffer,j=this._slicedChirpBuffer,ee=this._a;if(v)for(let H=0;H>1,oe=M[X];C[H]=oe*j[H],C[Z]=oe*j[Z]}else for(let H=0;H=E.length&&(G=2*(E.length-1)-G),v[B++]=E[G]}v.sort(),M[A]=v[C]}return M}function w(E,y){const M=Math.pow(10,y);return Math.round(E*M)/M}function g(E){const y=Math.round(E);return Math.abs(E)%1===.5?y%2===0?y:y-1:y}function S(E){const y=E.length,M=E[0].length,v=[y+1,M+1],C=Array.from({length:v[0]},()=>Array(v[1]).fill(1/0));C[0][0]=0;const A=Array.from({length:v[0]},()=>Array(v[1]).fill(-1));for(let ee=1;ee0||K>0;)switch(G.push(B-1),j.push(K-1),A[B][K]){case 0:--B,--K;break;case 1:--B;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${B}, ${K}]. Please file a bug report.`)}return G.reverse(),j.reverse(),[G,j]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>M,full:()=>j,full_like:()=>ee,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>g,matmul:()=>c,mean:()=>B,mean_pooling:()=>w,ones:()=>H,ones_like:()=>Z,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>me,rfft:()=>f,slice:()=>k,stack:()=>v,std_mean:()=>A,topk:()=>_,zeros:()=>X,zeros_like:()=>oe});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=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(...F){te(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(W,re)=>{if(typeof re=="string"){let _e=Number(re);if(Number.isInteger(_e))return W._getitem(_e)}return W[re]},set:(W,re,_e)=>W[re]=_e})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}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[F,...W]=this.dims;if(W.length>0){const re=W.reduce((_e,se)=>_e*se);for(let _e=0;_e0){const _e=re.reduce((se,ce)=>se*ce);return this._subarray(F,_e,re)}else return new a(this.type,[this.data[F]],re)}indexOf(F){const W=this.data;for(let re=0;repe)throw new Error(`Invalid slice: ${q}`);const xe=[Math.max(R,0),Math.min(pe,this.dims[we])];re.push(xe),W.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${q}`)}const _e=re.map(([we,q])=>q-we),se=_e.reduce((we,q)=>we*q),ce=this.data,$e=new ce.constructor(se),Ue=this.stride();for(let we=0;we=0;--R){const xe=_e[R];q+=(pe%xe+re[R][0])*Ue[R],pe=Math.floor(pe/xe)}$e[we]=ce[q]}return new a(this.type,$e,W)}permute(...F){return u(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,W=!1){return this.norm(1,F,W)}norm(F="fro",W=null,re=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const _e=this.data,se=(we,q)=>we+q**F;if(W===null){const we=_e.reduce(se,0)**(1/F);return new a(this.type,[we],[])}const[ce,$e,Ue]=C(se,this,W,re);if(F!==1)for(let we=0;we<$e.length;++we)$e[we]=$e[we]**(1/F);return new a(ce,$e,Ue)}normalize_(F=2,W=1){W=y(W,this.dims.length);const re=this.norm(F,W,!0),_e=this.data,se=re.data;for(let ce=0;ce<_e.length;++ce){let $e=0;for(let Ue=this.dims.length-1,we=ce,q=1;Ue>=0;--Ue){const R=this.dims[Ue];if(Ue!==W){const pe=we%R;$e+=pe*q,q*=this.dims[Ue]}we=Math.floor(we/R)}_e[ce]/=se[$e]}return this}normalize(F=2,W=1){return this.clone().normalize_(F,W)}stride(){return K(this.dims)}squeeze(F=null){return new a(this.type,this.data,S(this.dims,F))}squeeze_(F=null){return this.dims=S(this.dims,F),this}unsqueeze(F=null){return new a(this.type,this.data,E(this.dims,F))}unsqueeze_(F=null){return this.dims=E(this.dims,F),this}flatten_(F=0,W=-1){W=(W+this.dims.length)%this.dims.length;let re=this.dims.slice(0,F),_e=this.dims.slice(F,W+1),se=this.dims.slice(W+1);return this.dims=[...re,_e.reduce((ce,$e)=>ce*$e,1),...se],this}flatten(F=0,W=-1){return this.clone().flatten_(F,W)}view(...F){let W=-1;for(let _e=0;_e$e!==W?se*ce:se,1);F[W]=re.length/_e}return new a(this.type,re,F)}neg_(){const F=this.data;for(let W=0;WF?1:0;return new a("bool",W,this.dims)}lt(F){const W=new Uint8Array(this.data.length),re=this.data;for(let _e=0;_eMath.min(ce,$e),this,F,W,1/0);return new a(re,_e,se)}max(F=null,W=!1){if(F===null){const ce=(0,s.max)(this.data)[0];return new a(this.type,[ce],[])}const[re,_e,se]=C((ce,$e)=>Math.max(ce,$e),this,F,W,-1/0);return new a(re,_e,se)}argmin(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.min)(this.data)[1];return new a("int64",[BigInt(re)],[])}argmax(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.max)(this.data)[1];return new a("int64",[BigInt(re)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let W;const re=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(F);return re&&!_e?W=Number:!re&&_e&&(W=BigInt),new a(F,i[F].from(this.data,W),this.dims)}}function l(V,F){const W=V.length,re=F.reduce((se,ce)=>se*ce);if(W!==re)throw Error(`cannot reshape array of size ${W} into shape (${F})`);let _e=V;for(let se=F.length-1;se>=0;se--)_e=_e.reduce((ce,$e)=>{let Ue=ce[ce.length-1];return Ue.lengthnew a("int64",V,[V.length]);async function k(V,F,W,re,_e){return await(await n.TensorOpRegistry.slice)({x:V,s:T(F),e:T(W),a:T(re),t:T(_e??new Array(re.length).fill(1))})}function w(V,F){const W=V.data,re=F.data,_e=[V.dims[0],V.dims[2]],se=new W.constructor(_e[0]*_e[1]),[ce,$e,Ue]=V.dims;let we=0;for(let q=0;qW!==1):typeof F=="number"?V[F]===1&&V.splice(F,1):Array.isArray(F)&&(V=V.filter((W,re)=>W!==1||!F.includes(re))),V}function E(V,F){return F=y(F,V.length+1),V=V.slice(),V.splice(F,0,1),V}function y(V,F,W=null,re=!0){if(V<-F||V>=F){if(re)throw new Error(`IndexError: index ${V} is out of bounds for dimension${W===null?"":" "+W} with size ${F}`);return V<-F?0:F}return V<0&&(V=(V%F+F)%F),V}function M(V,F=0){F=y(F,V[0].dims.length);const W=V[0].dims.slice();W[F]=V.reduce((ce,$e)=>ce+$e.dims[F],0);const re=W.reduce((ce,$e)=>ce*$e,1),_e=new V[0].data.constructor(re),se=V[0].type;if(F===0){let ce=0;for(const $e of V){const Ue=$e.data;_e.set(Ue,ce),ce+=Ue.length}}else{let ce=0;for(let $e=0;$e=0;--pe){const Se=we[pe];let Ae=xe%Se;pe===F&&(Ae+=ce),R+=Ae*be,be*=W[pe],xe=Math.floor(xe/Se)}_e[R]=Ue[q]}ce+=we[F]}}return new a(se,_e,W)}function v(V,F=0){return M(V.map(W=>W.unsqueeze(F)),F)}function C(V,F,W=null,re=!1,_e=null){const se=F.data,ce=F.dims;W=y(W,ce.length);const $e=ce.slice();$e[W]=1;const Ue=new se.constructor(se.length/ce[W]);_e!==null&&Ue.fill(_e);for(let we=0;we=0;--R){const be=ce[R];if(R!==W){const Se=pe%be;q+=Se*xe,xe*=$e[R]}pe=Math.floor(pe/be)}Ue[q]=V(Ue[q],se[we],we,q)}return re||$e.splice(W,1),[F.type,Ue,$e]}function A(V,F=null,W=1,re=!1){const _e=V.data,se=V.dims;if(F===null){const xe=_e.reduce((Fe,ze)=>Fe+ze,0)/_e.length,be=Math.sqrt(_e.reduce((Fe,ze)=>Fe+(ze-xe)**2,0)/(_e.length-W)),Se=new a(V.type,[xe],[]);return[new a(V.type,[be],[]),Se]}F=y(F,se.length);const ce=B(V,F,re),$e=ce.data,[Ue,we,q]=C((pe,xe,be,Se)=>pe+(xe-$e[Se])**2,V,F,re);for(let pe=0;pewe+q,0);return new a(V.type,[Ue/_e.length],[])}F=y(F,re.length);const[se,ce,$e]=C((Ue,we)=>Ue+we,V,F,W);if(re[F]!==1)for(let Ue=0;Ue=0;--W)F[W]=re,re*=V[W];return F}function G(V,F,W,re){const _e=V.reduce((se,ce)=>se*ce,1);return new a(W,new re(_e).fill(F),V)}function j(V,F){let W,re;if(typeof F=="number")W="float32",re=Float32Array;else if(typeof F=="bigint")W="int64",re=BigInt64Array;else if(typeof F=="boolean")W="bool",re=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return G(V,F,W,re)}function ee(V,F){return j(V.dims,F)}function H(V){return G(V,1n,"int64",BigInt64Array)}function Z(V){return H(V.dims)}function X(V){return G(V,0n,"int64",BigInt64Array)}function oe(V){return X(V.dims)}function me(V){const F=V.reduce((W,re)=>W*re,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),V)}function ae(V,F){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const W=F==="binary",re=W?"int8":"uint8",_e=W?Int8Array:Uint8Array,se=V.data,ce=new _e(se.length/8);for(let $e=0;$e0?1:0,we=Math.floor($e/8),q=$e%8;ce[we]|=Ue<<7-q,W&&q===0&&(ce[we]-=128)}return new a(re,ce,[V.dims[0],V.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((d,c)=>new n(d,(c+1)/(u.length+1)*p))),this.frames=u,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:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],c=document.createElement("video");if(c.crossOrigin="anonymous",c.muted=!0,typeof l=="string")c.src=l;else if(l instanceof Blob)c.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)c.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(S=>c.onloadedmetadata=S),c.seekable.start(0)===c.seekable.end(0)){const E=await(await fetch(c.src)).blob();c.src=URL.createObjectURL(E),await new Promise(y=>c.onloadedmetadata=y)}const f=c.duration;let _,T;u!=null?(_=u,T=u===1?0:f/(u-1)):(T=1/p,_=Math.floor(f/T));let k=[];for(let S=0;S<_;++S)k.push(u===1?f/2:S*T);const w=document.createElement("canvas");w.width=c.videoWidth,w.height=c.videoHeight;const g=w.getContext("2d",{willReadFrequently:!0});for(const S of k){c.currentTime=S,await new Promise(v=>{c.onseeked=v}),g.drawImage(c,0,0,w.width,w.height);const E=g.getImageData(0,0,w.width,w.height),y=new s.RawImage(E.data,w.width,w.height,4),M=new n(y,S);d.push(M)}return c.remove(),new i(d,f)}}},Ng={};function $t(e){var r=Ng[e];if(r!==void 0)return r.exports;var t=Ng[e]={exports:{}};return bx[e](t,t.exports,$t),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;$t.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 o=Object.create(null);$t.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,$t.d(o,n),o}})(),$t.d=(e,r)=>{for(var t in r)$t.o(r,t)&&!$t.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},$t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),$t.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ - !*** ./src/transformers.js ***! - \*****************************/$t.r(m),$t.d(m,{ASTFeatureExtractor:()=>d.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:()=>o.AutoConfig,AutoFeatureExtractor:()=>c.AutoFeatureExtractor,AutoImageProcessor:()=>T.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:()=>g.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:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.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:()=>d.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:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>E.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:()=>u.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:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.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,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:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.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:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.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:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.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:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.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:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.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:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.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:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.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:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.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:()=>w.Qwen2VLProcessor,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.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:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.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:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.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:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.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:()=>y.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:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.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:()=>w.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:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.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:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.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=$t("./src/env.js"),r=$t("./src/pipelines.js"),t=$t("./src/models.js"),s=$t("./src/tokenizers.js"),o=$t("./src/configs.js"),n=$t("./src/utils/audio.js"),i=$t("./src/utils/image.js"),a=$t("./src/utils/video.js"),l=$t("./src/utils/tensor.js"),u=$t("./src/utils/maths.js"),p=$t("./src/base/feature_extraction_utils.js"),d=$t("./src/models/feature_extractors.js"),c=$t("./src/models/auto/feature_extraction_auto.js"),f=$t("./src/base/image_processors_utils.js"),_=$t("./src/models/image_processors.js"),T=$t("./src/models/auto/image_processing_auto.js"),k=$t("./src/base/processing_utils.js"),w=$t("./src/models/processors.js"),g=$t("./src/models/auto/processing_auto.js"),S=$t("./src/generation/streamers.js"),E=$t("./src/generation/stopping_criteria.js"),y=$t("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC,m.AutoModelForCausalLM,m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection;var yx=m.AutoProcessor,vx=m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DPTFeatureExtractor,m.DPTForDepthEstimation,m.DPTImageProcessor,m.DPTModel,m.DPTPreTrainedModel,m.DacDecoderModel,m.DacDecoderOutput,m.DacEncoderModel,m.DacEncoderOutput,m.DacFeatureExtractor,m.DacModel,m.DacPreTrainedModel,m.DataTypeMap,m.DebertaForMaskedLM,m.DebertaForQuestionAnswering,m.DebertaForSequenceClassification,m.DebertaForTokenClassification,m.DebertaModel,m.DebertaPreTrainedModel,m.DebertaTokenizer,m.DebertaV2ForMaskedLM,m.DebertaV2ForQuestionAnswering,m.DebertaV2ForSequenceClassification,m.DebertaV2ForTokenClassification,m.DebertaV2Model,m.DebertaV2PreTrainedModel,m.DebertaV2Tokenizer,m.DecisionTransformerModel,m.DecisionTransformerPreTrainedModel,m.DeiTFeatureExtractor,m.DeiTForImageClassification,m.DeiTImageProcessor,m.DeiTModel,m.DeiTPreTrainedModel,m.DepthAnythingForDepthEstimation,m.DepthAnythingPreTrainedModel,m.DepthEstimationPipeline,m.DepthProForDepthEstimation,m.DepthProPreTrainedModel,m.DetrFeatureExtractor,m.DetrForObjectDetection,m.DetrForSegmentation,m.DetrImageProcessor,m.DetrModel,m.DetrObjectDetectionOutput,m.DetrPreTrainedModel,m.DetrSegmentationOutput,m.Dinov2ForImageClassification,m.Dinov2Model,m.Dinov2PreTrainedModel,m.Dinov2WithRegistersForImageClassification,m.Dinov2WithRegistersModel,m.Dinov2WithRegistersPreTrainedModel,m.DistilBertForMaskedLM,m.DistilBertForQuestionAnswering,m.DistilBertForSequenceClassification,m.DistilBertForTokenClassification,m.DistilBertModel,m.DistilBertPreTrainedModel,m.DistilBertTokenizer,m.DocumentQuestionAnsweringPipeline,m.DonutFeatureExtractor,m.DonutImageProcessor,m.DonutSwinModel,m.DonutSwinPreTrainedModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline,m.InterruptableStoppingCriteria,m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.LiteWhisperForConditionalGeneration,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.PatchTSMixerForPrediction,m.PatchTSMixerModel,m.PatchTSMixerPreTrainedModel,m.PatchTSTForPrediction,m.PatchTSTModel,m.PatchTSTPreTrainedModel,m.Phi3ForCausalLM,m.Phi3Model,m.Phi3PreTrainedModel,m.Phi3VForCausalLM,m.Phi3VImageProcessor,m.Phi3VPreTrainedModel,m.Phi3VProcessor,m.PhiForCausalLM,m.PhiModel,m.PhiPreTrainedModel,m.Pipeline,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SuppressTokensAtBeginLogitsProcessor,m.Swin2SRForImageSuperResolution,m.Swin2SRImageProcessor,m.Swin2SRModel,m.Swin2SRPreTrainedModel,m.SwinForImageClassification,m.SwinForSemanticSegmentation,m.SwinModel,m.SwinPreTrainedModel,m.T5ForConditionalGeneration,m.T5Model,m.T5PreTrainedModel,m.T5Tokenizer,m.TableTransformerForObjectDetection,m.TableTransformerModel,m.TableTransformerObjectDetectionOutput,m.TableTransformerPreTrainedModel,m.TemperatureLogitsWarper,m.Tensor,m.Text2TextGenerationPipeline,m.TextClassificationPipeline,m.TextGenerationPipeline;var xx=m.TextStreamer;m.TextToAudioPipeline,m.TokenClassificationPipeline,m.TokenClassifierOutput,m.TokenizerModel,m.TopKLogitsWarper,m.TopPLogitsWarper,m.TrOCRForCausalLM,m.TrOCRPreTrainedModel,m.TranslationPipeline,m.UltravoxModel,m.UltravoxPreTrainedModel,m.UltravoxProcessor,m.UniSpeechForCTC,m.UniSpeechForSequenceClassification,m.UniSpeechModel,m.UniSpeechPreTrainedModel,m.UniSpeechSatForAudioFrameClassification,m.UniSpeechSatForCTC,m.UniSpeechSatForSequenceClassification,m.UniSpeechSatModel,m.UniSpeechSatPreTrainedModel,m.VLChatProcessor,m.VLMImageProcessor,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor;var Tx=m.WhisperForConditionalGeneration;m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env;var Ex=m.full;m.full_like,m.getKeyValueShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data,m.pipeline,m.quantize_embeddings,m.rand,m.read_audio,m.rfft,m.round,m.slice,m.softmax,m.spectrogram,m.stack,m.std_mean,m.topk,m.window_function,m.zeros,m.zeros_like;const Px=64;class Gn{static async getInstance(r){return this.model_id="onnx-community/whisper-large-v3-turbo",this.tokenizer??(this.tokenizer=vx.from_pretrained(this.model_id,{progress_callback:r})),this.processor??(this.processor=yx.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=Tx.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])}}te(Gn,"model_id",null),te(Gn,"tokenizer"),te(Gn,"processor"),te(Gn,"model");async function Cx(e){const r=atob(e),t=new Uint8Array(r.length);for(let n=0;n{i??(i=performance.now());let _;a++>0&&(_=a/(performance.now()-i)*1e3),globalThis.postMessage({status:"update",output:f,tps:_,numTokens:a})},u=new xx(s,{skip_prompt:!0,decode_kwargs:{skip_special_tokens:!0},callback_function:l}),p=await o(t),d=await n.generate({...p,max_new_tokens:Px,language:r,streamer:u}),c=s.batch_decode(d,{skip_special_tokens:!0});globalThis.postMessage({status:"complete",output:c}),cu=!1}async function $x(){globalThis.postMessage({status:"loading",data:"Loading model..."});const[e,r,t]=await Gn.getInstance(s=>{globalThis.postMessage(s)});globalThis.postMessage({status:"loading",data:"Compiling shaders and warming up model..."}),await t.generate({input_features:Ex([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":$x();break;case"generate":Sx(t);break}})})(); diff --git a/assets/xai-_FNFPrWi.js b/assets/xai-CEcx0MIE.js similarity index 66% rename from assets/xai-_FNFPrWi.js rename to assets/xai-CEcx0MIE.js index e8138890092f2284a717d8267fca8404d0198836..345bb3f843f44d61fff7128446b695adaef33b60 100644 --- a/assets/xai-_FNFPrWi.js +++ b/assets/xai-CEcx0MIE.js @@ -1 +1 @@ -import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-DA8bJuvF.js";import{d as U,g as V,S as k,s as y,h as v,H as $,v as K,A as h,o as S,w as u,i as l,b as t}from"./index-BQKiy4UR.js";import"./three-vrm-animation.module-DtlqIxay.js";import"./mcp-DQCTu0C2.js";import"./mini_xsschema-P_8cZcRg.js";import{u as w}from"./providers-kjOpfeNb.js";import"./Select.vue_vue_type_style_index_0_lang-CdNsRrhL.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-BheCfLJF.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-rVjiRQS_.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-x8xUEJYM.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BUIEH7SV.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-DqVSQvRV.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-CyGzqBlh.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-ggPZf4Zf.js";import"./Input.vue_vue_type_script_setup_true_lang-CkN-mlBP.js";const a="xai",C=U({__name:"xai",setup(I){const{t:m}=V(),b=k(),d=w(),{providers:o}=y(d),n=v(()=>d.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}});$(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return S(),h(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:u(()=>[l(t(P),null,{default:u(()=>[l(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=x=>r.value=x),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"xai-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.x.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; +import"./Stage.vue_vue_type_style_index_0_scoped_e41b35dc_lang-BSxtbxMR.js";import{d as U,g as V,S as k,s as y,h as v,H as $,v as K,A as h,o as S,w as u,i as l,b as t}from"./index-CQudhZin.js";import"./three-vrm-animation.module-Dklr5eVx.js";import"./mcp-C9U4MroK.js";import"./mini_xsschema-P_8cZcRg.js";import{u as w}from"./providers-Y3Mr8_DF.js";import"./Select.vue_vue_type_style_index_0_lang-COUgWdqQ.js";import{_ as z,a as M}from"./ProviderBaseUrlInput.vue_vue_type_script_setup_true_lang-DblEmB5i.js";import{_ as N}from"./ProviderApiKeyInput.vue_vue_type_script_setup_true_lang-Bz5V2NMr.js";import{_ as P,a as R}from"./ProviderSettingsContainer.vue_vue_type_script_setup_true_lang-C1viGef8.js";import{_ as B}from"./ProviderSettingsLayout.vue_vue_type_script_setup_true_lang-BzVP69oi.js";import{b as _}from"./route-block-B_A1xBdJ.js";import"./index-LHmcipjy.js";import"./floating-ui.core-CgBsuaUc.js";import"./Collapsable.vue_vue_type_script_setup_true_lang-C_oeG5EH.js";import"./TransitionVertical.vue_vue_type_script_setup_true_lang-DzZuJ6Ph.js";import"./FieldInput.vue_vue_type_script_setup_true_lang-Cjz2od2D.js";import"./Input.vue_vue_type_script_setup_true_lang-BPw4nzGW.js";const a="xai",C=U({__name:"xai",setup(I){const{t:m}=V(),b=k(),d=w(),{providers:o}=y(d),n=v(()=>d.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}});$(()=>{var e,i;d.initializeProvider(a),r.value=((e=o.value[a])==null?void 0:e.apiKey)||"",s.value=((i=o.value[a])==null?void 0:i.baseUrl)||""}),K([r,s],()=>{o.value[a]={...o.value[a],apiKey:r.value,baseUrl:s.value||""}});function g(){var e;o.value[a]={...(e=n.value)==null?void 0:e.defaultOptions}}return(e,i)=>{var c,f;return S(),h(t(B),{"provider-name":(c=n.value)==null?void 0:c.localizedName,"provider-icon":(f=n.value)==null?void 0:f.icon,"on-back":()=>t(b).back()},{default:u(()=>[l(t(P),null,{default:u(()=>[l(t(R),{title:t(m)("settings.pages.providers.common.section.basic.title"),description:t(m)("settings.pages.providers.common.section.basic.description"),"on-reset":g},{default:u(()=>{var p;return[l(t(N),{modelValue:r.value,"onUpdate:modelValue":i[0]||(i[0]=x=>r.value=x),"provider-name":(p=n.value)==null?void 0:p.localizedName,placeholder:"xai-..."},null,8,["modelValue","provider-name"])]}),_:1},8,["title","description"]),l(t(z),{title:t(m)("settings.pages.providers.common.section.advanced.title")},{default:u(()=>[l(t(M),{modelValue:s.value,"onUpdate:modelValue":i[1]||(i[1]=p=>s.value=p),placeholder:"https://api.x.ai/v1/"},null,8,["modelValue"])]),_:1},8,["title"])]),_:1})]),_:1},8,["provider-name","provider-icon","on-back"])}}});typeof _=="function"&&_(C);export{C as default}; diff --git a/assets/zod-CxRm5Gac-D7xrOp6Y.js b/assets/zod-CxRm5Gac-CPS76V3O.js similarity index 70% rename from assets/zod-CxRm5Gac-D7xrOp6Y.js rename to assets/zod-CxRm5Gac-CPS76V3O.js index 0738001dd7d08cc878544db4f36f5dfffe1ba59b..47dc8c4a5b207bbbd738d48aa0a5e496dfa51205 100644 --- a/assets/zod-CxRm5Gac-D7xrOp6Y.js +++ b/assets/zod-CxRm5Gac-CPS76V3O.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mcp-DQCTu0C2.js","assets/index-BQKiy4UR.js","assets/index-C-ktGyiB.css","assets/index-BOS-VO_F.js"])))=>i.map(i=>d[i]); -import{L as n}from"./index-BQKiy4UR.js";const c=async()=>{let r=e=>{throw new Error('xsschema: Missing dependencies "zod" or "@zod/mini".')},a=e=>{throw new Error('xsschema: Missing dependencies "zod-to-json-schema".')};try{const{z:e}=await n(async()=>{const{z:o}=await import("./mini_xsschema-P_8cZcRg.js").then(t=>t.m);return{z:o}},[]);r=e.toJSONSchema}catch{}try{const{z:e}=await n(async()=>{const{z:o}=await import("./mcp-DQCTu0C2.js").then(t=>t.i);return{z:o}},__vite__mapDeps([0,1,2]));"toJSONSchema"in e&&(r=e.toJSONSchema)}catch(e){e instanceof Error&&console.error(e.message)}try{const{zodToJsonSchema:e}=await n(async()=>{const{zodToJsonSchema:o}=await import("./index-BOS-VO_F.js");return{zodToJsonSchema:o}},__vite__mapDeps([3,0,1,2]));a=e}catch(e){e instanceof Error&&console.error(e.message)}return async e=>"_zod"in e?r(e):a(e)};export{c as getToJsonSchemaFn}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mcp-C9U4MroK.js","assets/index-CQudhZin.js","assets/index-C-ktGyiB.css","assets/index-Lt-e6-Iy.js"])))=>i.map(i=>d[i]); +import{L as n}from"./index-CQudhZin.js";const c=async()=>{let r=e=>{throw new Error('xsschema: Missing dependencies "zod" or "@zod/mini".')},a=e=>{throw new Error('xsschema: Missing dependencies "zod-to-json-schema".')};try{const{z:e}=await n(async()=>{const{z:o}=await import("./mini_xsschema-P_8cZcRg.js").then(t=>t.m);return{z:o}},[]);r=e.toJSONSchema}catch{}try{const{z:e}=await n(async()=>{const{z:o}=await import("./mcp-C9U4MroK.js").then(t=>t.i);return{z:o}},__vite__mapDeps([0,1,2]));"toJSONSchema"in e&&(r=e.toJSONSchema)}catch(e){e instanceof Error&&console.error(e.message)}try{const{zodToJsonSchema:e}=await n(async()=>{const{zodToJsonSchema:o}=await import("./index-Lt-e6-Iy.js");return{zodToJsonSchema:o}},__vite__mapDeps([3,0,1,2]));a=e}catch(e){e instanceof Error&&console.error(e.message)}return async e=>"_zod"in e?r(e):a(e)};export{c as getToJsonSchemaFn}; diff --git a/index.html b/index.html index 4515cb1f322460c7ae26391bf712d5d1eab6ef43..bcd645f236bd9a2d6fe318f2052d7681490fe445 100644 --- a/index.html +++ b/index.html @@ -7,7 +7,7 @@ - + - +