ug-js-sdk 3.0.46 → 3.0.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ug-js-sdk.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*! For license information please see ug-js-sdk.mjs.LICENSE.txt */
|
|
2
|
-
var __webpack_modules__={20:(t,e)=>{function n(t,e,n){for(var r=0;r<n.length;r++)t.setUint8(e+r,n.charCodeAt(r))}Object.defineProperty(e,"__esModule",{value:!0}),e.audioFileToArray=e.encodeWAV=e.arrayBufferToBase64=e.minFramesForTargetMS=void 0,e.minFramesForTargetMS=function(t,e,n=16e3){return Math.ceil(t*n/1e3/e)},e.arrayBufferToBase64=function(t){const e=new Uint8Array(t),n=e.byteLength,r=new Array(n);for(var i=0;i<n;i++){const t=e[i];if(void 0===t)break;r[i]=String.fromCharCode(t)}return btoa(r.join(""))},e.encodeWAV=function(t,e=3,r=16e3,i=1,o=32){var s=o/8,a=i*s,u=new ArrayBuffer(44+t.length*s),l=new DataView(u);return n(l,0,"RIFF"),l.setUint32(4,36+t.length*s,!0),n(l,8,"WAVE"),n(l,12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,e,!0),l.setUint16(22,i,!0),l.setUint32(24,r,!0),l.setUint32(28,r*a,!0),l.setUint16(32,a,!0),l.setUint16(34,o,!0),n(l,36,"data"),l.setUint32(40,t.length*s,!0),1===e?function(t,e,n){for(var r=0;r<n.length;r++,e+=2){var i=Math.max(-1,Math.min(1,n[r]));t.setInt16(e,i<0?32768*i:32767*i,!0)}}(l,44,t):function(t,e,n){for(var r=0;r<n.length;r++,e+=4)t.setFloat32(e,n[r],!0)}(l,44,t),u},e.audioFileToArray=async function(t){const e=new OfflineAudioContext(1,1,44100),n=new FileReader;let r=null;if(await new Promise(i=>{n.addEventListener("loadend",t=>{const o=n.result;e.decodeAudioData(o,t=>{r=t,e.startRendering().then(t=>{console.log("Rendering completed successfully"),i()}).catch(t=>{console.error(`Rendering failed: ${t}`)})},t=>{console.log(`Error with decoding audio data: ${t}`)})}),n.readAsArrayBuffer(t)}),null===r)throw Error("some shit");let i=r,o=new Float32Array(i.length);for(let t=0;t<i.length;t++)for(let e=0;e<i.numberOfChannels;e++)o[t]+=i.getChannelData(e)[t];return{audio:o,sampleRate:i.sampleRate}}},28:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||r(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.SileroV5=e.SileroLegacy=void 0,i(n(55),e);var o=n(461);Object.defineProperty(e,"SileroLegacy",{enumerable:!0,get:function(){return o.SileroLegacy}});var s=n(463);Object.defineProperty(e,"SileroV5",{enumerable:!0,get:function(){return s.SileroV5}})},33:(t,e)=>{var n;Object.defineProperty(e,"__esModule",{value:!0}),e.Message=void 0,function(t){t.AudioFrame="AUDIO_FRAME",t.SpeechStart="SPEECH_START",t.VADMisfire="VAD_MISFIRE",t.SpeechEnd="SPEECH_END",t.SpeechStop="SPEECH_STOP",t.SpeechRealStart="SPEECH_REAL_START",t.FrameProcessed="FRAME_PROCESSED"}(n||(e.Message=n={}))},55:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},61:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.baseAssetPath=void 0;const n="undefined"!=typeof window&&void 0!==window.document?window.document.currentScript:null;let r="/";n&&(r=n.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),e.baseAssetPath=r},264:(module,__unused_webpack_exports,__webpack_require__)=>{!function(t,e){module.exports=e(__webpack_require__(450))}(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(t,e,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return k.buffer!=M&&W(k.buffer),F}function i(){return k.buffer!=M&&W(k.buffer),$}function o(){return k.buffer!=M&&W(k.buffer),L}function s(){return k.buffer!=M&&W(k.buffer),N}function a(){return k.buffer!=M&&W(k.buffer),j}var u,l,c;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise(function(t,e){l=t,c=e});var d,h,p,f,g,m,b=Object.assign({},u),y="./this.program",_=(t,e)=>{throw e},w="object"==typeof window,v="function"==typeof importScripts,x="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,T=u.ENVIRONMENT_IS_PTHREAD||!1,S="";function A(t){return u.locateFile?u.locateFile(t,S):S+t}if(x){let e;S=v?n(908).dirname(S)+"/":"//",m=()=>{g||(f=n(1384),g=n(908))},d=function(t,e){return m(),t=g.normalize(t),f.readFileSync(t,e?void 0:"utf8")},p=t=>((t=d(t,!0)).buffer||(t=new Uint8Array(t)),t),h=(t,e,n)=>{m(),t=g.normalize(t),f.readFile(t,function(t,r){t?n(t):e(r.buffer)})},1<process.argv.length&&(y=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(t){if(!(t instanceof lt))throw t}),process.on("unhandledRejection",function(t){throw t}),_=(t,e)=>{if(Z())throw process.exitCode=t,e;e instanceof lt||D("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(9925)}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(w||v)&&(v?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),r&&(S=r),S=0!==S.indexOf("blob:")?S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1):"",x||(d=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},v&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),h=(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)}));x&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var E=console.log.bind(console),O=console.warn.bind(console);x&&(m(),E=t=>f.writeSync(1,t+"\n"),O=t=>f.writeSync(2,t+"\n"));var I,P=u.print||E,D=u.printErr||O;Object.assign(u,b),b=null,u.thisProgram&&(y=u.thisProgram),u.quit&&(_=u.quit),u.wasmBinary&&(I=u.wasmBinary);var C=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&ot("no native wasm support detected");var k,R,M,F,$,L,N,j,U=!1,B="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function V(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&B)return B.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var i=t[e++];if(128&i){var o=63&t[e++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var s=63&t[e++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function H(t,e){return(t>>>=0)?V(i(),t,e):""}function z(t,e,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<t.length;++o){var s=t.charCodeAt(o);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&t.charCodeAt(++o)),127>=s){if(n>=r)break;e[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;e[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;e[n++>>>0]=224|s>>12}else{if(n+3>=r)break;e[n++>>>0]=240|s>>18,e[n++>>>0]=128|s>>12&63}e[n++>>>0]=128|s>>6&63}e[n++>>>0]=128|63&s}}return e[n>>>0]=0,n-i}function G(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function W(t){M=t,u.HEAP8=F=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=L=new Int32Array(t),u.HEAPU8=$=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=N=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=j=new Float64Array(t)}T&&(M=u.buffer);var q=u.INITIAL_MEMORY||16777216;if(T)k=u.wasmMemory,M=u.buffer;else if(u.wasmMemory)k=u.wasmMemory;else if(!((k=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw D("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"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");k&&(M=k.buffer),q=M.byteLength,W(M);var X,Y=[],K=[],J=[],Q=[];function Z(){return C||!1}function tt(){var t=u.preRun.shift();Y.unshift(t)}var et,nt=0,rt=null,it=null;function ot(t){throw T?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),D(t="Aborted("+t+")"),U=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),c(t),t}function st(){return et.startsWith("data:application/octet-stream;base64,")}function at(){var t=et;try{if(t==et&&I)return new Uint8Array(I);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){ot(t)}}et="ort-wasm-threaded.wasm",st()||(et=A(et));var ut={};function lt(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function ct(t){(t=ft.Vb[t])||ot(),ft.mc(t)}function dt(t){var e=ft.Cc();if(!e)return 6;ft.ac.push(e),ft.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 ht(t){if(T)return qt(1,1,t);Z()||(ft.oc(),u.onExit&&u.onExit(t),U=!0),_(t,new lt(t))}function pt(t,e){if(!e&&T)throw mt(t),"unwind";Z()||T||(be(),gt(J),me(0),re[1].length&&ie(1,10),re[2].length&&ie(2,10),ft.oc()),ht(t)}var ft={Yb:[],ac:[],qc:[],Vb:{},fc:function(){T&&ft.Ec()},Pc:function(){},Ec:function(){ft.receiveObjectTransfer=ft.Gc,ft.threadInitTLS=ft.pc,ft.setExitStatus=ft.nc,C=!1},nc:function(){},oc:function(){for(var t of Object.values(ft.Vb))ft.mc(t);for(t of ft.Yb)t.terminate();ft.Yb=[]},mc:function(t){var e=t.Ub;delete ft.Vb[e],ft.Yb.push(t),ft.ac.splice(ft.ac.indexOf(t),1),t.Ub=0,xe(e)},Gc:function(){},pc:function(){ft.qc.forEach(t=>t())},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ft.Bc=t.Ub),n.targetThread&&n.targetThread!=pe()){var i=ft.Vb[n.Qc];i?i.postMessage(n,n.transferList):D('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?Bt(n.queue):"spawnThread"===r?dt(n):"cleanupThread"===r?ct(n.thread):"killThread"===r?(n=n.thread,r=ft.Vb[n],delete ft.Vb[n],r.terminate(),xe(n),ft.ac.splice(ft.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ft.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?P("Thread "+n.threadId+": "+n.text):"printErr"===r?D("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&&D("worker sent an unknown command "+r);ft.Bc=void 0},t.onerror=t=>{throw D("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},x&&(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||r,wasmMemory:k,wasmModule:R})},yc:function(){var t=A("ort-wasm-threaded.worker.js");ft.Yb.push(new Worker(t))},Cc:function(){return 0==ft.Yb.length&&(ft.yc(),ft.Fc(ft.Yb[0])),ft.Yb.pop()}};function gt(t){for(;0<t.length;)t.shift()(u)}function mt(t){if(T)return qt(2,0,t);try{pt(t)}catch(t){t instanceof lt||"unwind"==t||_(1,t)}}u.PThread=ft,u.establishStackSpace=function(){var t=pe(),e=o()[t+44>>2>>>0];t=o()[t+48>>2>>>0],Ae(e,e-t),Oe(e)};var bt=[];function yt(t){var e=bt[t];return e||(t>=bt.length&&(bt.length=t+1),bt[t]=e=X.get(t)),e}u.invokeEntryPoint=function(t,e){t=yt(t)(e),Z()?ft.nc(t):Te(t)};var _t,wt,vt=[],xt=0,Tt=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){s()[this.Sb+4>>2>>>0]=t},this.bc=function(){return s()[this.Sb+4>>2>>>0]},this.wc=function(t){s()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return s()[this.Sb+8>>2>>>0]},this.rc=function(){o()[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(o(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(o(),this.Sb>>2,1)},this.cc=function(t){s()[this.Sb+16>>2>>>0]=t},this.tc=function(){return s()[this.Sb+16>>2>>>0]},this.vc=function(){if(De(this.bc()))return s()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function At(t){return ge(new St(t).Sb)}function Et(t,e,n,r){return T?qt(3,1,t,e,n,r):Ot(t,e,n,r)}function Ot(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return D("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return T&&0===i.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:i},T?(t.Oc="spawnThread",postMessage(t,i),0):dt(t))}function It(t,e,n){return T?qt(4,1,t,e,n):0}function Pt(t,e){if(T)return qt(5,1,t,e)}function Dt(t,e){if(T)return qt(6,1,t,e)}function Ct(t,e,n){if(T)return qt(7,1,t,e,n)}function kt(t,e,n){return T?qt(8,1,t,e,n):0}function Rt(t,e){if(T)return qt(9,1,t,e)}function Mt(t,e,n){if(T)return qt(10,1,t,e,n)}function Ft(t,e,n,r){if(T)return qt(11,1,t,e,n,r)}function $t(t,e,n,r){if(T)return qt(12,1,t,e,n,r)}function Lt(t,e,n,r){if(T)return qt(13,1,t,e,n,r)}function Nt(t){if(T)return qt(14,1,t)}function jt(t,e){if(T)return qt(15,1,t,e)}function Ut(t,e,n){if(T)return qt(16,1,t,e,n)}function Bt(t){Atomics.store(o(),t>>2,1),pe()&&ve(t),Atomics.compareExchange(o(),t>>2,1,0)}function Vt(t){return s()[t>>>2]+4294967296*o()[t+4>>>2]}function Ht(t,e,n,r,i,o){return T?qt(17,1,t,e,n,r,i,o):-52}function zt(t,e,n,r,i,o){if(T)return qt(18,1,t,e,n,r,i,o)}function Gt(t){var n=G(t)+1,r=fe(n);return r&&z(t,e(),r,n),r}function Wt(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}if(T)return qt(19,1,t,e,n);var i=(new Date).getFullYear(),a=new Date(i,0,1),u=new Date(i,6,1);i=a.getTimezoneOffset();var l=u.getTimezoneOffset(),c=Math.max(i,l);o()[t>>2>>>0]=60*c,o()[e>>2>>>0]=Number(i!=l),t=r(a),e=r(u),t=Gt(t),e=Gt(e),l<i?(s()[n>>2>>>0]=t,s()[n+4>>2>>>0]=e):(s()[n>>2>>>0]=e,s()[n+4>>2>>>0]=t)}function qt(t,e){var n=arguments.length-2,r=arguments;return function(t){var e=Ee();return t=t(),Oe(e),t}(()=>{for(var i=Ie(8*n),o=i>>3,s=0;s<n;s++){var u=r[2+s];a()[o+s>>>0]=u}return we(t,n,i,e)})}u.executeNotifiedProxyingQueue=Bt,wt=x?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:T?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var Xt,Yt=[],Kt={};function Jt(){if(!Xt){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",_:y||"./this.program"};for(t in Kt)void 0===Kt[t]?delete e[t]:e[t]=Kt[t];var n=[];for(t in e)n.push(t+"="+e[t]);Xt=n}return Xt}function Qt(t,n){if(T)return qt(20,1,t,n);var r=0;return Jt().forEach(function(i,o){var a=n+r;for(o=s()[t+4*o>>2>>>0]=a,a=0;a<i.length;++a)e()[(0|o++)>>>0]=i.charCodeAt(a);e()[(0|o)>>>0]=0,r+=i.length+1}),0}function Zt(t,e){if(T)return qt(21,1,t,e);var n=Jt();s()[t>>2>>>0]=n.length;var r=0;return n.forEach(function(t){r+=t.length+1}),s()[e>>2>>>0]=r,0}function te(t){return T?qt(22,1,t):52}function ee(t,e,n,r){return T?qt(23,1,t,e,n,r):52}function ne(t,e,n,r,i){return T?qt(24,1,t,e,n,r,i):70}var re=[null,[],[]];function ie(t,e){var n=re[t];0===e||10===e?((1===t?P:D)(V(n,0)),n.length=0):n.push(e)}function oe(t,e,n,r){if(T)return qt(25,1,t,e,n,r);for(var o=0,a=0;a<n;a++){var u=s()[e>>2>>>0],l=s()[e+4>>2>>>0];e+=8;for(var c=0;c<l;c++)ie(t,i()[u+c>>>0]);o+=l}return s()[r>>2>>>0]=o,0}var se=0;function ae(t){return 0==t%4&&(0!=t%100||0==t%400)}var ue=[31,29,31,30,31,30,31,31,30,31,30,31],le=[31,28,31,30,31,30,31,31,30,31,30,31];function ce(t,n,r,i){function s(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function a(t,e){return s(t,e,"0")}function u(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function l(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function c(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ae(t.getFullYear())?ue:le)[n];if(!(e>r-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=l(new Date(t.getFullYear(),0,4)),n=l(n),0>=u(e,t)?0>=u(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var d=o()[i+40>>2>>>0];for(var h in i={Lc:o()[i>>2>>>0],Kc:o()[i+4>>2>>>0],dc:o()[i+8>>2>>>0],jc:o()[i+12>>2>>>0],ec:o()[i+16>>2>>>0],Xb:o()[i+20>>2>>>0],Tb:o()[i+24>>2>>>0],Wb:o()[i+28>>2>>>0],Rc:o()[i+32>>2>>>0],Jc:o()[i+36>>2>>>0],Mc:d?H(d):""},r=H(r),d={"%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(h,"g"),d[h]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),f="January February March April May June July August September October November December".split(" ");for(h in d={"%a":function(t){return p[t.Tb].substring(0,3)},"%A":function(t){return p[t.Tb]},"%b":function(t){return f[t.ec].substring(0,3)},"%B":function(t){return f[t.ec]},"%C":function(t){return a((t.Xb+1900)/100|0,2)},"%d":function(t){return a(t.jc,2)},"%e":function(t){return s(t.jc,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return a(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12<t&&(t-=12),a(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(ae(t.Xb+1900)?ue:le)[n++]);return a(t.jc+e,3)},"%m":function(t){return a(t.ec+1,2)},"%M":function(t){return a(t.Kc,2)},"%n":function(){return"\n"},"%p":function(t){return 0<=t.dc&&12>t.dc?"AM":"PM"},"%S":function(t){return a(t.Lc,2)},"%t":function(){return"\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return a(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&&ae(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ae(t.Xb%400-1))&&e++}return a(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return a(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"),d)r.includes(h)&&(r=r.replace(new RegExp(h,"g"),d[h](i)));return h=function(t){var e=Array(G(t)+1);return z(t,e,0,e.length),e}(r=r.replace(/\0\0/g,"%")),h.length>n?0:(function(t,n){e().set(t,n>>>0)}(h,t),h.length-1)}ft.fc();var de=[null,ht,mt,Et,It,Pt,Dt,Ct,kt,Rt,Mt,Ft,$t,Lt,Nt,jt,Ut,Ht,zt,Wt,Qt,Zt,te,ee,ne,oe],he={b:function(t){return fe(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),xt--),t.ic(!1),vt.push(t),t.sc(),t.vc()},ma:function(t){throw D("Unexpected exception thrown, this is not properly supported - aborting"),U=!0,t},x:function(){Se(0);var t=vt.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&yt(e)(t.Zb),At(t.Zb)}Tt=0},e:function(){var t=Tt;if(!t)return se=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return se=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Pe(o,n,e.Sb+16))return se=o,t}return se=n,t},l:function(){var t=Tt;if(!t)return se=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return se=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Pe(o,n,e.Sb+16))return se=o,t}return se=n,t},h:function(){var t=Tt;if(!t)return se=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return se=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Pe(o,n,e.Sb+16))return se=o,t}return se=n,t},t:At,M:function(){var t=vt.pop();t||ot("no exception to throw");var e=t.Zb;throw t.kc()||(vt.push(t),t.ic(!0),t.hc(!1),xt++),Tt=e,e},c:function(t,e,n){throw new St(t).fc(e,n),Tt=t,xt++,t},pa:function(){return xt},Fa:function(t){ye(t,!v,1,!w),ft.pc()},T:function(t){T?postMessage({cmd:"cleanupThread",thread:t}):ct(t)},xa:Ot,j:function(t){throw Tt||(Tt=t),t},H:It,Ma:Pt,ua:Dt,wa:Ct,oa:kt,Ka:Rt,Ca:Mt,Ja:Ft,V:$t,va:Lt,sa:Nt,La:jt,ta:Ut,Ta:function(){},X:function(){ot("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){ot("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout(()=>Bt(r));else if(T)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ft.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Vt(t)),o()[e>>2>>>0]=t.getUTCSeconds(),o()[e+4>>2>>>0]=t.getUTCMinutes(),o()[e+8>>2>>>0]=t.getUTCHours(),o()[e+12>>2>>>0]=t.getUTCDate(),o()[e+16>>2>>>0]=t.getUTCMonth(),o()[e+20>>2>>>0]=t.getUTCFullYear()-1900,o()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Vt(t)),o()[e>>2>>>0]=t.getSeconds(),o()[e+4>>2>>>0]=t.getMinutes(),o()[e+8>>2>>>0]=t.getHours(),o()[e+12>>2>>>0]=t.getDate(),o()[e+16>>2>>>0]=t.getMonth(),o()[e+20>>2>>>0]=t.getFullYear()-1900,o()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;o()[e+28>>2>>>0]=r,o()[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)),o()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(o()[t+20>>2>>>0]+1900,o()[t+16>>2>>>0],o()[t+12>>2>>>0],o()[t+8>>2>>>0],o()[t+4>>2>>>0],o()[t>>2>>>0],0),n=o()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),s=new Date(e.getFullYear(),6,1).getTimezoneOffset(),a=i.getTimezoneOffset(),u=Math.min(a,s);return 0>n?o()[t+32>>2>>>0]=Number(s!=a&&u==r):0<n!=(u==r)&&(s=Math.max(a,s),e.setTime(e.getTime()+6e4*((0<n?u:s)-r))),o()[t+24>>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,o()[t+28>>2>>>0]=n,o()[t>>2>>>0]=e.getSeconds(),o()[t+4>>2>>>0]=e.getMinutes(),o()[t+8>>2>>>0]=e.getHours(),o()[t+12>>2>>>0]=e.getDate(),o()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Ht,Ba:zt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Wt(e,n,r))},y:function(){ot("")},U:function(){if(!x&&!v){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";_t||(_t={}),_t[t]||(_t[t]=1,x&&(t="warning: "+t),D(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){i().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return x?n(3993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Yt.length=e,n>>=3;for(var r=0;r<e;r++)Yt[r]=a()[n+r>>>0];return(0>t?ut[-t-1]:de[t]).apply(null,Yt)},qa:function(t){var e=i().length;if((t>>>=0)<=e||4294901760<t)return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var o=Math;r=Math.max(t,r),o=o.min.call(o,4294901760,r+(65536-r%65536)%65536);t:{try{k.grow(o-M.byteLength+65535>>>16),W(k.buffer);var s=1;break t}catch(t){}s=void 0}if(s)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Zt,J:pt,I:te,S:ee,ga:ne,R:oe,d:function(){return se},na:function t(r,i){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(x)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()=>ot("randomDevice")}());for(var o=0;o<i;o++)e()[(r+o|0)>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return yt(t)(e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return yt(t)(e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return yt(t)()}catch(t){if(Oe(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return yt(t)(e)}catch(t){if(Oe(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return yt(t)(e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return yt(t)(e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return yt(t)(e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var i=Ee();try{return yt(t)(e,n,r)}catch(t){if(Oe(i),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,i){var o=Ee();try{return yt(t)(e,n,r,i)}catch(t){if(Oe(o),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,i,o){var s=Ee();try{return yt(t)(e,n,r,i,o)}catch(t){if(Oe(s),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,i,o){var s=Ee();try{return yt(t)(e,n,r,i,o)}catch(t){if(Oe(s),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,i,o,s){var a=Ee();try{return yt(t)(e,n,r,i,o,s)}catch(t){if(Oe(a),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,i,o,s,a){var u=Ee();try{return yt(t)(e,n,r,i,o,s,a)}catch(t){if(Oe(u),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,i,o,s,a,u,l,c,d){var h=Ee();try{return yt(t)(e,n,r,i,o,s,a,u,l,c,d)}catch(t){if(Oe(h),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,i,o,s,a){var u=Ee();try{return je(t,e,n,r,i,o,s,a)}catch(t){if(Oe(u),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,i,o,s){var a=Ee();try{return ke(t,e,n,r,i,o,s)}catch(t){if(Oe(a),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,i){var o=Ee();try{return Ue(t,e,n,r,i)}catch(t){if(Oe(o),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var i=Ee();try{return Le(t,e,n,r)}catch(t){if(Oe(i),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return Ce(t)}catch(t){if(Oe(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return Ne(t,e)}catch(t){if(Oe(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return Re(t,e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{yt(t)()}catch(t){if(Oe(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{yt(t)(e)}catch(t){if(Oe(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{yt(t)(e,n)}catch(t){if(Oe(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var i=Ee();try{yt(t)(e,n,r)}catch(t){if(Oe(i),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var i=Ee();try{yt(t)(e,n,r)}catch(t){if(Oe(i),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,i){var o=Ee();try{yt(t)(e,n,r,i)}catch(t){if(Oe(o),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,i,o){var s=Ee();try{yt(t)(e,n,r,i,o)}catch(t){if(Oe(s),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,i,o,s){var a=Ee();try{yt(t)(e,n,r,i,o,s)}catch(t){if(Oe(a),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,i,o,s,a){var u=Ee();try{yt(t)(e,n,r,i,o,s,a)}catch(t){if(Oe(u),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,i,o,s,a,u){var l=Ee();try{yt(t)(e,n,r,i,o,s,a,u)}catch(t){if(Oe(l),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,i,o,s,a,u,l,c){var d=Ee();try{yt(t)(e,n,r,i,o,s,a,u,l,c)}catch(t){if(Oe(d),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,i,o,s,a,u,l,c,d,h,p,f,g){var m=Ee();try{yt(t)(e,n,r,i,o,s,a,u,l,c,d,h,p,f,g)}catch(t){if(Oe(m),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,i,o,s,a){var u=Ee();try{Me(t,e,n,r,i,o,s,a)}catch(t){if(Oe(u),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,i,o,s,a,u,l,c,d){var h=Ee();try{$e(t,e,n,r,i,o,s,a,u,l,c,d)}catch(t){if(Oe(h),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,i,o){var s=Ee();try{Fe(t,e,n,r,i,o)}catch(t){if(Oe(s),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:k||u.wasmMemory,G:function(t){se=t},la:ce,z:function(t,e,n,r){return ce(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ft.qc.push(u.asm.sb),X=u.asm.ub,K.unshift(u.asm.Va),R=e,T||(nt--,u.monitorRunDependencies&&u.monitorRunDependencies(nt),0==nt&&(null!==rt&&(clearInterval(rt),rt=null),it&&(t=it,it=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!I&&(w||v)){if("function"==typeof fetch&&!et.startsWith("file://"))return fetch(et,{credentials:"same-origin"}).then(function(t){if(!t.ok)throw"failed to load wasm binary file at '"+et+"'";return t.arrayBuffer()}).catch(function(){return at()});if(h)return new Promise(function(t,e){h(et,function(e){t(new Uint8Array(e))},e)})}return Promise.resolve().then(function(){return at()})}().then(function(t){return WebAssembly.instantiate(t,r)}).then(function(t){return t}).then(t,function(t){D("failed to asynchronously prepare wasm: "+t),ot(t)})}var r={a:he};if(T||(nt++,u.monitorRunDependencies&&u.monitorRunDependencies(nt)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return D("Module.instantiateWasm callback failed with error: "+t),!1}(I||"function"!=typeof WebAssembly.instantiateStreaming||st()||et.startsWith("file://")||x||"function"!=typeof fetch?n(e):fetch(et,{credentials:"same-origin"}).then(function(t){return WebAssembly.instantiateStreaming(t,r).then(e,function(t){return D("wasm streaming compile failed: "+t),D("falling back to ArrayBuffer instantiation"),n(e)})})).catch(c)}(),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 pe=u._pthread_self=function(){return(pe=u._pthread_self=u.asm.ob).apply(null,arguments)},fe=u._malloc=function(){return(fe=u._malloc=u.asm.pb).apply(null,arguments)},ge=u._free=function(){return(ge=u._free=u.asm.qb).apply(null,arguments)},me=u._fflush=function(){return(me=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 be=u.___funcs_on_exit=function(){return(be=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ye=u.__emscripten_thread_init=function(){return(ye=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 _e,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)},ve=u.__emscripten_proxy_execute_task_queue=function(){return(ve=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},xe=u.__emscripten_thread_free_data=function(){return(xe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Te=u.__emscripten_thread_exit=function(){return(Te=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Ae=u._emscripten_stack_set_limits=function(){return(Ae=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)},Oe=u.stackRestore=function(){return(Oe=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ie=u.stackAlloc=function(){return(Ie=u.stackAlloc=u.asm.Fb).apply(null,arguments)},Pe=u.___cxa_can_catch=function(){return(Pe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},De=u.___cxa_is_pointer_type=function(){return(De=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},Ce=u.dynCall_j=function(){return(Ce=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)},Re=u.dynCall_jii=function(){return(Re=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Me=u.dynCall_viiiiij=function(){return(Me=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Fe=u.dynCall_vjji=function(){return(Fe=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},$e=u.dynCall_viiijjjii=function(){return($e=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Le=u.dynCall_iij=function(){return(Le=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},Ne=u.dynCall_ji=function(){return(Ne=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},je=u.dynCall_iiiiiij=function(){return(je=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Ue=u.dynCall_iiij=function(){return(Ue=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function Be(){function t(){if(!_e&&(_e=!0,u.calledRun=!0,!U)&&(T||gt(K),l(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!T)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Q.unshift(t)}gt(Q)}}if(!(0<nt))if(T)l(u),T||gt(K),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)tt();gt(Y),0<nt||(u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),t()},1)):t())}}if(u.UTF8ToString=H,u.stringToUTF8=function(t,e,n){return z(t,i(),e,n)},u.lengthBytesUTF8=G,u.keepRuntimeAlive=Z,u.wasmMemory=k,u.stackSave=Ee,u.stackRestore=Oe,u.stackAlloc=Ie,u.ExitStatus=lt,u.PThread=ft,it=function t(){_e||Be(),_e||(it=t)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return Be(),t.ready});t.exports=i},932:(t,e,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,i,o;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise(function(t,e){i=t,o=e});var s,a,u,l,c,d,h=Object.assign({},e),p="./this.program",f=(t,e)=>{throw e},g="object"==typeof window,m="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,y="";b?(y=m?n(908).dirname(y)+"/":"//",d=()=>{c||(l=n(1384),c=n(908))},s=function(t,e){return d(),t=c.normalize(t),l.readFileSync(t,e?void 0:"utf8")},u=t=>((t=s(t,!0)).buffer||(t=new Uint8Array(t)),t),a=(t,e,n)=>{d(),t=c.normalize(t),l.readFile(t,function(t,r){t?n(t):e(r.buffer)})},1<process.argv.length&&(p=process.argv[1].replace(/\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",function(t){if(!(t instanceof J))throw t}),process.on("unhandledRejection",function(t){throw t}),f=(t,e)=>{if(x||0<B)throw process.exitCode=t,e;e instanceof J||v("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(g||m)&&(m?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),r&&(y=r),y=0!==y.indexOf("blob:")?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},m&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),a=(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 _,w=e.print||console.log.bind(console),v=e.printErr||console.warn.bind(console);Object.assign(e,h),h=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(f=e.quit),e.wasmBinary&&(_=e.wasmBinary);var x=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&q("no native wasm support detected");var T,S,A,E,O,I,P=!1,D="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function C(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&D)return D.decode(t.subarray(e,n));for(r="";e<n;){var i=t[e++];if(128&i){var o=63&t[e++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|o);else{var s=63&t[e++];65536>(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function k(t,e){return(t>>>=0)?C(E,t,e):""}function R(t,e,n,r){if(!(0<r))return 0;var i=n>>>=0;r=n+r-1;for(var o=0;o<t.length;++o){var s=t.charCodeAt(o);if(55296<=s&&57343>=s&&(s=65536+((1023&s)<<10)|1023&t.charCodeAt(++o)),127>=s){if(n>=r)break;e[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;e[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;e[n++>>>0]=224|s>>12}else{if(n+3>=r)break;e[n++>>>0]=240|s>>18,e[n++>>>0]=128|s>>12&63}e[n++>>>0]=128|s>>6&63}e[n++>>>0]=128|63&s}}return e[n>>>0]=0,n-i}function M(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function F(){var t=T.buffer;S=t,e.HEAP8=A=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=O=new Int32Array(t),e.HEAPU8=E=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=I=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var $,L=[],N=[],j=[],U=[],B=0;function V(){var t=e.preRun.shift();L.unshift(t)}var H,z=0,G=null,W=null;function q(t){throw e.onAbort&&e.onAbort(t),v(t="Aborted("+t+")"),P=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),o(t),t}function X(){return H.startsWith("data:application/octet-stream;base64,")}if(H="ort-wasm.wasm",!X()){var Y=H;H=e.locateFile?e.locateFile(Y,y):y+Y}function K(){var t=H;try{if(t==H&&_)return new Uint8Array(_);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){q(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Q(t){for(;0<t.length;)t.shift()(e)}var Z=[],tt=0,et=0;function nt(t){this.Db=t,this.zb=t-24,this.Ub=function(t){I[this.zb+4>>2>>>0]=t},this.Eb=function(){return I[this.zb+4>>2>>>0]},this.Sb=function(t){I[this.zb+8>>2>>>0]=t},this.Wb=function(){return I[this.zb+8>>2>>>0]},this.Tb=function(){O[this.zb>>2>>>0]=0},this.Ib=function(t){A[(this.zb+12|0)>>>0]=t?1:0},this.Pb=function(){return 0!=A[(this.zb+12|0)>>>0]},this.Jb=function(t){A[(this.zb+13|0)>>>0]=t?1:0},this.Lb=function(){return 0!=A[(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(){O[this.zb>>2>>>0]+=1},this.Xb=function(){var t=O[this.zb>>2>>>0];return O[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){I[this.zb+16>>2>>>0]=t},this.Ob=function(){return I[this.zb+16>>2>>>0]},this.Qb=function(){if(It(this.Eb()))return I[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function rt(t){return wt(new nt(t).zb)}var it=[];function ot(t){var e=it[t];return e||(t>=it.length&&(it.length=t+1),it[t]=e=$.get(t)),e}function st(t){var e=M(t)+1,n=_t(e);return n&&R(t,A,n,e),n}var at={};function ut(){if(!lt){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 at)void 0===at[t]?delete e[t]:e[t]=at[t];var n=[];for(t in e)n.push(t+"="+e[t]);lt=n}return lt}var lt,ct=[null,[],[]];function dt(t,e){var n=ct[t];0===e||10===e?((1===t?w:v)(C(n,0)),n.length=0):n.push(e)}var ht=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ft=[31,29,31,30,31,30,31,31,30,31,30,31],gt=[31,28,31,30,31,30,31,31,30,31,30,31];function mt(t,e,n,r){function i(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function o(t,e){return i(t,e,"0")}function s(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function a(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function u(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(pt(t.getFullYear())?ft:gt)[n];if(!(e>r-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=a(new Date(t.getFullYear(),0,4)),n=a(n),0>=s(e,t)?0>=s(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var l=O[r+40>>2>>>0];for(var c in r={$b:O[r>>2>>>0],Zb:O[r+4>>2>>>0],Gb:O[r+8>>2>>>0],Kb:O[r+12>>2>>>0],Hb:O[r+16>>2>>>0],Cb:O[r+20>>2>>>0],Ab:O[r+24>>2>>>0],Bb:O[r+28>>2>>>0],bc:O[r+32>>2>>>0],Yb:O[r+36>>2>>>0],ac:l?k(l):""},n=k(n),l={"%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(c,"g"),l[c]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),h="January February March April May June July August September October November December".split(" ");for(c in l={"%a":function(t){return d[t.Ab].substring(0,3)},"%A":function(t){return d[t.Ab]},"%b":function(t){return h[t.Hb].substring(0,3)},"%B":function(t){return h[t.Hb]},"%C":function(t){return o((t.Cb+1900)/100|0,2)},"%d":function(t){return o(t.Kb,2)},"%e":function(t){return i(t.Kb,2," ")},"%g":function(t){return u(t).toString().substring(2)},"%G":function(t){return u(t)},"%H":function(t){return o(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12<t&&(t-=12),o(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(pt(t.Cb+1900)?ft:gt)[n++]);return o(t.Kb+e,3)},"%m":function(t){return o(t.Hb+1,2)},"%M":function(t){return o(t.Zb,2)},"%n":function(){return"\n"},"%p":function(t){return 0<=t.Gb&&12>t.Gb?"AM":"PM"},"%S":function(t){return o(t.$b,2)},"%t":function(){return"\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return o(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 o(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return o(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"),l)n.includes(c)&&(n=n.replace(new RegExp(c,"g"),l[c](r)));return c=function(t){var e=Array(M(t)+1);return R(t,e,0,e.length),e}(n=n.replace(/\0\0/g,"%")),c.length>e?0:(A.set(c,t>>>0),c.length-1)}var bt={a:function(t){return _t(t+24)+24},m:function(t){return(t=new nt(t)).Pb()||(t.Ib(!0),tt--),t.Jb(!1),Z.push(t),t.Nb(),t.Qb()},ia:function(t){throw v("Unexpected exception thrown, this is not properly supported - aborting"),P=!0,t},w:function(){Tt(0);var t=Z.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&ot(e)(t.Db),rt(t.Db)}et=0},d:function(){var t=et;if(!t)return ht=0;var e=new nt(t);e.Fb(t);var n=e.Eb();if(!n)return ht=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Ot(o,n,e.zb+16))return ht=o,t}return ht=n,t},k:function(){var t=et;if(!t)return ht=0;var e=new nt(t);e.Fb(t);var n=e.Eb();if(!n)return ht=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Ot(o,n,e.zb+16))return ht=o,t}return ht=n,t},g:function(){var t=et;if(!t)return ht=0;var e=new nt(t);e.Fb(t);var n=e.Eb();if(!n)return ht=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i<r.length;i++){var o=r[i];if(0===o||o===n)break;if(Ot(o,n,e.zb+16))return ht=o,t}return ht=n,t},s:rt,L:function(){var t=Z.pop();t||q("no exception to throw");var e=t.Db;throw t.Lb()||(Z.push(t),t.Jb(!0),t.Ib(!1),tt++),et=e,e},b:function(t,e,n){throw new nt(t).Rb(e,n),et=t,tt++,t},la:function(){return tt},i:function(t){throw et||(et=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){q("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){q("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(I[t>>>2]+4294967296*O[t+4>>>2])),O[e>>2>>>0]=t.getUTCSeconds(),O[e+4>>2>>>0]=t.getUTCMinutes(),O[e+8>>2>>>0]=t.getUTCHours(),O[e+12>>2>>>0]=t.getUTCDate(),O[e+16>>2>>>0]=t.getUTCMonth(),O[e+20>>2>>>0]=t.getUTCFullYear()-1900,O[e+24>>2>>>0]=t.getUTCDay(),O[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*(I[t>>>2]+4294967296*O[t+4>>>2])),O[e>>2>>>0]=t.getSeconds(),O[e+4>>2>>>0]=t.getMinutes(),O[e+8>>2>>>0]=t.getHours(),O[e+12>>2>>>0]=t.getDate(),O[e+16>>2>>>0]=t.getMonth(),O[e+20>>2>>>0]=t.getFullYear()-1900,O[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);O[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,O[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),O[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(O[t+20>>2>>>0]+1900,O[t+16>>2>>>0],O[t+12>>2>>>0],O[t+8>>2>>>0],O[t+4>>2>>>0],O[t>>2>>>0],0),n=O[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),s=i.getTimezoneOffset(),a=Math.min(s,o);return 0>n?O[t+32>>2>>>0]=Number(o!=s&&a==r):0<n!=(a==r)&&(o=Math.max(s,o),e.setTime(e.getTime()+6e4*((0<n?a:o)-r))),O[t+24>>2>>>0]=e.getDay(),O[t+28>>2>>>0]=(e.getTime()-i.getTime())/864e5|0,O[t>>2>>>0]=e.getSeconds(),O[t+4>>2>>>0]=e.getMinutes(),O[t+8>>2>>>0]=e.getHours(),O[t+12>>2>>>0]=e.getDate(),O[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 i=(new Date).getFullYear(),o=new Date(i,0,1),s=new Date(i,6,1);i=o.getTimezoneOffset();var a=s.getTimezoneOffset();O[t>>2>>>0]=60*Math.max(i,a),O[e>>2>>>0]=Number(i!=a),t=r(o),e=r(s),t=st(t),e=st(e),a<i?(I[n>>2>>>0]=t,I[n+4>>2>>>0]=e):(I[n>>2>>>0]=e,I[n+4>>2>>>0]=t)}(e,n,r))},B:function(){q("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){E.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=E.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 i=Math;r=Math.max(t,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);t:{try{T.grow(i-S.byteLength+65535>>>16),F();var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},va:function(t,e){var n=0;return ut().forEach(function(r,i){var o=e+n;for(i=I[t+4*i>>2>>>0]=o,o=0;o<r.length;++o)A[(0|i++)>>>0]=r.charCodeAt(o);A[(0|i)>>>0]=0,n+=r.length+1}),0},wa:function(t,e){var n=ut();I[t>>2>>>0]=n.length;var r=0;return n.forEach(function(t){r+=t.length+1}),I[e>>2>>>0]=r,0},ba:function(t){x||0<B||(xt(),Q(j),vt(0),ct[1].length&&dt(1,10),ct[2].length&&dt(2,10)),x||0<B||(e.onExit&&e.onExit(t),P=!0),f(t,new J(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var i=0,o=0;o<n;o++){var s=I[e>>2>>>0],a=I[e+4>>2>>>0];e+=8;for(var u=0;u<a;u++)dt(t,E[s+u>>>0]);i+=a}return I[r>>2>>>0]=i,0},c:function(){return ht},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()=>q("randomDevice")}());for(var i=0;i<r;i++)A[(e+i|0)>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},fa:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},J:function(t){var e=St();try{return ot(t)()}catch(t){if(At(e),t!==t+0)throw t;Tt(1,0)}},e:function(t,e){var n=St();try{return ot(t)(e)}catch(t){if(At(n),t!==t+0)throw t;Tt(1,0)}},N:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},O:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},j:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},o:function(t,e,n,r){var i=St();try{return ot(t)(e,n,r)}catch(t){if(At(i),t!==t+0)throw t;Tt(1,0)}},p:function(t,e,n,r,i){var o=St();try{return ot(t)(e,n,r,i)}catch(t){if(At(o),t!==t+0)throw t;Tt(1,0)}},M:function(t,e,n,r,i,o){var s=St();try{return ot(t)(e,n,r,i,o)}catch(t){if(At(s),t!==t+0)throw t;Tt(1,0)}},r:function(t,e,n,r,i,o){var s=St();try{return ot(t)(e,n,r,i,o)}catch(t){if(At(s),t!==t+0)throw t;Tt(1,0)}},v:function(t,e,n,r,i,o,s){var a=St();try{return ot(t)(e,n,r,i,o,s)}catch(t){if(At(a),t!==t+0)throw t;Tt(1,0)}},K:function(t,e,n,r,i,o,s,a){var u=St();try{return ot(t)(e,n,r,i,o,s,a)}catch(t){if(At(u),t!==t+0)throw t;Tt(1,0)}},D:function(t,e,n,r,i,o,s,a,u,l,c,d){var h=St();try{return ot(t)(e,n,r,i,o,s,a,u,l,c,d)}catch(t){if(At(h),t!==t+0)throw t;Tt(1,0)}},X:function(t,e,n,r,i,o,s,a){var u=St();try{return Lt(t,e,n,r,i,o,s,a)}catch(t){if(At(u),t!==t+0)throw t;Tt(1,0)}},V:function(t,e,n,r,i,o,s){var a=St();try{return Dt(t,e,n,r,i,o,s)}catch(t){if(At(a),t!==t+0)throw t;Tt(1,0)}},U:function(t,e,n,r,i){var o=St();try{return Nt(t,e,n,r,i)}catch(t){if(At(o),t!==t+0)throw t;Tt(1,0)}},Z:function(t,e,n,r){var i=St();try{return Ft(t,e,n,r)}catch(t){if(At(i),t!==t+0)throw t;Tt(1,0)}},W:function(t){var e=St();try{return Pt(t)}catch(t){if(At(e),t!==t+0)throw t;Tt(1,0)}},Y:function(t,e){var n=St();try{return $t(t,e)}catch(t){if(At(n),t!==t+0)throw t;Tt(1,0)}},T:function(t,e,n){var r=St();try{return Ct(t,e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},f:function(t){var e=St();try{ot(t)()}catch(t){if(At(e),t!==t+0)throw t;Tt(1,0)}},q:function(t,e){var n=St();try{ot(t)(e)}catch(t){if(At(n),t!==t+0)throw t;Tt(1,0)}},h:function(t,e,n){var r=St();try{ot(t)(e,n)}catch(t){if(At(r),t!==t+0)throw t;Tt(1,0)}},da:function(t,e,n,r){var i=St();try{ot(t)(e,n,r)}catch(t){if(At(i),t!==t+0)throw t;Tt(1,0)}},l:function(t,e,n,r){var i=St();try{ot(t)(e,n,r)}catch(t){if(At(i),t!==t+0)throw t;Tt(1,0)}},t:function(t,e,n,r,i){var o=St();try{ot(t)(e,n,r,i)}catch(t){if(At(o),t!==t+0)throw t;Tt(1,0)}},u:function(t,e,n,r,i,o){var s=St();try{ot(t)(e,n,r,i,o)}catch(t){if(At(s),t!==t+0)throw t;Tt(1,0)}},x:function(t,e,n,r,i,o,s){var a=St();try{ot(t)(e,n,r,i,o,s)}catch(t){if(At(a),t!==t+0)throw t;Tt(1,0)}},z:function(t,e,n,r,i,o,s,a){var u=St();try{ot(t)(e,n,r,i,o,s,a)}catch(t){if(At(u),t!==t+0)throw t;Tt(1,0)}},ga:function(t,e,n,r,i,o,s,a,u){var l=St();try{ot(t)(e,n,r,i,o,s,a,u)}catch(t){if(At(l),t!==t+0)throw t;Tt(1,0)}},A:function(t,e,n,r,i,o,s,a,u,l,c){var d=St();try{ot(t)(e,n,r,i,o,s,a,u,l,c)}catch(t){if(At(d),t!==t+0)throw t;Tt(1,0)}},C:function(t,e,n,r,i,o,s,a,u,l,c,d,h,p,f,g){var m=St();try{ot(t)(e,n,r,i,o,s,a,u,l,c,d,h,p,f,g)}catch(t){if(At(m),t!==t+0)throw t;Tt(1,0)}},aa:function(t,e,n,r,i,o,s,a){var u=St();try{kt(t,e,n,r,i,o,s,a)}catch(t){if(At(u),t!==t+0)throw t;Tt(1,0)}},_:function(t,e,n,r,i,o,s,a,u,l,c,d){var h=St();try{Mt(t,e,n,r,i,o,s,a,u,l,c,d)}catch(t){if(At(h),t!==t+0)throw t;Tt(1,0)}},$:function(t,e,n,r,i,o){var s=St();try{Rt(t,e,n,r,i,o)}catch(t){if(At(s),t!==t+0)throw t;Tt(1,0)}},n:function(t){return t},F:function(t){ht=t},ha:mt,y:function(t,e,n,r){return mt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,T=e.asm.Ka,F(),$=e.asm.ib,N.unshift(e.asm.La),z--,e.monitorRunDependencies&&e.monitorRunDependencies(z),0==z&&(null!==G&&(clearInterval(G),G=null),W&&(t=W,W=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!_&&(g||m)){if("function"==typeof fetch&&!H.startsWith("file://"))return fetch(H,{credentials:"same-origin"}).then(function(t){if(!t.ok)throw"failed to load wasm binary file at '"+H+"'";return t.arrayBuffer()}).catch(function(){return K()});if(a)return new Promise(function(t,e){a(H,function(e){t(new Uint8Array(e))},e)})}return Promise.resolve().then(function(){return K()})}().then(function(t){return WebAssembly.instantiate(t,i)}).then(function(t){return t}).then(t,function(t){v("failed to asynchronously prepare wasm: "+t),q(t)})}var i={a:bt};if(z++,e.monitorRunDependencies&&e.monitorRunDependencies(z),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return v("Module.instantiateWasm callback failed with error: "+t),!1}(_||"function"!=typeof WebAssembly.instantiateStreaming||X()||H.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(H,{credentials:"same-origin"}).then(function(t){return WebAssembly.instantiateStreaming(t,i).then(n,function(t){return v("wasm streaming compile failed: "+t),v("falling back to ArrayBuffer instantiation"),r(n)})})).catch(o)}(),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 yt,_t=e._malloc=function(){return(_t=e._malloc=e.asm.eb).apply(null,arguments)},wt=e._free=function(){return(wt=e._free=e.asm.fb).apply(null,arguments)},vt=e._fflush=function(){return(vt=e._fflush=e.asm.gb).apply(null,arguments)},xt=e.___funcs_on_exit=function(){return(xt=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Tt=e._setThrew=function(){return(Tt=e._setThrew=e.asm.jb).apply(null,arguments)},St=e.stackSave=function(){return(St=e.stackSave=e.asm.kb).apply(null,arguments)},At=e.stackRestore=function(){return(At=e.stackRestore=e.asm.lb).apply(null,arguments)},Et=e.stackAlloc=function(){return(Et=e.stackAlloc=e.asm.mb).apply(null,arguments)},Ot=e.___cxa_can_catch=function(){return(Ot=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},It=e.___cxa_is_pointer_type=function(){return(It=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Pt=e.dynCall_j=function(){return(Pt=e.dynCall_j=e.asm.pb).apply(null,arguments)},Dt=e.dynCall_iiiiij=function(){return(Dt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Ct=e.dynCall_jii=function(){return(Ct=e.dynCall_jii=e.asm.rb).apply(null,arguments)},kt=e.dynCall_viiiiij=function(){return(kt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},Rt=e.dynCall_vjji=function(){return(Rt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Mt=e.dynCall_viiijjjii=function(){return(Mt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Ft=e.dynCall_iij=function(){return(Ft=e.dynCall_iij=e.asm.vb).apply(null,arguments)},$t=e.dynCall_ji=function(){return($t=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Lt=e.dynCall_iiiiiij=function(){return(Lt=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},Nt=e.dynCall_iiij=function(){return(Nt=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function jt(){function t(){if(!yt&&(yt=!0,e.calledRun=!0,!P)){if(Q(N),i(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();U.unshift(t)}Q(U)}}if(!(0<z)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)V();Q(L),0<z||(e.setStatus?(e.setStatus("Running..."),setTimeout(function(){setTimeout(function(){e.setStatus("")},1),t()},1)):t())}}if(e.UTF8ToString=k,e.stringToUTF8=function(t,e,n){return R(t,E,e,n)},e.lengthBytesUTF8=M,e.stackSave=St,e.stackRestore=At,e.stackAlloc=Et,W=function t(){yt||jt(),yt||(W=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return jt(),t.ready});t.exports=i},4537:t=>{t.exports=function(t,e){for(var n=new Array(arguments.length-1),r=0,i=2,o=!0;i<arguments.length;)n[r++]=arguments[i++];return new Promise(function(i,s){n[r]=function(t){if(o)if(o=!1,t)s(t);else{for(var e=new Array(arguments.length-1),n=0;n<e.length;)e[n++]=arguments[n];i.apply(null,e)}};try{t.apply(e||null,n)}catch(t){o&&(o=!1,s(t))}})}},7419:(t,e)=>{var n=e;n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&"="===t.charAt(e);)++n;return Math.ceil(3*t.length)/4-n};for(var r=new Array(64),i=new Array(123),o=0;o<64;)i[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;n.encode=function(t,e,n){for(var i,o=null,s=[],a=0,u=0;e<n;){var l=t[e++];switch(u){case 0:s[a++]=r[l>>2],i=(3&l)<<4,u=1;break;case 1:s[a++]=r[i|l>>4],i=(15&l)<<2,u=2;break;case 2:s[a++]=r[i|l>>6],s[a++]=r[63&l],u=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0)}return u&&(s[a++]=r[i],s[a++]=61,1===u&&(s[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";n.decode=function(t,e,n){for(var r,o=n,a=0,u=0;u<t.length;){var l=t.charCodeAt(u++);if(61===l&&a>1)break;if(void 0===(l=i[l]))throw Error(s);switch(a){case 0:r=l,a=1;break;case 1:e[n++]=r<<2|(48&l)>>4,r=l,a=2;break;case 2:e[n++]=(15&r)<<4|(60&l)>>2,r=l,a=3;break;case 3:e[n++]=(3&r)<<6|l,a=0}}if(1===a)throw Error(s);return n-o},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},9211:t=>{function e(){this._listeners={}}t.exports=e,e.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this},e.prototype.off=function(t,e){if(void 0===t)this._listeners={};else if(void 0===e)this._listeners[t]=[];else for(var n=this._listeners[t],r=0;r<n.length;)n[r].fn===e?n.splice(r,1):++r;return this},e.prototype.emit=function(t){var e=this._listeners[t];if(e){for(var n=[],r=1;r<arguments.length;)n.push(arguments[r++]);for(r=0;r<e.length;)e[r].fn.apply(e[r++].ctx,n)}return this}},945:t=>{function e(t){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),n=new Uint8Array(e.buffer),r=128===n[3];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function o(t,r,i){e[0]=t,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function s(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],e[0]}function a(t,r){return n[3]=t[r],n[2]=t[r+1],n[1]=t[r+2],n[0]=t[r+3],e[0]}t.writeFloatLE=r?i:o,t.writeFloatBE=r?o:i,t.readFloatLE=r?s:a,t.readFloatBE=r?a:s}():function(){function e(t,e,n,r){var i=e<0?1:0;if(i&&(e=-e),0===e)t(1/e>0?0:2147483648,n,r);else if(isNaN(e))t(2143289344,n,r);else if(e>34028234663852886e22)t((i<<31|2139095040)>>>0,n,r);else if(e<11754943508222875e-54)t((i<<31|Math.round(e/1401298464324817e-60))>>>0,n,r);else{var o=Math.floor(Math.log(e)/Math.LN2);t((i<<31|o+127<<23|8388607&Math.round(e*Math.pow(2,-o)*8388608))>>>0,n,r)}}function s(t,e,n){var r=t(e,n),i=2*(r>>31)+1,o=r>>>23&255,s=8388607&r;return 255===o?s?NaN:i*(1/0):0===o?1401298464324817e-60*i*s:i*Math.pow(2,o-150)*(s+8388608)}t.writeFloatLE=e.bind(null,n),t.writeFloatBE=e.bind(null,r),t.readFloatLE=s.bind(null,i),t.readFloatBE=s.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),n=new Uint8Array(e.buffer),r=128===n[7];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function o(t,r,i){e[0]=t,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function s(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],n[4]=t[r+4],n[5]=t[r+5],n[6]=t[r+6],n[7]=t[r+7],e[0]}function a(t,r){return n[7]=t[r],n[6]=t[r+1],n[5]=t[r+2],n[4]=t[r+3],n[3]=t[r+4],n[2]=t[r+5],n[1]=t[r+6],n[0]=t[r+7],e[0]}t.writeDoubleLE=r?i:o,t.writeDoubleBE=r?o:i,t.readDoubleLE=r?s:a,t.readDoubleBE=r?a:s}():function(){function e(t,e,n,r,i,o){var s=r<0?1:0;if(s&&(r=-r),0===r)t(0,i,o+e),t(1/r>0?0:2147483648,i,o+n);else if(isNaN(r))t(0,i,o+e),t(2146959360,i,o+n);else if(r>17976931348623157e292)t(0,i,o+e),t((s<<31|2146435072)>>>0,i,o+n);else{var a;if(r<22250738585072014e-324)t((a=r/5e-324)>>>0,i,o+e),t((s<<31|a/4294967296)>>>0,i,o+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),t(4503599627370496*(a=r*Math.pow(2,-u))>>>0,i,o+e),t((s<<31|u+1023<<20|1048576*a&1048575)>>>0,i,o+n)}}}function s(t,e,n,r,i){var o=t(r,i+e),s=t(r,i+n),a=2*(s>>31)+1,u=s>>>20&2047,l=4294967296*(1048575&s)+o;return 2047===u?l?NaN:a*(1/0):0===u?5e-324*a*l:a*Math.pow(2,u-1075)*(l+4503599627370496)}t.writeDoubleLE=e.bind(null,n,0,4),t.writeDoubleBE=e.bind(null,r,4,0),t.readDoubleLE=s.bind(null,i,0,4),t.readDoubleBE=s.bind(null,o,4,0)}(),t}function n(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function r(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function i(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}t.exports=e(e)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}module.exports=inquire},6662:t=>{t.exports=function(t,e,n){var r=n||8192,i=r>>>1,o=null,s=r;return function(n){if(n<1||n>i)return t(n);s+n>r&&(o=t(r),s=0);var a=e.call(o,s,s+=n);return 7&s&&(s=1+(7|s)),a}}},4997:(t,e)=>{var n=e;n.length=function(t){for(var e=0,n=0,r=0;r<t.length;++r)(n=t.charCodeAt(r))<128?e+=1:n<2048?e+=2:55296==(64512&n)&&56320==(64512&t.charCodeAt(r+1))?(++r,e+=4):e+=3;return e},n.read=function(t,e,n){if(n-e<1)return"";for(var r,i=null,o=[],s=0;e<n;)(r=t[e++])<128?o[s++]=r:r>191&&r<224?o[s++]=(31&r)<<6|63&t[e++]:r>239&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,o[s++]=55296+(r>>10),o[s++]=56320+(1023&r)):o[s++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))},n.write=function(t,e,n){for(var r,i,o=n,s=0;s<t.length;++s)(r=t.charCodeAt(s))<128?e[n++]=r:r<2048?(e[n++]=r>>6|192,e[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(s+1)))?(r=65536+((1023&r)<<10)+(1023&i),++s,e[n++]=r>>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128);return n-o}},3442:(t,e)=>{e.__esModule=!0;var n=function(){function t(e){if(!e)throw new TypeError("Invalid argument; `value` has no value.");this.value=t.EMPTY,e&&t.isGuid(e)&&(this.value=e)}return t.isGuid=function(e){var n=e.toString();return e&&(e instanceof t||t.validator.test(n))},t.create=function(){return new t([t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-"))},t.createEmpty=function(){return new t("emptyguid")},t.parse=function(e){return new t(e)},t.raw=function(){return[t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-")},t.gen=function(t){for(var e="",n=0;n<t;n++)e+=(65536*(1+Math.random())|0).toString(16).substring(1);return e},t.prototype.equals=function(e){return t.isGuid(e)&&this.value===e.toString()},t.prototype.isEmpty=function(){return this.value===t.EMPTY},t.prototype.toString=function(){return this.value},t.prototype.toJSON=function(){return{value:this.value}},t.validator=new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$","i"),t.EMPTY="00000000-0000-0000-0000-000000000000",t}();e.Guid=n},3720:t=>{t.exports=n;var e=null;try{e=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(t){}function n(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function r(t){return!0===(t&&t.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},o={};function s(t,e){var n,r,s;return e?(s=0<=(t>>>=0)&&t<256)&&(r=o[t])?r:(n=u(t,(0|t)<0?-1:0,!0),s&&(o[t]=n),n):(s=-128<=(t|=0)&&t<128)&&(r=i[t])?r:(n=u(t,t<0?-1:0,!1),s&&(i[t]=n),n)}function a(t,e){if(isNaN(t))return e?b:m;if(e){if(t<0)return b;if(t>=p)return x}else{if(t<=-f)return T;if(t+1>=f)return v}return t<0?a(-t,e).neg():u(t%h|0,t/h|0,e)}function u(t,e,r){return new n(t,e,r)}n.fromInt=s,n.fromNumber=a,n.fromBits=u;var l=Math.pow;function c(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return c(t.substring(1),e,n).neg();for(var i=a(l(n,8)),o=m,s=0;s<t.length;s+=8){var u=Math.min(8,t.length-s),d=parseInt(t.substring(s,s+u),n);if(u<8){var h=a(l(n,u));o=o.mul(h).add(a(d))}else o=(o=o.mul(i)).add(a(d))}return o.unsigned=e,o}function d(t,e){return"number"==typeof t?a(t,e):"string"==typeof t?c(t,e):u(t.low,t.high,"boolean"==typeof e?e:t.unsigned)}n.fromString=c,n.fromValue=d;var h=4294967296,p=h*h,f=p/2,g=s(1<<24),m=s(0);n.ZERO=m;var b=s(0,!0);n.UZERO=b;var y=s(1);n.ONE=y;var _=s(1,!0);n.UONE=_;var w=s(-1);n.NEG_ONE=w;var v=u(-1,2147483647,!1);n.MAX_VALUE=v;var x=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=x;var T=u(0,-2147483648,!1);n.MIN_VALUE=T;var S=n.prototype;S.toInt=function(){return this.unsigned?this.low>>>0:this.low},S.toNumber=function(){return this.unsigned?(this.high>>>0)*h+(this.low>>>0):this.high*h+(this.low>>>0)},S.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(T)){var e=a(t),n=this.div(e),r=n.mul(e).sub(this);return n.toString(t)+r.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var i=a(l(t,6),this.unsigned),o=this,s="";;){var u=o.div(i),c=(o.sub(u.mul(i)).toInt()>>>0).toString(t);if((o=u).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},S.getHighBits=function(){return this.high},S.getHighBitsUnsigned=function(){return this.high>>>0},S.getLowBits=function(){return this.low},S.getLowBitsUnsigned=function(){return this.low>>>0},S.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&!(t&1<<e);e--);return 0!=this.high?e+33:e+1},S.isZero=function(){return 0===this.high&&0===this.low},S.eqz=S.isZero,S.isNegative=function(){return!this.unsigned&&this.high<0},S.isPositive=function(){return this.unsigned||this.high>=0},S.isOdd=function(){return!(1&~this.low)},S.isEven=function(){return!(1&this.low)},S.equals=function(t){return r(t)||(t=d(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&this.high===t.high&&this.low===t.low},S.eq=S.equals,S.notEquals=function(t){return!this.eq(t)},S.neq=S.notEquals,S.ne=S.notEquals,S.lessThan=function(t){return this.comp(t)<0},S.lt=S.lessThan,S.lessThanOrEqual=function(t){return this.comp(t)<=0},S.lte=S.lessThanOrEqual,S.le=S.lessThanOrEqual,S.greaterThan=function(t){return this.comp(t)>0},S.gt=S.greaterThan,S.greaterThanOrEqual=function(t){return this.comp(t)>=0},S.gte=S.greaterThanOrEqual,S.ge=S.greaterThanOrEqual,S.compare=function(t){if(r(t)||(t=d(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},S.comp=S.compare,S.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(y)},S.neg=S.negate,S.add=function(t){r(t)||(t=d(t));var e=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,s=t.high>>>16,a=65535&t.high,l=t.low>>>16,c=0,h=0,p=0,f=0;return p+=(f+=o+(65535&t.low))>>>16,h+=(p+=i+l)>>>16,c+=(h+=n+a)>>>16,c+=e+s,u((p&=65535)<<16|(f&=65535),(c&=65535)<<16|(h&=65535),this.unsigned)},S.subtract=function(t){return r(t)||(t=d(t)),this.add(t.neg())},S.sub=S.subtract,S.multiply=function(t){if(this.isZero())return m;if(r(t)||(t=d(t)),e)return u(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return m;if(this.eq(T))return t.isOdd()?T:m;if(t.eq(T))return this.isOdd()?T:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(g)&&t.lt(g))return a(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,o=this.low>>>16,s=65535&this.low,l=t.high>>>16,c=65535&t.high,h=t.low>>>16,p=65535&t.low,f=0,b=0,y=0,_=0;return y+=(_+=s*p)>>>16,b+=(y+=o*p)>>>16,y&=65535,b+=(y+=s*h)>>>16,f+=(b+=i*p)>>>16,b&=65535,f+=(b+=o*h)>>>16,b&=65535,f+=(b+=s*c)>>>16,f+=n*p+i*h+o*c+s*l,u((y&=65535)<<16|(_&=65535),(f&=65535)<<16|(b&=65535),this.unsigned)},S.mul=S.multiply,S.divide=function(t){if(r(t)||(t=d(t)),t.isZero())throw Error("division by zero");var n,i,o;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?u((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?b:m;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return b;if(t.gt(this.shru(1)))return _;o=b}else{if(this.eq(T))return t.eq(y)||t.eq(w)?T:t.eq(T)?y:(n=this.shr(1).div(t).shl(1)).eq(m)?t.isNegative()?y:w:(i=this.sub(t.mul(n)),o=n.add(i.div(t)));if(t.eq(T))return this.unsigned?b:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=m}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(n)/Math.LN2),c=s<=48?1:l(2,s-48),h=a(n),p=h.mul(t);p.isNegative()||p.gt(i);)p=(h=a(n-=c,this.unsigned)).mul(t);h.isZero()&&(h=y),o=o.add(h),i=i.sub(p)}return o},S.div=S.divide,S.modulo=function(t){return r(t)||(t=d(t)),e?u((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},S.mod=S.modulo,S.rem=S.modulo,S.not=function(){return u(~this.low,~this.high,this.unsigned)},S.and=function(t){return r(t)||(t=d(t)),u(this.low&t.low,this.high&t.high,this.unsigned)},S.or=function(t){return r(t)||(t=d(t)),u(this.low|t.low,this.high|t.high,this.unsigned)},S.xor=function(t){return r(t)||(t=d(t)),u(this.low^t.low,this.high^t.high,this.unsigned)},S.shiftLeft=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?u(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):u(0,this.low<<t-32,this.unsigned)},S.shl=S.shiftLeft,S.shiftRight=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?u(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):u(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},S.shr=S.shiftRight,S.shiftRightUnsigned=function(t){if(r(t)&&(t=t.toInt()),0==(t&=63))return this;var e=this.high;return t<32?u(this.low>>>t|e<<32-t,e>>>t,this.unsigned):u(32===t?e:e>>>t-32,0,this.unsigned)},S.shru=S.shiftRightUnsigned,S.shr_u=S.shiftRightUnsigned,S.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},S.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},S.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},S.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},S.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},n.fromBytes=function(t,e,r){return r?n.fromBytesLE(t,e):n.fromBytesBE(t,e)},n.fromBytesLE=function(t,e){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},n.fromBytesBE=function(t,e){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},1446:(t,e,n)=>{var r,i,o,s=n(2100),a=s.Reader,u=s.Writer,l=s.util,c=s.roots.default||(s.roots.default={});c.onnx=((o={}).Version=(r={},(i=Object.create(r))[r[0]="_START_VERSION"]=0,i[r[1]="IR_VERSION_2017_10_10"]=1,i[r[2]="IR_VERSION_2017_10_30"]=2,i[r[3]="IR_VERSION_2017_11_3"]=3,i[r[4]="IR_VERSION_2019_1_22"]=4,i[r[5]="IR_VERSION"]=5,i),o.AttributeProto=function(){function t(t){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.name="",t.prototype.refAttrName="",t.prototype.docString="",t.prototype.type=0,t.prototype.f=0,t.prototype.i=l.Long?l.Long.fromBits(0,0,!1):0,t.prototype.s=l.newBuffer([]),t.prototype.t=null,t.prototype.g=null,t.prototype.floats=l.emptyArray,t.prototype.ints=l.emptyArray,t.prototype.strings=l.emptyArray,t.prototype.tensors=l.emptyArray,t.prototype.graphs=l.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.name&&t.hasOwnProperty("name")&&e.uint32(10).string(t.name),null!=t.f&&t.hasOwnProperty("f")&&e.uint32(21).float(t.f),null!=t.i&&t.hasOwnProperty("i")&&e.uint32(24).int64(t.i),null!=t.s&&t.hasOwnProperty("s")&&e.uint32(34).bytes(t.s),null!=t.t&&t.hasOwnProperty("t")&&c.onnx.TensorProto.encode(t.t,e.uint32(42).fork()).ldelim(),null!=t.g&&t.hasOwnProperty("g")&&c.onnx.GraphProto.encode(t.g,e.uint32(50).fork()).ldelim(),null!=t.floats&&t.floats.length){e.uint32(58).fork();for(var n=0;n<t.floats.length;++n)e.float(t.floats[n]);e.ldelim()}if(null!=t.ints&&t.ints.length){for(e.uint32(66).fork(),n=0;n<t.ints.length;++n)e.int64(t.ints[n]);e.ldelim()}if(null!=t.strings&&t.strings.length)for(n=0;n<t.strings.length;++n)e.uint32(74).bytes(t.strings[n]);if(null!=t.tensors&&t.tensors.length)for(n=0;n<t.tensors.length;++n)c.onnx.TensorProto.encode(t.tensors[n],e.uint32(82).fork()).ldelim();if(null!=t.graphs&&t.graphs.length)for(n=0;n<t.graphs.length;++n)c.onnx.GraphProto.encode(t.graphs[n],e.uint32(90).fork()).ldelim();return null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(106).string(t.docString),null!=t.type&&t.hasOwnProperty("type")&&e.uint32(160).int32(t.type),null!=t.refAttrName&&t.hasOwnProperty("refAttrName")&&e.uint32(170).string(t.refAttrName),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.AttributeProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.name=t.string();break;case 21:r.refAttrName=t.string();break;case 13:r.docString=t.string();break;case 20:r.type=t.int32();break;case 2:r.f=t.float();break;case 3:r.i=t.int64();break;case 4:r.s=t.bytes();break;case 5:r.t=c.onnx.TensorProto.decode(t,t.uint32());break;case 6:r.g=c.onnx.GraphProto.decode(t,t.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos<o;)r.floats.push(t.float());else r.floats.push(t.float());break;case 8:if(r.ints&&r.ints.length||(r.ints=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.ints.push(t.int64());else r.ints.push(t.int64());break;case 9:r.strings&&r.strings.length||(r.strings=[]),r.strings.push(t.bytes());break;case 10:r.tensors&&r.tensors.length||(r.tensors=[]),r.tensors.push(c.onnx.TensorProto.decode(t,t.uint32()));break;case 11:r.graphs&&r.graphs.length||(r.graphs=[]),r.graphs.push(c.onnx.GraphProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.name&&t.hasOwnProperty("name")&&!l.isString(t.name))return"name: string expected";if(null!=t.refAttrName&&t.hasOwnProperty("refAttrName")&&!l.isString(t.refAttrName))return"refAttrName: string expected";if(null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString))return"docString: string expected";if(null!=t.type&&t.hasOwnProperty("type"))switch(t.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:}if(null!=t.f&&t.hasOwnProperty("f")&&"number"!=typeof t.f)return"f: number expected";if(null!=t.i&&t.hasOwnProperty("i")&&!(l.isInteger(t.i)||t.i&&l.isInteger(t.i.low)&&l.isInteger(t.i.high)))return"i: integer|Long expected";if(null!=t.s&&t.hasOwnProperty("s")&&!(t.s&&"number"==typeof t.s.length||l.isString(t.s)))return"s: buffer expected";if(null!=t.t&&t.hasOwnProperty("t")&&(n=c.onnx.TensorProto.verify(t.t)))return"t."+n;if(null!=t.g&&t.hasOwnProperty("g")&&(n=c.onnx.GraphProto.verify(t.g)))return"g."+n;if(null!=t.floats&&t.hasOwnProperty("floats")){if(!Array.isArray(t.floats))return"floats: array expected";for(var e=0;e<t.floats.length;++e)if("number"!=typeof t.floats[e])return"floats: number[] expected"}if(null!=t.ints&&t.hasOwnProperty("ints")){if(!Array.isArray(t.ints))return"ints: array expected";for(e=0;e<t.ints.length;++e)if(!(l.isInteger(t.ints[e])||t.ints[e]&&l.isInteger(t.ints[e].low)&&l.isInteger(t.ints[e].high)))return"ints: integer|Long[] expected"}if(null!=t.strings&&t.hasOwnProperty("strings")){if(!Array.isArray(t.strings))return"strings: array expected";for(e=0;e<t.strings.length;++e)if(!(t.strings[e]&&"number"==typeof t.strings[e].length||l.isString(t.strings[e])))return"strings: buffer[] expected"}if(null!=t.tensors&&t.hasOwnProperty("tensors")){if(!Array.isArray(t.tensors))return"tensors: array expected";for(e=0;e<t.tensors.length;++e)if(n=c.onnx.TensorProto.verify(t.tensors[e]))return"tensors."+n}if(null!=t.graphs&&t.hasOwnProperty("graphs")){if(!Array.isArray(t.graphs))return"graphs: array expected";for(e=0;e<t.graphs.length;++e){var n;if(n=c.onnx.GraphProto.verify(t.graphs[e]))return"graphs."+n}}return null},t.fromObject=function(t){if(t instanceof c.onnx.AttributeProto)return t;var e=new c.onnx.AttributeProto;switch(null!=t.name&&(e.name=String(t.name)),null!=t.refAttrName&&(e.refAttrName=String(t.refAttrName)),null!=t.docString&&(e.docString=String(t.docString)),t.type){case"UNDEFINED":case 0:e.type=0;break;case"FLOAT":case 1:e.type=1;break;case"INT":case 2:e.type=2;break;case"STRING":case 3:e.type=3;break;case"TENSOR":case 4:e.type=4;break;case"GRAPH":case 5:e.type=5;break;case"FLOATS":case 6:e.type=6;break;case"INTS":case 7:e.type=7;break;case"STRINGS":case 8:e.type=8;break;case"TENSORS":case 9:e.type=9;break;case"GRAPHS":case 10:e.type=10}if(null!=t.f&&(e.f=Number(t.f)),null!=t.i&&(l.Long?(e.i=l.Long.fromValue(t.i)).unsigned=!1:"string"==typeof t.i?e.i=parseInt(t.i,10):"number"==typeof t.i?e.i=t.i:"object"==typeof t.i&&(e.i=new l.LongBits(t.i.low>>>0,t.i.high>>>0).toNumber())),null!=t.s&&("string"==typeof t.s?l.base64.decode(t.s,e.s=l.newBuffer(l.base64.length(t.s)),0):t.s.length&&(e.s=t.s)),null!=t.t){if("object"!=typeof t.t)throw TypeError(".onnx.AttributeProto.t: object expected");e.t=c.onnx.TensorProto.fromObject(t.t)}if(null!=t.g){if("object"!=typeof t.g)throw TypeError(".onnx.AttributeProto.g: object expected");e.g=c.onnx.GraphProto.fromObject(t.g)}if(t.floats){if(!Array.isArray(t.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");e.floats=[];for(var n=0;n<t.floats.length;++n)e.floats[n]=Number(t.floats[n])}if(t.ints){if(!Array.isArray(t.ints))throw TypeError(".onnx.AttributeProto.ints: array expected");for(e.ints=[],n=0;n<t.ints.length;++n)l.Long?(e.ints[n]=l.Long.fromValue(t.ints[n])).unsigned=!1:"string"==typeof t.ints[n]?e.ints[n]=parseInt(t.ints[n],10):"number"==typeof t.ints[n]?e.ints[n]=t.ints[n]:"object"==typeof t.ints[n]&&(e.ints[n]=new l.LongBits(t.ints[n].low>>>0,t.ints[n].high>>>0).toNumber())}if(t.strings){if(!Array.isArray(t.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(e.strings=[],n=0;n<t.strings.length;++n)"string"==typeof t.strings[n]?l.base64.decode(t.strings[n],e.strings[n]=l.newBuffer(l.base64.length(t.strings[n])),0):t.strings[n].length&&(e.strings[n]=t.strings[n])}if(t.tensors){if(!Array.isArray(t.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");for(e.tensors=[],n=0;n<t.tensors.length;++n){if("object"!=typeof t.tensors[n])throw TypeError(".onnx.AttributeProto.tensors: object expected");e.tensors[n]=c.onnx.TensorProto.fromObject(t.tensors[n])}}if(t.graphs){if(!Array.isArray(t.graphs))throw TypeError(".onnx.AttributeProto.graphs: array expected");for(e.graphs=[],n=0;n<t.graphs.length;++n){if("object"!=typeof t.graphs[n])throw TypeError(".onnx.AttributeProto.graphs: object expected");e.graphs[n]=c.onnx.GraphProto.fromObject(t.graphs[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.floats=[],n.ints=[],n.strings=[],n.tensors=[],n.graphs=[]),e.defaults){if(n.name="",n.f=0,l.Long){var r=new l.Long(0,0,!1);n.i=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.i=e.longs===String?"0":0;e.bytes===String?n.s="":(n.s=[],e.bytes!==Array&&(n.s=l.newBuffer(n.s))),n.t=null,n.g=null,n.docString="",n.type=e.enums===String?"UNDEFINED":0,n.refAttrName=""}if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.f&&t.hasOwnProperty("f")&&(n.f=e.json&&!isFinite(t.f)?String(t.f):t.f),null!=t.i&&t.hasOwnProperty("i")&&("number"==typeof t.i?n.i=e.longs===String?String(t.i):t.i:n.i=e.longs===String?l.Long.prototype.toString.call(t.i):e.longs===Number?new l.LongBits(t.i.low>>>0,t.i.high>>>0).toNumber():t.i),null!=t.s&&t.hasOwnProperty("s")&&(n.s=e.bytes===String?l.base64.encode(t.s,0,t.s.length):e.bytes===Array?Array.prototype.slice.call(t.s):t.s),null!=t.t&&t.hasOwnProperty("t")&&(n.t=c.onnx.TensorProto.toObject(t.t,e)),null!=t.g&&t.hasOwnProperty("g")&&(n.g=c.onnx.GraphProto.toObject(t.g,e)),t.floats&&t.floats.length){n.floats=[];for(var i=0;i<t.floats.length;++i)n.floats[i]=e.json&&!isFinite(t.floats[i])?String(t.floats[i]):t.floats[i]}if(t.ints&&t.ints.length)for(n.ints=[],i=0;i<t.ints.length;++i)"number"==typeof t.ints[i]?n.ints[i]=e.longs===String?String(t.ints[i]):t.ints[i]:n.ints[i]=e.longs===String?l.Long.prototype.toString.call(t.ints[i]):e.longs===Number?new l.LongBits(t.ints[i].low>>>0,t.ints[i].high>>>0).toNumber():t.ints[i];if(t.strings&&t.strings.length)for(n.strings=[],i=0;i<t.strings.length;++i)n.strings[i]=e.bytes===String?l.base64.encode(t.strings[i],0,t.strings[i].length):e.bytes===Array?Array.prototype.slice.call(t.strings[i]):t.strings[i];if(t.tensors&&t.tensors.length)for(n.tensors=[],i=0;i<t.tensors.length;++i)n.tensors[i]=c.onnx.TensorProto.toObject(t.tensors[i],e);if(t.graphs&&t.graphs.length)for(n.graphs=[],i=0;i<t.graphs.length;++i)n.graphs[i]=c.onnx.GraphProto.toObject(t.graphs[i],e);return null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.type&&t.hasOwnProperty("type")&&(n.type=e.enums===String?c.onnx.AttributeProto.AttributeType[t.type]:t.type),null!=t.refAttrName&&t.hasOwnProperty("refAttrName")&&(n.refAttrName=t.refAttrName),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.AttributeType=function(){var t={},e=Object.create(t);return e[t[0]="UNDEFINED"]=0,e[t[1]="FLOAT"]=1,e[t[2]="INT"]=2,e[t[3]="STRING"]=3,e[t[4]="TENSOR"]=4,e[t[5]="GRAPH"]=5,e[t[6]="FLOATS"]=6,e[t[7]="INTS"]=7,e[t[8]="STRINGS"]=8,e[t[9]="TENSORS"]=9,e[t[10]="GRAPHS"]=10,e}(),t}(),o.ValueInfoProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.name="",t.prototype.type=null,t.prototype.docString="",t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.name&&t.hasOwnProperty("name")&&e.uint32(10).string(t.name),null!=t.type&&t.hasOwnProperty("type")&&c.onnx.TypeProto.encode(t.type,e.uint32(18).fork()).ldelim(),null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(26).string(t.docString),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.ValueInfoProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.name=t.string();break;case 2:r.type=c.onnx.TypeProto.decode(t,t.uint32());break;case 3:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.name&&t.hasOwnProperty("name")&&!l.isString(t.name))return"name: string expected";if(null!=t.type&&t.hasOwnProperty("type")){var e=c.onnx.TypeProto.verify(t.type);if(e)return"type."+e}return null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString)?"docString: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.ValueInfoProto)return t;var e=new c.onnx.ValueInfoProto;if(null!=t.name&&(e.name=String(t.name)),null!=t.type){if("object"!=typeof t.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");e.type=c.onnx.TypeProto.fromObject(t.type)}return null!=t.docString&&(e.docString=String(t.docString)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.name="",n.type=null,n.docString=""),null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.type&&t.hasOwnProperty("type")&&(n.type=c.onnx.TypeProto.toObject(t.type,e)),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.NodeProto=function(){function t(t){if(this.input=[],this.output=[],this.attribute=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.input=l.emptyArray,t.prototype.output=l.emptyArray,t.prototype.name="",t.prototype.opType="",t.prototype.domain="",t.prototype.attribute=l.emptyArray,t.prototype.docString="",t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.input&&t.input.length)for(var n=0;n<t.input.length;++n)e.uint32(10).string(t.input[n]);if(null!=t.output&&t.output.length)for(n=0;n<t.output.length;++n)e.uint32(18).string(t.output[n]);if(null!=t.name&&t.hasOwnProperty("name")&&e.uint32(26).string(t.name),null!=t.opType&&t.hasOwnProperty("opType")&&e.uint32(34).string(t.opType),null!=t.attribute&&t.attribute.length)for(n=0;n<t.attribute.length;++n)c.onnx.AttributeProto.encode(t.attribute[n],e.uint32(42).fork()).ldelim();return null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(50).string(t.docString),null!=t.domain&&t.hasOwnProperty("domain")&&e.uint32(58).string(t.domain),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.NodeProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(t.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(t.string());break;case 3:r.name=t.string();break;case 4:r.opType=t.string();break;case 7:r.domain=t.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(c.onnx.AttributeProto.decode(t,t.uint32()));break;case 6:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.input&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(var e=0;e<t.input.length;++e)if(!l.isString(t.input[e]))return"input: string[] expected"}if(null!=t.output&&t.hasOwnProperty("output")){if(!Array.isArray(t.output))return"output: array expected";for(e=0;e<t.output.length;++e)if(!l.isString(t.output[e]))return"output: string[] expected"}if(null!=t.name&&t.hasOwnProperty("name")&&!l.isString(t.name))return"name: string expected";if(null!=t.opType&&t.hasOwnProperty("opType")&&!l.isString(t.opType))return"opType: string expected";if(null!=t.domain&&t.hasOwnProperty("domain")&&!l.isString(t.domain))return"domain: string expected";if(null!=t.attribute&&t.hasOwnProperty("attribute")){if(!Array.isArray(t.attribute))return"attribute: array expected";for(e=0;e<t.attribute.length;++e){var n=c.onnx.AttributeProto.verify(t.attribute[e]);if(n)return"attribute."+n}}return null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString)?"docString: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.NodeProto)return t;var e=new c.onnx.NodeProto;if(t.input){if(!Array.isArray(t.input))throw TypeError(".onnx.NodeProto.input: array expected");e.input=[];for(var n=0;n<t.input.length;++n)e.input[n]=String(t.input[n])}if(t.output){if(!Array.isArray(t.output))throw TypeError(".onnx.NodeProto.output: array expected");for(e.output=[],n=0;n<t.output.length;++n)e.output[n]=String(t.output[n])}if(null!=t.name&&(e.name=String(t.name)),null!=t.opType&&(e.opType=String(t.opType)),null!=t.domain&&(e.domain=String(t.domain)),t.attribute){if(!Array.isArray(t.attribute))throw TypeError(".onnx.NodeProto.attribute: array expected");for(e.attribute=[],n=0;n<t.attribute.length;++n){if("object"!=typeof t.attribute[n])throw TypeError(".onnx.NodeProto.attribute: object expected");e.attribute[n]=c.onnx.AttributeProto.fromObject(t.attribute[n])}}return null!=t.docString&&(e.docString=String(t.docString)),e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.input=[],n.output=[],n.attribute=[]),e.defaults&&(n.name="",n.opType="",n.docString="",n.domain=""),t.input&&t.input.length){n.input=[];for(var r=0;r<t.input.length;++r)n.input[r]=t.input[r]}if(t.output&&t.output.length)for(n.output=[],r=0;r<t.output.length;++r)n.output[r]=t.output[r];if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.opType&&t.hasOwnProperty("opType")&&(n.opType=t.opType),t.attribute&&t.attribute.length)for(n.attribute=[],r=0;r<t.attribute.length;++r)n.attribute[r]=c.onnx.AttributeProto.toObject(t.attribute[r],e);return null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.ModelProto=function(){function t(t){if(this.opsetImport=[],this.metadataProps=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.irVersion=l.Long?l.Long.fromBits(0,0,!1):0,t.prototype.opsetImport=l.emptyArray,t.prototype.producerName="",t.prototype.producerVersion="",t.prototype.domain="",t.prototype.modelVersion=l.Long?l.Long.fromBits(0,0,!1):0,t.prototype.docString="",t.prototype.graph=null,t.prototype.metadataProps=l.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.irVersion&&t.hasOwnProperty("irVersion")&&e.uint32(8).int64(t.irVersion),null!=t.producerName&&t.hasOwnProperty("producerName")&&e.uint32(18).string(t.producerName),null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&e.uint32(26).string(t.producerVersion),null!=t.domain&&t.hasOwnProperty("domain")&&e.uint32(34).string(t.domain),null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&e.uint32(40).int64(t.modelVersion),null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(50).string(t.docString),null!=t.graph&&t.hasOwnProperty("graph")&&c.onnx.GraphProto.encode(t.graph,e.uint32(58).fork()).ldelim(),null!=t.opsetImport&&t.opsetImport.length)for(var n=0;n<t.opsetImport.length;++n)c.onnx.OperatorSetIdProto.encode(t.opsetImport[n],e.uint32(66).fork()).ldelim();if(null!=t.metadataProps&&t.metadataProps.length)for(n=0;n<t.metadataProps.length;++n)c.onnx.StringStringEntryProto.encode(t.metadataProps[n],e.uint32(114).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.ModelProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.irVersion=t.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(c.onnx.OperatorSetIdProto.decode(t,t.uint32()));break;case 2:r.producerName=t.string();break;case 3:r.producerVersion=t.string();break;case 4:r.domain=t.string();break;case 5:r.modelVersion=t.int64();break;case 6:r.docString=t.string();break;case 7:r.graph=c.onnx.GraphProto.decode(t,t.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(c.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.irVersion&&t.hasOwnProperty("irVersion")&&!(l.isInteger(t.irVersion)||t.irVersion&&l.isInteger(t.irVersion.low)&&l.isInteger(t.irVersion.high)))return"irVersion: integer|Long expected";if(null!=t.opsetImport&&t.hasOwnProperty("opsetImport")){if(!Array.isArray(t.opsetImport))return"opsetImport: array expected";for(var e=0;e<t.opsetImport.length;++e)if(n=c.onnx.OperatorSetIdProto.verify(t.opsetImport[e]))return"opsetImport."+n}if(null!=t.producerName&&t.hasOwnProperty("producerName")&&!l.isString(t.producerName))return"producerName: string expected";if(null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&!l.isString(t.producerVersion))return"producerVersion: string expected";if(null!=t.domain&&t.hasOwnProperty("domain")&&!l.isString(t.domain))return"domain: string expected";if(null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&!(l.isInteger(t.modelVersion)||t.modelVersion&&l.isInteger(t.modelVersion.low)&&l.isInteger(t.modelVersion.high)))return"modelVersion: integer|Long expected";if(null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString))return"docString: string expected";if(null!=t.graph&&t.hasOwnProperty("graph")&&(n=c.onnx.GraphProto.verify(t.graph)))return"graph."+n;if(null!=t.metadataProps&&t.hasOwnProperty("metadataProps")){if(!Array.isArray(t.metadataProps))return"metadataProps: array expected";for(e=0;e<t.metadataProps.length;++e){var n;if(n=c.onnx.StringStringEntryProto.verify(t.metadataProps[e]))return"metadataProps."+n}}return null},t.fromObject=function(t){if(t instanceof c.onnx.ModelProto)return t;var e=new c.onnx.ModelProto;if(null!=t.irVersion&&(l.Long?(e.irVersion=l.Long.fromValue(t.irVersion)).unsigned=!1:"string"==typeof t.irVersion?e.irVersion=parseInt(t.irVersion,10):"number"==typeof t.irVersion?e.irVersion=t.irVersion:"object"==typeof t.irVersion&&(e.irVersion=new l.LongBits(t.irVersion.low>>>0,t.irVersion.high>>>0).toNumber())),t.opsetImport){if(!Array.isArray(t.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");e.opsetImport=[];for(var n=0;n<t.opsetImport.length;++n){if("object"!=typeof t.opsetImport[n])throw TypeError(".onnx.ModelProto.opsetImport: object expected");e.opsetImport[n]=c.onnx.OperatorSetIdProto.fromObject(t.opsetImport[n])}}if(null!=t.producerName&&(e.producerName=String(t.producerName)),null!=t.producerVersion&&(e.producerVersion=String(t.producerVersion)),null!=t.domain&&(e.domain=String(t.domain)),null!=t.modelVersion&&(l.Long?(e.modelVersion=l.Long.fromValue(t.modelVersion)).unsigned=!1:"string"==typeof t.modelVersion?e.modelVersion=parseInt(t.modelVersion,10):"number"==typeof t.modelVersion?e.modelVersion=t.modelVersion:"object"==typeof t.modelVersion&&(e.modelVersion=new l.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber())),null!=t.docString&&(e.docString=String(t.docString)),null!=t.graph){if("object"!=typeof t.graph)throw TypeError(".onnx.ModelProto.graph: object expected");e.graph=c.onnx.GraphProto.fromObject(t.graph)}if(t.metadataProps){if(!Array.isArray(t.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(e.metadataProps=[],n=0;n<t.metadataProps.length;++n){if("object"!=typeof t.metadataProps[n])throw TypeError(".onnx.ModelProto.metadataProps: object expected");e.metadataProps[n]=c.onnx.StringStringEntryProto.fromObject(t.metadataProps[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.opsetImport=[],n.metadataProps=[]),e.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.irVersion=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.irVersion=e.longs===String?"0":0;n.producerName="",n.producerVersion="",n.domain="",l.Long?(r=new l.Long(0,0,!1),n.modelVersion=e.longs===String?r.toString():e.longs===Number?r.toNumber():r):n.modelVersion=e.longs===String?"0":0,n.docString="",n.graph=null}if(null!=t.irVersion&&t.hasOwnProperty("irVersion")&&("number"==typeof t.irVersion?n.irVersion=e.longs===String?String(t.irVersion):t.irVersion:n.irVersion=e.longs===String?l.Long.prototype.toString.call(t.irVersion):e.longs===Number?new l.LongBits(t.irVersion.low>>>0,t.irVersion.high>>>0).toNumber():t.irVersion),null!=t.producerName&&t.hasOwnProperty("producerName")&&(n.producerName=t.producerName),null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&(n.producerVersion=t.producerVersion),null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&("number"==typeof t.modelVersion?n.modelVersion=e.longs===String?String(t.modelVersion):t.modelVersion:n.modelVersion=e.longs===String?l.Long.prototype.toString.call(t.modelVersion):e.longs===Number?new l.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber():t.modelVersion),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.graph&&t.hasOwnProperty("graph")&&(n.graph=c.onnx.GraphProto.toObject(t.graph,e)),t.opsetImport&&t.opsetImport.length){n.opsetImport=[];for(var i=0;i<t.opsetImport.length;++i)n.opsetImport[i]=c.onnx.OperatorSetIdProto.toObject(t.opsetImport[i],e)}if(t.metadataProps&&t.metadataProps.length)for(n.metadataProps=[],i=0;i<t.metadataProps.length;++i)n.metadataProps[i]=c.onnx.StringStringEntryProto.toObject(t.metadataProps[i],e);return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.StringStringEntryProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.key="",t.prototype.value="",t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.key&&t.hasOwnProperty("key")&&e.uint32(10).string(t.key),null!=t.value&&t.hasOwnProperty("value")&&e.uint32(18).string(t.value),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.StringStringEntryProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.key=t.string();break;case 2:r.value=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.key&&t.hasOwnProperty("key")&&!l.isString(t.key)?"key: string expected":null!=t.value&&t.hasOwnProperty("value")&&!l.isString(t.value)?"value: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.StringStringEntryProto)return t;var e=new c.onnx.StringStringEntryProto;return null!=t.key&&(e.key=String(t.key)),null!=t.value&&(e.value=String(t.value)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.key="",n.value=""),null!=t.key&&t.hasOwnProperty("key")&&(n.key=t.key),null!=t.value&&t.hasOwnProperty("value")&&(n.value=t.value),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.TensorAnnotation=function(){function t(t){if(this.quantParameterTensorNames=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.tensorName="",t.prototype.quantParameterTensorNames=l.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.tensorName&&t.hasOwnProperty("tensorName")&&e.uint32(10).string(t.tensorName),null!=t.quantParameterTensorNames&&t.quantParameterTensorNames.length)for(var n=0;n<t.quantParameterTensorNames.length;++n)c.onnx.StringStringEntryProto.encode(t.quantParameterTensorNames[n],e.uint32(18).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TensorAnnotation;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.tensorName=t.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(c.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorName&&t.hasOwnProperty("tensorName")&&!l.isString(t.tensorName))return"tensorName: string expected";if(null!=t.quantParameterTensorNames&&t.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(t.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var e=0;e<t.quantParameterTensorNames.length;++e){var n=c.onnx.StringStringEntryProto.verify(t.quantParameterTensorNames[e]);if(n)return"quantParameterTensorNames."+n}}return null},t.fromObject=function(t){if(t instanceof c.onnx.TensorAnnotation)return t;var e=new c.onnx.TensorAnnotation;if(null!=t.tensorName&&(e.tensorName=String(t.tensorName)),t.quantParameterTensorNames){if(!Array.isArray(t.quantParameterTensorNames))throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");e.quantParameterTensorNames=[];for(var n=0;n<t.quantParameterTensorNames.length;++n){if("object"!=typeof t.quantParameterTensorNames[n])throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");e.quantParameterTensorNames[n]=c.onnx.StringStringEntryProto.fromObject(t.quantParameterTensorNames[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.quantParameterTensorNames=[]),e.defaults&&(n.tensorName=""),null!=t.tensorName&&t.hasOwnProperty("tensorName")&&(n.tensorName=t.tensorName),t.quantParameterTensorNames&&t.quantParameterTensorNames.length){n.quantParameterTensorNames=[];for(var r=0;r<t.quantParameterTensorNames.length;++r)n.quantParameterTensorNames[r]=c.onnx.StringStringEntryProto.toObject(t.quantParameterTensorNames[r],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.GraphProto=function(){function t(t){if(this.node=[],this.initializer=[],this.input=[],this.output=[],this.valueInfo=[],this.quantizationAnnotation=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.node=l.emptyArray,t.prototype.name="",t.prototype.initializer=l.emptyArray,t.prototype.docString="",t.prototype.input=l.emptyArray,t.prototype.output=l.emptyArray,t.prototype.valueInfo=l.emptyArray,t.prototype.quantizationAnnotation=l.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.node&&t.node.length)for(var n=0;n<t.node.length;++n)c.onnx.NodeProto.encode(t.node[n],e.uint32(10).fork()).ldelim();if(null!=t.name&&t.hasOwnProperty("name")&&e.uint32(18).string(t.name),null!=t.initializer&&t.initializer.length)for(n=0;n<t.initializer.length;++n)c.onnx.TensorProto.encode(t.initializer[n],e.uint32(42).fork()).ldelim();if(null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(82).string(t.docString),null!=t.input&&t.input.length)for(n=0;n<t.input.length;++n)c.onnx.ValueInfoProto.encode(t.input[n],e.uint32(90).fork()).ldelim();if(null!=t.output&&t.output.length)for(n=0;n<t.output.length;++n)c.onnx.ValueInfoProto.encode(t.output[n],e.uint32(98).fork()).ldelim();if(null!=t.valueInfo&&t.valueInfo.length)for(n=0;n<t.valueInfo.length;++n)c.onnx.ValueInfoProto.encode(t.valueInfo[n],e.uint32(106).fork()).ldelim();if(null!=t.quantizationAnnotation&&t.quantizationAnnotation.length)for(n=0;n<t.quantizationAnnotation.length;++n)c.onnx.TensorAnnotation.encode(t.quantizationAnnotation[n],e.uint32(114).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.GraphProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(c.onnx.NodeProto.decode(t,t.uint32()));break;case 2:r.name=t.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(c.onnx.TensorProto.decode(t,t.uint32()));break;case 10:r.docString=t.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(c.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(c.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(c.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(c.onnx.TensorAnnotation.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.node&&t.hasOwnProperty("node")){if(!Array.isArray(t.node))return"node: array expected";for(var e=0;e<t.node.length;++e)if(n=c.onnx.NodeProto.verify(t.node[e]))return"node."+n}if(null!=t.name&&t.hasOwnProperty("name")&&!l.isString(t.name))return"name: string expected";if(null!=t.initializer&&t.hasOwnProperty("initializer")){if(!Array.isArray(t.initializer))return"initializer: array expected";for(e=0;e<t.initializer.length;++e)if(n=c.onnx.TensorProto.verify(t.initializer[e]))return"initializer."+n}if(null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString))return"docString: string expected";if(null!=t.input&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(e=0;e<t.input.length;++e)if(n=c.onnx.ValueInfoProto.verify(t.input[e]))return"input."+n}if(null!=t.output&&t.hasOwnProperty("output")){if(!Array.isArray(t.output))return"output: array expected";for(e=0;e<t.output.length;++e)if(n=c.onnx.ValueInfoProto.verify(t.output[e]))return"output."+n}if(null!=t.valueInfo&&t.hasOwnProperty("valueInfo")){if(!Array.isArray(t.valueInfo))return"valueInfo: array expected";for(e=0;e<t.valueInfo.length;++e)if(n=c.onnx.ValueInfoProto.verify(t.valueInfo[e]))return"valueInfo."+n}if(null!=t.quantizationAnnotation&&t.hasOwnProperty("quantizationAnnotation")){if(!Array.isArray(t.quantizationAnnotation))return"quantizationAnnotation: array expected";for(e=0;e<t.quantizationAnnotation.length;++e){var n;if(n=c.onnx.TensorAnnotation.verify(t.quantizationAnnotation[e]))return"quantizationAnnotation."+n}}return null},t.fromObject=function(t){if(t instanceof c.onnx.GraphProto)return t;var e=new c.onnx.GraphProto;if(t.node){if(!Array.isArray(t.node))throw TypeError(".onnx.GraphProto.node: array expected");e.node=[];for(var n=0;n<t.node.length;++n){if("object"!=typeof t.node[n])throw TypeError(".onnx.GraphProto.node: object expected");e.node[n]=c.onnx.NodeProto.fromObject(t.node[n])}}if(null!=t.name&&(e.name=String(t.name)),t.initializer){if(!Array.isArray(t.initializer))throw TypeError(".onnx.GraphProto.initializer: array expected");for(e.initializer=[],n=0;n<t.initializer.length;++n){if("object"!=typeof t.initializer[n])throw TypeError(".onnx.GraphProto.initializer: object expected");e.initializer[n]=c.onnx.TensorProto.fromObject(t.initializer[n])}}if(null!=t.docString&&(e.docString=String(t.docString)),t.input){if(!Array.isArray(t.input))throw TypeError(".onnx.GraphProto.input: array expected");for(e.input=[],n=0;n<t.input.length;++n){if("object"!=typeof t.input[n])throw TypeError(".onnx.GraphProto.input: object expected");e.input[n]=c.onnx.ValueInfoProto.fromObject(t.input[n])}}if(t.output){if(!Array.isArray(t.output))throw TypeError(".onnx.GraphProto.output: array expected");for(e.output=[],n=0;n<t.output.length;++n){if("object"!=typeof t.output[n])throw TypeError(".onnx.GraphProto.output: object expected");e.output[n]=c.onnx.ValueInfoProto.fromObject(t.output[n])}}if(t.valueInfo){if(!Array.isArray(t.valueInfo))throw TypeError(".onnx.GraphProto.valueInfo: array expected");for(e.valueInfo=[],n=0;n<t.valueInfo.length;++n){if("object"!=typeof t.valueInfo[n])throw TypeError(".onnx.GraphProto.valueInfo: object expected");e.valueInfo[n]=c.onnx.ValueInfoProto.fromObject(t.valueInfo[n])}}if(t.quantizationAnnotation){if(!Array.isArray(t.quantizationAnnotation))throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");for(e.quantizationAnnotation=[],n=0;n<t.quantizationAnnotation.length;++n){if("object"!=typeof t.quantizationAnnotation[n])throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");e.quantizationAnnotation[n]=c.onnx.TensorAnnotation.fromObject(t.quantizationAnnotation[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.node=[],n.initializer=[],n.input=[],n.output=[],n.valueInfo=[],n.quantizationAnnotation=[]),e.defaults&&(n.name="",n.docString=""),t.node&&t.node.length){n.node=[];for(var r=0;r<t.node.length;++r)n.node[r]=c.onnx.NodeProto.toObject(t.node[r],e)}if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),t.initializer&&t.initializer.length)for(n.initializer=[],r=0;r<t.initializer.length;++r)n.initializer[r]=c.onnx.TensorProto.toObject(t.initializer[r],e);if(null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),t.input&&t.input.length)for(n.input=[],r=0;r<t.input.length;++r)n.input[r]=c.onnx.ValueInfoProto.toObject(t.input[r],e);if(t.output&&t.output.length)for(n.output=[],r=0;r<t.output.length;++r)n.output[r]=c.onnx.ValueInfoProto.toObject(t.output[r],e);if(t.valueInfo&&t.valueInfo.length)for(n.valueInfo=[],r=0;r<t.valueInfo.length;++r)n.valueInfo[r]=c.onnx.ValueInfoProto.toObject(t.valueInfo[r],e);if(t.quantizationAnnotation&&t.quantizationAnnotation.length)for(n.quantizationAnnotation=[],r=0;r<t.quantizationAnnotation.length;++r)n.quantizationAnnotation[r]=c.onnx.TensorAnnotation.toObject(t.quantizationAnnotation[r],e);return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.TensorProto=function(){function t(t){if(this.dims=[],this.floatData=[],this.int32Data=[],this.stringData=[],this.int64Data=[],this.externalData=[],this.doubleData=[],this.uint64Data=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.dims=l.emptyArray,t.prototype.dataType=0,t.prototype.segment=null,t.prototype.floatData=l.emptyArray,t.prototype.int32Data=l.emptyArray,t.prototype.stringData=l.emptyArray,t.prototype.int64Data=l.emptyArray,t.prototype.name="",t.prototype.docString="",t.prototype.rawData=l.newBuffer([]),t.prototype.externalData=l.emptyArray,t.prototype.dataLocation=0,t.prototype.doubleData=l.emptyArray,t.prototype.uint64Data=l.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.dims&&t.dims.length){e.uint32(10).fork();for(var n=0;n<t.dims.length;++n)e.int64(t.dims[n]);e.ldelim()}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&e.uint32(16).int32(t.dataType),null!=t.segment&&t.hasOwnProperty("segment")&&c.onnx.TensorProto.Segment.encode(t.segment,e.uint32(26).fork()).ldelim(),null!=t.floatData&&t.floatData.length){for(e.uint32(34).fork(),n=0;n<t.floatData.length;++n)e.float(t.floatData[n]);e.ldelim()}if(null!=t.int32Data&&t.int32Data.length){for(e.uint32(42).fork(),n=0;n<t.int32Data.length;++n)e.int32(t.int32Data[n]);e.ldelim()}if(null!=t.stringData&&t.stringData.length)for(n=0;n<t.stringData.length;++n)e.uint32(50).bytes(t.stringData[n]);if(null!=t.int64Data&&t.int64Data.length){for(e.uint32(58).fork(),n=0;n<t.int64Data.length;++n)e.int64(t.int64Data[n]);e.ldelim()}if(null!=t.name&&t.hasOwnProperty("name")&&e.uint32(66).string(t.name),null!=t.rawData&&t.hasOwnProperty("rawData")&&e.uint32(74).bytes(t.rawData),null!=t.doubleData&&t.doubleData.length){for(e.uint32(82).fork(),n=0;n<t.doubleData.length;++n)e.double(t.doubleData[n]);e.ldelim()}if(null!=t.uint64Data&&t.uint64Data.length){for(e.uint32(90).fork(),n=0;n<t.uint64Data.length;++n)e.uint64(t.uint64Data[n]);e.ldelim()}if(null!=t.docString&&t.hasOwnProperty("docString")&&e.uint32(98).string(t.docString),null!=t.externalData&&t.externalData.length)for(n=0;n<t.externalData.length;++n)c.onnx.StringStringEntryProto.encode(t.externalData[n],e.uint32(106).fork()).ldelim();return null!=t.dataLocation&&t.hasOwnProperty("dataLocation")&&e.uint32(112).int32(t.dataLocation),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TensorProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos<o;)r.dims.push(t.int64());else r.dims.push(t.int64());break;case 2:r.dataType=t.int32();break;case 3:r.segment=c.onnx.TensorProto.Segment.decode(t,t.uint32());break;case 4:if(r.floatData&&r.floatData.length||(r.floatData=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.floatData.push(t.float());else r.floatData.push(t.float());break;case 5:if(r.int32Data&&r.int32Data.length||(r.int32Data=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.int32Data.push(t.int32());else r.int32Data.push(t.int32());break;case 6:r.stringData&&r.stringData.length||(r.stringData=[]),r.stringData.push(t.bytes());break;case 7:if(r.int64Data&&r.int64Data.length||(r.int64Data=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.int64Data.push(t.int64());else r.int64Data.push(t.int64());break;case 8:r.name=t.string();break;case 12:r.docString=t.string();break;case 9:r.rawData=t.bytes();break;case 13:r.externalData&&r.externalData.length||(r.externalData=[]),r.externalData.push(c.onnx.StringStringEntryProto.decode(t,t.uint32()));break;case 14:r.dataLocation=t.int32();break;case 10:if(r.doubleData&&r.doubleData.length||(r.doubleData=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.doubleData.push(t.double());else r.doubleData.push(t.double());break;case 11:if(r.uint64Data&&r.uint64Data.length||(r.uint64Data=[]),2==(7&i))for(o=t.uint32()+t.pos;t.pos<o;)r.uint64Data.push(t.uint64());else r.uint64Data.push(t.uint64());break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.dims&&t.hasOwnProperty("dims")){if(!Array.isArray(t.dims))return"dims: array expected";for(var e=0;e<t.dims.length;++e)if(!(l.isInteger(t.dims[e])||t.dims[e]&&l.isInteger(t.dims[e].low)&&l.isInteger(t.dims[e].high)))return"dims: integer|Long[] expected"}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&!l.isInteger(t.dataType))return"dataType: integer expected";if(null!=t.segment&&t.hasOwnProperty("segment")&&(n=c.onnx.TensorProto.Segment.verify(t.segment)))return"segment."+n;if(null!=t.floatData&&t.hasOwnProperty("floatData")){if(!Array.isArray(t.floatData))return"floatData: array expected";for(e=0;e<t.floatData.length;++e)if("number"!=typeof t.floatData[e])return"floatData: number[] expected"}if(null!=t.int32Data&&t.hasOwnProperty("int32Data")){if(!Array.isArray(t.int32Data))return"int32Data: array expected";for(e=0;e<t.int32Data.length;++e)if(!l.isInteger(t.int32Data[e]))return"int32Data: integer[] expected"}if(null!=t.stringData&&t.hasOwnProperty("stringData")){if(!Array.isArray(t.stringData))return"stringData: array expected";for(e=0;e<t.stringData.length;++e)if(!(t.stringData[e]&&"number"==typeof t.stringData[e].length||l.isString(t.stringData[e])))return"stringData: buffer[] expected"}if(null!=t.int64Data&&t.hasOwnProperty("int64Data")){if(!Array.isArray(t.int64Data))return"int64Data: array expected";for(e=0;e<t.int64Data.length;++e)if(!(l.isInteger(t.int64Data[e])||t.int64Data[e]&&l.isInteger(t.int64Data[e].low)&&l.isInteger(t.int64Data[e].high)))return"int64Data: integer|Long[] expected"}if(null!=t.name&&t.hasOwnProperty("name")&&!l.isString(t.name))return"name: string expected";if(null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString))return"docString: string expected";if(null!=t.rawData&&t.hasOwnProperty("rawData")&&!(t.rawData&&"number"==typeof t.rawData.length||l.isString(t.rawData)))return"rawData: buffer expected";if(null!=t.externalData&&t.hasOwnProperty("externalData")){if(!Array.isArray(t.externalData))return"externalData: array expected";for(e=0;e<t.externalData.length;++e){var n;if(n=c.onnx.StringStringEntryProto.verify(t.externalData[e]))return"externalData."+n}}if(null!=t.dataLocation&&t.hasOwnProperty("dataLocation"))switch(t.dataLocation){default:return"dataLocation: enum value expected";case 0:case 1:}if(null!=t.doubleData&&t.hasOwnProperty("doubleData")){if(!Array.isArray(t.doubleData))return"doubleData: array expected";for(e=0;e<t.doubleData.length;++e)if("number"!=typeof t.doubleData[e])return"doubleData: number[] expected"}if(null!=t.uint64Data&&t.hasOwnProperty("uint64Data")){if(!Array.isArray(t.uint64Data))return"uint64Data: array expected";for(e=0;e<t.uint64Data.length;++e)if(!(l.isInteger(t.uint64Data[e])||t.uint64Data[e]&&l.isInteger(t.uint64Data[e].low)&&l.isInteger(t.uint64Data[e].high)))return"uint64Data: integer|Long[] expected"}return null},t.fromObject=function(t){if(t instanceof c.onnx.TensorProto)return t;var e=new c.onnx.TensorProto;if(t.dims){if(!Array.isArray(t.dims))throw TypeError(".onnx.TensorProto.dims: array expected");e.dims=[];for(var n=0;n<t.dims.length;++n)l.Long?(e.dims[n]=l.Long.fromValue(t.dims[n])).unsigned=!1:"string"==typeof t.dims[n]?e.dims[n]=parseInt(t.dims[n],10):"number"==typeof t.dims[n]?e.dims[n]=t.dims[n]:"object"==typeof t.dims[n]&&(e.dims[n]=new l.LongBits(t.dims[n].low>>>0,t.dims[n].high>>>0).toNumber())}if(null!=t.dataType&&(e.dataType=0|t.dataType),null!=t.segment){if("object"!=typeof t.segment)throw TypeError(".onnx.TensorProto.segment: object expected");e.segment=c.onnx.TensorProto.Segment.fromObject(t.segment)}if(t.floatData){if(!Array.isArray(t.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(e.floatData=[],n=0;n<t.floatData.length;++n)e.floatData[n]=Number(t.floatData[n])}if(t.int32Data){if(!Array.isArray(t.int32Data))throw TypeError(".onnx.TensorProto.int32Data: array expected");for(e.int32Data=[],n=0;n<t.int32Data.length;++n)e.int32Data[n]=0|t.int32Data[n]}if(t.stringData){if(!Array.isArray(t.stringData))throw TypeError(".onnx.TensorProto.stringData: array expected");for(e.stringData=[],n=0;n<t.stringData.length;++n)"string"==typeof t.stringData[n]?l.base64.decode(t.stringData[n],e.stringData[n]=l.newBuffer(l.base64.length(t.stringData[n])),0):t.stringData[n].length&&(e.stringData[n]=t.stringData[n])}if(t.int64Data){if(!Array.isArray(t.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");for(e.int64Data=[],n=0;n<t.int64Data.length;++n)l.Long?(e.int64Data[n]=l.Long.fromValue(t.int64Data[n])).unsigned=!1:"string"==typeof t.int64Data[n]?e.int64Data[n]=parseInt(t.int64Data[n],10):"number"==typeof t.int64Data[n]?e.int64Data[n]=t.int64Data[n]:"object"==typeof t.int64Data[n]&&(e.int64Data[n]=new l.LongBits(t.int64Data[n].low>>>0,t.int64Data[n].high>>>0).toNumber())}if(null!=t.name&&(e.name=String(t.name)),null!=t.docString&&(e.docString=String(t.docString)),null!=t.rawData&&("string"==typeof t.rawData?l.base64.decode(t.rawData,e.rawData=l.newBuffer(l.base64.length(t.rawData)),0):t.rawData.length&&(e.rawData=t.rawData)),t.externalData){if(!Array.isArray(t.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(e.externalData=[],n=0;n<t.externalData.length;++n){if("object"!=typeof t.externalData[n])throw TypeError(".onnx.TensorProto.externalData: object expected");e.externalData[n]=c.onnx.StringStringEntryProto.fromObject(t.externalData[n])}}switch(t.dataLocation){case"DEFAULT":case 0:e.dataLocation=0;break;case"EXTERNAL":case 1:e.dataLocation=1}if(t.doubleData){if(!Array.isArray(t.doubleData))throw TypeError(".onnx.TensorProto.doubleData: array expected");for(e.doubleData=[],n=0;n<t.doubleData.length;++n)e.doubleData[n]=Number(t.doubleData[n])}if(t.uint64Data){if(!Array.isArray(t.uint64Data))throw TypeError(".onnx.TensorProto.uint64Data: array expected");for(e.uint64Data=[],n=0;n<t.uint64Data.length;++n)l.Long?(e.uint64Data[n]=l.Long.fromValue(t.uint64Data[n])).unsigned=!0:"string"==typeof t.uint64Data[n]?e.uint64Data[n]=parseInt(t.uint64Data[n],10):"number"==typeof t.uint64Data[n]?e.uint64Data[n]=t.uint64Data[n]:"object"==typeof t.uint64Data[n]&&(e.uint64Data[n]=new l.LongBits(t.uint64Data[n].low>>>0,t.uint64Data[n].high>>>0).toNumber(!0))}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),e.defaults&&(n.dataType=0,n.segment=null,n.name="",e.bytes===String?n.rawData="":(n.rawData=[],e.bytes!==Array&&(n.rawData=l.newBuffer(n.rawData))),n.docString="",n.dataLocation=e.enums===String?"DEFAULT":0),t.dims&&t.dims.length){n.dims=[];for(var r=0;r<t.dims.length;++r)"number"==typeof t.dims[r]?n.dims[r]=e.longs===String?String(t.dims[r]):t.dims[r]:n.dims[r]=e.longs===String?l.Long.prototype.toString.call(t.dims[r]):e.longs===Number?new l.LongBits(t.dims[r].low>>>0,t.dims[r].high>>>0).toNumber():t.dims[r]}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&(n.dataType=t.dataType),null!=t.segment&&t.hasOwnProperty("segment")&&(n.segment=c.onnx.TensorProto.Segment.toObject(t.segment,e)),t.floatData&&t.floatData.length)for(n.floatData=[],r=0;r<t.floatData.length;++r)n.floatData[r]=e.json&&!isFinite(t.floatData[r])?String(t.floatData[r]):t.floatData[r];if(t.int32Data&&t.int32Data.length)for(n.int32Data=[],r=0;r<t.int32Data.length;++r)n.int32Data[r]=t.int32Data[r];if(t.stringData&&t.stringData.length)for(n.stringData=[],r=0;r<t.stringData.length;++r)n.stringData[r]=e.bytes===String?l.base64.encode(t.stringData[r],0,t.stringData[r].length):e.bytes===Array?Array.prototype.slice.call(t.stringData[r]):t.stringData[r];if(t.int64Data&&t.int64Data.length)for(n.int64Data=[],r=0;r<t.int64Data.length;++r)"number"==typeof t.int64Data[r]?n.int64Data[r]=e.longs===String?String(t.int64Data[r]):t.int64Data[r]:n.int64Data[r]=e.longs===String?l.Long.prototype.toString.call(t.int64Data[r]):e.longs===Number?new l.LongBits(t.int64Data[r].low>>>0,t.int64Data[r].high>>>0).toNumber():t.int64Data[r];if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.rawData&&t.hasOwnProperty("rawData")&&(n.rawData=e.bytes===String?l.base64.encode(t.rawData,0,t.rawData.length):e.bytes===Array?Array.prototype.slice.call(t.rawData):t.rawData),t.doubleData&&t.doubleData.length)for(n.doubleData=[],r=0;r<t.doubleData.length;++r)n.doubleData[r]=e.json&&!isFinite(t.doubleData[r])?String(t.doubleData[r]):t.doubleData[r];if(t.uint64Data&&t.uint64Data.length)for(n.uint64Data=[],r=0;r<t.uint64Data.length;++r)"number"==typeof t.uint64Data[r]?n.uint64Data[r]=e.longs===String?String(t.uint64Data[r]):t.uint64Data[r]:n.uint64Data[r]=e.longs===String?l.Long.prototype.toString.call(t.uint64Data[r]):e.longs===Number?new l.LongBits(t.uint64Data[r].low>>>0,t.uint64Data[r].high>>>0).toNumber(!0):t.uint64Data[r];if(null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),t.externalData&&t.externalData.length)for(n.externalData=[],r=0;r<t.externalData.length;++r)n.externalData[r]=c.onnx.StringStringEntryProto.toObject(t.externalData[r],e);return null!=t.dataLocation&&t.hasOwnProperty("dataLocation")&&(n.dataLocation=e.enums===String?c.onnx.TensorProto.DataLocation[t.dataLocation]:t.dataLocation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.DataType=function(){var t={},e=Object.create(t);return e[t[0]="UNDEFINED"]=0,e[t[1]="FLOAT"]=1,e[t[2]="UINT8"]=2,e[t[3]="INT8"]=3,e[t[4]="UINT16"]=4,e[t[5]="INT16"]=5,e[t[6]="INT32"]=6,e[t[7]="INT64"]=7,e[t[8]="STRING"]=8,e[t[9]="BOOL"]=9,e[t[10]="FLOAT16"]=10,e[t[11]="DOUBLE"]=11,e[t[12]="UINT32"]=12,e[t[13]="UINT64"]=13,e[t[14]="COMPLEX64"]=14,e[t[15]="COMPLEX128"]=15,e[t[16]="BFLOAT16"]=16,e}(),t.Segment=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.begin=l.Long?l.Long.fromBits(0,0,!1):0,t.prototype.end=l.Long?l.Long.fromBits(0,0,!1):0,t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.begin&&t.hasOwnProperty("begin")&&e.uint32(8).int64(t.begin),null!=t.end&&t.hasOwnProperty("end")&&e.uint32(16).int64(t.end),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TensorProto.Segment;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.begin=t.int64();break;case 2:r.end=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.begin&&t.hasOwnProperty("begin")&&!(l.isInteger(t.begin)||t.begin&&l.isInteger(t.begin.low)&&l.isInteger(t.begin.high))?"begin: integer|Long expected":null!=t.end&&t.hasOwnProperty("end")&&!(l.isInteger(t.end)||t.end&&l.isInteger(t.end.low)&&l.isInteger(t.end.high))?"end: integer|Long expected":null},t.fromObject=function(t){if(t instanceof c.onnx.TensorProto.Segment)return t;var e=new c.onnx.TensorProto.Segment;return null!=t.begin&&(l.Long?(e.begin=l.Long.fromValue(t.begin)).unsigned=!1:"string"==typeof t.begin?e.begin=parseInt(t.begin,10):"number"==typeof t.begin?e.begin=t.begin:"object"==typeof t.begin&&(e.begin=new l.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber())),null!=t.end&&(l.Long?(e.end=l.Long.fromValue(t.end)).unsigned=!1:"string"==typeof t.end?e.end=parseInt(t.end,10):"number"==typeof t.end?e.end=t.end:"object"==typeof t.end&&(e.end=new l.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.begin=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.begin=e.longs===String?"0":0;l.Long?(r=new l.Long(0,0,!1),n.end=e.longs===String?r.toString():e.longs===Number?r.toNumber():r):n.end=e.longs===String?"0":0}return null!=t.begin&&t.hasOwnProperty("begin")&&("number"==typeof t.begin?n.begin=e.longs===String?String(t.begin):t.begin:n.begin=e.longs===String?l.Long.prototype.toString.call(t.begin):e.longs===Number?new l.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber():t.begin),null!=t.end&&t.hasOwnProperty("end")&&("number"==typeof t.end?n.end=e.longs===String?String(t.end):t.end:n.end=e.longs===String?l.Long.prototype.toString.call(t.end):e.longs===Number?new l.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber():t.end),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),t.DataLocation=function(){var t={},e=Object.create(t);return e[t[0]="DEFAULT"]=0,e[t[1]="EXTERNAL"]=1,e}(),t}(),o.TensorShapeProto=function(){function t(t){if(this.dim=[],t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.dim=l.emptyArray,t.create=function(e){return new t(e)},t.encode=function(t,e){if(e||(e=u.create()),null!=t.dim&&t.dim.length)for(var n=0;n<t.dim.length;++n)c.onnx.TensorShapeProto.Dimension.encode(t.dim[n],e.uint32(10).fork()).ldelim();return e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TensorShapeProto;t.pos<n;){var i=t.uint32();i>>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(c.onnx.TensorShapeProto.Dimension.decode(t,t.uint32()))):t.skipType(7&i)}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.dim&&t.hasOwnProperty("dim")){if(!Array.isArray(t.dim))return"dim: array expected";for(var e=0;e<t.dim.length;++e){var n=c.onnx.TensorShapeProto.Dimension.verify(t.dim[e]);if(n)return"dim."+n}}return null},t.fromObject=function(t){if(t instanceof c.onnx.TensorShapeProto)return t;var e=new c.onnx.TensorShapeProto;if(t.dim){if(!Array.isArray(t.dim))throw TypeError(".onnx.TensorShapeProto.dim: array expected");e.dim=[];for(var n=0;n<t.dim.length;++n){if("object"!=typeof t.dim[n])throw TypeError(".onnx.TensorShapeProto.dim: object expected");e.dim[n]=c.onnx.TensorShapeProto.Dimension.fromObject(t.dim[n])}}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.dim=[]),t.dim&&t.dim.length){n.dim=[];for(var r=0;r<t.dim.length;++r)n.dim[r]=c.onnx.TensorShapeProto.Dimension.toObject(t.dim[r],e)}return n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.Dimension=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}var e;return t.prototype.dimValue=l.Long?l.Long.fromBits(0,0,!1):0,t.prototype.dimParam="",t.prototype.denotation="",Object.defineProperty(t.prototype,"value",{get:l.oneOfGetter(e=["dimValue","dimParam"]),set:l.oneOfSetter(e)}),t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.dimValue&&t.hasOwnProperty("dimValue")&&e.uint32(8).int64(t.dimValue),null!=t.dimParam&&t.hasOwnProperty("dimParam")&&e.uint32(18).string(t.dimParam),null!=t.denotation&&t.hasOwnProperty("denotation")&&e.uint32(26).string(t.denotation),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TensorShapeProto.Dimension;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.dimValue=t.int64();break;case 2:r.dimParam=t.string();break;case 3:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";var e={};if(null!=t.dimValue&&t.hasOwnProperty("dimValue")&&(e.value=1,!(l.isInteger(t.dimValue)||t.dimValue&&l.isInteger(t.dimValue.low)&&l.isInteger(t.dimValue.high))))return"dimValue: integer|Long expected";if(null!=t.dimParam&&t.hasOwnProperty("dimParam")){if(1===e.value)return"value: multiple values";if(e.value=1,!l.isString(t.dimParam))return"dimParam: string expected"}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!l.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.TensorShapeProto.Dimension)return t;var e=new c.onnx.TensorShapeProto.Dimension;return null!=t.dimValue&&(l.Long?(e.dimValue=l.Long.fromValue(t.dimValue)).unsigned=!1:"string"==typeof t.dimValue?e.dimValue=parseInt(t.dimValue,10):"number"==typeof t.dimValue?e.dimValue=t.dimValue:"object"==typeof t.dimValue&&(e.dimValue=new l.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber())),null!=t.dimParam&&(e.dimParam=String(t.dimParam)),null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.dimValue&&t.hasOwnProperty("dimValue")&&("number"==typeof t.dimValue?n.dimValue=e.longs===String?String(t.dimValue):t.dimValue:n.dimValue=e.longs===String?l.Long.prototype.toString.call(t.dimValue):e.longs===Number?new l.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber():t.dimValue,e.oneofs&&(n.value="dimValue")),null!=t.dimParam&&t.hasOwnProperty("dimParam")&&(n.dimParam=t.dimParam,e.oneofs&&(n.value="dimParam")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),t}(),o.TypeProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}var e;return t.prototype.tensorType=null,t.prototype.denotation="",Object.defineProperty(t.prototype,"value",{get:l.oneOfGetter(e=["tensorType"]),set:l.oneOfSetter(e)}),t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.tensorType&&t.hasOwnProperty("tensorType")&&c.onnx.TypeProto.Tensor.encode(t.tensorType,e.uint32(10).fork()).ldelim(),null!=t.denotation&&t.hasOwnProperty("denotation")&&e.uint32(50).string(t.denotation),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TypeProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.tensorType=c.onnx.TypeProto.Tensor.decode(t,t.uint32());break;case 6:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorType&&t.hasOwnProperty("tensorType")){var e=c.onnx.TypeProto.Tensor.verify(t.tensorType);if(e)return"tensorType."+e}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!l.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.TypeProto)return t;var e=new c.onnx.TypeProto;if(null!=t.tensorType){if("object"!=typeof t.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");e.tensorType=c.onnx.TypeProto.Tensor.fromObject(t.tensorType)}return null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.tensorType&&t.hasOwnProperty("tensorType")&&(n.tensorType=c.onnx.TypeProto.Tensor.toObject(t.tensorType,e),e.oneofs&&(n.value="tensorType")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.Tensor=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.elemType=0,t.prototype.shape=null,t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.elemType&&t.hasOwnProperty("elemType")&&e.uint32(8).int32(t.elemType),null!=t.shape&&t.hasOwnProperty("shape")&&c.onnx.TensorShapeProto.encode(t.shape,e.uint32(18).fork()).ldelim(),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.TypeProto.Tensor;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.elemType=t.int32();break;case 2:r.shape=c.onnx.TensorShapeProto.decode(t,t.uint32());break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.elemType&&t.hasOwnProperty("elemType")&&!l.isInteger(t.elemType))return"elemType: integer expected";if(null!=t.shape&&t.hasOwnProperty("shape")){var e=c.onnx.TensorShapeProto.verify(t.shape);if(e)return"shape."+e}return null},t.fromObject=function(t){if(t instanceof c.onnx.TypeProto.Tensor)return t;var e=new c.onnx.TypeProto.Tensor;if(null!=t.elemType&&(e.elemType=0|t.elemType),null!=t.shape){if("object"!=typeof t.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");e.shape=c.onnx.TensorShapeProto.fromObject(t.shape)}return e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.elemType=0,n.shape=null),null!=t.elemType&&t.hasOwnProperty("elemType")&&(n.elemType=t.elemType),null!=t.shape&&t.hasOwnProperty("shape")&&(n.shape=c.onnx.TensorShapeProto.toObject(t.shape,e)),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),t}(),o.OperatorSetIdProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n<e.length;++n)null!=t[e[n]]&&(this[e[n]]=t[e[n]])}return t.prototype.domain="",t.prototype.version=l.Long?l.Long.fromBits(0,0,!1):0,t.create=function(e){return new t(e)},t.encode=function(t,e){return e||(e=u.create()),null!=t.domain&&t.hasOwnProperty("domain")&&e.uint32(10).string(t.domain),null!=t.version&&t.hasOwnProperty("version")&&e.uint32(16).int64(t.version),e},t.encodeDelimited=function(t,e){return this.encode(t,e).ldelim()},t.decode=function(t,e){t instanceof a||(t=a.create(t));for(var n=void 0===e?t.len:t.pos+e,r=new c.onnx.OperatorSetIdProto;t.pos<n;){var i=t.uint32();switch(i>>>3){case 1:r.domain=t.string();break;case 2:r.version=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.domain&&t.hasOwnProperty("domain")&&!l.isString(t.domain)?"domain: string expected":null!=t.version&&t.hasOwnProperty("version")&&!(l.isInteger(t.version)||t.version&&l.isInteger(t.version.low)&&l.isInteger(t.version.high))?"version: integer|Long expected":null},t.fromObject=function(t){if(t instanceof c.onnx.OperatorSetIdProto)return t;var e=new c.onnx.OperatorSetIdProto;return null!=t.domain&&(e.domain=String(t.domain)),null!=t.version&&(l.Long?(e.version=l.Long.fromValue(t.version)).unsigned=!1:"string"==typeof t.version?e.version=parseInt(t.version,10):"number"==typeof t.version?e.version=t.version:"object"==typeof t.version&&(e.version=new l.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults)if(n.domain="",l.Long){var r=new l.Long(0,0,!1);n.version=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.version=e.longs===String?"0":0;return null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.version&&t.hasOwnProperty("version")&&("number"==typeof t.version?n.version=e.longs===String?String(t.version):t.version:n.version=e.longs===String?l.Long.prototype.toString.call(t.version):e.longs===Number?new l.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber():t.version),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o),t.exports=c},2100:(t,e,n)=>{t.exports=n(9482)},9482:(t,e,n)=>{var r=e;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=i,i()},1408:(t,e,n)=>{t.exports=u;var r,i=n(9693),o=i.LongBits,s=i.utf8;function a(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function u(t){this.buf=t,this.pos=0,this.len=t.length}var l,c="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new u(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new u(t);throw Error("illegal buffer")},d=function(){return i.Buffer?function(t){return(u.create=function(t){return i.Buffer.isBuffer(t)?new r(t):c(t)})(t)}:c};function h(){var t=new o(0,0),e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw a(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw a(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function p(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}u.create=d(),u.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,u.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},u.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},u.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw a(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?new this.buf.constructor(0):this._slice.call(this.buf,e,n)},u.prototype.string=function(){var t=this.bytes();return s.read(t,0,t.length)},u.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw a(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},u._configure=function(t){r=t,u.create=d(),r._configure();var e=i.Long?"toLong":"toNumber";i.merge(u.prototype,{int64:function(){return h.call(this)[e](!1)},uint64:function(){return h.call(this)[e](!0)},sint64:function(){return h.call(this).zzDecode()[e](!1)},fixed64:function(){return f.call(this)[e](!0)},sfixed64:function(){return f.call(this)[e](!1)}})}},593:(t,e,n)=>{t.exports=o;var r=n(1408);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(t){r.call(this,t)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},o._configure()},5054:t=>{t.exports={}},5994:(t,e,n)=>{e.Service=n(7948)},7948:(t,e,n)=>{t.exports=i;var r=n(9693);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(e),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function t(e,n,i,o,s){if(!o)throw TypeError("request must be specified");var a=this;if(!s)return r.asPromise(t,a,e,n,i,o);if(a.rpcImpl)try{return a.rpcImpl(e,n[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),function(t,n){if(t)return a.emit("error",t,e),s(t);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return a.emit("error",t,e),s(t)}return a.emit("data",n,e),s(null,n)}a.end(!0)})}catch(t){return a.emit("error",t,e),void setTimeout(function(){s(t)},0)}else setTimeout(function(){s(Error("already ended"))},0)},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(t,e,n)=>{t.exports=i;var r=n(9693);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return o;var e=t<0;e&&(t=-t);var n=t>>>0,r=(t-n)/4294967296>>>0;return e&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):o},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=1+~this.lo>>>0,n=~this.hi>>>0;return e||(n=n+1>>>0),-(e+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var a=String.prototype.charCodeAt;i.fromHash=function(t){return t===s?o:new i((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},i.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)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},9693:function(t,e,n){var r=e;function i(t,e,n){for(var r=Object.keys(e),i=0;i<r.length;++i)void 0!==t[r[i]]&&n||(t[r[i]]=e[r[i]]);return t}function o(t){function e(t,n){if(!(this instanceof e))return new e(t,n);Object.defineProperty(this,"message",{get:function(){return t}}),Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&i(this,n)}return(e.prototype=Object.create(Error.prototype)).constructor=e,Object.defineProperty(e.prototype,"name",{get:function(){return t}}),e.prototype.toString=function(){return this.name+": "+this.message},e}r.asPromise=n(4537),r.base64=n(7419),r.EventEmitter=n(9211),r.float=n(945),r.inquire=n(7199),r.utf8=n(4997),r.pool=n(6662),r.LongBits=n(1945),r.isNode=Boolean(void 0!==n.g&&n.g&&n.g.process&&n.g.process.versions&&n.g.process.versions.node),r.global=r.isNode&&n.g||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isInteger=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},r.isString=function(t){return"string"==typeof t||t instanceof String},r.isObject=function(t){return t&&"object"==typeof t},r.isset=r.isSet=function(t,e){var n=t[e];return!(null==n||!t.hasOwnProperty(e))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r._Buffer_allocUnsafe(t):new r.Array(t):r.Buffer?r._Buffer_from(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){var n=r.LongBits.fromHash(t);return r.Long?r.Long.fromBits(n.lo,n.hi,e):n.toNumber(Boolean(e))},r.merge=i,r.lcFirst=function(t){return t.charAt(0).toLowerCase()+t.substring(1)},r.newError=o,r.ProtocolError=o("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n<t.length;++n)e[t[n]]=1;return function(){for(var t=Object.keys(this),n=t.length-1;n>-1;--n)if(1===e[t[n]]&&void 0!==this[t[n]]&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n<t.length;++n)t[n]!==e&&delete this[t[n]]}},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var t=r.Buffer;t?(r._Buffer_from=t.from!==Uint8Array.from&&t.from||function(e,n){return new t(e,n)},r._Buffer_allocUnsafe=t.allocUnsafe||function(e){return new t(e)}):r._Buffer_from=r._Buffer_allocUnsafe=null}},1173:(t,e,n)=>{t.exports=d;var r,i=n(9693),o=i.LongBits,s=i.base64,a=i.utf8;function u(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}function l(){}function c(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function d(){this.len=0,this.head=new u(l,0,0),this.tail=this.head,this.states=null}var h=function(){return i.Buffer?function(){return(d.create=function(){return new r})()}:function(){return new d}};function p(t,e,n){e[n]=255&t}function f(t,e){this.len=t,this.next=void 0,this.val=e}function g(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function m(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}d.create=h(),d.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(d.alloc=i.pool(d.alloc,i.Array.prototype.subarray)),d.prototype._push=function(t,e,n){return this.tail=this.tail.next=new u(t,e,n),this.len+=e,this},f.prototype=Object.create(u.prototype),f.prototype.fn=function(t,e,n){for(;t>127;)e[n++]=127&t|128,t>>>=7;e[n]=t},d.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new f((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},d.prototype.int32=function(t){return t<0?this._push(g,10,o.fromNumber(t)):this.uint32(t)},d.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},d.prototype.uint64=function(t){var e=o.from(t);return this._push(g,e.length(),e)},d.prototype.int64=d.prototype.uint64,d.prototype.sint64=function(t){var e=o.from(t).zzEncode();return this._push(g,e.length(),e)},d.prototype.bool=function(t){return this._push(p,1,t?1:0)},d.prototype.fixed32=function(t){return this._push(m,4,t>>>0)},d.prototype.sfixed32=d.prototype.fixed32,d.prototype.fixed64=function(t){var e=o.from(t);return this._push(m,4,e.lo)._push(m,4,e.hi)},d.prototype.sfixed64=d.prototype.fixed64,d.prototype.float=function(t){return this._push(i.float.writeFloatLE,4,t)},d.prototype.double=function(t){return this._push(i.float.writeDoubleLE,8,t)};var b=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r<t.length;++r)e[n+r]=t[r]};d.prototype.bytes=function(t){var e=t.length>>>0;if(!e)return this._push(p,1,0);if(i.isString(t)){var n=d.alloc(e=s.length(t));s.decode(t,n,0),t=n}return this.uint32(e)._push(b,e,t)},d.prototype.string=function(t){var e=a.length(t);return e?this.uint32(e)._push(a.write,e,t):this._push(p,1,0)},d.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new u(l,0,0),this.len=0,this},d.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 u(l,0,0),this.len=0),this},d.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},d.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},d._configure=function(t){r=t,d.create=h(),r._configure()}},3155:(t,e,n)=>{t.exports=o;var r=n(1173);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(){r.call(this)}function s(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r<t.length;)e[n++]=t[r++]}},o.prototype.bytes=function(t){i.isString(t)&&(t=i._Buffer_from(t,"base64"));var e=t.length>>>0;return this.uint32(e),e&&this._push(o.writeBytesBuffer,e,t),this},o.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this._push(s,e,t),this},o._configure()},7714:(t,e,n)=>{e.R=void 0;const r=n(6919),i=n(7448);e.R=new class{async init(){}async createSessionHandler(t,e){const n=new r.Session(e);return await n.loadModel(t),new i.OnnxjsSessionHandler(n)}}},4200:(t,e,n)=>{e.c8=e.rX=void 0;const r=n(1670),i=n(5381),o=n(2157),s=n(2306);e.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=!0),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=!1),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const t="undefined"==typeof navigator?(0,i.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},e.c8=new class{async init(){(0,e.rX)(),await(0,o.initWasm)()}async createSessionHandler(t,e){const n=new s.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(t,e),Promise.resolve(n)}}},6018:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||r(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),i(n(1670),e);const o=n(1670);{const t=n(7714).R;(0,o.registerBackend)("webgl",t,-10)}{const t=n(4200).c8;(0,o.registerBackend)("cpu",t,10),(0,o.registerBackend)("wasm",t,10),(0,o.registerBackend)("xnnpack",t,9)}},246:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createAttributeWithCacheKey=void 0;class n{constructor(t){Object.assign(this,t)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this._cacheKey}}e.createAttributeWithCacheKey=t=>new n(t)},7778:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Attribute=void 0;const r=n(1446),i=n(9395),o=n(9162),s=n(2517);var a=i.onnxruntime.experimental.fbs;class u{constructor(t){if(this._attributes=new Map,null!=t){for(const e of t)e instanceof r.onnx.AttributeProto?this._attributes.set(e.name,[u.getValue(e),u.getType(e)]):e instanceof a.Attribute&&this._attributes.set(e.name(),[u.getValue(e),u.getType(e)]);if(this._attributes.size<t.length)throw new Error("duplicated attribute names")}}set(t,e,n){this._attributes.set(t,[n,e])}delete(t){this._attributes.delete(t)}getFloat(t,e){return this.get(t,"float",e)}getInt(t,e){return this.get(t,"int",e)}getString(t,e){return this.get(t,"string",e)}getTensor(t,e){return this.get(t,"tensor",e)}getFloats(t,e){return this.get(t,"floats",e)}getInts(t,e){return this.get(t,"ints",e)}getStrings(t,e){return this.get(t,"strings",e)}getTensors(t,e){return this.get(t,"tensors",e)}get(t,e,n){const r=this._attributes.get(t);if(void 0===r){if(void 0!==n)return n;throw new Error(`required attribute not found: ${t}`)}if(r[1]!==e)throw new Error(`type mismatch: expected ${e} but got ${r[1]}`);return r[0]}static getType(t){const e=t instanceof r.onnx.AttributeProto?t.type:t.type();switch(e){case r.onnx.AttributeProto.AttributeType.FLOAT:return"float";case r.onnx.AttributeProto.AttributeType.INT:return"int";case r.onnx.AttributeProto.AttributeType.STRING:return"string";case r.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case r.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case r.onnx.AttributeProto.AttributeType.INTS:return"ints";case r.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case r.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[e]}`)}}static getValue(t){const e=t instanceof r.onnx.AttributeProto?t.type:t.type();if(e===r.onnx.AttributeProto.AttributeType.GRAPH||e===r.onnx.AttributeProto.AttributeType.GRAPHS)throw new Error("graph attribute is not supported yet");const n=this.getValueNoCheck(t);if(e===r.onnx.AttributeProto.AttributeType.INT&&s.LongUtil.isLong(n))return s.LongUtil.longToNumber(n);if(e===r.onnx.AttributeProto.AttributeType.INTS){const t=n,e=new Array(t.length);for(let n=0;n<t.length;n++){const r=t[n];e[n]=s.LongUtil.longToNumber(r)}return e}if(e===r.onnx.AttributeProto.AttributeType.TENSOR)return t instanceof r.onnx.AttributeProto?o.Tensor.fromProto(n):o.Tensor.fromOrtTensor(n);if(e===r.onnx.AttributeProto.AttributeType.TENSORS){if(t instanceof r.onnx.AttributeProto)return n.map(t=>o.Tensor.fromProto(t));if(t instanceof a.Attribute)return n.map(t=>o.Tensor.fromOrtTensor(t))}if(e===r.onnx.AttributeProto.AttributeType.STRING&&t instanceof r.onnx.AttributeProto){const t=n;return(0,s.decodeUtf8String)(t)}return e===r.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof r.onnx.AttributeProto?n.map(s.decodeUtf8String):n}static getValueNoCheck(t){return t instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case r.onnx.AttributeProto.AttributeType.INT:return t.i;case r.onnx.AttributeProto.AttributeType.STRING:return t.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case r.onnx.AttributeProto.AttributeType.INTS:return t.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case a.AttributeType.FLOAT:return t.f();case a.AttributeType.INT:return t.i();case a.AttributeType.STRING:return t.s();case a.AttributeType.TENSOR:return t.t();case a.AttributeType.GRAPH:return t.g();case a.AttributeType.FLOATS:return t.floatsArray();case a.AttributeType.INTS:{const e=[];for(let n=0;n<t.intsLength();n++)e.push(t.ints(n));return e}case a.AttributeType.STRINGS:{const e=[];for(let n=0;n<t.stringsLength();n++)e.push(t.strings(n));return e}case a.AttributeType.TENSORS:{const e=[];for(let n=0;n<t.tensorsLength();n++)e.push(t.tensors(n));return e}default:throw new Error(`unsupported attribute type: ${a.AttributeType[t.type()]}`)}}}e.Attribute=u},7091:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveBackend=e.backend=void 0;const r=n(5038),i=new Map;async function o(t){const n=e.backend;if(void 0!==n[t]&&function(t){const e=t;return"initialize"in e&&"function"==typeof e.initialize&&"createSessionHandler"in e&&"function"==typeof e.createSessionHandler&&"dispose"in e&&"function"==typeof e.dispose}(n[t])){const e=n[t];let r=e.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return i.set(t,e),e}}e.backend={webgl:new r.WebGLBackend},e.resolveBackend=async function t(e){if(!e)return t(["webgl"]);{const t="string"==typeof e?[e]:e;for(const e of t){const t=i.get(e);if(t)return t;const n=await o(e);if(n)return n}}throw new Error("no available backend to use")}},5038:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLBackend=void 0;const r=n(1670),i=n(6231),o=n(6416),s=n(7305);e.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(t){r.env.webgl.contextId=t}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(t){r.env.webgl.matmulMaxBatchSize=t}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(t){r.env.webgl.textureCacheMode=t}get pack(){return r.env.webgl.pack}set pack(t){r.env.webgl.pack=t}get async(){return r.env.webgl.async}set async(t){r.env.webgl.async=t}initialize(){try{return this.glContext=(0,s.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=!1),"boolean"!=typeof this.async&&(this.async=!1),i.Logger.setWithEnv(r.env),i.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(t){return i.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${t}`),!1}}createSessionHandler(t){return new o.WebGLSessionHandler(this,t)}dispose(){this.glContext.dispose()}}},5107:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CoordsGlslLib=void 0;const r=n(2517),i=n(8520),o=n(5060),s=n(7859),a=n(9390);class u extends i.GlslLib{constructor(t){super(t)}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 i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ")}}coordsToOffset(){return{coordsToOffset:new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ")}}getOutputSamplingSnippet(){const t=this.context.outputTextureLayout;return t.isPacked?this.getPackedOutputSamplingSnippet(t):this.getUnpackedOutputSamplingSnippet(t)}getPackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},s="getOutputCoords";switch(e.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(e,n);break;case 2:r[s]=this.getOutputPacked2DCoords(e,n);break;case 3:r[s]=this.getOutputPacked3DCoords(e,n);break;default:r[s]=this.getOutputPackedNDCoords(e,n)}const a=`\n void setOutput(vec4 val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = val;\n }\n `;return r.floatTextureSetRGBA=new i.GlslLibRoutine(a),r}getUnpackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},s="getOutputCoords";switch(e.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(e,n);break;case 2:r[s]=this.getOutputUnpacked2DCoords(e,n);break;case 3:r[s]=this.getOutputUnpacked3DCoords(e,n);break;case 4:r[s]=this.getOutputUnpacked4DCoords(e,n);break;case 5:r[s]=this.getOutputUnpacked5DCoords(e,n);break;case 6:r[s]=this.getOutputUnpacked6DCoords(e,n);break;default:throw new Error(`Unsupported output dimensionality: ${e.length}`)}const a=`\n void setOutput(float val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n }\n `;return r.floatTextureSetR=new i.GlslLibRoutine(a),r}getOutputScalarCoords(){return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ")}getOutputPacked1DCoords(t,e){const n=e;let r="";return 1===n[0]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.y * ${n[1]}.0);\n }\n `,new i.GlslLibRoutine(r)):1===n[1]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.x * ${n[0]}.0);\n }\n `,new i.GlslLibRoutine(r)):(r=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n }\n `,new i.GlslLibRoutine(r))}getOutputPacked2DCoords(t,e){let n="";if(r.ArrayUtil.arraysEqual(t,e))return n=`\n ivec2 getOutputCoords() {\n return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]}));\n }\n `,new i.GlslLibRoutine(n);const o=e,s=Math.ceil(t[1]/2);return n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${o[0]}, ${o[1]}));\n\n int index = resTexRC.y * ${o[0]} + resTexRC.x;\n\n // reverse r and c order for packed texture\n int r = imod(index, ${s}) * 2;\n int c = 2 * (index / ${s});\n\n return ivec2(r, c);\n }\n `,new i.GlslLibRoutine(n)}getOutputPacked3DCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[2]/2),o=r*Math.ceil(t[1]/2),s=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec3(b, r, c);\n }\n `;return new i.GlslLibRoutine(s)}getOutputPackedNDCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2);let s=o,a="",u="b, r, c";for(let e=2;e<t.length-1;e++)s*=t[t.length-e-1],a=`\n int b${e} = index / ${s};\n index -= b${e} * ${s};\n `+a,u=`b${e}, `+u;const l=`\n ivec${t.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n ${a}\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec${t.length}(${u});\n }\n `;return new i.GlslLibRoutine(l)}getOutputUnpacked1DCoords(t,e){const n=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n return resTexRC.y * ${e[0]} + resTexRC.x;\n }\n `;return new i.GlslLibRoutine(n)}getOutputUnpacked2DCoords(t,e){const n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n int r = index / ${t[1]};\n int c = index - r * ${t[1]};\n return ivec2(r, c);\n }\n `;return new i.GlslLibRoutine(n)}getOutputUnpacked3DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d"],a=o.map((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`).join("");return n=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec3(r, c, d);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked4DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d","d2"],a=o.map((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`).join("");return n=`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec4(r, c, d, d2);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked5DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d","d2","d3"],a=o.map((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`).join("");return n=`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec5(r, c, d, d2, d3);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked6DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d","d2","d3","d4"],a=o.map((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`).join("");return n=`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec6(r, c, d, d2, d3, d4);\n }\n `,new i.GlslLibRoutine(n)}getCommonUtilFuncs(){const t={};let e="uvFromFlat";t[e]=new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "),e="packedUVfrom1D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="packedUVfrom2D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="packedUVfrom3D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="sampleTexture";const n=(0,o.getGlsl)(this.context.glContext.version);return t[e]=new i.GlslLibRoutine(`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }`),t}getInputsSamplingSnippets(){const t={},e=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((n,r)=>{const i=this.context.inputTextureLayouts[r],o=(0,a.generateShaderFuncNameFromInputSamplerName)(n);i.isPacked?t[o]=this.getPackedSamplerFromInput(o,n,i):t[o]=this.getUnpackedSamplerFromInput(o,n,i);const s=(0,a.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);i.unpackedShape.length<=e.unpackedShape.length&&(i.isPacked?t[s]=this.getPackedSamplerAtOutputCoords(s,i,e,n):t[s]=this.getUnpackedSamplerAtOutputCoords(s,i,e,n))}),t}getPackedSamplerAtOutputCoords(t,e,n,o){const s=e.unpackedShape,u=n.unpackedShape,l=o,c=(0,a.generateShaderFuncNameFromInputSamplerName)(l),d=s.length,h=u.length,p=r.BroadcastUtil.getBroadcastDims(s,u),f=(0,a.getCoordsDataType)(h),g=h-d;let m;const b=(0,a.getGlChannels)();m=0===d?"":h<2&&p.length>=1?"coords = 0;":p.map(t=>`coords.${b[t+g]} = 0;`).join("\n");let y="";y=h<2&&d>0?"coords":s.map((t,e)=>`coords.${b[e+g]}`).join(", ");let _="return outputValue;";const w=1===r.ShapeUtil.size(s),v=1===r.ShapeUtil.size(u);if(1!==d||w||v){if(w&&!v)_=1===h?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(p.length){const t=d-2,e=d-1;p.indexOf(t)>-1&&p.indexOf(e)>-1?_="return vec4(outputValue.x);":p.indexOf(t)>-1?_="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":p.indexOf(e)>-1&&(_="return vec4(outputValue.xx, outputValue.zz);")}}else _="\n return vec4(outputValue.xy, outputValue.xy);\n ";const x=`\n vec4 ${t}() {\n ${f} coords = getOutputCoords();\n \n int lastDim = coords.${b[h-1]};\n coords.${b[h-1]} = coords.${b[h-2]};\n coords.${b[h-2]} = lastDim;\n \n ${m}\n vec4 outputValue = ${c}(${y});\n ${_}\n }\n `;return new i.GlslLibRoutine(x,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(t,e,n,o){const s=[n.width,n.height],u=[e.width,e.height],l=e.unpackedShape.length,c=n.unpackedShape.length,d=e.unpackedShape,h=n.unpackedShape,p=(0,a.generateShaderFuncNameFromInputSamplerName)(o);if(l===c&&r.ArrayUtil.arraysEqual(u,s)){const e=`\n float ${t}() {\n return sampleTexture(${o}, TexCoords);\n }\n `;return new i.GlslLibRoutine(e,["coordinates.sampleTexture"])}const f=(0,a.getCoordsDataType)(c),g=r.BroadcastUtil.getBroadcastDims(d,h),m=c-l;let b;const y=(0,a.getGlChannels)();b=0===l?"":c<2&&g.length>=1?"coords = 0;":g.map(t=>`coords.${y[t+m]} = 0;`).join("\n");let _="";_=c<2&&l>0?"coords":e.unpackedShape.map((t,e)=>`coords.${y[e+m]}`).join(", ");const w=`\n float ${t}() {\n ${f} coords = getOutputCoords();\n ${b}\n return ${p}(${_});\n }\n `;return new i.GlslLibRoutine(w,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(t,e,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(t,e);case 1:return this.getPackedSampler1D(t,e,n);case 2:return this.getPackedSampler2D(t,e,n);case 3:return this.getPackedSampler3D(t,e,n);default:return this.getPackedSamplerND(t,e,n)}}getUnpackedSamplerFromInput(t,e,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(t,e,n);case 1:return this.getUnpackedSampler1D(t,e,n);case 2:return this.getUnpackedSampler2D(t,e,n);case 3:return this.getUnpackedSampler3D(t,e,n);case 4:return this.getUnpackedSampler4D(t,e,n);case 5:return this.getUnpackedSampler5D(t,e,n);case 6:return this.getUnpackedSampler6D(t,e,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(t,e){const n=`\n vec4 ${t}() {\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, halfCR);\n }\n `;return new i.GlslLibRoutine(n)}getPackedSampler1D(t,e,n){const r=[n.width,n.height],s=[r[1],r[0]],a=(0,o.getGlsl)(this.context.glContext.version),u=`vec4 ${t}(int index) {\n vec2 uv = packedUVfrom1D(\n ${s[0]}, ${s[1]}, index);\n return ${a.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(u,["coordinates.packedUVfrom1D"])}getPackedSampler2D(t,e,n){const s=n.unpackedShape,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=a[0],c=a[1];if(null!=a&&r.ArrayUtil.arraysEqual(s,a)){const n=`vec4 ${t}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${l}.0);\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(n)}const d=a,h=Math.ceil(s[1]/2),p=`vec4 ${t}(int row, int col) {\n vec2 uv = packedUVfrom2D(${d[1]}, ${d[0]}, ${h}, row, col);\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(p,["coordinates.packedUVfrom2D"])}getPackedSampler3D(t,e,n){const r=n.unpackedShape,s=[n.width,n.height],u=[s[0],s[1]],l=(0,o.getGlsl)(this.context.glContext.version);if(1===r[0]){const o=r.slice(1),s=[1,2],u=(0,a.squeezeInputShape)(r,o),l=["b","row","col"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=u;const d=this.getPackedSamplerFromInput(t,e,c),h=`${d.routineBody}\n vec4 ${t}(int b, int row, int col) {\n return ${t}(${(0,a.getSqueezedParams)(l,s)});\n } `;return new i.GlslLibRoutine(h,d.dependencies)}const c=u[0],d=u[1],h=Math.ceil(r[2]/2),p=`vec4 ${t}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${d}, ${c}, ${h*Math.ceil(r[1]/2)}, ${h}, b, row, col);\n return ${l.texture2D}(${e}, uv);}`;return new i.GlslLibRoutine(p,["coordinates.packedUVfrom3D"])}getPackedSamplerND(t,e,n){const r=n.unpackedShape,s=r.length,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=[a[0],a[1]],c=l[1],d=l[0],h=Math.ceil(r[s-1]/2);let p=h*Math.ceil(r[s-2]/2),f="int b, int row, int col",g=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let t=2;t<s-1;t++)f=`int b${t}, `+f,p*=r[s-t-1],g=`b${t} * ${p} + `+g;const m=`vec4 ${t}(${f}) {\n int index = ${g};\n int texR = index / ${d};\n int texC = index - texR * ${d};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${c});\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(m)}getUnpackedSamplerScalar(t,e,n){const[r,o]=[n.width,n.height];if(1===r&&1===o){const n=`\n float ${t}() {\n return sampleTexture(${e}, halfCR);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${t}() {\n int offset_${e} = coordsToOffset(TexCoords, ${r}, ${o});\n vec2 uv = uvFromFlat(${r}, ${o}, offset_${e});\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler1D(t,e,n){const r=n.width,o=n.height;if(1===o&&1===r){const n=`\n float ${t}(int index) {\n return sampleTexture(${e}, halfCR);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===o){const n=`\n float ${t}(int index) {\n vec2 uv = vec2((float(index) + 0.5) / ${r}.0, 0.5);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}if(1===r){const n=`\n float ${t}(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o}.0);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const s=`\n float ${t}(int index) {\n vec2 uv = uvFromFlat(${r}, ${o}, index);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(s,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(t,e,n){const o=n.unpackedShape,u=[n.height,n.width];if(null!=u&&r.ArrayUtil.arraysEqual(o,u)){const n=`\n float ${t}(int row, int col) {\n vec2 uv = (vec2(row, col) + halfCR) / vec2(${u[1]}.0, ${u[0]}.0);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture"])}const{newShape:l,keptDims:c}=(0,s.squeezeShape)(o),d=l;if(d.length<o.length){const r=(0,a.squeezeInputShape)(o,d),s=JSON.parse(JSON.stringify(n));s.unpackedShape=r;const u=["col","row"],l=`\n ${this.getUnpackedSamplerFromInput(t,e,s).routineBody}\n float ${t}(int row, int col) {\n return ${t}(${(0,a.getSqueezedParams)(u,c)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture"])}const h=u[1],p=u[0];if(1===p){const n=`\n float ${t}(int row, int col) {\n int offset_${e} = coordsToOffset(TexCoords, ${h}, ${p});\n float index = dot(vec3(row, col, offset_${e}), vec3(${o[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}if(1===h){const n=`\n float ${t}(int row, int col) {\n int offset_${e} = coordsToOffset(TexCoords, ${h}, ${p});\n float index = dot(vec3(row, col, offset_${e}), vec3(${o[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${p}.0, 0.5);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(n,["coordinates.sampleTexture","coordinates.coordsToOffset"])}const f=`\n float ${t}(int row, int col) {\n int index = col * ${o[1]} + row;\n vec2 uv = uvFromFlat(${h}, ${p}, index);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(t,e,n){const r=n.unpackedShape,o=r[1]*r[2],u=r[2],{newShape:l,keptDims:c}=(0,s.squeezeShape)(r),d=l;if(d.length<r.length){const o=(0,a.squeezeInputShape)(r,d),s=["batch","col","row"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=this.getUnpackedSamplerFromInput(t,e,u),h=c.reverse(),p=`\n ${l.routineBody}\n float ${t}(int batch, int row, int col) {\n return ${t}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new i.GlslLibRoutine(p,l.dependencies)}const h=`\n float ${t}(int depth, int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = depth * ${o} + col * ${u} + row;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(h,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler4D(t,e,n){const r=n.unpackedShape,o=r[3],s=r[2]*o,a=`\n float ${t}(int row, int col, int depth, int depth2) {\n int index = row * ${r[1]*s} + col * ${s} +\n depth2 * ${o} + depth;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(a,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(t,e,n){const r=n.unpackedShape,o=r[4],u=r[3]*o,l=r[2]*u,c=r[1]*l,{newShape:d,keptDims:h}=(0,s.squeezeShape)(r);if(d.length<r.length){const o=(0,a.squeezeInputShape)(r,d),s=["row","col","depth","depth2","depth3"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=`\n ${this.getUnpackedSamplerFromInput(t,e,u).routineBody}\n float ${t}(int row, int col, int depth, int depth2, int depth3) {\n return ${t}(${(0,a.getSqueezedParams)(s,h)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const p=`\n float ${t}(int row, int col, int depth, int depth2, int depth3) {\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth3 * ${o} + depth2;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(p,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(t,e,n){const r=n.unpackedShape,o=r[5],u=r[4]*o,l=r[3]*u,c=r[2]*l,d=r[1]*c,{newShape:h,keptDims:p}=(0,s.squeezeShape)(r);if(h.length<r.length){const o=(0,a.squeezeInputShape)(r,h),s=["row","col","depth","depth2","depth3","depth4"],u=JSON.parse(JSON.stringify(n));u.unpackedShape=o;const l=`\n ${this.getUnpackedSamplerFromInput(t,e,u).routineBody}\n float ${t}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${t}(${(0,a.getSqueezedParams)(s,p)});\n }\n `;return new i.GlslLibRoutine(l,["coordinates.sampleTexture","coordinates.uvFromFlat"])}const f=`\n float ${t}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = row * ${d} + col * ${c} + depth * ${l} +\n depth2 * ${u} + depth3 * ${o} + depth4;\n vec2 uv = uvFromFlat(${n.width}, ${n.height}, index);\n return sampleTexture(${e}, uv);\n }\n `;return new i.GlslLibRoutine(f,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}toVec(){const t=this.context.outputTextureLayout,e=t.shape.length,n=t.strides,r=t.width,o=t.height,s=[];for(let t=0;t<e-1;++t)s.push(`\n c[${t}] = offset / ${n[t]};`),s.push(`\n offset -= c[${t}] * ${n[t]};`);s.push(`\n c[${e-1}] = offset;`);const a=`\n void toVec(vec2 texCoords, out int c[${e}]) {\n int offset = coordsToOffset(texCoords, ${r}, ${o});\n ${s.join("")}\n }\n void toVec(int offset, out int c[${e}]) {\n ${s.join("")}\n }\n `;return{toVec:new i.GlslLibRoutine(a,["coordinates.coordsToOffset"])}}valueFrom(){const t={};return this.context.programInfo.inputNames.forEach((e,n)=>{const r=this.context.inputTextureLayouts[n],o=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let s=`_${e}`;t[s]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!1),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),s+="_T",t[s]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!0),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),t}getValueFromSingle(t,e,n,r,i){let s=`_${t}`;return i&&(s+="_T"),`\n float ${s}(int m[${e}]) {\n int offset = indicesToOffset${s}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n float value = getColorAsFloat(${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords));\n return value;\n }\n `}getPackedValueFrom(t,e,n,r,i){let s=`_${t}_Pack`;return i&&(s+="_T"),`\n vec4 ${s}(int m[${e}]) {\n int offset = indicesToOffset_${t}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords);\n }\n `}}e.CoordsGlslLib=u},8520:(t,e)=>{var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TopologicalSortGlslRoutines=e.GlslLibRoutineNode=e.GlslLibRoutine=e.GlslLib=e.GlslContext=e.FunctionType=void 0,(n=e.FunctionType||(e.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",e.GlslContext=class{constructor(t,e,n,r){this.glContext=t,this.programInfo=e,this.inputTextureLayouts=n,this.outputTextureLayout=r}},e.GlslLib=class{constructor(t){this.context=t}},e.GlslLibRoutine=class{constructor(t,e){this.routineBody=t,this.dependencies=e}},e.GlslLibRoutineNode=class{constructor(t,e,n){this.name=t,this.dependencies=n||[],e&&(this.routineBody=e)}addDependency(t){t&&this.dependencies.push(t)}},e.TopologicalSortGlslRoutines=class{static returnOrderedNodes(t){if(!t||0===t.length)return[];if(1===t.length)return t;const e=new Set,n=new Set,r=new Array;return this.createOrderedNodes(t,e,n,r),r}static createOrderedNodes(t,e,n,r){for(let i=0;i<t.length;++i)this.dfsTraverse(t[i],e,n,r)}static dfsTraverse(t,e,n,r){if(!t||n.has(t.name))return;if(e.has(t.name))throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");e.add(t.name);const i=t.dependencies;if(i&&i.length>0)for(let t=0;t<i.length;++t)this.dfsTraverse(i[t],e,n,r);r.push(t),n.add(t.name),e.delete(t.name)}}},7341:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.EncodingGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ")}}encodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n highp vec4 encode(highp float f) {\n highp float F = abs(f);\n highp float Sign = step(0.0,-f);\n highp float Exponent = floor(log2(F));\n highp float Mantissa = (exp2(- Exponent) * F);\n Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n highp vec4 rgba;\n rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));\n rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n ${t}\n rgba = rgba / 255.0; // values need to be normalized to [0,1]\n return rgba;\n }\n `)}}decodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n highp float decode(highp vec4 rgba) {\n rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n ${t}\n highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n return Result;\n }\n `)}}static isLittleEndian(){const t=new ArrayBuffer(4),e=new Uint32Array(t),n=new Uint8Array(t);if(e[0]=3735928559,239===n[0])return!0;if(222===n[0])return!1;throw new Error("unknown endianness")}}e.EncodingGlslLib=i},9894:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FragColorGlslLib=void 0;const r=n(8520),i=n(5060);class o extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const t=(0,i.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n void setFragColor(float value) {\n ${t.output} = encode(value);\n }\n `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ",["encoding.decode"])}}}e.FragColorGlslLib=o},2848:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;e.replaceInlines=function(t){const e={};let r;for(;null!==(r=n.exec(t));){const t=r[3].split(",").map(t=>{const e=t.trim().split(" ");return e&&2===e.length?{type:e[0],name:e[1]}:null}).filter(t=>null!==t);e[r[2]]={params:t,body:r[4]}}for(const n in e){const i="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),o=new RegExp(i,"gm");for(;null!==(r=o.exec(t));){const i=r[1],o=r[2],s=r[3].split(","),a=i?`${i} ${o};`:"";let u=e[n].body,l="";e[n].params.forEach((t,e)=>{t&&(l+=`${t.type} ${t.name} = ${s[e]};\n`)}),u=`${l}\n ${u}`,u=u.replace("return",`${o} = `);const c=`\n ${a}\n {\n ${u}\n }\n `;t=t.replace(r[0],c)}}return t.replace(n,"")}},8879:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.GlslPreprocessor=void 0;const r=n(8520),i=n(2848),o=n(5483),s=n(5060);e.GlslPreprocessor=class{constructor(t,e,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(t,e,n,i),Object.keys(o.glslRegistry).forEach(t=>{const e=new o.glslRegistry[t](this.context);this.libs[t]=e});const s=this.glslLibRoutineDependencyGraph;for(const t in this.libs){const e=this.libs[t].getFunctions();for(const n in e){const i=t+"."+n;let o;s[i]?(o=s[i],o.routineBody=e[n].routineBody):(o=new r.GlslLibRoutineNode(i,e[n].routineBody),s[i]=o);const a=e[n].dependencies;if(a)for(let t=0;t<a.length;++t)if(s[a[t]])o.addDependency(s[a[t]]);else{const e=new r.GlslLibRoutineNode(a[t]);s[a[t]]=e,o.addDependency(e)}}}}preprocess(){const t=this.context.programInfo;let e=t.shaderSource;return this.context.programInfo.hasMain||(e=`${e}\n ${(0,s.getDefaultFragShaderMain)(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),e=(0,i.replaceInlines)(e),`${(0,s.getFragShaderPreamble)(this.context.glContext.version)}\n ${this.getUniforms(t.inputNames,t.variables)}\n ${this.getImports(e)}\n ${e}`}getImports(t){const e=this.selectGlslLibRoutinesToBeIncluded(t);if(0===e.length)return"";let n="";for(let t=0;t<e.length;++t){if(!e[t].routineBody)throw new Error(`Missing body for the Glsl Library routine: ${e[t].name}`);n+=e[t].routineBody+"\n"}return n}selectGlslLibRoutinesToBeIncluded(t){const e=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach(n=>{const r=n.split(".")[1];-1!==t.indexOf(r)&&e.push(this.glslLibRoutineDependencyGraph[n])}),r.TopologicalSortGlslRoutines.returnOrderedNodes(e)}getUniforms(t,e){const n=[];if(t)for(const e of t)n.push(`uniform sampler2D ${e};`);if(e)for(const t of e)n.push(`uniform ${t.type} ${t.name}${t.arrayLength?`[${t.arrayLength}]`:""};`);return n.join("\n")}}},5483:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.glslRegistry=void 0;const r=n(5107),i=n(7341),o=n(9894),s=n(2655),a=n(3891);e.glslRegistry={encoding:i.EncodingGlslLib,fragcolor:o.FragColorGlslLib,vec:a.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},2655:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ShapeUtilsGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const t=this.context.outputTextureLayout.shape.length,e={};return this.context.programInfo.inputNames.forEach((n,i)=>{const o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=t){const i=o.length,s=t-i,a=`bcastIndices_${n}`;let u="";for(let t=0;t<i;++t)u+=`\n realIndices[${t}] = int( mod(float(bcastedIndices[${s+t}]), ${o[t]}.0) );\n `;const l=`\n void ${a} (int bcastedIndices[${t}], out int realIndices[${i}]) {\n ${u}\n }\n `;e[a]=new r.GlslLibRoutine(l)}}),e}bcastMatmulIndex(){const t=this.context.outputTextureLayout.shape.length,e={};return this.context.programInfo.inputNames.forEach((n,i)=>{const o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>t)){const i=o.length,s=t-i,a=`bcastMatmulIndices_${n}`;let u="";for(let t=0;t<i-2;++t)u+=`\n realIndices[${t}] = int( mod(float(bcastedIndices[${s+t}]), ${o[t]}.0) );\n `;const l=`\n void ${a}(int bcastedIndices[${t}], out int realIndices[${i}]) {\n ${u}\n realIndices[${i-1}] = bcastedIndices[${t-1}];\n realIndices[${i-2}] = bcastedIndices[${t-2}];\n }\n `;e[a]=new r.GlslLibRoutine(l)}}),e}indicesToOffset(){const t={};return this.context.programInfo.inputNames.forEach((e,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`indicesToOffset_${e}`;t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s)),u=`indicesToOffset_${e}_T`,t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s.slice().reverse()))}),t}static indexToOffsetSingle(t,e,n){let r="";for(let t=e-1;t>=0;--t)r+=`\n offset += indices[${t}] * ${n[t]};\n `;return`\n int ${t}(int indices[${e}]) {\n int offset = 0;\n ${r}\n return offset;\n }\n `}offsetToIndices(){const t={};return this.context.programInfo.inputNames.forEach((e,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`offsetToIndices_${e}`;t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s)),u=`offsetToIndices_${e}_T`,t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s.slice().reverse()))}),t}static offsetToIndicesSingle(t,e,n){const r=[];for(let t=0;t<e-1;++t)r.push(`\n indices[${t}] = offset / ${n[t]};`),r.push(`\n offset -= indices[${t}] * ${n[t]};`);return r.push(`\n indices[${e-1}] = offset;`),`\n void ${t}(int offset, out int indices[${e}]) {\n ${r.join("")}\n }\n `}incrementIndices(){const t={};return this.context.programInfo.inputNames.forEach((e,n)=>{const i=this.context.inputTextureLayouts[n].shape,o=i.length,s=`incrementIndices_${e}`;let a="";for(let t=0;t<o;++t)a+=`\n shape[${t}] = ${i[t]};`;const u=`\n void ${s}(int axis, out int indices[${o}]) {\n int shape[${o}];\n ${a};\n for(int i = ${o} -1 ; i >= 0; --i) {\n if(i > axis) continue;\n indices[i] += 1;\n if(indices[i] < shape[i]) {\n break;\n }\n indices[i] = 0;\n }\n }\n `;t[s]=new r.GlslLibRoutine(u)}),t}}e.ShapeUtilsGlslLib=i},5060:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultFragShaderMain=e.getFragShaderPreamble=e.getVertexShaderSource=e.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function i(t){return 1===t?n:r}e.getGlsl=i,e.getVertexShaderSource=function(t){const e=i(t);return`${e.version}\n precision highp float;\n ${e.attribute} vec3 position;\n ${e.attribute} vec2 textureCoord;\n\n ${e.varyingVertex} vec2 TexCoords;\n\n void main()\n {\n gl_Position = vec4(position, 1.0);\n TexCoords = textureCoord;\n }`},e.getFragShaderPreamble=function(t){const e=i(t);return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFrag} vec2 TexCoords;\n ${e.outputDeclaration}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n // Custom vector types to handle higher dimenalities.\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n `},e.getDefaultFragShaderMain=function(t,e){return`\n void main() {\n int indices[${e}];\n toVec(TexCoords, indices);\n vec4 result = vec4(process(indices));\n ${i(t).output} = result;\n }\n `}},3891:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.VecGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const t=this.context.outputTextureLayout.shape.length,e={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const i in e){const o=`${i}Vec`;let s="";for(let n=0;n<t;++n)s+=`\n dest[${n}] ${e[i]} src[${n}];\n `;const a=`\n void ${o}(int src[${t}], out int dest[${t}]) {\n ${s}\n }\n `;n[o]=new r.GlslLibRoutine(a)}return n}copyVec(){const t=this.context.outputTextureLayout.shape.length;let e="";for(let n=0;n<t;++n)e+=`\n dest[${n}] = src[${n}];\n `;const n=`\n void copyVec(int src[${t}], out int dest[${t}]) {\n ${e}\n }\n `;return{copyVec:new r.GlslLibRoutine(n)}}setVecItem(){const t=this.context.outputTextureLayout.shape.length;let e=`\n if(index < 0)\n index =${t} + index;\n if (index == 0)\n m[0] = value;\n `;for(let n=1;n<t-1;++n)e+=`\n else if (index == ${n})\n m[${n}] = value;\n `;e+=`\n else\n m[${t-1}] = value;\n `;const n=`\n void setVecItem(out int m[${t}], int index, int value) {\n ${e}\n }\n `;return{setVecItem:new r.GlslLibRoutine(n)}}getVecItem(){const t=this.context.outputTextureLayout.shape.length;let e=`\n if(index < 0)\n index = ${t} + index;\n if (index == 0)\n return m[0];\n `;for(let n=1;n<t-1;++n)e+=`\n else if (index == ${n})\n return m[${n}];\n `;e+=`\n else\n return m[${t-1}];\n `;const n=`\n int getVecItem(int m[${t}], int index) {\n ${e}\n }\n `;return{getVecItem:new r.GlslLibRoutine(n)}}}e.VecGlslLib=i},8316:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLInferenceHandler=void 0;const r=n(6231),i=n(9162),o=n(2517),s=n(2403),a=n(7019),u=n(8710),l=n(5611),c=n(4057),d=n(2039);e.WebGLInferenceHandler=class{constructor(t){this.session=t,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(t,e){return(0,c.calculateTextureWidthAndHeight)(this.session.layoutStrategy,t,e)}executeProgram(t,e){if(e.length<t.inputNames.length)throw new Error(`Input size mustn't be less than ${t.inputNames.length}.`);if(t.inputNames.length!==t.inputTypes.length)throw new Error("input names size does not match input types");const n=[];for(let r=0;r<t.inputNames.length;++r)n[r]=this.getOrCreateTextureData(e[r],t.inputTypes[r]);const r=((t,e)=>{const n=e.map(t=>`${t.unpackedShape.join(",")};${t.width}x${t.height}`).join("_");let r=t.name;return t.cacheHint&&(r+="["+t.cacheHint+"]"),r+=":"+n,r})(t,n);let i=this.session.programManager.getArtifact(r);const o=i?i.programInfo:"function"==typeof t.get?t.get():t,s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o.output.dims,o.output.textureType),a=this.createTextureData(s,o.output.type);return i||(i=this.session.programManager.build(o,n,a),this.session.programManager.setArtifact(r,i)),this.runProgram(i,n,a),a}run(t,e){return this.executeProgram(t,e).tensor}runProgram(t,e,n){for(let n=0;n<e.length;++n)if(!!e[n].isPacked!=(t.programInfo.inputTypes[n]===d.TextureType.packed))throw new Error(`input[${n}] property packed inconsistent`);if(!!n.isPacked!=(t.programInfo.output.textureType===d.TextureType.packed))throw new Error("output property packed inconsistent");this.session.programManager.run(t,e,n)}getOrCreateTextureData(t,e){let n=this.getTextureData(t.dataId,e===d.TextureType.packed);if(!n&&(n=this.getTextureData(t.dataId,e!==d.TextureType.packed),n))return e===d.TextureType.packed?this.pack(n):this.unpack(n);if(!n){const r=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,t.dims,e);if(e===d.TextureType.packedLastDimension){const n=1,r=4,i=t.dims;if(4===i.length){const o=[i[0],Math.ceil(i[1]*i[2]*i[3]/r)],s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o,e);let a=t.numberData;if(i[1]*i[2]*i[3]%r!=0){const e=i[0],o=i[1]*i[2]*i[3],s=Math.ceil(o*n/r)*r;a=new Float32Array(e*s);for(let r=0;r<e;++r){const e=r*o,i=r*s+r%n*o;a.set(t.numberData.subarray(e,e+o),i)}}return this.createTextureData(s,t.type,a,t,1)}}if(e===d.TextureType.packed){const e=(0,c.createTextureLayoutFromShape)(this.session.layoutStrategy,t.dims,1,[],{reverseWH:!0}),r=this.createTextureData(e,t.type,t.numberData,t,1);n=this.pack(r)}else n=this.createTextureData(r,t.type,t.numberData,t,1)}return n}createTextureDataFromLayoutBindTensor(t,e,n,r){return this.createTextureData(t,e,n,r,1)}createTextureData(t,e,n,i,o){r.Logger.verbose("InferenceHandler",`Creating TextureData: layout:[${JSON.stringify(t)}]`);const s=this.session.textureManager.createTextureFromLayout(e,t,n,o);return this.createTextureDataFromTexture(t,e,s,i)}reshapeUnpacked(t,e){const n=this.getOrCreateTextureData(t,d.TextureType.unpacked),r={channels:n.channels,height:n.height,width:n.width,shape:0!==e.length?e:[1],strides:o.ShapeUtil.computeStrides(e),unpackedShape:e};return this.createTextureDataFromTexture(r,t.type,n.texture).tensor}reshapePacked(t,e){const n=this.getOrCreateTextureData(t,d.TextureType.packed);if((0,a.isReshapeCheap)(t.dims,e)){const r={channels:n.channels,height:n.height,width:n.width,shape:0!==e.length?e:[1],strides:o.ShapeUtil.computeStrides(e),unpackedShape:e,isPacked:!0};return this.createTextureDataFromTexture(r,t.type,n.texture).tensor}const r=(0,a.processDims3D)(t.dims),i=(0,a.processDims3D)(e),s=this.reshapePacked(t,r),u=this.run((0,a.createPackedReshape3DProgramInfoLoader)(this,s,i),[s]);return this.reshapePacked(u,e)}cast(t,e){const n=this.getOrCreateTextureData(t,d.TextureType.unpacked);return this.createTextureDataFromTexture(n,e,n.texture).tensor}createTextureDataFromTexture(t,e,n,r,o){const s=Object.assign(Object.assign({},t),{tensor:r||new i.Tensor(t.unpackedShape,e,t=>this.readTexture(s),async t=>this.readTextureAsync(s),void 0,o),texture:n});return this.setTextureData(s.tensor.dataId,s,t.isPacked),s}getTextureData(t,e=!1){return this.session.isInitializer(t)?this.session.getTextureData(t,e):e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){this.session.isInitializer(t)?this.session.setTextureData(t,e,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(t,e)}isTextureLayoutCached(t,e=!1){return!!this.getTextureData(t.dataId,e)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(t=>this.session.textureManager.releaseTexture(t)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(t=>this.session.textureManager.releaseTexture(t)),this.unpackedTextureDataCache=new Map}readTexture(t){return t.isPacked?this.readTexture(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}async readTextureAsync(t){return t.isPacked?this.readTextureAsync(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}pack(t){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,t.tensor),[t.tensor])}unpack(t){return this.executeProgram((0,l.createUnpackProgramInfoLoader)(this,t.tensor),[t.tensor])}}},1640:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=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 i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WEBGL_OP_RESOLVE_RULES=void 0;const s=n(2898),a=o(n(7839)),u=n(4196),l=n(2069),c=n(8138),d=n(9663),h=n(5193),p=n(7992),f=n(1253),g=n(4776),m=n(6572),b=n(3346),y=n(5623),_=n(2870),w=n(2143),v=n(4939),x=n(718),T=n(2268),S=n(8117),A=n(2278),E=n(5524),O=n(5975),I=n(3933),P=n(6558),D=n(5723),C=n(3738),k=o(n(4909)),R=n(8428),M=n(9793);e.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",a.add],["And","","7+",a.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",w.averagePool,w.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",u.cast,u.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",l.concat,l.parseConcatAttributes],["Conv","","1+",c.conv,c.parseConvAttributes],["ConvTranspose","","1+",d.convTranspose,d.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",a.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",h.depthToSpace,h.parseDepthToSpaceAttributes],["Equal","","7+",a.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",p.flatten,p.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",c.conv,c.parseConvAttributes],["Gather","","1+",f.gather,f.parseGatherAttributes],["Gemm","","7-10",g.gemm,g.parseGemmAttributesV7],["Gemm","","11+",g.gemm,g.parseGemmAttributesV11],["GlobalAveragePool","","1+",w.globalAveragePool,w.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",w.globalMaxPool],["Greater","","7+",a.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",m.imageScaler,m.parseImageScalerAttributes],["InstanceNormalization","","6+",b.instanceNormalization,b.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",a.less],["Log","","6+",k.log],["MatMul","","1+",y.matMul,y.parseMatMulAttributes],["MaxPool","","1+",w.maxPool,w.parseMaxPoolAttributes],["Mul","","7+",a.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",a.or],["Pad","","2-10",_.padV2,_.parsePadAttributesV2],["Pad","","11+",_.padV11,_.parsePadAttributesV11],["Pow","","7+",a.pow],["PRelu","","7+",a.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+",x.reshape],["Resize","","10",T.resize,T.parseResizeAttributesV10],["Resize","","11+",T.resize,T.parseResizeAttributesV11],["Shape","","1+",S.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",A.sliceV10],["Slice","","1-9",A.slice,A.parseSliceAttributes],["Softmax","","1-12",E.softmax,E.parseSoftmaxAttributes],["Softmax","","13+",E.softmaxV13,E.parseSoftmaxAttributesV13],["Split","","2-12",O.split,O.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",I.squeeze,I.parseSqueezeAttributes],["Squeeze","","13+",I.squeezeV13],["Sub","","7+",a.sub],["Sum","","6+",P.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",D.tile],["Transpose","","1+",C.transpose,C.parseTransposeAttributes],["Upsample","","7-8",M.upsample,M.parseUpsampleAttributesV7],["Upsample","","9",M.upsample,M.parseUpsampleAttributesV9],["Unsqueeze","","1-12",R.unsqueeze,R.parseUnsqueezeAttributes],["Unsqueeze","","13+",R.unsqueezeV13],["Xor","","7+",a.xor]]},2898:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseBatchNormalizationAttributes=e.batchNormalization=void 0;const r=n(246),i=n(5060),o=n(2039),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};e.batchNormalization=(t,e,n)=>(u(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(t,e,n)}),e)]),e.parseBatchNormalizationAttributes=t=>{const e=t.attributes.getFloat("epsilon",1e-5),n=t.attributes.getFloat("momentum",.9),i=t.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:e,momentum:n,spatial:i})};const a=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),a=e[0].dims.length,[u,l]=t.calculateTextureWidthAndHeight(e[1].dims,o.TextureType.unpacked),c=`\n float process(int[${a}] indices) {\n vec2 position = offsetToCoords(indices[1], ${u}, ${l});\n float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n float b = getColorAsFloat(${r.texture2D}(B, position));\n\n return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n }`;return Object.assign(Object.assign({},s),{output:{dims:e[0].dims,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:c})},u=t=>{if(!t||5!==t.length)throw new Error("BatchNormalization requires 5 inputs.");const e=t[0],n=t[1],r=t[2],i=t[3],o=t[4];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==i.dims.length||1!==o.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1]||o.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==i.type&&"float64"!==i.type||"float32"!==o.type&&"float64"!==o.type)throw new Error("invalid input tensor types.")}},7839:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.xor=e.sub=e.pRelu=e.pow=e.or=e.mul=e.less=e.greater=e.equal=e.div=e.and=e.add=e.glslPRelu=e.glslPow=e.glslXor=e.glslOr=e.glslAnd=e.glslLess=e.glslGreater=e.glslEqual=e.glslSub=e.glslMul=e.glslDiv=e.glslAdd=void 0;const r=n(2517),i=n(8520),o=n(5060),s=n(2039);function a(){const t="add_";return{body:`\n float ${t}(float a, float b) {\n return a + b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 + v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function u(){const t="div_";return{body:`\n float ${t}(float a, float b) {\n return a / b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 / v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function l(){const t="mul_";return{body:`\n float ${t}(float a, float b) {\n return a * b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 * v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function c(){const t="sub_";return{body:`\n float ${t}(float a, float b) {\n return a - b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 - v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function d(){const t="equal_";return{body:`\n float ${t}(float a, float b) {\n return float(a == b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4(equal(v1, v2));\n }\n `,name:t,type:i.FunctionType.ValueBased}}function h(){const t="greater_";return{body:`\n float ${t}(float a, float b) {\n return float(a > b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4( v1.r > v2.r ,\n v1.g > v2.g,\n v1.b > v2.b,\n v1.a > v2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function p(){const t="less_";return{body:`\n float ${t}(float a, float b) {\n return float(a < b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4( v1.r < v2.r ,\n v1.g < v2.g,\n v1.b < v2.b,\n v1.a < v2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function f(){const t="and_";return{body:`\n float ${t}(float a, float b) {\n return float( bool(a) && bool(b) );\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r && b2.r ,\n b1.g && b2.g,\n b1.b && b2.b,\n b1.a && b2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function g(){const t="or_";return{body:`\n float ${t}(float a, float b) {\n return float( bool(a) || bool(b) );\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r || b2.r ,\n b1.g || b2.g,\n b1.b || b2.b,\n b1.a || b2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function m(){const t="xor_";return{body:`\n float ${t}(float a, float b) {\n return float( bool(a) ^^ bool(b) );\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r ^^ b2.r ,\n b1.g ^^ b2.g,\n b1.b ^^ b2.b,\n b1.a ^^ b2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function b(){return function(t){const e=`${t}_`;return{body:`\n float ${e}(float a, float b) {\n return ${t}(a, b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return ${t}(v1, v2);\n }\n `,name:e,type:i.FunctionType.ValueBased}}("pow")}function y(){const t="prelu_";return{body:`\n float ${t}(float a, float b) {\n return a < 0.0 ? a * b: a;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4(\n v1.r < 0.0 ? v1.r * v2.r: v1.r,\n v1.g < 0.0 ? v1.g * v2.g: v1.g,\n v1.b < 0.0 ? v1.b * v2.b: v1.b,\n v1.a < 0.0 ? v1.a * v2.a: v1.a\n );\n }\n `,name:t,type:i.FunctionType.ValueBased}}e.glslAdd=a,e.glslDiv=u,e.glslMul=l,e.glslSub=c,e.glslEqual=d,e.glslGreater=h,e.glslLess=p,e.glslAnd=f,e.glslOr=g,e.glslXor=m,e.glslPow=b,e.glslPRelu=y;const _=(t,e,n,r=e[0].type,i)=>{const o=t.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>w(t,e,n,r)}},w=(t,e,n,i=e[0].type)=>{const a=t.session.pack?s.TextureType.packed:s.TextureType.unpacked,u=!r.ShapeUtil.areEqual(e[0].dims,e[1].dims);let l=e[0].dims;const c=t.session.pack;if(u){const s=r.BroadcastUtil.calcShape(e[0].dims,e[1].dims,!1);if(!s)throw new Error("Can't perform binary op on the given tensors");l=s;const u=l.length,d=0!==e[0].dims.length?e[0].dims.length:1,h=0!==e[1].dims.length?e[1].dims.length:1,p=0!==e[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",f=0!==e[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",g=(0,o.getGlsl)(t.session.backend.glContext.version),m=c?`\n ${n.body}\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n vec4 result = ${n.name}(a, b);\n ${g.output} = result;\n }`:`\n ${n.body}\n float process(int indices[${u}]) {\n int aindices[${d}];\n int bindices[${h}];\n ${p}\n ${f}\n return ${n.name}(_A(aindices), _B(bindices));\n }`;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:l,type:i,textureType:a},shaderSource:m,hasMain:c}}const d=(0,o.getGlsl)(t.session.backend.glContext.version),h=`\n ${n.body}\n void main() {\n vec4 v1 = ${d.texture2D}(A, TexCoords);\n vec4 v2 = ${d.texture2D}(B, TexCoords);\n vec4 result = ${n.name}(v1, v2);\n ${d.output} = result;\n }\n `;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:e[0].dims,type:i,textureType:a},shaderSource:h,hasMain:!0}};e.add=(t,e)=>[t.run(_(t,e,a()),e)],e.and=(t,e)=>[t.run(_(t,e,f(),"bool"),e)],e.div=(t,e)=>[t.run(_(t,e,u()),e)],e.equal=(t,e)=>[t.run(_(t,e,d(),"bool"),e)],e.greater=(t,e)=>[t.run(_(t,e,h(),"bool"),e)],e.less=(t,e)=>[t.run(_(t,e,p(),"bool"),e)],e.mul=(t,e)=>[t.run(_(t,e,l()),e)],e.or=(t,e)=>[t.run(_(t,e,g(),"bool"),e)],e.pow=(t,e)=>[t.run(_(t,e,b()),e)],e.pRelu=(t,e)=>[t.run(_(t,e,y()),e)],e.sub=(t,e)=>[t.run(_(t,e,c()),e)],e.xor=(t,e)=>[t.run(_(t,e,m(),"bool"),e)]},4196:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseCastAttributes=e.cast=void 0;const r=n(2517);e.cast=(t,e,n)=>(i(e),[t.cast(e[0],n)]),e.parseCastAttributes=t=>r.ProtoUtil.tensorDataTypeFromProto(t.attributes.getInt("to"));const i=t=>{if(!t||1!==t.length)throw new Error("Cast requires 1 input.");if("string"===t[0].type)throw new Error("Invalid input type.")}},1163:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedConcatProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827);e.createPackedConcatProgramInfoLoader=(t,e,n)=>{const u=(l=e.length,c=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:l},(t,e)=>`X${e}`),inputTypes:Array(l).fill(i.TextureType.packed),cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const l=n[0].dims.slice();if(u>=l.length||u<-1*l.length)throw new Error("axis specified for concat doesn't match input dimensionality");u<0&&(u=l.length+u);const c=l.slice(0);for(let t=1;t<n.length;t++){const e=n[t].dims.slice();for(let t=0;t<l.length;t++)if(t===u)c[u]+=e[t];else if(l[t]!==e[t])throw new Error("non concat dimensions must match")}const d=c.length,h=(0,s.getChannels)("coords",d),p=(0,o.getCoordsDataType)(d),f=(0,s.unpackFromChannel)(),g=n.map(t=>t.dims),m=(0,o.getGlChannels)(d),b=new Array(g.length-1);b[0]=g[0][u];for(let t=1;t<b.length;t++)b[t]=b[t-1]+g[t][u];const y=m[u],_=m.slice(-2),w=m.join();let v=`if (${y} < ${b[0]}) {\n return getChannel(\n getX0(${w}), vec2(${_.join()}));\n }`;for(let t=1;t<b.length;t++){const e=b[t-1];v+=`\n if (${y} < ${b[t]} && ${y} >= ${b[t-1]}) {\n return getChannel(\n getX${t}(${a(m,y,e)}),\n vec2(${a(_,y,e)}));\n }`}const x=b.length,T=b[b.length-1];v+=`\n return getChannel(\n getX${x}(${a(m,y,T)}),\n vec2(${a(_,y,T)}));`;const S=(0,r.getGlsl)(t.session.backend.glContext.version),A=`\n ${f}\n float getValue(${m.map(t=>"int "+t)}) {\n ${v}\n }\n\n void main() {\n ${p} coords = getOutputCoords();\n int lastDim = coords.${m[d-1]};\n coords.${m[d-1]} = coords.${m[d-2]};\n coords.${m[d-2]} = lastDim;\n\n vec4 result = vec4(getValue(${h}), 0., 0., 0.);\n\n ${h[d-1]} = ${h[d-1]} + 1;\n if (${h[d-1]} < ${c[d-1]}) {\n result.g = getValue(${h});\n }\n\n ${h[d-2]} = ${h[d-2]} + 1;\n if (${h[d-2]} < ${c[d-2]}) {\n result.a = getValue(${h});\n }\n\n ${h[d-1]} = ${h[d-1]} - 1;\n if (${h[d-2]} < ${c[d-2]} &&\n ${h[d-1]} < ${c[d-1]}) {\n result.b = getValue(${h});\n }\n ${S.output} = result;\n }\n `;return Object.assign(Object.assign({},e),{output:{dims:c,type:n[0].type,textureType:i.TextureType.packed},shaderSource:A,hasMain:!0})})(t,u,e,n.axis)})};const a=(t,e,n)=>{const r=t.indexOf(e);return t.map((t,e)=>e===r?`${t} - ${n}`:t).join()}},2069:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseConcatAttributes=e.concat=void 0;const r=n(246),i=n(2039),o=n(1163);e.concat=(t,e,n)=>(d(e),t.session.pack&&e[0].dims.length>1?[t.run((0,o.createPackedConcatProgramInfoLoader)(t,e,n),e)]:[t.run(s(t,e,n),e)]);const s=(t,e,n)=>{const r=(o=e.length,s=n.cacheKey,{name:"Concat",inputNames:Array.from({length:o},(t,e)=>`X${e}`),inputTypes:Array(o).fill(i.TextureType.unpacked),cacheHint:s});var o,s;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice();if(r>=o.length||r<-1*o.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=o.length+r);const s=o.slice(0);for(let t=1;t<n.length;t++){const e=n[t].dims.slice();for(let t=0;t<o.length;t++)if(t===r)s[r]+=e[t];else if(o[t]!==e[t])throw new Error("non concat dimensions must match")}const d=s.length,h=new Array(n.length);let p=0;for(let t=0;t<h.length;++t)p+=n[t].dims[r],h[t]=p;let f="";f=n.length<5?a(h):u(h);const g=`\n ${l(n.length,d)}\n ${c(h)}\n ${f}\n float process(int indices[${d}]) {\n int textureIndex = getTextureWhereDataResides (indices[${r}]);\n\n if(textureIndex != 0) {\n indices[${r}] = indices[${r}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));\n }\n\n return fetchDataFromCorrectTexture(textureIndex, indices);\n }`;return Object.assign(Object.assign({},e),{output:{dims:s,type:n[0].type,textureType:i.TextureType.unpacked},shaderSource:g})})(0,r,e,n.axis)})},a=t=>`int getTextureWhereDataResides(int index) {\n ${t.map((t,e)=>`if(index<${t}) {return ${e};}\n`).join("")}\n }`,u=t=>a(t),l=(t,e)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let e=0;e<t;++e)0===e?n.push(`\tif (textureIndex == ${e}) { return _X${e}(indices); }`):e===t-1?n.push(`\telse { return _X${e}(indices); }`):n.push(`\telse if (textureIndex == ${e}) { return _X${e}(indices); }`);return n.push("\t}"),n.join("\n")},c=t=>{const e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n<t.length;++n)0===n?e.push(`\tif (index == ${n}) { return ${t[n]}; }`):n===t.length-1?e.push(`\telse { return ${t[n]}; }`):e.push(`\telse if (index == ${n}) { return ${t[n]}; }`);return e.push("\t}"),e.join("\n")};e.parseConcatAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis")});const d=t=>{if(!t||t.length<1)throw new Error("too few inputs");const e=t[0].type,n=t[0].dims.length;if("string"===e)throw new Error("string tensor is not supported yet");for(const r of t){if(r.type!==e)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},4770:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(6231),i=n(5060),o=n(2039),s=n(8138),a=n(2823);e.createUnpackedGroupedConvProgramInfoLoader=(t,e,n)=>{const u=(l=e.length>2,c=n.cacheKey,{name:"GroupedConv",inputNames:l?["X","W","Bias"]:["X","W"],inputTypes:l?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const l=e.length>2?"value += getBias(output_channel);":"",c=e[0].dims.slice(),d=e[1].dims.slice(),h=d[0]/u.group;r.Logger.verbose("GroupedConv",`autpPad:${u.autoPad}, dilations:${u.dilations}, group:${u.group}, kernelShape:${u.kernelShape}, pads:${u.pads}, strides:${u.strides}`);const p=(0,s.calculateOutputShape)(c,d,u.dilations,u.pads,u.strides),f=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:g,applyActivation:m}=(0,a.getActivationSnippet)(u),b=`\n const ivec2 strides = ivec2(${u.strides[0]}, ${u.strides[1]});\n const ivec2 pads = ivec2(${u.pads[0]}, ${u.pads[1]});\n ${g}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n ivec2 xRCCorner = coords.zw * strides - pads;\n int group_id = output_channel / ${h};\n\n float value = 0.0;\n for (int wInChannel = 0; wInChannel < ${d[1]}; wInChannel++) {\n int input_channel = group_id * ${d[1]} + wInChannel;\n for (int wHeight = 0; wHeight < ${d[2]}; wHeight++) {\n int xHeight = xRCCorner.x + wHeight * ${u.dilations[0]};\n\n if (xHeight < 0 || xHeight >= ${c[2]}) {\n continue;\n }\n\n for (int wWidth = 0; wWidth < ${d[3]}; wWidth++) {\n int xWidth = xRCCorner.y + wWidth * ${u.dilations[1]};\n if (xWidth < 0 || xWidth >= ${c[3]}) {\n continue;\n }\n\n float xVal = getX(batch, input_channel, xWidth, xHeight);\n float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n value += xVal*wVal;\n }\n }\n }\n ${l}\n ${m}\n ${f.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:p,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:b,hasMain:!0})})(t,e,u,n)})}},1386:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.conv2DPacked=e.conv2DPackedPointwise=void 0;const r=n(8138),i=n(8555),o=n(708);e.conv2DPackedPointwise=(t,e,n)=>{const i=e[0].dims,s=e[1].dims,a=(0,r.calculateOutputShape)(i,s,n.dilations,n.pads,n.strides),u=t.reshapePacked(e[0],[i[1],i[2]*i[3]]),l=t.reshapePacked(e[1],[s[0],s[1]]),c=e.length>2?[l,u,e[2]]:[l,u],d=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,c,n),c);return t.reshapePacked(d,a)},e.conv2DPacked=(t,e,n)=>{const s=e[0].dims,a=e[1].dims,u=(0,r.calculateOutputShape)(s,a,n.dilations,n.pads,n.strides),l=t.run((0,i.createPackedIm2ColProgramInfoLoader)(t,e[0],e[1],u,n),[e[0]]),c=t.reshapePacked(e[1],[a[0],a[1]*a[2]*a[3]]),d=3===e.length?[c,l,e[2]]:[c,l],h=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,d,n),d);return t.reshapePacked(h,u)}},9663:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvTransposeAttributes=e.convTranspose=void 0;const r=n(246),i=n(5060),o=n(2039),s=n(2823),a=(t,e,n,r,i,o)=>(t-1)*e+n+(r-1)*i+1-o,u=(t,e,n,r,i)=>{const o=Math.floor(t/2);"SAME_UPPER"===e?(n[r]=o,n[i]=t-o):"SAME_LOWER"===e&&(n[r]=t-o,n[i]=o)};e.convTranspose=(t,e,n)=>(h(e,n),l(t,e,n));const l=(t,e,n)=>{const r=d(n,e);return[c(t,e,r)]},c=(t,e,n)=>t.run(((t,e,n)=>{const r=(a=e.length>2,u=n.cacheKey,{name:"ConvTranspose",inputNames:a?["X","W","B"]:["X","W"],inputTypes:a?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:u});var a,u;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const a=e.length>2?"getB(output_channel)":"0.0",u=e[0].dims,l=e[1].dims,c=l[1],d=l[0]/r.group,h=[e[0].dims[0],e[1].dims[1]*r.group,...r.outputShape],p=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:f,applyActivation:g}=(0,s.getActivationSnippet)(r),m=`\n const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n ${f}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n\n ivec2 loc = coords.zw + pads;\n\n int group_id = output_channel / ${c};\n int wOutChannel = output_channel - group_id * ${c};\n\n float value = ${a};\n for (int inChannelOffset = 0; inChannelOffset < ${d}; inChannelOffset++) {\n int input_channel = group_id * ${d} + inChannelOffset;\n for (int wWOff = 0; wWOff < ${l[2]}; wWOff++) {\n for (int wHOff = 0; wHOff < ${l[3]}; wHOff++) {\n ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n ivec2 wLoc = loc - wOff;\n ivec2 wLocIn = wLoc / strides;\n if (\n wLocIn * strides == wLoc &&\n wLocIn.x >= 0 && wLocIn.x < ${u[2]} &&\n wLocIn.y >= 0 && wLocIn.y < ${u[3]}\n ) {\n float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n value += xVal * wVal;\n }\n }\n }\n }\n ${g}\n ${p.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:h,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:m,hasMain:!0})})(t,e,r,n)})})(t,e,n),e),d=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t<e[1].dims.length;++t)n.push(e[1].dims[t]);const r=t.pads.slice(),i=t.outputShape.slice();((t,e,n,r,i,o,s,l)=>{const c=t.length-2,d=0===l.length;for(let h=0;h<c;++h){const p=d?t[h+2]*o[h]:l[h],f=a(t[h+2],o[h],i[h],e[h],n[h],p);u(f,r,i,h,h+c),d&&l.push(o[h]*(t[h+2]-1)+s[h]+(e[h]-1)*n[h]+1-i[h]-i[h+c])}})(e[0].dims,n,t.dilations,t.autoPad,r,t.strides,t.outputPadding,i);const o=Object.assign({},t);return Object.assign(o,{kernelShape:n,pads:r,outputShape:i,cacheKey:t.cacheKey}),o};e.parseConvTransposeAttributes=t=>{const e=t.attributes,n=(0,s.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),a=e.getInt("group",1),u=e.getInts("kernel_shape",[]),l=e.getInts("output_padding",[0,0]),c=e.getInts("output_shape",[]),d=e.getInts("pads",[0,0,0,0]),h=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:a,kernelShape:u,outputPadding:l,outputShape:c,pads:d,strides:h},n))};const h=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=t[1].dims[1]*e.group;if(3===t.length&&(1!==t[2].dims.length||t[2].dims[0]!==n))throw new Error("invalid bias");const r=t[0].dims.length-2;if(e.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(e.strides.length!==r)throw new Error(`strides should be ${r}D`);if(e.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(e.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==e.outputShape.length&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvAttributes=e.conv=e.calculateOutputShape=void 0;const r=n(246),i=n(2517),o=n(4770),s=n(1386),a=n(9828),u=n(2823),l=n(3248),c=n(5623);e.calculateOutputShape=(t,e,n,r,i)=>{const o=t[0],s=t.slice(2),a=s.length,u=e[0],l=e.slice(2).map((t,e)=>t+(t-1)*(n[e]-1)),c=s.map((t,e)=>t+r[e]+r[e+a]).map((t,e)=>Math.floor((t-l[e]+i[e])/i[e]));return[o,u].concat(...c)},e.conv=(t,e,n)=>(g(e,n),d(t,e,n));const d=(t,e,n)=>{const r=f(n,e),i=t.session.pack,a=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[t.run((0,o.createUnpackedGroupedConvProgramInfoLoader)(t,e,r),e)]:a&&i?[h(t,e,r)]:i&&4===e[0].dims.length&&1===e[0].dims[0]&&!a?[(0,s.conv2DPacked)(t,e,r)]:[p(t,e,r)]},h=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),a=t.reshapeUnpacked(n[0],[i[1],i[2]*i[3]]),u=t.reshapeUnpacked(n[1],[o[0],o[1]]),l=n.length>2?[u,a,n[2]]:[u,a],d=t.run((0,c.createMatmulProgramInfoLoader)(l,r),l);return t.reshapeUnpacked(d,s)},p=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),u=t.run((0,l.createIm2ColProgramInfoLoader)(t,n[0],n[1],s,r),[n[0]]),c=3===n.length?[u,n[1],n[2]]:[u,n[1]];return t.run((0,a.createDotProductProgramInfoLoader)(t,n,s,r),c)},f=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t<e[1].dims.length;++t)n.push(e[1].dims[t]);const r=t.pads.slice();i.PoolConvUtil.adjustPadsBasedOnAutoPad(e[0].dims,t.strides,t.dilations,n,r,t.autoPad);const o=Object.assign({},t);return Object.assign(o,{kernelShape:n,pads:r,cacheKey:t.cacheKey}),o};e.parseConvAttributes=t=>{const e=t.attributes,n=(0,u.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),s=e.getInt("group",1),a=e.getInts("kernel_shape",[]),l=e.getInts("pads",[0,0,0,0]),c=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:s,kernelShape:a,pads:l,strides:c},n))};const g=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[1]*e.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===t.length&&(1!==t[2].dims.length||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");const n=t[0].dims.length-2;if(e.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(e.strides.length!==n)throw new Error(`strides should be ${n}D`);if(e.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("Conv input(bias) should be float tensor")}},5193:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseDepthToSpaceAttributes=e.depthToSpace=void 0;const r=n(3738);e.depthToSpace=(t,e,n)=>{i(e);const o=n.blocksize,s=o*o,a="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],u="DCR"===n.mode?[e[0].dims[0],o,o,e[0].dims[1]/s,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/s,o,o,e[0].dims[2],e[0].dims[3]],l=t.reshapeUnpacked(e[0],u),c={perm:a,cacheKey:`${a}`},[d]=(0,r.transpose)(t,[l],c),h=[e[0].dims[0],e[0].dims[1]/s,e[0].dims[2]*o,e[0].dims[3]*o];return[t.reshapeUnpacked(d,h)]},e.parseDepthToSpaceAttributes=t=>{const e=t.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);const n=t.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:e}};const i=t=>{if(1!==t.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`);if("string"===t[0].type||4!==t[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createDotProductProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),s=n(2823),a=n(3248);e.createDotProductProgramInfoLoader=(t,e,n,u)=>{const l=((t,e)=>({name:"ConvDotProduct",inputNames:t?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:t?[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.packedLastDimension],cacheKey:e.activationCacheKey}))(e.length>2,u);return Object.assign(Object.assign({},l),{get:()=>((t,e,n,u,l)=>{const c=n[0].dims,d=n[1].dims,h=[d[0],Math.ceil(c[1]*d[2]*d[3]/4)],p=(0,a.calculateIm2ColDims)(c,d,u),[f,g]=t.calculateTextureWidthAndHeight(h,o.TextureType.packedLastDimension),m=r.ShapeUtil.computeStrides(p),[b,y]=t.calculateTextureWidthAndHeight(p,o.TextureType.packedLastDimension),_=u.length,w=n.length<3?"0.0":"_B(b)",v=Math.ceil(c[1]*d[2]*d[3]/4),{activationFunction:x,applyActivation:T}=(0,s.getActivationSnippet)(l),S=(0,i.getGlsl)(t.session.backend.glContext.version),A=`\n${x}\nfloat process(int indices[${_}]) {\n int b[1];\n b[0] = indices[1];\n int im2col[4];\n im2col[0] = indices[0];\n im2col[1] = indices[2];\n im2col[2] = indices[3];\n int im2colOffset = im2col[0] * ${m[0]} + im2col[1] * ${m[1]} + im2col[2] * ${m[2]};\n int kernelOffset = indices[1] * ${h[1]};\n float value = ${w};\n for (int i = 0; i < ${v}; ++i) {\n vec2 im2colCoords = offsetToCoords(im2colOffset, ${b}, ${y});\n vec2 kernelCoords = offsetToCoords(kernelOffset, ${f}, ${g});\n value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords));\n ++im2colOffset;\n ++kernelOffset;\n }\n ${T}\n return value;\n}`;return Object.assign(Object.assign({},e),{output:{dims:u,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:A})})(t,l,e,n,u)})}},7992:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseFlattenAttributes=e.flatten=void 0;const r=n(2517);e.flatten=(t,e,n)=>{i(e,n);const o=r.ShapeUtil.flattenShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.parseFlattenAttributes=t=>t.attributes.getInt("axis",1);const i=(t,e)=>{if(!t||1!==t.length)throw new Error("Flatten requires 1 input.");const n=t[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(e<-n||e>n)throw new Error("Invalid axis");if("string"===t[0].type)throw new Error("string tensor is not supported.")}},2823:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseInternalActivationAttributes=e.getActivationSnippet=void 0;const r=n(2517),i=n(4909);e.getActivationSnippet=function(t){let e;switch(t.activation){case"Relu":e=(0,i.glslRelu)();break;case"Sigmoid":e=(0,i.glslSigmoid)();break;case"Clip":e=(0,i.glslClip)(t.clipMin,t.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=e.name;return{activationFunction:e.body,applyActivation:`value = ${n}_(value);`}},e.parseInternalActivationAttributes=t=>{const e=t.getString("activation","");if("Clip"===e){const[n,i]=t.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:e,clipMax:i,clipMin:n,activationCacheKey:`${e}:${n},${i}`}}return{activation:e,activationCacheKey:e}}},1253:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseGatherAttributes=e.gather=void 0;const r=n(246),i=n(782),o=n(2517),s=n(2039);e.gather=(t,e,n)=>(l(e,n.axis),[t.run(u(t,e,n),e)]),e.parseGatherAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",0)});const a={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},u=(t,e,n)=>{const r=Object.assign(Object.assign({},a),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const i=n[0].dims.slice(),a=n[1].dims.slice(),u=new Array(i.length+a.length-1);r=o.ShapeUtil.normalizeAxis(r,i.length);const l=[];for(let t=0;t<u.length;t++)t<r?(u[t]=i[t],l.push(`inputIdx[${t}] = outputIdx[${t}];`)):t<r+a.length?(u[t]=a[t-r],l.push(`indexDataIdx[${t-r}] = outputIdx[${t}];`)):(u[t]=i[t-a.length+1],l.push(`inputIdx[${t-a.length+1}] = outputIdx[${t}];`));const c=`\n float process(int outputIdx[${u.length||1}]) {\n int inputIdx[${i.length}];\n int indexDataIdx[${a.length||1}];\n indexDataIdx[0] = 0;\n ${l.join("\n ")}\n int idx = int(_B(indexDataIdx));\n inputIdx[${r}] = idx < 0 ? idx + ${i[r]} : idx;\n return _A(inputIdx);\n }`;return Object.assign(Object.assign({},e),{output:{dims:u,type:n[0].type,textureType:s.TextureType.unpacked},shaderSource:c})})(0,r,e,n.axis)})},l=(t,e)=>{if(!t||2!==t.length)throw new Error("Gather requires 2 inputs.");const n=t[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(e<-n||e>n-1)throw new Error("Invalid axis.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invaid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invaid input type.")}},4776:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseGemmAttributesV11=e.parseGemmAttributesV7=e.gemm=void 0;const r=n(246),i=n(2517),o=n(2039);e.gemm=(t,e,n)=>(l(e,n),[t.run(a(e,n),e)]);const s=(t,e)=>{const n=0!==t.attributes.getInt("transA",0),i=0!==t.attributes.getInt("transB",0),o=t.attributes.getFloat("alpha",1),s=t.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:i,alpha:o,beta:s,isOptionalC:e})};e.parseGemmAttributesV7=t=>s(t,!1),e.parseGemmAttributesV11=t=>s(t,!0);const a=(t,e)=>{const n={name:"Gemm",inputNames:3===t.length?["A","B","C"]:["A","B"],inputTypes:3===t.length?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],key:e.cacheKey};return Object.assign(Object.assign({},n),{get:()=>u(n,t,e)})},u=(t,e,n)=>{const r=e[0].dims.slice(),s=e[1].dims.slice(),[a,u]=i.GemmUtil.getShapeOfGemmResult(r,n.transA,s,n.transB,3===e.length?e[2].dims:void 0),l=[a,u];if(!l)throw new Error("Can't use gemm on the given tensors");let c=r[r.length-1],d="";n.transA&&(c=r[0]),n.transA&&n.transB?d="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?d="value += _A_T(a) * _B(b);":!n.transA&&n.transB?d="value += _A(a) * _B_T(b);":n.transA||n.transB||(d="value += _A(a) * _B(b);");const h=l.length,p=`\n float process(int indices[${h}]) {\n int a[${h}];\n int b[${h}];\n ${3===e.length?`int c[${e[2].dims.length}];`:""}\n\n copyVec(indices, a);\n copyVec(indices, b);\n ${3===e.length?"bcastIndices_C(indices, c);":""}\n\n float value = 0.0;\n for (int k=0; k<${c}; ++k) {\n a[${h-1}] = k;\n b[${h-2}] = k;\n ${d}\n }\n\n value = value * alpha;\n ${3===e.length?"value += beta * _C(c);":""}\n return value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:l,type:e[0].type,textureType:o.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:p})},l=(t,e)=>{if(!t)throw new Error("Input is missing");if(e.isOptionalC&&(t.length<2||t.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&3!==t.length)throw new Error("Gemm requires 3 inputs");if(3===t.length&&1!==t[2].dims.length&&2!==t[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type||3===t.length&&"float32"!==t[2].type&&"float64"!==t[2].type)throw new Error("Invalid input type.");if(t[0].type!==t[1].type||3===t.length&&t[0].type!==t[2].type)throw new Error("Input types are mismatched")}},8555:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedIm2ColProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(2827);e.createPackedIm2ColProgramInfoLoader=(t,e,n,s,a)=>{const u=(l=a.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[i.TextureType.packed],cacheHint:l});var l;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,s,a,u)=>{const l=n.dims,c=s.dims,d=a.length,h=[c[1]*c[2]*c[3],a[2]*a[3]],p=c[2]*c[3],f=(0,o.unpackFromChannel)(),g=(0,r.getGlsl)(t.session.backend.glContext.version);let m="";for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)m+=`\n blockIndex = rc.x + ${e};\n pos = rc.y + ${t};\n\n if(blockIndex < ${h[1]} && pos < ${h[0]}) {\n offsetY = int(blockIndex / (${a[d-1]})) * ${u.strides[0]} -\n ${u.pads[0]};\n d0 = offsetY + ${u.dilations[0]} * (imod(pos, ${p}) / ${c[2]});\n\n if(d0 < ${l[2]} && d0 >= 0) {\n offsetX = imod(blockIndex, ${a[d-1]}) * ${u.strides[1]} -\n ${u.pads[1]};\n d1 = offsetX + ${u.dilations[1]} * imod(imod(pos, ${p}), ${c[2]});\n\n if(d1 < ${l[3]} && d1 >= 0) {\n\n ch = int(float(pos)/ ${p}.);\n innerDims = vec2(d0, d1);\n result[${2*t+e}] = getChannel(\n getA(0, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n\n `;const b=`\n ${f}\n\n void main() {\n ivec2 rc = getOutputCoords();\n vec4 result = vec4(0.0);\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n ${m}\n ${g.output} = result;\n }\n `;return Object.assign(Object.assign({},e),{output:{dims:h,type:n.type,textureType:i.TextureType.packed},shaderSource:b,hasMain:!0})})(t,u,e,n,s,a)})}},3248:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.calculateIm2ColDims=e.createIm2ColProgramInfoLoader=void 0;const r=n(2039);e.createIm2ColProgramInfoLoader=(t,n,i,o,s)=>{const a=(u=s.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:u});var u;return Object.assign(Object.assign({},a),{get:()=>((t,n,i,o,s,a)=>{const u=i.dims,l=o.dims,c=s.length,d=(0,e.calculateIm2ColDims)(u,l,s,4),h=`\n const int XC = ${u[1]};\n const int XH = ${u[2]};\n const int XW = ${u[3]};\n const int KH = ${a.kernelShape[0]};\n const int KW = ${a.kernelShape[1]};\n const int dilationH = ${a.dilations[0]};\n const int dilationW = ${a.dilations[1]};\n const int strideH = ${a.strides[0]};\n const int strideW = ${a.strides[1]};\n const int padH = ${a.pads[0]};\n const int padW = ${a.pads[1]};\n const int KHKW = KH*KW;\n const int XCKHKW = XC * KHKW;\n const int outputChannels = 4;\n vec4 process(int indices[${c}]) {\n int b = indices[0]; // batch size\n int oh = indices[1] * strideH - padH; //output height\n int ow = indices[2] * strideW - padW; //output width\n int p = indices[3] * outputChannels; //patch\n vec4 value = vec4(0.0);\n for(int i=0; i < outputChannels; ++i) {\n if(p < XCKHKW) {\n int patchC = p / KHKW;\n int patchH = (p - patchC*KHKW) / KW;\n int patchW = (p - patchC*KHKW) - patchH * KW;\n int xh2 = oh + patchH * dilationH;\n int xw2 = ow + patchW * dilationW;\n int x[${u.length}];\n x[0] = b;\n x[1] = patchC;\n x[2] = xh2;\n x[3] = xw2;\n if(xh2 >= 0 &&\n xh2 < XH &&\n xw2 >= 0 &&\n xw2 < XW) {\n value[i] = _X(x);\n }\n }\n ++p;\n }\n return value;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:d,type:i.type,textureType:r.TextureType.packedLastDimension},shaderSource:h})})(0,a,n,i,o,s)})},e.calculateIm2ColDims=(t,e,n,r=4)=>[n[0],n[2],n[3],Math.ceil(t[1]*e[2]*e[3]/r)]},6572:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseImageScalerAttributes=e.imageScaler=void 0;const r=n(246),i=n(2039);e.imageScaler=(t,e,n)=>(u(e),[t.run(s(t,e,n),e)]),e.parseImageScalerAttributes=t=>{const e=t.attributes.getFloat("scale"),n=t.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:e,bias:n})};const o={name:"ImageScaler",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=(t,e,n)=>{const r=Object.assign(Object.assign({},o),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice(),s=o.length,u=`\n ${a(r.bias.length)}\n float process(int indices[${s}]) {\n return _X(indices) * scale + getBias(bias, indices[1]);\n }`;return Object.assign(Object.assign({},e),{output:{dims:o,type:n[0].type,textureType:i.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:u})})(0,r,e,n)})},a=t=>{const e=[`float getBias(float bias[${t}], int channel) {`];for(let n=0;n<t;++n)0===n?e.push(`\tif (channel == ${n}) { return bias[${n}]; }`):n===t-1?e.push(`\telse { return bias[${n}]; }`):e.push(`\telse if (channel == ${n}) { return bias[${n}]; }`);return e.push("\t}"),e.join("\n")},u=t=>{if(!t||1!==t.length)throw new Error("ImageScaler requires 1 input.");if(4!==t[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")}},3346:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseInstanceNormalizationAttributes=e.instanceNormalization=void 0;const r=n(5060),i=n(2039);e.instanceNormalization=(t,e,n)=>{l(e);const r=t.run(s(e[0]),e);return[t.run(u(t,e[0],n,r.dims),[e[0],r,e[1],e[2]])]},e.parseInstanceNormalizationAttributes=t=>t.attributes.getFloat("epsilon",1e-5);const o={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=t=>Object.assign(Object.assign({},o),{get:()=>((t,e)=>{const n=e.dims.slice(),r=n[1],o=n[2]*n[3],s=[n[0],r],a=`\n vec4 process(int[2] indices) {\n vec4 v = vec4(0.0);\n int a[4];\n a[0] = indices[0];\n a[1] = indices[1];\n float temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += x;\n }\n }\n float mean = temp / float(${o});\n temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += (x - mean) * (x - mean);\n }\n }\n v.r = mean;\n v.g = temp / float(${o});\n\n return v;\n }`;return Object.assign(Object.assign({},t),{output:{dims:s,type:e.type,textureType:i.TextureType.packedLastDimension},shaderSource:a})})(o,t)}),a={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked,i.TextureType.unpacked]},u=(t,e,n,o)=>{const s=Object.assign(Object.assign({},a),{cacheHint:`${n}`});return Object.assign(Object.assign({},s),{get:()=>((t,e,n,o,s)=>{const a=(0,r.getGlsl)(t.session.backend.glContext.version),[u,l]=t.calculateTextureWidthAndHeight(s,i.TextureType.packedLastDimension),[c,d]=[u/4,l],h=`\n vec4 get_MeanAndVariance(int[2] mv) {\n int offset = indicesToOffset_MeanAndVariance(mv);\n vec2 coords = offsetToCoords(offset, ${c}, ${d});\n return ${a.texture2D}(MeanAndVariance, coords);\n }\n\n float process(int[4] indices) {\n int mv[2];\n mv[0] = indices[0];\n mv[1] = indices[1];\n vec4 mean_and_variance = get_MeanAndVariance(mv);\n float mean = mean_and_variance.r;\n float variance = mean_and_variance.g;\n\n int sb[1];\n sb[0] = indices[1];\n float scale = _Scale(sb);\n float b = _B(sb);\n\n return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n }`;return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:o}],shaderSource:h})})(t,s,e,n,o)})},l=t=>{if(!t||3!==t.length)throw new Error("InstanceNormalization requires 3 inputs.");const e=t[0],n=t[1],r=t[2];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==t[0].dims.length)throw new Error("Only support 4-D input shape.")}},708:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedMatmulProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),s=n(9390),a=n(2823),u=n(5623);e.createPackedMatmulProgramInfoLoader=(t,e,n)=>{const l=(c=e.length>2,d=n.activationCacheKey,{name:"MatMul (packed)",inputNames:c?["A","B","Bias"]:["A","B"],inputTypes:c?[o.TextureType.packed,o.TextureType.packed,o.TextureType.packed]:[o.TextureType.packed,o.TextureType.packed],cacheHint:d});var c,d;return Object.assign(Object.assign({},l),{get:()=>((t,e,n,l)=>{const c=n.length>2,d=c?"value += getBiasForMatmul();":"",h=n[0].dims,p=n[1].dims,f=r.BroadcastUtil.calcShape(h,p,!0),g=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!f)throw new Error("Can't use matmul on the given tensors");const m=h[h.length-1],b=Math.ceil(m/2),y=h.length,_=p.length,w=(0,i.getGlsl)(t.session.backend.glContext.version),v=(0,s.getCoordsDataType)(f.length),x=f.length,T=(0,s.getGlChannels)(),{activationFunction:S,applyActivation:A}=(0,a.getActivationSnippet)(l),E=c?`${(0,u.getBiasForMatmul)(v,T,n[2].dims,f,!0)}`:"",O=g?`${function(t,e,n,i){let o=[],s=[];const a=n[0].dims,u=n[1].dims,l=a.length,c=u.length,d=i.length,h=d-l,p=d-c;o=a.map((t,n)=>`coords.${e[n+h]}`),o[l-1]="i*2",o.join(", "),s=u.map((t,n)=>`coords.${e[n+p]}`),s[c-2]="i*2",s.join(", ");const f=r.BroadcastUtil.getBroadcastDims(a,i),g=r.BroadcastUtil.getBroadcastDims(u,i),m=f.map(t=>`coords.${e[t+h]} = 0;`).join("\n"),b=g.map(t=>`coords.${e[t+p]} = 0;`).join("\n"),y=`int lastDim = coords.${e[d-1]};\n coords.${e[d-1]} = coords.${e[d-2]};\n coords.${e[d-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n ${t} coords = getOutputCoords();\n ${y}\n ${m}\n vec4 outputValue = getA(${o});\n return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n ${t} coords = getOutputCoords();\n ${y}\n ${b}\n vec4 outputValue = getB(${s});\n return outputValue;\n}`}(v,T,n,f)}`:"",I=g?"getAAtOutCoordsMatmul(i)":`getA(${function(t,e){let n="";for(let r=0;r<e-2;r++)n+=`rc.${t[r]}, `;return n+=`rc.${t[e-2]}, i*2`,n}(T,y)})`,P=g?"getBAtOutCoordsMatmul(i)":`getB(${function(t,e){let n="";for(let r=0;r<e-2;r++)n+=`rc.${t[r]}, `;return n+=`i*2, rc.${t[e-1]}`,n}(T,_)})`,D=`\n ${O}\n ${E}\n ${S}\n void main() {\n ${g?"":`${v} rc =\n getOutputCoords(); int lastDim = rc.${T[x-1]}; rc.${T[x-1]} =\n rc.${T[x-2]}; rc.${T[x-2]} = lastDim;\n `}\n\n vec4 value = vec4(0);\n for (int i = 0; i < ${b}; i++) {\n vec4 a = ${I};\n vec4 b = ${P};\n\n value += (a.rrbb * b.rgrg);\n value += (a.ggaa * b.baba);\n }\n ${d}\n ${A}\n ${w.output} = value;\n }`;return Object.assign(Object.assign({},e),{output:{dims:f,type:n[0].type,textureType:o.TextureType.packed},shaderSource:D,hasMain:!0})})(t,l,e,n)})}},5623:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getBiasForMatmul=e.createMatmulProgramInfoLoader=e.parseMatMulAttributes=e.matMul=void 0;const r=n(2517),i=n(2039),o=n(9390),s=n(2823),a=n(708);function u(t,e){const n=(a=t.length>2,u=e.activationCacheKey,{name:"MatMul",inputNames:a?["A","B","Bias"]:["A","B"],inputTypes:a?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:u});var a,u;return Object.assign(Object.assign({},n),{get:()=>function(t,e,n){const a=e[0].dims,u=e[1].dims,l=r.BroadcastUtil.calcShape(a,u,!0);if(!l)throw new Error("Can't use matmul on the given tensors");const d=(0,o.getCoordsDataType)(l.length),h=(0,o.getGlChannels)(),{activationFunction:p,applyActivation:f}=(0,s.getActivationSnippet)(n),g=e.length>2,m=g?"value += getBiasForMatmul();":"",b=g?`${c(d,h,e[2].dims,l,!1)}`:"",y=l.length,_=a.length,w=u.length,v=`\n ${p}\n ${b}\n float process(int indices[${y}]) {\n int a[${_}];\n int b[${w}];\n bcastMatmulIndices_A(indices, a);\n bcastMatmulIndices_B(indices, b);\n\n float value;\n for (int k=0; k<${a[a.length-1]}; ++k) {\n a[${_-1}] = k;\n b[${w-2}] = k;\n value += _A(a) * _B(b);\n }\n ${m}\n ${f}\n return value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:l,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:v})}(n,t,e)})}e.matMul=(t,e,n)=>(l(e),t.session.pack?[t.run((0,a.createPackedMatmulProgramInfoLoader)(t,e,n),e)]:[t.run(u(e,n),e)]),e.parseMatMulAttributes=t=>(0,s.parseInternalActivationAttributes)(t.attributes),e.createMatmulProgramInfoLoader=u;const l=t=>{if(!t||2!==t.length)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("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type)throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function c(t,e,n,i,o){let s="";const a=n.length,u=i.length,l=u-a;s=u<2&&a>0?"coords":n.map((t,n)=>`coords.${e[n+l]}`).join(", ");const c=r.BroadcastUtil.getBroadcastDims(n,i).map(t=>`coords.${e[t+l]} = 0;`).join("\n");let d="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(d="vec4(outputValue.x)"),o?`\nvec4 getBiasForMatmul() {\n ${t} coords = getOutputCoords();\n ${c}\n vec4 outputValue = getBias(${s});\n return ${d};\n}`:`\nfloat getBiasForMatmul() {\n ${t} coords = getOutputCoords();\n ${c}\n return getBias(coords.x);\n}`}e.getBiasForMatmul=c},2403:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createPackProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827),a={name:"pack",inputNames:["A"],inputTypes:[i.TextureType.unpackedReversed]};e.createPackProgramInfoLoader=(t,e)=>Object.assign(Object.assign({},a),{get:()=>((t,e)=>{const n=(0,r.getGlsl)(t.session.backend.glContext.version),u=e.dims,l=u.length,c=e.dims.length,d=(0,o.getCoordsDataType)(c),h=(0,s.getChannels)("rc",c),p=(f=c,g=h,m=u[u.length-2],b=u[u.length-1],0===f||1===f?"":`\n int r = ${g[f-2]};\n int c = ${g[f-1]};\n int rp1 = ${g[f-2]} + 1;\n int cp1 = ${g[f-1]} + 1;\n bool rEdge = rp1 >= ${b};\n bool cEdge = cp1 >= ${m};\n `);var f,g,m,b;let y;y=0===l?[1,1]:1===l?[u[0],1]:[u[c-1],u[c-2]];const _=function(t,e,n){if(0===t)return"false";if(1===t)return`rc > ${e[0]}`;let r="";for(let i=t-2;i<t;i++)r+=`${n[i]} >= ${e[i-t+2]}`,i<t-1&&(r+="||");return r}(c,y,h),w=function(t,e){const n=t.length;if(0===n)return"getA(), 0, 0, 0";if(1===n)return`getA(rc),\n rc + 1 >= ${t[0]} ? 0. : getA(rc + 1),\n 0, 0`;let r="";if(n>2)for(let t=0;t<n-2;++t)r+=`${e[t]},`;return`getA(${r}r, c),\n rEdge ? 0. : getA(${r}rp1, c),\n cEdge ? 0. : getA(${r}r, cp1),\n rEdge || cEdge ? 0. : getA(${r}rp1, cp1)`}(u,h),v=`\n void main() {\n ${d} rc = getOutputCoords();\n\n if(${_}) {\n ${n.output} = vec4(0);\n } else {\n ${p}\n\n ${n.output} = vec4(${w});\n }\n }\n `;return Object.assign(Object.assign({},a),{hasMain:!0,output:{dims:e.dims,type:e.type,textureType:i.TextureType.packed},shaderSource:v})})(t,e)})},2827:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.unpackFromChannel=e.getChannels=e.getVecChannels=void 0;const r=n(9390);function i(t,e){return(0,r.getGlChannels)(e).map(e=>`${t}.${e}`)}e.getVecChannels=i,e.getChannels=function(t,e){return 1===e?[t]:i(t,e)},e.unpackFromChannel=function(){return"\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "}},2870:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parsePadAttributesV11=e.padV11=e.parsePadAttributesV2=e.padV2=void 0;const r=n(246),i=n(2517),o=n(5060),s=n(2039),a={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};e.padV2=(t,e,n)=>(c(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>l(t,e[0],n)}),e)]),e.parsePadAttributesV2=t=>{const e=t.attributes.getString("mode","constant"),n=t.attributes.getFloat("value",0),i=t.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:e,value:n,pads:i})},e.padV11=(t,n,r)=>{d(n);const i=u(t,n,r);return(0,e.padV2)(t,[n[0]],i)},e.parsePadAttributesV11=t=>t.attributes.getString("mode","constant");const u=(t,e,n)=>{if(!t.session.isInitializer(e[1].dataId)||e.length>=3&&!t.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");const i=Array.from(e[1].integerData),o=e.length>=3?e[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:i,value:o})},l=(t,e,n)=>{const r=i.ShapeUtil.padShape(e.dims.slice(),n.pads),o=r.length,a=`\n ${h(t,e,n)}\n float process(int[${o}] indices) {\n return padA(indices);\n }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:r,type:e.type,textureType:s.TextureType.unpacked},shaderSource:a}},c=t=>{if(!t||1!==t.length)throw new Error("Pad requires 1 input");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},d=t=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==t[1].type)throw new Error("Invalid input type.");if(t.length>=3&&"string"===t[2].type)throw new Error("Invalid input type.")},h=(t,e,n)=>{const r=(0,o.getGlsl)(t.session.backend.glContext.version),[a,u]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),l=i.ShapeUtil.computeStrides(e.dims);switch(n.mode){case"constant":return p(r,e.dims,l,a,u,n.pads,n.value);case"reflect":return f(r,e.dims,l,a,u,n.pads);case"edge":return g(r,e.dims,l,a,u,n.pads);default:throw new Error("Invalid mode")}},p=(t,e,n,r,i,o,s)=>{const a=e.length;let u="";for(let t=a-1;t>=0;--t)u+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) return constant;\n if (k >= ${e[t]}) return constant;\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${a}]) {\n const float constant = float(${s});\n int offset = 0;\n int k = 0;\n ${u}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `},f=(t,e,n,r,i,o)=>{const s=e.length;let a="";for(let t=s-1;t>=0;--t)a+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) { k = -k; }\n {\n const int _2n_1 = ${2*(e[t]-1)};\n k = int( mod( float(k), float(_2n_1) ) ) ;\n if(k >= ${e[t]}) { k = _2n_1 - k; }\n }\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `},g=(t,e,n,r,i,o)=>{const s=e.length;let a="";for(let t=s-1;t>=0;--t)a+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) k = 0;\n if (k >= ${e[t]}) k = ${e[t]-1};\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `}},2143:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.globalMaxPool=e.parseMaxPoolAttributes=e.maxPool=e.parseGlobalAveragePoolAttributes=e.globalAveragePool=e.parseAveragePoolAttributes=e.averagePool=void 0;const r=n(246),i=n(2517),o=n(2039);e.averagePool=(t,e,n)=>{d(e);const r={name:"AveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>s(e,r,!1,n)}),e)]},e.parseAveragePoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=0!==t.attributes.getInt("count_include_pad",0),o=t.attributes.getInts("kernel_shape"),s=t.attributes.getInts("strides",[]),a=t.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:i,kernelShape:o,strides:s,pads:a})};const s=(t,e,n,r)=>{const[s,a]=u(t,r,n),l=i.ShapeUtil.size(s.kernelShape);let c="";s.countIncludePad?c+=`value /= float(${l});`:c+=`value /= float(${l} - pad);`;const d=`\n ${h(t[0].dims,s,"value += _X(x);",c,"0.0")}\n `;return Object.assign(Object.assign({},e),{output:{dims:a,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:d})};e.globalAveragePool=(t,e,n)=>{d(e);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[t.run(Object.assign(Object.assign({},r),{get:()=>s(e,r,!0,n)}),e)]},e.parseGlobalAveragePoolAttributes=t=>{const e=0!==t.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},e.maxPool=(t,e,n)=>{d(e);const r={name:"MaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>a(e,r,!1,n)}),e)]},e.parseMaxPoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=t.attributes.getInts("kernel_shape"),o=t.attributes.getInts("strides",[]),s=t.attributes.getInts("pads",[]),a=t.attributes.getInt("storage_order",0),u=t.attributes.getInts("dilations",[]);if(0!==a)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:o,pads:s,storageOrder:a,dilations:u})};const a=(t,e,n,r)=>{const[i,s]=u(t,r,n),a=`\n ${h(t[0].dims,i,"\n value = max(_X(x), value);\n ","","-1e5")}\n `;return Object.assign(Object.assign({},e),{output:{dims:s,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:a})},u=(t,e,n)=>{const r=t[0].dims.slice(),o=Object.hasOwnProperty.call(e,"dilations"),s=e.kernelShape.slice(),a=e.strides.slice(),u=o?e.dilations.slice():[],l=e.pads.slice();i.PoolConvUtil.adjustPoolAttributes(n,r,s,a,u,l);const c=i.PoolConvUtil.computePoolOutputShape(n,r,a,u,s,l,e.autoPad),d=Object.assign({},e);return o?Object.assign(d,{kernelShape:s,strides:a,pads:l,dilations:u,cacheKey:e.cacheKey}):Object.assign(d,{kernelShape:s,strides:a,pads:l,cacheKey:e.cacheKey}),[d,c]},l={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},c={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.globalMaxPool=(t,e)=>(d(e),[t.run(Object.assign(Object.assign({},c),{get:()=>a(e,c,!0,l)}),e)]);const d=t=>{if(!t||1!==t.length)throw new Error("Pool ops requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},h=(t,e,n,r,o)=>{const s=t.length;if(e.kernelShape.length<=2){const i=e.kernelShape[e.kernelShape.length-1],a=e.strides[e.strides.length-1],u=e.pads[e.pads.length/2-1],l=e.pads[e.pads.length-1],c=t[s-1];let d="",h="",p="";if(d=u+l!==0?`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n if (x[${s} - 1] < 0 || x[${s} - 1] >= ${c}) {\n pad++;\n continue;\n }\n ${n}\n }`:`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n ${n}\n }`,2===e.kernelShape.length){const n=e.kernelShape[e.kernelShape.length-2],r=e.strides[e.strides.length-2],o=e.pads[e.pads.length/2-2],a=e.pads[e.pads.length-2],u=t[s-2];h=o+a!==0?`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n if (x[${s} - 2] < 0 || x[${s} - 2] >= ${u}) {\n pad+= ${i};\n continue;\n }\n `:`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n `,p="\n }\n "}return`\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n\n float value = ${o};\n int pad = 0;\n ${h}\n ${d}\n ${p}\n ${r}\n return value;\n }\n `}{const a=i.ShapeUtil.size(e.kernelShape),u=i.ShapeUtil.computeStrides(e.kernelShape),l=u.length,c=e.pads.length,d=f(l),h=p(t,"inputDims"),g=p(e.pads,"pads"),m=p(u,"kernelStrides"),b=p(e.strides,"strides");let y="";return y=e.pads.reduce((t,e)=>t+e)?`\n if (x[j] >= inputDims[j] || x[j] < 0) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n ${n}\n }`:`\n }\n ${n}\n `,`\n ${d}\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n int offset[${l}];\n int pads[${c}];\n int inputDims[${s}];\n int kernelStrides[${l}];\n int strides[${l}];\n ${g}\n ${h}\n ${b}\n ${m}\n\n float value = ${o};\n int pad = 0;\n bool isPad = false;\n for (int i = 0; i < ${a}; i++) {\n offsetToIndices(i, kernelStrides, offset);\n isPad = false;\n for (int j = ${s} - ${l}; j < ${s}; j++) {\n x[j] = indices[j] * strides[j - ${s} + ${l}]\n + offset[j - ${s} + ${l}] - pads[j - 2];\n ${y}\n }\n ${r}\n\n return value;\n }\n `}},p=(t,e)=>{let n="";for(let r=0;r<t.length;r++)n+=`\n ${e}[${r}] = ${t[r]};\n `;return n},f=t=>`\n void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) {\n if (${t} == 0) {\n return;\n }\n for (int i = 0; i < ${t} - 1; ++i) {\n indices[i] = offset / strides[i];\n offset -= indices[i] * strides[i];\n }\n indices[${t} - 1] = offset;\n }`},4939:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reduceLogSumSquare=e.reduceLogSum=e.reduceProd=e.reduceMin=e.reduceMax=e.reduceMean=e.reduceSum=e.parseReduceAttributes=void 0;const r=n(246),i=n(782),o=n(2517),s=n(2039),a=(t,e,n,r,i)=>{l(e);const o={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},o),{cacheHint:n.cacheKey,get:()=>u(t,e,n,r,i,o)}),e)]};e.parseReduceAttributes=t=>{const e=t.attributes.getInts("axes",[]),n=1===t.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:e,keepDims:n})};const u=(t,e,n,r,i,a)=>{const u=[],l=e[0].dims.length||1,c=[],d=o.ShapeUtil.normalizeAxes(n.axes,e[0].dims.length),h=i(e,d);let p=h[1];for(let t=0;t<e[0].dims.length;t++)d.indexOf(t)>=0||0===d.length?(n.keepDims&&u.push(1),p=`\n for(int j${t} = 0; j${t} < ${e[0].dims[t]}; j${t}++) {\n inputIdx[${t}] = j${t};\n ${p}\n }`):(c.push(`inputIdx[${t}] = outputIdx[${u.length}];`),u.push(e[0].dims[t]));const f=`\n float process(int outputIdx[${u.length||1}]) {\n float value; // final result\n int inputIdx[${l}]; // addressing input data\n ${c.join("\n")}\n ${h[0]} // init ops for reduce max/min\n ${p}\n ${h[2]} // final computation for reduce mean\n return value;\n }`;return Object.assign(Object.assign({},a),{output:{dims:u,type:e[0].type,textureType:s.TextureType.unpacked},shaderSource:f})},l=t=>{if(!t||1!==t.length)throw new Error("Reduce op requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.reduceSum=(t,e,n)=>a(t,e,n,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),e.reduceMean=(t,e,n)=>a(t,e,n,"ReduceMean",(t,e)=>{let n=1;for(let r=0;r<t[0].dims.length;r++)(e.indexOf(r)>=0||0===e.length)&&(n*=t[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]}),e.reduceMax=(t,e,n)=>a(t,e,n,"ReduceMax",(t,e)=>{const n=[];for(let r=0;r<t[0].dims.length;r++)(e.indexOf(r)>=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),e.reduceMin=(t,e,n)=>a(t,e,n,"ReduceMin",(t,e)=>{const n=[];for(let r=0;r<t[0].dims.length;r++)(e.indexOf(r)>=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),e.reduceProd=(t,e,n)=>a(t,e,n,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),e.reduceLogSum=(t,e,n)=>a(t,e,n,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),e.reduceLogSumSquare=(t,e,n)=>a(t,e,n,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isReshapeCheap=e.processDims3D=e.createPackedReshape3DProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),s=n(2827);e.createPackedReshape3DProgramInfoLoader=(t,e,n)=>{const a=(t=>({name:"Reshape (packed)",inputTypes:[o.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(n);return Object.assign(Object.assign({},a),{get:()=>((t,e,n,a)=>{const u=e.dims,l=a;let c="";for(let t=0;t<4;t++){let e="";switch(t){case 0:e="outputCoords = rc;";break;case 1:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:e="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}c+=`\n ${e}\n ${t>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n int flattenedIndex = getFlattenedIndex(outputCoords);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${t}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n ${t>0?"}":""}\n `}const d=(0,i.getGlsl)(t.session.backend.glContext.version),h=`\n ${function(t){const e=r.ShapeUtil.computeStrides(t),n=["b","r","c"],i="index";return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${e.map((t,r)=>`int ${n[r]} = ${i} / ${t}; ${r===e.length-1?`int ${n[r+1]} = ${i} - ${n[r]} * ${t}`:`index -= ${n[r]} * ${t}`};`).join("")}\n return ivec3(b, r, c);\n }\n `}(u)}\n ${function(t){const e=r.ShapeUtil.computeStrides(t);return`\n int getFlattenedIndex(ivec3 coords) {\n // reverse y, z order\n return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y;\n }\n`}(l)}\n ${(0,s.unpackFromChannel)()}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.0);\n\n ivec3 outputCoords;\n int rows = ${l[2]};\n int cols = ${l[1]};\n\n ${c}\n ${d.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:l,type:e.type,textureType:o.TextureType.packed},shaderSource:h,hasMain:!0})})(t,e,a,n)})},e.processDims3D=function(t){if(0===t.length)return[1,1,1];let e=1;for(let n=0;n<t.length-2;++n)e*=t[n];return[e,t.length>1?t[t.length-2]:1,t[t.length-1]]},e.isReshapeCheap=function(t,e){let n=!1;return n=0===t.length||0===e.length||(t.length<2||e.length<2?t[t.length-1]===e[e.length-1]:t[t.length-1]===e[e.length-1]&&t[t.length-2]===e[e.length-2]),n}},718:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reshape=void 0;const r=n(2517);e.reshape=(t,e)=>{const n=r.ShapeUtil.calculateReshapedDims(e[0].dims,e[1].integerData);return t.session.pack?[t.reshapePacked(e[0],n)]:[t.reshapeUnpacked(e[0],n)]}},2268:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseResizeAttributesV11=e.parseResizeAttributesV10=e.resize=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827),a=n(9793),u={name:"Resize",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.resize=(t,e,n)=>((0,a.validateInputs)(e,n),[t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>l(t,e,n)}),e)]),e.parseResizeAttributesV10=t=>(0,a.parseUpsampleAttributes)(t,10),e.parseResizeAttributesV11=t=>(0,a.parseUpsampleAttributes)(t,11);const l=(t,e,n)=>{const a=(0,r.getGlsl)(t.session.backend.glContext.version),[l,d]=c(e,n);if(l.every(t=>1===t)&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},u),{output:{dims:d,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:`void main() {\n vec4 v = ${a.texture2D}(X, TexCoords);\n ${a.output} = v;\n }`});const h=d.length;if(h<2)throw new Error(`output dimension should be at least 2, but got ${h}`);const p=d[h-2],f=d[h-1],g=e[0].dims;if(h!==g.length)throw new Error(`output dimension should match input ${g.length}, but got ${h}`);const m=g[h-2],b=g[h-1],y=l[h-2],_=l[h-1];let w="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":w="\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n ";break;case"half_pixel":w="\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n ";break;case"pytorch_half_pixel":w=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 fcoords = vec4(coords);\n return vec4(\n ${f}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n ${f}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n );\n }\n `;break;case"align_corners":w=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 resized = vec4(${f}.0 - 1.0, ${p}.0 - 1.0, ${f}.0 - 1.0,\n ${p}.0 - 1.0);\n vec4 original = vec4(${b}.0 - 1.0, ${m}.0 - 1.0, ${b}.0 - 1.0,\n ${m}.0 - 1.0);\n vec4 new_scale = original / resized;\n return vec4(coords) * new_scale;\n }\n `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}const v=(0,o.getCoordsDataType)(h),x=`\n const vec2 inputWH = vec2(${m}.0, ${b}.0);\n const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_}));\n ${(0,s.unpackFromChannel)()}\n ${w}\n float getAValue(int x10, int r, int c, int d) {\n return getChannel(getA(x10, r, c, d), vec2(c, d));\n }\n void main() {\n ${v} rc = getOutputCoords();\n\n int batch = rc[0];\n int depth = rc[1];\n\n // retrieve the 4 coordinates that is used in the 4 packed output values.\n ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n // calculate the source index in fraction\n vec4 sourceFrac = getSourceFracIndex(coords);\n\n // get the lower and upper bound of the 4 values that will be packed into one texel.\n ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n bool hasNextRow = rc.w < ${p-1};\n bool hasNextCol = rc.z < ${f-1};\n\n // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n vec4 topLeft = vec4(\n getAValue(batch, depth, x00.x, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n vec4 topRight = vec4(\n getAValue(batch, depth, x00.x, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n vec4 bottomLeft = vec4(\n getAValue(batch, depth, x00.z, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n vec4 bottomRight = vec4(\n getAValue(batch, depth, x00.z, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n // calculate the interpolation fraction on u and v direction\n vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n ${a.output} = vec4(newValue);\n }\n `;return Object.assign(Object.assign({},u),{output:{dims:d,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:x})},c=(t,e)=>{const n=t[0].dims;let r,i=e.scales;if(0===i.length){const o=t[e.scalesInputIdx];if(o&&0!==o.size){if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=d(o,e.mode,e.isResize)}else{const o=t[e.sizesInputIdx];if(!o||0===o.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(o.integerData),i=h(r,n,e.mode,e.isResize)}}else if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const o=r||n.map((t,e)=>Math.floor(t*i[e]));return[i,o]},d=(t,e,n)=>{const r=Array.from(t.floatData);return(0,a.scalesValidation)(r,e,n),r},h=(t,e,n,r)=>{const i=e.length,o=new Array(i);for(let n=0,r=i;n<r;n++)if(0===e[n]){if(0!==t[n])throw new Error("Input dim is zero but required output dim is non-zero.");o[n]=1}else o[n]=t[n]/e[n];return(0,a.scalesValidation)(o,n,r),o}},8117:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shape=void 0;const r=n(9162);e.shape=(t,e)=>(i(e),[new r.Tensor([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]);const i=t=>{if(!t||1!==t.length)throw new Error("Shape requires 1 input.")}},2278:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.sliceV10=e.parseSliceAttributes=e.slice=void 0;const r=n(246),i=n(782),o=n(2517),s=n(2039),a={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};e.slice=(t,e,n)=>(l(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),e)]),e.parseSliceAttributes=t=>{const e=t.attributes.getInts("starts"),n=t.attributes.getInts("ends"),i=t.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:e,ends:n,axes:i})};const u=(t,e,n)=>{const r=0===n.axes.length?e.dims.slice(0).map((t,e)=>e):n.axes,i=o.ShapeUtil.normalizeAxes(r,e.dims.length),u=n.starts.map((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]])),l=n.ends.map((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]])),c=e.dims.slice(),d=[];for(let t=0;t<i.length;t++)c[i[t]]=l[t]-u[t],u[t]>0&&d.push(`outputIdx[${i[t]}] += ${u[t]};`);const h=`\n float process(int outputIdx[${c.length}]) {\n ${d.join("\n ")}\n return _A(outputIdx);\n }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:e.type,textureType:s.TextureType.unpacked},shaderSource:h})},l=t=>{if(!t||1!==t.length)throw new Error("Slice requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.sliceV10=(t,e)=>{d(e);const n=c(t,e);return[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),[e[0]])]};const c=(t,e)=>{if(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)||e.length>=4&&!t.session.isInitializer(e[3].dataId)||e.length>=5&&!t.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some(t=>1!==t))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(e[1].integerData),r=Array.from(e[2].integerData),i=e.length>=4?Array.from(e[3].integerData):[];return{starts:n,ends:r,axes:i,cacheKey:`${i};${n};${r}`}},d=t=>{if(!t||t.length<3||t.length>5)throw new Error("Invalid input number.");if("int32"!==t[1].type||1!==t[1].dims.length)throw new Error("Invalid input type.");if("int32"!==t[2].type||1!==t[2].dims.length)throw new Error("Invalid input type.");if(t.length>=4&&("int32"!==t[3].type||1!==t[3].dims.length))throw new Error("Invalid input type.");if(t.length>=5&&("int32"!==t[4].type||1!==t[4].dims.length))throw new Error("Invalid input type.")}},5524:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.softmaxV13=e.parseSoftmaxAttributesV13=e.parseSoftmaxAttributes=e.softmax=void 0;const r=n(246),i=n(2517),o=n(5060),s=n(2039),a=n(3738),u={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},l={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},c={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};e.softmax=(t,e,n)=>{g(e);const r=e[0].dims.slice(),o=i.ShapeUtil.normalizeAxis(n.axis,r.length),s=i.ShapeUtil.sizeToDimension(r,o),a=i.ShapeUtil.sizeFromDimension(r,o);return d(t,e,n,s,a)},e.parseSoftmaxAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",1)}),e.parseSoftmaxAttributesV13=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",-1)}),e.softmaxV13=(t,e,n)=>{g(e);const o=e[0].dims.slice(),s=i.ShapeUtil.normalizeAxis(n.axis,o.length),u=o.length,l=s!==u-1,c=[];let h,p=[],f=[];l&&(p=Array.from({length:u}).map((t,e)=>e),p[s]=u-1,p[u-1]=s,p.map(t=>c.push(o[t])),h=(0,r.createAttributeWithCacheKey)({perm:p}),f=(0,a.transpose)(t,e,h));const m=l?i.ShapeUtil.sizeToDimension(c,u-1):i.ShapeUtil.sizeToDimension(o,u-1),b=l?i.ShapeUtil.sizeFromDimension(c,u-1):i.ShapeUtil.sizeFromDimension(o,u-1),y=d(t,l?f:e,n,m,b);return l?(0,a.transpose)(t,y,h):y};const d=(t,e,n,r,i)=>{const o=h(t,e[0],r,i,[r]),s=t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>o}),e),a=p(t,e[0],r,i,o.output.dims,[r]),d=t.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>a}),[e[0],s]),g=f(t,e[0],r,i,o.output.dims,a.output.dims);return[t.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>g}),[e[0],s,d])]},h=(t,e,n,r,i)=>{const[a,l]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),c=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const d=(0,o.getGlsl)(t.session.backend.glContext.version),h=`\n float process(int[${c}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float max = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset, ${a},\n ${l} )));\n for(int i=1; i<${r}; ++i)\n {\n float current = getColorAsFloat(${d.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${a}, ${l})));\n if(current > max)\n max = current;\n }\n\n return max;\n }`;return Object.assign(Object.assign({},u),{output:{dims:i,type:e.type,textureType:s.TextureType.unpacked},shaderSource:h})},p=(t,e,n,r,i,a)=>{const[u,c]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),d=a.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==a.length)throw new Error("Dimensionality of the output should be 1");if(a[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const h=`\n float process(int[${d}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float norm_factor = 0.0;\n float max = _Max(indices);\n for(int i=0; i<${r}; ++i)\n {\n norm_factor += exp(getColorAsFloat(${(0,o.getGlsl)(t.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${u}, ${c}))) - max);\n }\n\n return norm_factor;\n }`;return Object.assign(Object.assign({},l),{output:{dims:a,type:e.type,textureType:s.TextureType.unpacked},shaderSource:h})},f=(t,e,n,r,i,o)=>{const[a,u]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),l=e.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length||1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n||o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const d=`\n float process(int[${l}] indices) {\n\n // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n int offset = coordsToOffset(TexCoords, ${a}, ${u});\n\n //determine the logical row for this index\n int logical_row_index[1];\n logical_row_index[0] = offset / ${r};\n\n float norm_factor = _Norm(logical_row_index);\n\n // avoid possible division by 0\n // if norm_facor is 0, all elements are zero\n // if so, return 0\n if(norm_factor == 0.0)\n return 0.0;\n\n return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n }`;return Object.assign(Object.assign({},c),{output:{dims:e.dims,type:e.type,textureType:s.TextureType.unpacked},shaderSource:d})},g=t=>{if(!t||1!==t.length)throw new Error("Softmax requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type")}},5975:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseSplitAttributes=e.split=void 0;const r=n(246),i=n(2517),o=n(2039),s={name:"Split",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.split=(t,e,n)=>{l(e);const r=i.ShapeUtil.normalizeAxis(n.axis,e[0].dims.length),o=a(t,e,r,n),c=[];for(let i=0;i<o;++i)c.push(t.run(Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey};${i}`,get:()=>u(t,e[0],n,r,i)}),e));return c},e.parseSplitAttributes=t=>{const e=t.attributes.getInt("axis",0),n=t.attributes.getInts("split",[]),i=t.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:e,split:n,numOutputs:i})};const a=(t,e,n,r)=>{const[,o]=i.SplitUtil.splitShape(e[0].dims,n,r.split,r.numOutputs);return o.length},u=(t,e,n,r,a)=>{const[u,l]=i.SplitUtil.splitShape(e.dims,r,n.split,n.numOutputs),c=l[a],d=u[a],h=`\n float process(int indices[${d.length}]) {\n indices[${r}] += ${c};\n return _A(indices);\n }\n `;return Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey}:${a}`,output:{dims:d,type:e.type,textureType:o.TextureType.unpacked},shaderSource:h})},l=t=>{if(!t||1!==t.length)throw new Error("Split requires one input.");if("int8"!==t[0].type&&"uint8"!==t[0].type&&"int16"!==t[0].type&&"uint16"!==t[0].type&&"int32"!==t[0].type&&"uint32"!==t[0].type&&"float32"!==t[0].type&&"float64"!==t[0].type&&"bool"!==t[0].type)throw new Error("Invalid input type.")}},3933:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseSqueezeAttributes=e.squeezeV13=e.squeeze=void 0;const r=n(2517);e.squeeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.squeezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.squeezeV13=(t,n)=>(o(n),(0,e.squeeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseSqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Squeeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},6558:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.sum=void 0;const r=n(5060),i=n(2039);e.sum=(t,e)=>{s(e);const n={name:"Sum",inputNames:e.map((t,e)=>`X${e}`),inputTypes:new Array(e.length).fill(i.TextureType.unpacked)};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const o=(0,r.getGlsl)(t.session.backend.glContext.version),s=e[0].dims.slice(),a=`\n void main() {\n vec4 result = ${e.map((t,e)=>`${o.texture2D}(X${e},TexCoords)`).join(" + ")};\n ${o.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:s,type:e[0].type,textureType:i.TextureType.unpacked},hasMain:!0,shaderSource:a})},s=t=>{if(!t||0===t.length)throw new Error("Sum requires inputs.");const e=t[0].dims.length;for(let n=1;n<t.length;n++){if(e!==t[n].dims.length)throw new Error("Input shapes are mismatched.");for(let r=0;r<e;r++)if(t[0].dims[r]!==t[n].dims[r])throw new Error("Input shapes are not matched.")}if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.");for(let e=1;e<t.length;e++)if(t[0].type!==t[e].type)throw new Error("Input types are not matched.")}},5723:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.tile=void 0;const r=n(782),i=n(2039);e.tile=(t,e)=>{s(e);const n={name:"Tile",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const r=e[0].dims.slice(),o=new Array(r.length),s=[];for(let t=0;t<r.length;t++)o[t]=r[t]*e[1].numberData[t],s.push(`inputIdx[${t}] = int(mod(float(outputIdx[${t}]), ${r[t]}.));`);const a=o.length,u=`\n float process(int outputIdx[${a}]) {\n int inputIdx[${a}];\n ${s.join("\n")}\n return _A(inputIdx);\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:o,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:u})},s=t=>{if(!t||2!==t.length)throw new Error("Tile requires 2 input.");if(1!==t[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(t[1].dims[0]!==t[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invalid repeat type.")}},3738:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseTransposeAttributes=e.transpose=void 0;const r=n(246),i=n(2517),o=n(2039),s={name:"Transpose",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.transpose=(t,e,n)=>(d(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(t,e[0],n.perm)}),e)]),e.parseTransposeAttributes=t=>(0,r.createAttributeWithCacheKey)({perm:t.attributes.getInts("perm",[])});const a=(t,e,n)=>{const r=e.dims;n=u(r,n);const i=l(r,n),a=r.length,d=`\n ${c("perm",n,a)}\n float process(int indices[${a}]) {\n int a[${a}];\n perm(a, indices);\n return _A(a);\n }`;return Object.assign(Object.assign({},s),{output:{dims:i,type:e.type,textureType:o.TextureType.unpacked},shaderSource:d})},u=(t,e)=>(e&&e.length!==t.length&&(e=[...t.keys()].reverse()),e),l=(t,e)=>(e=u(t,e),i.ShapeUtil.sortBasedOnPerm(t,e)),c=(t,e,n)=>{const r=[];r.push(`void ${t}(out int a[${n}], int src[${n}]) {`);for(let t=0;t<n;++t)r.push(`\ta[${e[t]}]=src[${t}];`);return r.push("\t}"),r.join("\n")},d=t=>{if(!t||1!==t.length)throw new Error("Transpose requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("input should be float tensor")}},8710:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.encodeAsUint8=void 0;const r=n(5060),i=n(2039);e.encodeAsUint8=(t,e)=>{const n=e.shape,o=(0,r.getGlsl)(t.session.backend.glContext.version),s=`\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n highp vec4 encodeAsUint8(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float value = ${o.texture2D}(X,TexCoords).r;\n ${o.output} = encodeAsUint8(value);\n }`,a={name:"Uint8Encode",inputTypes:[i.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:e.tensor.type,textureType:i.TextureType.downloadUint8AsFloat},shaderSource:s,hasMain:!0};return t.executeProgram(a,[e.tensor])}},4909:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.tanh=e.tan=e.sqrt=e.sin=e.sigmoid=e.relu=e.not=e.neg=e.log=e.parseLeakyReluAttributes=e.leakyRelu=e.identity=e.floor=e.exp=e.parseEluAttributes=e.elu=e.cos=e.ceil=e.clipV11=e.parseClipAttributes=e.clip=e.atan=e.asin=e.acos=e.abs=e.glslTanh=e.glslTan=e.glslSqrt=e.glslSigmoid=e.glslRelu=e.glslSin=e.glslNot=e.glslNeg=e.glslLog=e.glslLeakyRelu=e.glslIdentity=e.glslClip=e.glslFloor=e.glslExp=e.glslElu=e.glslCos=e.glslCeil=e.glslAtan=e.glslAsin=e.glslAcos=e.glslAbs=void 0;const r=n(246),i=n(2517),o=n(8520),s=n(5060),a=n(2039);function u(){return P("abs")}function l(){return P("acos")}function c(){return P("asin")}function d(){return P("atan")}function h(){return P("ceil")}function p(){return P("cos")}function f(t){const e="elu";return{body:`\n const float alpha = float(${t});\n\n float ${e}_(float a) {\n return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function g(){return P("exp")}function m(){return P("floor")}function b(t,e){const n="clip";return{body:`\n const float min = float(${t});\n const float max = float(${e});\n\n float ${n}_(float a) {\n return clamp(a, min, max);\n }\n vec4 ${n}_(vec4 v) {\n return clamp(v, min, max);\n }\n `,name:n,type:o.FunctionType.ValueBased}}function y(){const t="indentity";return{body:`\n float ${t}_(float a) {\n return a;\n }\n vec4 ${t}_(vec4 v) {\n return v;\n }\n `,name:t,type:o.FunctionType.ValueBased}}function _(t){const e="leakyRelu";return{body:`\n const float alpha = float(${t});\n\n float ${e}_(float a) {\n return a < 0.0 ? a * alpha : a;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function w(){return P("log")}function v(){const t="neg";return{body:`\n float ${t}_(float a) {\n return -a;\n }\n vec4 ${t}_(vec4 v) {\n return -v;\n }\n `,name:t,type:o.FunctionType.ValueBased}}function x(){const t="not";return{body:`\n float ${t}_(float a) {\n return float( ! bool(a) );\n }\n bool ${t}_(bool a) {\n return !a;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n }\n bvec4 ${t}_(bvec4 v) {\n return bvec4(!v.x, !v.y, !v.z, !v.w);\n }\n `,name:t,type:o.FunctionType.ValueBased}}function T(){return P("sin")}function S(){const t="relu";return{body:`\n float ${t}_(float a) {\n return max( a, 0.0 );\n }\n vec4 ${t}_(vec4 v) {\n return max( v, 0.0 );\n }\n `,name:t,type:o.FunctionType.ValueBased}}function A(){const t="sigmoid";return{body:`\n float ${t}_(float a) {\n return 1.0 / (1.0 + exp(-a));\n }\n vec4 ${t}_(vec4 v) {\n return 1.0 / (1.0 + exp(-v));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function E(){return P("sqrt")}function O(){return P("tan")}function I(){const t="tanh";return{body:`\n float ${t}_(float a) {\n a = clamp(a, -10., 10.);\n a = exp(2.*a);\n return (a - 1.) / (a + 1.);\n }\n vec4 ${t}_(vec4 v) {\n v = clamp(v, -10., 10.);\n v = exp(2.*v);\n return (v - 1.) / (v + 1.);\n }\n `,name:t,type:o.FunctionType.ValueBased}}function P(t){return{body:`\n float ${t}_(float a) {\n return ${t}(a);\n }\n vec4 ${t}_(vec4 v) {\n return ${t}(v);\n }\n `,name:t,type:o.FunctionType.ValueBased}}e.glslAbs=u,e.glslAcos=l,e.glslAsin=c,e.glslAtan=d,e.glslCeil=h,e.glslCos=p,e.glslElu=f,e.glslExp=g,e.glslFloor=m,e.glslClip=b,e.glslIdentity=y,e.glslLeakyRelu=_,e.glslLog=w,e.glslNeg=v,e.glslNot=x,e.glslSin=T,e.glslRelu=S,e.glslSigmoid=A,e.glslSqrt=E,e.glslTan=O,e.glslTanh=I;const D=(t,e,n,r)=>{const i=t.session.pack?a.TextureType.packed:a.TextureType.unpacked,o={name:n.name,inputTypes:[i],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},o),{get:()=>((t,e,n,r)=>{const i=t.session.pack?a.TextureType.packed:a.TextureType.unpacked,o=(0,s.getGlsl)(t.session.backend.glContext.version);return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i},shaderSource:`\n ${r.body}\n void main() {\n vec4 v = ${o.texture2D}(A, TexCoords);\n v = ${r.name}_(v);\n ${o.output} = v;\n }\n `,hasMain:!0})})(t,o,e,n)})};e.abs=(t,e)=>[t.run(D(t,e[0],u()),e)],e.acos=(t,e)=>[t.run(D(t,e[0],l()),e)],e.asin=(t,e)=>[t.run(D(t,e[0],c()),e)],e.atan=(t,e)=>[t.run(D(t,e[0],d()),e)],e.clip=(t,e,n)=>[t.run(D(t,e[0],b(n.min,n.max),n.cacheKey),e)],e.parseClipAttributes=t=>(0,r.createAttributeWithCacheKey)({min:t.attributes.getFloat("min",i.MIN_CLIP),max:t.attributes.getFloat("max",i.MAX_CLIP)}),e.clipV11=(t,n)=>{const r=C(t,n);return(0,e.clip)(t,[n[0]],r)};const C=(t,e)=>{if(e.length>=3&&(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=e.length>=3?e[1].numberData[0]:i.MIN_CLIP,o=e.length>=3?e[2].numberData[0]:i.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:o})};e.ceil=(t,e)=>[t.run(D(t,e[0],h()),e)],e.cos=(t,e)=>[t.run(D(t,e[0],p()),e)],e.elu=(t,e,n)=>[t.run(D(t,e[0],f(n.alpha),n.cacheKey),e)],e.parseEluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",1)}),e.exp=(t,e)=>[t.run(D(t,e[0],g()),e)],e.floor=(t,e)=>[t.run(D(t,e[0],m()),e)],e.identity=(t,e)=>[t.run(D(t,e[0],y()),e)],e.leakyRelu=(t,e,n)=>[t.run(D(t,e[0],_(n.alpha),n.cacheKey),e)],e.parseLeakyReluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",.01)}),e.log=(t,e)=>[t.run(D(t,e[0],w()),e)],e.neg=(t,e)=>[t.run(D(t,e[0],v()),e)],e.not=(t,e)=>[t.run(D(t,e[0],x()),e)],e.relu=(t,e)=>[t.run(D(t,e[0],S()),e)],e.sigmoid=(t,e)=>[t.run(D(t,e[0],A()),e)],e.sin=(t,e)=>[t.run(D(t,e[0],T()),e)],e.sqrt=(t,e)=>[t.run(D(t,e[0],E()),e)],e.tan=(t,e)=>[t.run(D(t,e[0],O()),e)],e.tanh=(t,e)=>[t.run(D(t,e[0],I()),e)]},5611:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackProgramInfoLoader=e.createUnpackProgramInfo=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827),a={name:"unpack",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.createUnpackProgramInfo=(t,e)=>{const n=e.dims.length,u=(0,s.getChannels)("rc",n),l=u.slice(-2),c=(0,o.getCoordsDataType)(n),d=(0,s.unpackFromChannel)(),h=0===e.dims.length?"":function(t,e){if(1===t)return"rc";let n="";for(let r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(n,u),p=n<=1?"rc":`vec2(${l.join(",")})`,f=`\n ${d}\n void main() {\n ${c} rc = getOutputCoords();\n\n // Sample the texture with the coords to get the rgba channel value.\n vec4 packedInput = getA(${h});\n\n ${(0,r.getGlsl)(t.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${p}), 0, 0, 0);\n }\n `;return Object.assign(Object.assign({},a),{hasMain:!0,output:{dims:e.dims,type:e.type,textureType:i.TextureType.unpacked},shaderSource:f})},e.createUnpackProgramInfoLoader=(t,n)=>Object.assign(Object.assign({},a),{get:()=>(0,e.createUnpackProgramInfo)(t,n)})},8428:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.parseUnsqueezeAttributes=e.unsqueezeV13=e.unsqueeze=void 0;const r=n(2517);e.unsqueeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.unsqueezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.unsqueezeV13=(t,n)=>(o(n),(0,e.unsqueeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseUnsqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Unsqueeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},9793:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.scalesValidation=e.validateInputs=e.parseUpsampleAttributes=e.parseUpsampleAttributesV9=e.parseUpsampleAttributesV7=e.upsample=void 0;const r=n(246),i=n(5060),o=n(2039),s={name:"Upsample",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.upsample=(t,n,r)=>((0,e.validateInputs)(n,r),[t.run(Object.assign(Object.assign({},s),{cacheHint:r.cacheKey,get:()=>a(t,n,r)}),n)]),e.parseUpsampleAttributesV7=t=>(0,e.parseUpsampleAttributes)(t,7),e.parseUpsampleAttributesV9=t=>(0,e.parseUpsampleAttributes)(t,9),e.parseUpsampleAttributes=(t,n)=>{const i=n>=10,o=t.attributes.getString("mode","nearest");if("nearest"!==o&&"linear"!==o&&(n<11||"cubic"!==o))throw new Error(`unrecognized mode: ${o}`);let s=[];n<9&&(s=t.attributes.getFloats("scales"),(0,e.scalesValidation)(s,o,i));const a=t.attributes.getFloat("extrapolation_value",0),u=n>10?t.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(u))throw new Error(`coordinate_transform_mode '${u}' is not supported`);const l="tf_crop_and_resize"===u,c=l,d="nearest"===o&&n>=11?t.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(d))throw new Error(`nearest_mode '${d}' is not supported`);const h=t.attributes.getFloat("cubic_coeff_a",-.75),p=0!==t.attributes.getInt("exclude_outside",0);if(p&&"cubic"!==o)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const f=n<11||"nearest"===o&&"asymmetric"===u&&"floor"===d;let g=0,m=0,b=0;return n>10?t.inputs.length>2?(g=1,m=2,b=3):(m=1,b=2):9===n&&(m=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:i,mode:o,scales:s,extrapolationValue:a,coordinateTransformMode:u,useExtrapolation:c,needRoiInput:l,nearestMode:d,cubicCoefficientA:h,excludeOutside:p,useNearest2xOptimization:f,roiInputIdx:g,scalesInputIdx:m,sizesInputIdx:b})};const a=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),[a,u]=t.calculateTextureWidthAndHeight(e[0].dims,o.TextureType.unpacked),l=e[0].dims.map((t,e)=>Math.floor(t*n.scales[e])),[c,d]=t.calculateTextureWidthAndHeight(l,o.TextureType.unpacked),h=l.length,p=new Array(h),f=new Array(h);let g=`\n int output_pitches[${h}];\n int input_pitches[${h}];\n `;for(let t=h-1;t>=0;t--)p[t]=t===h-1?1:p[t+1]*l[t+1],f[t]=t===h-1?1:f[t+1]*e[0].dims[t+1],g+=`\n output_pitches[${t}] = ${p[t]};\n input_pitches[${t}] = ${f[t]};\n `;const m=`\n float getInputFloat(int index) {\n vec2 coords = offsetToCoords(index, ${a}, ${u});\n float value = getColorAsFloat(${r.texture2D}(X, coords));\n return value;\n }\n `,b="nearest"===n.mode?`\n ${m}\n float process(int indices[${h}]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int d, m;\n for (int dim = 0; dim < ${h}; ++dim) {\n d = output_index / output_pitches[dim];\n m = output_index - d * output_pitches[dim];\n output_index = m;\n\n if (scales[dim] != 1 && d > 0) {\n int d2 = d / scales[dim];\n m = d - d2 * scales[dim];\n d = d2;\n }\n input_index += input_pitches[dim] * d;\n }\n\n return getInputFloat(input_index);\n }`:4===h?`\n ${m}\n float process(int indices[4]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m / output_pitches[1];\n m = m - index_of_dim1 * output_pitches[1];\n index_of_dim2 = m / output_pitches[2];\n m = m - index_of_dim2 * output_pitches[2];\n index_of_dim3 = m;\n\n int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n index_of_input_dim2 = index_of_dim2 / scales[2];\n y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n index_of_input_dim3 = index_of_dim3 / scales[3];\n x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n input_index = index_of_dim0 * input_pitches[0] +\n index_of_dim1 * input_pitches[1] +\n index_of_input_dim2 * input_pitches[2] +\n index_of_input_dim3;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim2 = false;\n if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) {\n // It's the end in dimension 2\n x01 = x00;\n end_of_dim2 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[2]);\n }\n\n if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n // It's the end in dimension 3\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n }`:`\n ${m}\n float process(int indices[2]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${d});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m;\n\n int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n index_of_input_dim0 = index_of_dim0 / scales[0];\n y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n index_of_input_dim1 = index_of_dim1 / scales[1];\n x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim0 = false;\n if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) {\n // It's the end in dimension 0\n x01 = x00;\n end_of_dim0 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[0]);\n }\n\n if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n // It's the end in dimension 1\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n }`;return Object.assign(Object.assign({},s),{output:{dims:l,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:b,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map(t=>Math.ceil(t))}]})};e.validateInputs=(t,e)=>{if(!t||e.opset<9&&1!==t.length||e.opset>=9&&e.opset<11&&2!==t.length||e.opset>=11&&t.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&t[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if("string"===t[0].type)throw new Error("Invalid input tensor types.")},e.scalesValidation=(t,e,n)=>{if(n){for(const e of t)if(e<=0)throw new Error("Scale value should be greater than 0.")}else for(const e of t)if(e<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==e&&"cubic"!==e||2===t.length||4===t.length&&1===t[0]&&1===t[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}},1958:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProgramManager=void 0;const r=n(1670),i=n(6231),o=n(8879),s=n(5060);e.ProgramManager=class{constructor(t,e,n){this.profiler=t,this.glContext=e,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=t.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,()=>{var r;const o=this.glContext.gl,s=t.program;o.useProgram(s);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(t.attribLocations),this.bindUniforms(t.uniformLocations,null!==(r=t.programInfo.variables)&&void 0!==r?r:[],e)}catch(e){throw i.Logger.error("ProgramManager",t.programInfo.shaderSource),e}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(t=>this.glContext.deleteProgram(t.program))}build(t,e,n){return this.profiler.event("backend","ProgramManager.build",()=>{const r=new o.GlslPreprocessor(this.glContext,t,e,n),i=r.preprocess(),s=this.compile(i);return{programInfo:t,program:s,uniformLocations:this.getUniformLocations(s,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(s)}})}compile(t){if(!this.vertexShader){i.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const t=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(t,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&i.Logger.verbose("ProrgramManager",`FragShader:\n${t}\n`);const e=this.glContext.compileShader(t,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,e);return this.glContext.deleteShader(e),n}bindOutput(t){const e=t.width,n=t.height;i.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${e}/${n}, shape=${t.shape}, type=${t.tensor.type}`),this.glContext.attachFramebuffer(t.texture,e,n)}bindAttributes(t){const e=t.position,n=t.textureCoord;this.glContext.setVertexAttributes(e,n),this.attributesBound=!0}bindUniforms(t,e,n){var r;const i=this.glContext.gl;let o=0;for(const{name:s,type:a,location:u,arrayLength:l}of t){const t=null===(r=e.find(t=>t.name===s))||void 0===r?void 0:r.data;if("sampler2D"!==a&&!t)throw new Error(`variable '${s}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(n[o],u,o),o++;break;case"float":l?i.uniform1fv(u,t):i.uniform1f(u,t);break;case"int":l?i.uniform1iv(u,t):i.uniform1i(u,t);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(t,e,n){this.glContext.bindTextureToUniform(t.texture,n,e)}getAttribLocations(t){return{position:this.getAttribLocation(t,"position"),textureCoord:this.getAttribLocation(t,"textureCoord")}}getUniformLocations(t,e,n){const r=[];if(e)for(const n of e)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(t,n)});if(n)for(const e of n)r.push(Object.assign(Object.assign({},e),{location:this.getUniformLocation(t,e.name)}));return r}getUniformLocation(t,e){const n=this.glContext.gl.getUniformLocation(t,e);if(null===n)throw new Error(`Uniform ${e} not found.`);return n}getAttribLocation(t,e){return this.glContext.gl.getAttribLocation(t,e)}}},6416:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLSessionHandler=void 0;const r=n(6231),i=n(1047),o=n(8316),s=n(1640),a=n(1958),u=n(7859),l=n(5702);e.WebGLSessionHandler=class{constructor(t,e){this.backend=t,this.context=e,this.layoutStrategy=new u.PreferLogicalStrategy(t.glContext.maxTextureSize),this.programManager=new a.ProgramManager(this.context.profiler,t.glContext,this.layoutStrategy),this.textureManager=new l.TextureManager(t.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===t.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=t.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new o.WebGLInferenceHandler(this)}onGraphInitialized(t){const e=t.getValues().filter(t=>-1===t.from&&t.tensor).map(t=>t.tensor.dataId);this.initializers=new Set(e)}isInitializer(t){return!!this.initializers&&this.initializers.has(t)}addInitializer(t){this.initializers.add(t)}getTextureData(t,e){return e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(t,e):this.unpackedTextureDataCache.set(t,e)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(t=>this.textureManager.releaseTexture(t,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(t=>this.textureManager.releaseTexture(t,!0)),this.unpackedTextureDataCache=new Map}resolve(t,e,n){const r=(0,i.resolveOperator)(t,e,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(t,n):t}}}},7769:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Uint8DataEncoder=e.RGBAFloatDataEncoder=e.RedFloat32DataEncoder=void 0;const r=n(6231);e.RedFloat32DataEncoder=class{constructor(t,e=1){if(1===e)this.internalFormat=t.R32F,this.format=t.RED,this.textureType=t.FLOAT,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA32F,this.format=t.RGBA,this.textureType=t.FLOAT,this.channelSize=e}}encode(t,e){let n,i;return t.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(t)),e*this.channelSize>t.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),i=t,n=this.allocate(e*this.channelSize),i.forEach((t,e)=>n[e]=t)):(i=t,n=i),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter((t,e)=>e%4==0).subarray(0,e):t.subarray(0,e)}},e.RGBAFloatDataEncoder=class{constructor(t,e=1,n){if(1!==e&&4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.channelSize=e,this.textureType=n||t.FLOAT}encode(t,e){let n=t;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(e),t.forEach((t,e)=>n[4*e]=t)),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter((t,e)=>e%4==0).subarray(0,e):t.subarray(0,e)}},e.Uint8DataEncoder=class{constructor(t,e=1){if(this.channelSize=4,1===e)this.internalFormat=t.ALPHA,this.format=t.ALPHA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e}}encode(t,e){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}allocate(t){return new Uint8Array(t*this.channelSize)}decode(t,e){if(t instanceof Uint8Array)return t.subarray(0,e);throw new Error(`Invalid array type: ${t.constructor}`)}}},7859:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getBatchDim=e.sizeToSquarishShape=e.getRowsCols=e.sizeFromShape=e.isInt=e.parseAxisParam=e.squeezeShape=e.PreferLogicalStrategy=e.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(6231),i=n(2517);function o(t,e){const n=[],r=[],i=null!=e&&Array.isArray(e)&&0===e.length,o=null==e||i?null:s(e,t).sort();let a=0;for(let e=0;e<t.length;++e){if(null!=o){if(o[a]===e&&1!==t[e])throw new Error(`Can't squeeze axis ${e} since its dim '${t[e]}' is not 1`);(null==o[a]||o[a]>e)&&1===t[e]&&(n.push(t[e]),r.push(e)),o[a]<=e&&a++}1!==t[e]&&(n.push(t[e]),r.push(e))}return{newShape:n,keptDims:r}}function s(t,e){const n=e.length;return t=null==t?e.map((t,e)=>e):[].concat(t),(0,i.assert)(t.every(t=>t>=-n&&t<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${t}`),(0,i.assert)(t.every(a),()=>`All values in axis param must be integers but got axis ${t}`),t.map(t=>t<0?n+t:t)}function a(t){return t%1==0}function u(t){if(0===t.length)return 1;let e=t[0];for(let n=1;n<t.length;n++)e*=t[n];return e}function l(t){const e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}e.AlwaysKeepOriginalSizeStrategy=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){if(0===t.length)return[1,1];const n=this.maxTextureSize;if(e&&void 0!==e.breakAxis){const i=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce((t,e)=>t*e),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce((t,e)=>t*e);if(!(i>n||o>n))return[i,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}const i=t.reduce((t,e)=>t*e);let o=Math.floor(Math.sqrt(i));for(;o<n&&o<i&&i%o!=0;o++);if(o>=n||i%o!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${t}`);return[o,i/o]}},e.PreferLogicalStrategy=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){const n=this.computeTexture(t,e);return e&&e.isPacked&&(n[0]/=2,n[1]/=2),e&&e.reverseWH?[n[1],n[0]]:n}computeTexture(t,e){const n=e&&e.isPacked;if(0===t.length)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(e&&void 0!==e.breakAxis){const n=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce((t,e)=>t*e),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce((t,e)=>t*e);if(!(n>i||o>i))return[n,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}let s=t.slice(0);if(n&&(i*=2,s=s.map((t,e)=>e>=s.length-2?s[e]%2==0?s[e]:s[e]+1:s[e]),1===s.length&&(s=[2,s[0]])),2!==s.length){const t=o(s);s=t.newShape}const a=u(s);return s.length<=1&&a<=i?[1,a]:2===s.length&&s[0]<=i&&s[1]<=i?s:3===s.length&&s[0]*s[1]<=i&&s[2]<=i?[s[0]*s[1],s[2]]:3===s.length&&s[0]<=i&&s[1]*s[2]<=i?[s[0],s[1]*s[2]]:4===s.length&&s[0]*s[1]*s[2]<=i&&s[3]<=i?[s[0]*s[1]*s[2],s[3]]:4===s.length&&s[0]<=i&&s[1]*s[2]*s[3]<=i?[s[0],s[1]*s[2]*s[3]]:n?l(a/4).map(t=>2*t):l(a)}},e.squeezeShape=o,e.parseAxisParam=s,e.isInt=a,e.sizeFromShape=u,e.getRowsCols=function(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]},e.sizeToSquarishShape=l,e.getBatchDim=function(t,e=2){return u(t.slice(0,t.length-e))}},4057:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createTextureLayoutFromShape=e.calculateTextureWidthAndHeight=e.createTextureLayoutFromTextureType=void 0;const r=n(2517),i=n(2039);e.createTextureLayoutFromTextureType=(t,n,r)=>{const o=r===i.TextureType.unpacked||r===i.TextureType.unpackedReversed?1:4,s=r===i.TextureType.packed,a=r===i.TextureType.unpackedReversed||r===i.TextureType.packed,u=r===i.TextureType.packedLastDimension?n.length-1:void 0,l=r===i.TextureType.packedLastDimension?n.map((t,e)=>e===n.length-1?4*t:t):void 0;return(0,e.createTextureLayoutFromShape)(t,n,o,l,{isPacked:s,reverseWH:a,breakAxis:u})},e.calculateTextureWidthAndHeight=(t,n,r)=>{const i=(0,e.createTextureLayoutFromTextureType)(t,n,r);return[i.width,i.height]},e.createTextureLayoutFromShape=(t,e,n=1,i,o)=>{const s=!(!o||!o.isPacked),[a,u]=t.computeTextureWH(s&&i||e,o),l=e.length;let c=e.slice(0);if(0===l&&(c=[1]),1===n)i=e;else if(s){if(4!==n)throw new Error("a packed texture must be 4-channel");i=e,l>0&&(c[l-1]=Math.ceil(c[l-1]/2)),l>1&&(c[l-2]=Math.ceil(c[l-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:a,height:u,channels:n,isPacked:s,shape:c,strides:r.ShapeUtil.computeStrides(c),unpackedShape:i,reversedWH:o&&o.reverseWH}}},5702:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TextureManager=void 0;const r=n(6231);e.TextureManager=class{constructor(t,e,n,r){this.glContext=t,this.layoutStrategy=e,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(t,e,n,i){const o=this.toEncoderType(t),s=this.glContext.getEncoder(o,e.channels||1,i);if(e.isPacked&&1===i)throw new Error("not implemented");const a=e.width,u=e.height;let l,c;if(this.config.reuseTextures){l=`${a}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`,c=this.inUseTextures.get(l),c||(c=[],this.inUseTextures.set(l,c));const e=this.idleTextures.get(l);if(e&&e.length>0){const r=e.pop();return c.push(r),1===i&&this.glContext.updateTexture(r,a,u,s,this.toTextureData(t,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${e.width}x${e.height}`);const d=this.glContext.allocateTexture(a,u,s,this.toTextureData(t,n));return this.config.reuseTextures&&(c.push(d),this.textureLookup.set(d,l)),d}readTexture(t,e,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",()=>{const r=t.shape.reduce((t,e)=>t*e)*n,i=this.glContext.readTexture(t.texture,t.width,t.height,r,this.toEncoderType(e),n);return this.toTensorData(e,i)})}async readTextureAsync(t,e,n){const r=t.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const t=this.pendingRead.get(r);return new Promise(e=>null==t?void 0:t.push(e))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(r,[]);const i=t.shape.reduce((t,e)=>t*e)*n;await this.glContext.createAndWaitForFence();const o=this.glContext.readTexture(t.texture,t.width,t.height,i,this.toEncoderType(e),n),s=this.toTensorData(e,o),a=this.pendingRead.get(r);return this.pendingRead.delete(r),null==a||a.forEach(t=>t(s)),s})}readUint8TextureAsFloat(t){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{const e=t.shape.reduce((t,e)=>t*e),n=this.glContext.readTexture(t.texture,t.width,t.height,4*e,"byte",4);return new Float32Array(n.buffer,n.byteOffset,e)})}releaseTexture(t,e){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(t.texture),n)){e&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const e=r.indexOf(t.texture);if(-1!==e){r.splice(e,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(t.texture)}}}n&&!e||(r.Logger.verbose("TextureManager",`Deleting texture of size ${t.width}x${t.height}`),this.glContext.deleteTexture(t.texture))}toTensorData(t,e){switch(t){case"int16":return e instanceof Int16Array?e:Int16Array.from(e);case"int32":return e instanceof Int32Array?e:Int32Array.from(e);case"int8":return e instanceof Int8Array?e:Int8Array.from(e);case"uint16":return e instanceof Uint16Array?e:Uint16Array.from(e);case"uint32":return e instanceof Uint32Array?e:Uint32Array.from(e);case"uint8":case"bool":return e instanceof Uint8Array?e:Uint8Array.from(e);case"float32":return e instanceof Float32Array?e:Float32Array.from(e);case"float64":return e instanceof Float64Array?e:Float64Array.from(e);default:throw new Error(`TensorData type ${t} is not supported`)}}toTextureData(t,e){if(e)return e instanceof Float32Array?e:new Float32Array(e)}toEncoderType(t){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(t,e)=>{var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TextureType=void 0,(n=e.TextureType||(e.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},9390:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getGlChannels=e.getCoordsDataType=e.getSqueezedParams=e.squeezeInputShape=e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=e.generateShaderFuncNameFromInputSamplerName=e.repeatedTry=e.getPackedShape=void 0;const r=n(2517);e.getPackedShape=function(t){const e=t.length;return t.slice(0,e-1).concat(t[e-1]/4)},e.repeatedTry=async function(t,e=t=>0,n){return new Promise((r,i)=>{let o=0;const s=()=>{if(t())return void r();o++;const a=e(o);null!=n&&o>=n?i():setTimeout(s,a)};s()})},e.generateShaderFuncNameFromInputSamplerName=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,()=>"empty string found for sampler name"),"get"+t.charAt(0).toUpperCase()+t.slice(1)},e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,()=>"empty string found for sampler name"),"get"+t.charAt(0).toUpperCase()+t.slice(1)+"AtOutCoords"},e.squeezeInputShape=function(t,e){let n=JSON.parse(JSON.stringify(t));return n=e,n},e.getSqueezedParams=function(t,e){return e.map(e=>t[e]).join(", ")},e.getCoordsDataType=function(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error(`GPU for rank ${t} is not yet supported`)},e.getGlChannels=function(t=6){return["x","y","z","w","u","v"].slice(0,t)}},7305:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createNewWebGLContext=e.createWebGLContext=void 0;const r=n(6231),i=n(1713),o={};function s(t){const e=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)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 n;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!t||"webgl2"===t)&&(n=e.getContext("webgl2",o),n))try{return new i.WebGLContext(n,2)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!t||"webgl"===t)&&(n=e.getContext("webgl",o)||e.getContext("experimental-webgl",o),n))try{return new i.WebGLContext(n,1)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}e.createWebGLContext=function t(e){let n;e&&"webgl2"!==e||!("webgl2"in o)?e&&"webgl"!==e||!("webgl"in o)||(n=o.webgl):n=o.webgl2,n=n||s(e),e=e||1===n.version?"webgl":"webgl2";const r=n.gl;return o[e]=n,r.isContextLost()?(delete o[e],t(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},e.createNewWebGLContext=s},1713:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=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 i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLContext=e.linearSearchLastTrue=void 0;const s=n(1670),a=o(n(7769)),u=n(9390);function l(t){let e=0;for(;e<t.length&&t[e]();++e);return e-1}e.linearSearchLastTrue=l,e.WebGLContext=class{constructor(t,e){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=t,this.version=e,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(t,e,n,r){const i=this.gl,o=i.createTexture();i.bindTexture(i.TEXTURE_2D,o),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE);const s=r?n.encode(r,t*e):null;return i.texImage2D(i.TEXTURE_2D,0,n.internalFormat,t,e,0,n.format,n.textureType,s),this.checkError(),o}updateTexture(t,e,n,r,i){const o=this.gl;o.bindTexture(o.TEXTURE_2D,t);const s=r.encode(i,e*n);o.texSubImage2D(o.TEXTURE_2D,0,0,0,e,n,r.format,r.textureType,s),this.checkError()}attachFramebuffer(t,e,n){const r=this.gl;r.bindTexture(r.TEXTURE_2D,t),r.bindFramebuffer(r.FRAMEBUFFER,this.framebuffer),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t,0),this.checkError(),r.viewport(0,0,e,n),r.scissor(0,0,e,n)}readTexture(t,e,n,r,i,o){const s=this.gl;o||(o=1),this.frameBufferBound||this.attachFramebuffer(t,e,n);const a=this.getEncoder(i,o),u=a.allocate(e*n);return s.bindTexture(s.TEXTURE_2D,t),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,t,0),s.readPixels(0,0,e,n,s.RGBA,a.textureType,u),this.checkError(),a.decode(u,r)}isFramebufferReady(){return!0}getActiveTexture(){const t=this.gl;return"TEXTURE"+(t.getParameter(this.gl.ACTIVE_TEXTURE)-t.TEXTURE0)}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(t,e){const n=this.gl;n.vertexAttribPointer(t,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(t),-1!==e&&(n.vertexAttribPointer(e,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(e)),this.checkError()}createProgram(t,e){const n=this.gl,r=n.createProgram();return n.attachShader(r,t),n.attachShader(r,e),n.linkProgram(r),r}compileShader(t,e){const n=this.gl,r=n.createShader(e);if(!r)throw new Error(`createShader() returned null with type ${e}`);if(n.shaderSource(r,t),n.compileShader(r),!1===n.getShaderParameter(r,n.COMPILE_STATUS))throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(r)}\nShader source:\n${t}`);return r}deleteShader(t){this.gl.deleteShader(t)}bindTextureToUniform(t,e,n){const r=this.gl;r.activeTexture(r.TEXTURE0+e),this.checkError(),r.bindTexture(r.TEXTURE_2D,t),this.checkError(),r.uniform1i(n,e),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(s.env.debug){const t=this.gl,e=t.getError();let n="";switch(e){case t.NO_ERROR:return;case t.INVALID_ENUM:n="INVALID_ENUM";break;case t.INVALID_VALUE:n="INVALID_VALUE";break;case t.INVALID_OPERATION:n="INVALID_OPERATION";break;case t.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case t.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case t.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${e.toString(16)}`}throw new Error(n)}}deleteTexture(t){this.gl.deleteTexture(t)}deleteProgram(t){this.gl.deleteProgram(t)}getEncoder(t,e,n=0){if(2===this.version)return new a.RedFloat32DataEncoder(this.gl,e);switch(t){case"float":return 1===n||this.isRenderFloat32Supported?new a.RGBAFloatDataEncoder(this.gl,e):new a.RGBAFloatDataEncoder(this.gl,e,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new a.Uint8DataEncoder(this.gl,e);default:throw new Error(`Invalid dataType: ${t}`)}}clearActiveTextures(){const t=this.gl;for(let e=0;e<this.maxTextureImageUnits;++e)t.activeTexture(t.TEXTURE0+e),t.bindTexture(t.TEXTURE_2D,null)}dispose(){if(this.disposed)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteFramebuffer(this.framebuffer),t.bindBuffer(t.ARRAY_BUFFER,null),t.deleteBuffer(this.vertexbuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null),t.finish(),this.disposed=!0}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){const t=this.gl,e=t.createBuffer();if(!e)throw new Error("createBuffer() returned null");const n=this.createDefaultGeometry();return t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW),this.checkError(),e}createFramebuffer(){const t=this.gl.createFramebuffer();if(!t)throw new Error("createFramebuffer returned null");return t}queryVitalParameters(){const t=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),1===this.version&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw new Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.version}getExtensions(){2===this.version?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){const t=this.gl,e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);const n=2===this.version?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,n,1,1,0,t.RGBA,t.FLOAT,null);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0);const i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(e),t.deleteFramebuffer(r),i}checkRenderFloat32(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension)return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(2===this.version){if(!this.colorBufferFloatExtension)return!1}else{if(!this.textureFloatExtension)return!1;if(!this.gl.getExtension("WEBGL_color_buffer_float"))return!1}return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){const t=this.gl;let e,n,r,i,o;try{e=t.createTexture(),n=t.createFramebuffer(),t.bindTexture(t.TEXTURE_2D,e);const s=2===this.version?t.RGBA32F:t.RGBA;return t.texImage2D(t.TEXTURE_2D,0,s,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),t.enable(t.BLEND),r=t.createShader(t.VERTEX_SHADER),!!r&&(t.shaderSource(r,"void main(){}"),t.compileShader(r),i=t.createShader(t.FRAGMENT_SHADER),!!i&&(t.shaderSource(i,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),t.compileShader(i),o=t.createProgram(),!!o&&(t.attachShader(o,r),t.attachShader(o,i),t.linkProgram(o),t.useProgram(o),t.drawArrays(t.POINTS,0,1),t.getError()===t.NO_ERROR)))}finally{t.disable(t.BLEND),o&&t.deleteProgram(o),r&&t.deleteShader(r),i&&t.deleteShader(i),n&&(t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteFramebuffer(n)),e&&(t.bindTexture(t.TEXTURE_2D,null),t.deleteTexture(e))}}beginTimer(){if(2===this.version&&this.disjointTimerQueryWebgl2Extension){const t=this.gl,e=this.disjointTimerQueryWebgl2Extension,n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}throw new Error("WebGL1 profiling currently not supported.")}endTimer(){if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const t=this.gl,e=this.disjointTimerQueryWebgl2Extension;t.endQuery(e.TIME_ELAPSED_EXT)}}isTimerResultAvailable(t){let e=!1,n=!1;if(2!==this.version||!this.disjointTimerQueryWebgl2Extension)throw new Error("WebGL1 profiling currently not supported");{const r=this.gl,i=this.disjointTimerQueryWebgl2Extension;e=r.getQueryParameter(t,r.QUERY_RESULT_AVAILABLE),n=r.getParameter(i.GPU_DISJOINT_EXT)}return e&&!n}getTimerResult(t){let e=0;if(2!==this.version)throw new Error("WebGL1 profiling currently not supported");{const n=this.gl;e=n.getQueryParameter(t,n.QUERY_RESULT),n.deleteQuery(t)}return e/1e6}async waitForQueryAndGetTime(t){return await(0,u.repeatedTry)(()=>this.isTimerResultAvailable(t)),this.getTimerResult(t)}async createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e;const n=t,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),e=null===r?()=>!0:()=>{const t=n.clientWaitSync(r,0,0);return t===n.ALREADY_SIGNALED||t===n.CONDITION_SATISFIED},{query:r,isFencePassed:e}}async pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){const t=l(this.itemsToPoll.map(t=>t.isDoneFn));for(let e=0;e<=t;++e){const{resolveFn:t}=this.itemsToPoll[e];t()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}async addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||await(0,u.repeatedTry)(()=>(this.pollItems(),0===this.itemsToPoll.length))}}},1036:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ExecutionPlan=void 0;const r=n(6231);class i{constructor(t,e){this.op=t,this.node=e}}e.ExecutionPlan=class{constructor(t,e,n){this.graph=t,this.profiler=n,this.initialize(e)}initialize(t){this.profiler.event("session","ExecutionPlan.initialize",()=>{const e=this.graph.getNodes();if(e.length!==t.length)throw new Error("The size of nodes and OPs do not match.");this._ops=t.map((t,n)=>new i(t,e[n])),this.reset(),this._starter=[],this._ops.forEach((t,e)=>{let n=!0;for(const e of t.node.inputs)if(!this._values[e]&&-1===this.graph.getInputIndices().indexOf(e)){n=!1;break}n&&this._starter.push(e)})})}reset(){this._values=this.graph.getValues().map(t=>t.tensor)}async execute(t,e){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const n=t.createInferenceHandler(),i=this.graph.getInputIndices();if(e.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${i.length}`);e.forEach((t,e)=>{const n=i[e];this._values[n]=t});const o=this._starter.slice(0),s=this.graph.getValues(),a=this.graph.getNodes();let u=0;for(;u<o.length;){const t=o[u++],e=this._ops[t],i=e.node.inputs.map(t=>this._values[t]);if(-1!==i.indexOf(void 0))throw new Error(`unresolved input detected: op: ${e.node}`);const l=i;r.Logger.verbose("ExecPlan",`Runing op:${e.node.name} (${l.map((t,n)=>`'${e.node.inputs[n]}': ${t.type}[${t.dims.join(",")}]`).join(", ")})`);const c=await this.profiler.event("node",e.node.name,async()=>e.op.impl(n,l,e.op.context));if(c.length!==e.node.outputs.length)throw new Error("the size of output does not match model definition.");c.forEach((t,n)=>{const r=e.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${e.node.name}`);this._values[r]=t});const d=new Set;c.forEach((t,n)=>{const r=e.node.outputs[n];for(const t of s[r].to){const e=a[t];let n=!0;for(const t of e.inputs)if(!this._values[t]){n=!1;break}n&&d.add(t)}}),o.push(...d)}const l=[];for(let t=0;t<this.graph.getOutputIndices().length;t++){const e=this.graph.getOutputIndices()[t],n=this._values[e];if(void 0===n)throw new Error(`required output [${e}] does not have value`);0===e?await n.getData():n.data,l.push(n)}return r.Logger.verbose("ExecPlan","disposing of inferenceHandler"),n.dispose(),l})}}},7070:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Graph=void 0;const r=n(1446),i=n(7778),o=n(9395),s=n(9162),a=n(2517);var u=o.onnxruntime.experimental.fbs;e.Graph={from:(t,e)=>new d(t,e)};class l{constructor(t){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,t&&(this.type=a.ProtoUtil.tensorValueTypeFromProto(t.type.tensorType))}get from(){return this._from}get to(){return this._to}}class c{constructor(t,e){t instanceof r.onnx.NodeProto?(this.name=t.name,this.opType=t.opType,this.attributes=new i.Attribute(t.attribute)):t instanceof u.Node&&(this.name=null!=e?e:t.name(),this.opType=t.opType(),this.attributes=new i.Attribute(a.ProtoUtil.tensorAttributesFromORTFormat(t))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class d{constructor(t,e){if(!t)throw new TypeError("graph is empty");this.buildGraph(t),this.transformGraph(e),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(t){if(t instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(t);else{if(!(t instanceof u.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(t)}}buildGraphFromOnnxFormat(t){const e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!t.input)throw new Error("missing information in graph: input");const r=[];for(const n of t.input){if(e.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const t=this._allData.push(new l(n))-1;e.set(n.name,t),r.push(n.name)}if(!t.initializer)throw new Error("missing information in graph: initializer");for(const n of t.initializer){let t=e.get(n.name);if(void 0===t){const r=new l;r.type={shape:{dims:a.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:a.ProtoUtil.tensorDataTypeFromProto(n.dataType)},t=this._allData.push(r)-1,e.set(n.name,t)}this._allData[t]._from=-1,this._allData[t].tensor=s.Tensor.fromProto(n)}for(let t=0;t<this._allData.length;t++)this._allData[t].tensor||(this._allInputIndices.push(t),this._allInputNames.push(r[t]));if(!t.output)throw new Error("missing information in graph: output");for(const n of t.output){if(e.has(n.name))throw new Error(`duplicated output name: ${n.name}`);const t=this._allData.push(new l(n))-1;e.set(n.name,t),this._allOutputIndices.push(t),this._allOutputNames.push(n.name)}if(!t.node)throw new Error("missing information in graph: node");for(const e of t.node){if(!e.name)for(let t=0;;t++){const r=`unnamed_${e.opType}_${t}`;if(!n.has(r)){e.name=r;break}}if(n.has(e.name))throw new Error(`duplicated node name: ${e.name}`);const t=this._nodes.push(new c(e))-1;n.set(e.name,t)}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=t.node[n];if(!i.output)throw new Error(`missing output for node: ${i.name}`);for(const t of i.output){let o=e.get(t);if(void 0===o&&(o=this._allData.push(new l)-1,e.set(t,o)),r.outputs.push(o),void 0!==this._allData[o]._from)throw new Error(`multiple nodes output to one data value: ${o}`);if(this._allData[o]._from=n,"Constant"===i.opType){if(!i.attribute||1!==i.attribute.length||!i.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!i.output||1!==i.output.length)throw new Error("missing output or incorrect number of outputs for this Constant operator");r.outputs.pop(),r.executeNode=!1,this._allData[o]._from=-1,this._allData[o].tensor=s.Tensor.fromProto(i.attribute[0].t)}}}for(let n=0;n<this._nodes.length;n++){const r=this._nodes[n],i=t.node[n];if(!i.input)throw new Error(`missing input for node: ${i.name}`);for(const t of i.input){const o=e.get(t);if(void 0===o){if(""===t&&3===i.input.length&&"Resize"===i.opType)continue;throw new Error(`unrecognized input '${t}' for node: ${i.name}`)}r.inputs.push(o),this._allData[o]._to.push(n)}}return!0}buildGraphFromOrtFormat(t){var e,n,r;const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const o=new Map,d=[];for(let o=0;o<t.inputsLength();o++){const s=t.inputs(o);if(i.has(s))throw new Error(`duplicated input name: ${s}`);for(let o=0;o<t.nodeArgsLength();o++)if((null===(e=t.nodeArgs(o))||void 0===e?void 0:e.name())===s){const e=new l;if((null===(r=null===(n=t.nodeArgs(o))||void 0===n?void 0:n.type())||void 0===r?void 0:r.valueType())!==u.TypeInfoValue.tensor_type)throw new Error("Unexpected value type for the nodeArg.");const c=t.nodeArgs(o).type().value(new u.TensorTypeAndShape),h=a.ProtoUtil.tensorDataTypeFromProto(c.elemType()),p=c.shape(),f=[];for(let t=0;t<p.dimLength();t++)f.push(a.LongUtil.longToNumber(p.dim(t).value().dimValue()));e.type={shape:{dims:f},tensorType:h};const g=this._allData.push(e)-1;i.set(s,g),d.push(s)}}for(let e=0;e<t.initializersLength();e++){const n=t.initializers(e);let r=i.get(n.name());if(void 0===r){const t=new l,e=a.ProtoUtil.tensorDimsFromORTFormat(n),o=a.ProtoUtil.tensorDataTypeFromProto(n.dataType());t.type={shape:{dims:e},tensorType:o},r=this._allData.push(t)-1,i.set(n.name(),r)}this._allData[r]._from=-1,this._allData[r].tensor=s.Tensor.fromOrtTensor(n)}for(let t=0;t<this._allData.length;t++)this._allData[t].tensor||(this._allInputIndices.push(t),this._allInputNames.push(d[t]));for(let e=0;e<t.outputsLength();e++){const n=t.outputs(e);if(i.has(n))throw new Error(`duplicated output name: ${n}`);const r=this._allData.push(new l)-1;i.set(n,r),this._allOutputIndices.push(r),this._allOutputNames.push(n)}if(!t.nodes)throw new Error("missing information in graph: node");for(let e=0;e<t.nodesLength();e++){const n=t.nodes(e);let r=n.name();if(!r)for(let t=0;r=`unnamed_${n.opType()}_${t}`,o.has(r);t++);if(o.has(r))throw new Error(`duplicated node name: ${r}`);const i=this._nodes.push(new c(n,r))-1;o.set(r,i)}for(let e=0;e<this._nodes.length;e++){const n=this._nodes[e],r=t.nodes(e);if(null==r)throw new Error(`No node exists at index ${e}`);if(0===(null==r?void 0:r.outputsLength()))throw new Error(`missing output for node: ${r.name}`);for(let t=0;t<(null==r?void 0:r.outputsLength());t++){const o=null==r?void 0:r.outputs(t);let a=i.get(o);if(void 0===a&&(a=this._allData.push(new l)-1,i.set(o,a)),n.outputs.push(a),void 0!==this._allData[a]._from)throw new Error(`multiple nodes output to one data value: ${a}`);if(this._allData[a]._from=e,"Constant"===r.opType()){if(1!==r.attributesLength()||!r.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(1!==r.outputsLength())throw new Error("missing output or incorrect number of outputs for this Constant operator");n.outputs.pop(),n.executeNode=!1,this._allData[a]._from=-1,this._allData[a].tensor=s.Tensor.fromOrtTensor(r.attributes(0).t())}}}for(let e=0;e<this._nodes.length;e++){const n=this._nodes[e],r=t.nodes(e);if(0===r.inputsLength())throw new Error(`missing input for node: ${r.name}`);for(let t=0;t<r.inputsLength();t++){const o=r.inputs(t),s=i.get(o);if(void 0===s)throw new Error(`unrecognized input '${o}' for node: ${r.name()}`);n.inputs.push(s),this._allData[s]._to.push(e)}}}checkIsAcyclic(){const t=new Set;this._allInputIndices.forEach(e=>{this._allData[e]._to.forEach(e=>{t.add(e)})});const e=Array.from(t),n=new Array(this._nodes.length).fill("white");for(;e.length>0;){const t=e.pop();"gray"===n[t]?n[t]="black":(e.push(t),n[t]="gray",this._nodes[t].outputs.forEach(r=>{const i=this._allData[r];if(void 0!==i.tensor)throw new Error("node outputs should not be initialized");if(i._from!==t)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach(t=>{if("gray"===n[t])throw new Error("model graph is cyclic");"white"===n[t]&&e.push(t)})}))}}transformGraph(t){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),t&&t.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let t=0;for(let e=0;e<this._nodes.length;e++)this._nodes[e].executeNode?t>0&&(this._nodes[e].inputs.forEach(n=>{const r=this._allData[n]._to.indexOf(e+t);-1!==r&&(this._allData[n]._to[r]=e)}),this._nodes[e].outputs.forEach(n=>{this._allData[n]._from&&this._allData[n]._from===e+t&&(this._allData[n]._from=e)})):(t++,this._nodes[e].outputs.forEach(t=>{this._allData[t]._from=-2}),this._nodes.splice(e,1),e--);t=0;for(let e=0;e<this._allData.length;e++)if(-2!==this._allData[e].from||-1!==this._allOutputIndices.indexOf(e+t)){if(t>0){let n=-1;void 0!==this._allData[e].from&&-1!==this._allData[e].from?(n=this._nodes[this._allData[e].from].outputs.indexOf(e+t),-1!==n&&(this._nodes[this._allData[e].from].outputs[n]=e)):(n=this._allInputIndices.indexOf(e+t),-1!==n&&(this._allInputIndices[n]=e)),this._allData[e].to.forEach(r=>{n=this._nodes[r].inputs.indexOf(e+t),-1!==n&&(this._nodes[r].inputs[n]=e)}),0===this._allData[e].to.length&&(n=this._allOutputIndices.indexOf(e+t),-1!==n&&(this._allOutputIndices[n]=e))}}else t++,this._allData.splice(e,1),e--}deleteNode(t){const e=this._nodes[t];if(e.outputs.length>1)for(let t=1;t<e.outputs.length;t++)if(this._allData[e.outputs[t]].to.length>0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");e.executeNode=!1;const n=e.inputs[0],r=e.outputs[0],i=this._allData[r].to,o=this._allData[n].to.indexOf(t);if(-1===o)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[n].to.splice(o,1),this._allData[r]._to=[];const s=this._allOutputIndices.indexOf(r);if(-1!==s&&(this._allOutputIndices[s]=n),i&&i.length>0)for(const t of i){const e=this._nodes[t].inputs.indexOf(r);if(-1===e)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[t].inputs[e]=n,this._allData[n].to.push(t)}}removeAllDropoutNodes(){let t=0;for(const e of this._nodes){if("Dropout"===e.opType){if(1!==e.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==e.outputs.length&&2!==e.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===e.outputs.length&&0!==this._allData[e.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(t)}t++}}removeAllIdentityNodes(){let t=0;for(const e of this._nodes)"Identity"===e.opType&&this.deleteNode(t),t++}isActivation(t){switch(t.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const t of this._nodes)if("Conv"===t.opType){const e=this._allData[t.outputs[0]]._to;if(1===e.length&&this.isActivation(this._nodes[e[0]])){const n=this._nodes[e[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{t.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(e){t.attributes.set("activation_params","floats",[a.MIN_CLIP,a.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;t.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}t.attributes.set("activation","string",n.opType),this.deleteNode(e[0])}}}}},6231:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.now=e.Profiler=e.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(t,e,n){}},console:new class{log(t,e,n){console.log(`${this.color(t)} ${n?"[35m"+n+"[0m ":""}${e}`)}color(t){switch(t){case"verbose":return"[34;40mv[0m";case"info":return"[32mi[0m";case"warning":return"[30;43mw[0m";case"error":return"[31;40me[0m";case"fatal":return"[101mf[0m";default:throw new Error(`unsupported severity: ${t}`)}}}},i={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let o={"":i};function s(t,e,n,r){if(void 0===e)return i=t,{verbose:s.verbose.bind(null,i),info:s.info.bind(null,i),warning:s.warning.bind(null,i),error:s.error.bind(null,i),fatal:s.fatal.bind(null,i)};if(void 0===n)a(t,e);else if("number"==typeof n&&void 0===r)a(t,e);else if("string"==typeof n&&void 0===r)a(t,n,0,e);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");a(t,n,0,e)}var i}function a(t,e,i,s){const a=o[s||""]||o[""];n[t]<n[a.minimalSeverity]||(a.logDateTime&&(e=`${(new Date).toISOString()}|${e}`),a.logSourceLocation,r[a.provider].log(t,e,s))}!function(t){function e(t){o={},n("",t||{})}function n(t,n){if("*"===t)e(n);else{const e=o[t]||i;o[t]={provider:n.provider||e.provider,minimalSeverity:n.minimalSeverity||e.minimalSeverity,logDateTime:void 0===n.logDateTime?e.logDateTime:n.logDateTime,logSourceLocation:void 0===n.logSourceLocation?e.logSourceLocation:n.logSourceLocation}}}t.verbose=function(e,n){t("verbose",e,n)},t.info=function(e,n){t("info",e,n)},t.warning=function(e,n){t("warning",e,n)},t.error=function(e,n){t("error",e,n)},t.fatal=function(e,n){t("fatal",e,n)},t.reset=e,t.set=n,t.setWithEnv=function(t){const e={};t.logLevel&&(e.minimalSeverity=t.logLevel),n("",e)}}(s||(s={})),e.Logger=s;class u{constructor(t,e,n,r,i,o){this.category=t,this.name=e,this.startTime=n,this.endCallback=r,this.timer=i,this.ctx=o}end(){return this.endCallback(this)}async checkTimer(){if(void 0===this.ctx||void 0===this.timer)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}}class l{constructor(t,e,n,r){this.category=t,this.name=e,this.startTime=n,this.endTime=r}}e.Profiler=class{static create(t){return void 0===t?new this:new this(t.maxNumberEvents,t.flushBatchSize,t.flushIntervalInMilliseconds)}constructor(t,e,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=void 0===t?1e4:t,this._flushBatchSize=void 0===e?10:e,this._flushIntervalInMilliseconds=void 0===n?5e3:n}start(){this._started=!0,this._timingEvents=[],this._flushTime=(0,e.now)(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer])}event(t,e,n,r){const i=this._started?this.begin(t,e,r):void 0;let o=!1;const s=n();if(s&&"function"==typeof s.then)return o=!0,new Promise((t,e)=>{s.then(async e=>{i&&await i.end(),t(e)},async t=>{i&&await i.end(),e(t)})});if(!o&&i){const t=i.end();if(t&&"function"==typeof t.then)return new Promise((e,n)=>{t.then(()=>{e(s)},t=>{n(t)})})}return s}begin(t,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,e.now)();return this.flush(r),new u(t,n,r,t=>this.endSync(t))}{const e=r.beginTimer();return new u(t,n,0,async t=>this.end(t),e,r)}}async end(t){const e=await t.checkTimer();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new l(t.category,t.name,t.startTime,e)),this.flush(e))}endSync(t){const n=(0,e.now)();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new l(t.category,t.name,t.startTime,n)),this.flush(n))}logOneEvent(t){e.Logger.verbose(`Profiler.${t.category}`,`${(t.endTime-t.startTime).toFixed(2)}ms on event '${t.name}' at ${t.endTime.toFixed(2)}`)}flush(t){if(this._timingEvents.length-this._flushPointer>=this._flushBatchSize||t-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointer<t+this._flushBatchSize&&this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer]);this._flushTime=(0,e.now)()}}get started(){return this._started}},e.now="undefined"!=typeof performance&&performance.now?()=>performance.now():Date.now},2644:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Model=void 0;const r=n(5686),i=n(1446),o=n(7070),s=n(9395),a=n(2517);var u=s.onnxruntime.experimental.fbs;e.Model=class{constructor(){}load(t,e,n){if(!n)try{return void this.loadFromOnnxFormat(t,e)}catch(t){if(void 0!==n)throw t}this.loadFromOrtFormat(t,e)}loadFromOnnxFormat(t,e){const n=i.onnx.ModelProto.decode(t);if(a.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map(t=>({domain:t.domain,version:a.LongUtil.longToNumber(t.version)})),this._graph=o.Graph.from(n.graph,e)}loadFromOrtFormat(t,e){const n=new r.flatbuffers.ByteBuffer(t),i=u.InferenceSession.getRootAsInferenceSession(n).model();if(a.LongUtil.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let t=0;t<i.opsetImportLength();t++){const e=i.opsetImport(t);this._opsets.push({domain:null==e?void 0:e.domain(),version:a.LongUtil.longToNumber(e.version())})}this._graph=o.Graph.from(i.graph(),e)}get graph(){return this._graph}get opsets(){return this._opsets}}},782:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FLOAT_TYPES=e.INT_TYPES=e.NUMBER_TYPES=void 0,e.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],e.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],e.FLOAT_TYPES=["float32","float64"]},1047:(t,e)=>{function n(t,e){if(e.endsWith("+")){const n=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(n)&&n<=t}if(2===e.split("-").length){const n=e.split("-"),r=Number.parseInt(n[0],10),i=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(i)&&r<=t&&t<=i}return Number.parseInt(e,10)===t}Object.defineProperty(e,"__esModule",{value:!0}),e.resolveOperator=void 0,e.resolveOperator=function(t,e,r){for(const i of r){const r=i[0],o=i[1],s=i[2],a=i[3],u=i[4];if(t.opType===r)for(const t of e)if((t.domain===o||"ai.onnx"===t.domain&&""===o)&&n(t.version,s))return{opImpl:a,opInit:u}}throw new TypeError(`cannot resolve operator '${t.opType}' with opsets: ${e.map(t=>`${t.domain||"ai.onnx"} v${t.version}`).join(", ")}`)}},9395:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.onnxruntime=void 0;const r=n(5686);var i,o;(function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.INT=2]="INT",t[t.STRING=3]="STRING",t[t.TENSOR=4]="TENSOR",t[t.GRAPH=5]="GRAPH",t[t.FLOATS=6]="FLOATS",t[t.INTS=7]="INTS",t[t.STRINGS=8]="STRINGS",t[t.TENSORS=9]="TENSORS",t[t.GRAPHS=10]="GRAPHS",t[t.SPARSE_TENSOR=11]="SPARSE_TENSOR",t[t.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(e=t.AttributeType||(t.AttributeType={}))})((o=(i=e.onnxruntime||(e.onnxruntime={})).experimental||(i.experimental={})).fbs||(o.fbs={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.VALUE=1]="VALUE",t[t.PARAM=2]="PARAM"}(e=t.DimensionValueType||(t.DimensionValueType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.UINT8=2]="UINT8",t[t.INT8=3]="INT8",t[t.UINT16=4]="UINT16",t[t.INT16=5]="INT16",t[t.INT32=6]="INT32",t[t.INT64=7]="INT64",t[t.STRING=8]="STRING",t[t.BOOL=9]="BOOL",t[t.FLOAT16=10]="FLOAT16",t[t.DOUBLE=11]="DOUBLE",t[t.UINT32=12]="UINT32",t[t.UINT64=13]="UINT64",t[t.COMPLEX64=14]="COMPLEX64",t[t.COMPLEX128=15]="COMPLEX128",t[t.BFLOAT16=16]="BFLOAT16"}(e=t.TensorDataType||(t.TensorDataType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.Primitive=0]="Primitive",t[t.Fused=1]="Fused"}(e=t.NodeType||(t.NodeType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.NONE=0]="NONE",t[t.tensor_type=1]="tensor_type",t[t.sequence_type=2]="sequence_type",t[t.map_type=3]="map_type"}(e=t.TypeInfoValue||(t.TypeInfoValue={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dim(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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 n.startShape(t),n.addDim(t,e),n.endShape(t)}}e.Shape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}value(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),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,r){return n.startDimension(t),n.addValue(t,e),n.addDenotation(t,r),n.endDimension(t)}}e.Dimension=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt8(this.bb_pos+e):t.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(e,n){e.addFieldInt8(0,n,t.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,r,i){return n.startDimensionValue(t),n.addDimType(t,e),n.addDimValue(t,r),n.addDimParam(t,i),n.endDimensionValue(t)}}e.DimensionValue=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}shape(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return n.startTensorTypeAndShape(t),n.addElemType(t,e),n.addShape(t,r),n.endTensorTypeAndShape(t)}}e.TensorTypeAndShape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}valueType(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return n.startMapType(t),n.addKeyType(t,e),n.addValueType(t,r),n.endMapType(t)}}e.MapType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),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 n.startSequenceType(t),n.addElemType(t,e),n.endSequenceType(t)}}e.SequenceType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){(t.fbs||(t.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,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(t,e,n,r){return t.prep(4,12),t.writeInt32(r),t.writeInt32(n),t.writeInt32(e),t.offset()}}}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,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(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,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,r,i){return n.startNodeEdge(t),n.addNodeIndex(t,e),n.addInputEdges(t,r),n.addOutputEdges(t,i),n.endNodeEdge(t)}}e.NodeEdge=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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 e=this.bb.__offset(this.bb_pos,16);return e?this.bb.readInt32(this.bb_pos+e):t.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(e,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new t.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){e.addFieldInt32(6,n,t.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,r,i,o,s,a,u,l,c,d,h,p,f){return n.startNode(t),n.addName(t,e),n.addDocString(t,r),n.addDomain(t,i),n.addSinceVersion(t,o),n.addIndex(t,s),n.addOpType(t,a),n.addType(t,u),n.addExecutionProviderType(t,l),n.addInputs(t,c),n.addOutputs(t,d),n.addAttributes(t,h),n.addInputArgCounts(t,p),n.addImplicitInputs(t,f),n.endNode(t)}}e.Node=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),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,r,i){return n.startValueInfo(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.endValueInfo(t)}}e.ValueInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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 e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):t.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(e,n){e.addFieldInt8(1,n,t.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return n.startTypeInfo(t),n.addDenotation(t,e),n.addValueType(t,r),n.addValue(t,i),n.endTypeInfo(t)}}e.TypeInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__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,n,r){return e.startOperatorSetId(t),e.addDomain(t,n),e.addVersion(t,r),e.endOperatorSetId(t)}}t.OperatorSetId=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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 e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):t.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(e,n){e.addFieldInt32(3,n,t.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,r,i,o,s,a){return n.startTensor(t),n.addName(t,e),n.addDocString(t,r),n.addDims(t,i),n.addDataType(t,o),n.addRawData(t,s),n.addStringData(t,a),n.endTensor(t)}}e.Tensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}values(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),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,r,i){return n.startSparseTensor(t),n.addValues(t,e),n.addIndices(t,r),n.addDims(t,i),n.endSparseTensor(t)}}e.SparseTensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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 e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt32(this.bb_pos+e):t.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(e){let n=this.bb.__offset(this.bb_pos,16);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),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(e,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){e.addFieldInt32(2,n,t.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,r,i,o,s,a,u,l,c,d,h,p,f){return n.startAttribute(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.addF(t,o),n.addI(t,s),n.addS(t,a),n.addT(t,u),n.addG(t,l),n.addFloats(t,c),n.addInts(t,d),n.addStrings(t,h),n.addTensors(t,p),n.addGraphs(t,f),n.endAttribute(t)}}e.Attribute=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}initializers(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new t.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new t.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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,r,i,o,s,a,u,l){return n.startGraph(t),n.addInitializers(t,e),n.addNodeArgs(t,r),n.addNodes(t,i),n.addMaxNodeIndex(t,o),n.addNodeEdges(t,s),n.addInputs(t,a),n.addOutputs(t,u),n.addSparseInitializers(t,l),n.endGraph(t)}}e.Graph=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),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,r,i,o,s,a,u,l,c){return n.startModel(t),n.addIrVersion(t,e),n.addOpsetImport(t,r),n.addProducerName(t,i),n.addProducerVersion(t,o),n.addDomain(t,s),n.addModelVersion(t,a),n.addDocString(t,u),n.addGraph(t,l),n.addGraphDocString(t,c),n.endModel(t)}}e.Model=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__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,n,r){return e.startKernelCreateInfos(t),e.addNodeIndices(t,n),e.addKernelDefHashes(t,r),e.endKernelCreateInfos(t)}}t.KernelCreateInfos=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),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,r){return n.startSubGraphSessionState(t),n.addGraphId(t,e),n.addSessionState(t,r),n.endSubGraphSessionState(t)}}e.SubGraphSessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}kernels(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),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,r){return n.startSessionState(t),n.addKernels(t,e),n.addSubGraphSessionStates(t,r),n.endSessionState(t)}}e.SessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{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 n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__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(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),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,r,i){return n.startInferenceSession(t),n.addOrtVersion(t,e),n.addModel(t,r),n.addSessionState(t,i),n.endInferenceSession(t)}}e.InferenceSession=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={}))},7448:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxjsSessionHandler=void 0;const r=n(1670),i=n(9162);e.OnnxjsSessionHandler=class{constructor(t){this.session=t,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(t,e,n){const o=new Map;for(const e in t)if(Object.hasOwnProperty.call(t,e)){const n=t[e];o.set(e,new i.Tensor(n.dims,n.type,void 0,void 0,n.data))}const s=await this.session.run(o),a={};return s.forEach((t,e)=>{a[e]=new r.Tensor(t.type,t.data,t.dims)}),a}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Session=void 0;const r=n(7067),i=n(1296),o=n(7091),s=n(1036),a=n(6231),u=n(2644);e.Session=class{constructor(t={}){this._initialized=!1,this.backendHint=t.backendHint,this.profiler=a.Profiler.create(t.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(t,e,n){await this.profiler.event("session","Session.loadModel",async()=>{const s=await(0,o.resolveBackend)(this.backendHint);if(this.sessionHandler=s.createSessionHandler(this.context),this._model=new u.Model,"string"==typeof t){const e=t.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(t);this.initialize(n,e)}else{const n=await fetch(t),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),e)}}else if(ArrayBuffer.isView(t))this.initialize(t);else{const r=new Uint8Array(t,e||0,n||t.byteLength);this.initialize(r)}})}initialize(t,e){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(t,n,e),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.ExecutionPlan(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(t){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{const e=this.normalizeAndValidateInputs(t),n=await this._executionPlan.execute(this.sessionHandler,e);return this.createOutput(n)})}normalizeAndValidateInputs(t){const e=this._model.graph.getInputNames();if(Array.isArray(t)){if(t.length!==e.length)throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`)}else{if(t.size!==e.length)throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`);const n=new Array(t.size);let r=0;for(let i=0;i<e.length;++i){const o=t.get(e[i]);if(!o)throw new Error(`missing input tensor for: '${name}'`);n[r++]=o}t=n}if(this.context.graphInputTypes&&0!==this.context.graphInputTypes.length&&this.context.graphInputDims&&0!==this.context.graphInputDims.length)this.validateInputTensorDims(this.context.graphInputDims,t,!1);else{const e=this._model.graph.getInputIndices(),n=this._model.graph.getValues(),r=new Array(e.length);for(let i=0;i<e.length;++i){const o=n[e[i]];r[i]=o.type.shape.dims,this.context.graphInputTypes.push(o.type.tensorType),this.context.graphInputDims.push(t[i].dims)}this.validateInputTensorDims(r,t,!0)}return this.validateInputTensorTypes(this.context.graphInputTypes,t),t}validateInputTensorTypes(t,e){for(let n=0;n<e.length;n++){const r=t[n],i=e[n].type;if(r!==i)throw new Error(`input tensor[${n}] check failed: expected type '${r}' but got ${i}`)}}validateInputTensorDims(t,e,n){for(let r=0;r<e.length;r++){const i=t[r],o=e[r].dims;if(!this.compareTensorDims(i,o,n))throw new Error(`input tensor[${r}] check failed: expected shape '[${i.join(",")}]' but got [${o.join(",")}]`)}}compareTensorDims(t,e,n){if(t.length!==e.length)return!1;for(let r=0;r<t.length;++r)if(t[r]!==e[r]&&(!n||0!==t[r]))return!1;return!0}createOutput(t){const e=this._model.graph.getOutputNames();if(t.length!==e.length)throw new Error("expected number of outputs do not match number of generated outputs");const n=new Map;for(let r=0;r<e.length;++r)n.set(e[r],t[r]);return n}initializeOps(t){const e=t.getNodes();this._ops=new Array(e.length);for(let n=0;n<e.length;n++)this._ops[n]=this.sessionHandler.resolve(e[n],this._model.opsets,t)}}},9162:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Tensor=void 0;const i=n(3442),o=r(n(3720)),s=n(1446),a=n(9395),u=n(2517);var l=a.onnxruntime.experimental.fbs;class c{get data(){if(void 0===this.cache){const t=this.dataProvider(this.dataId);if(t.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=t}return this.cache}get stringData(){if("string"!==this.type)throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if("string"!==this.type)return this.data;throw new TypeError("type cannot be non-number (string)")}get(t){return this.data[u.ShapeUtil.indicesToOffset(t,this.strides)]}set(t,e){this.data[u.ShapeUtil.indicesToOffset(t,this.strides)]=e}async getData(){return void 0===this.cache&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=u.ShapeUtil.computeStrides(this.dims)),this._strides}constructor(t,e,n,r,o,s=i.Guid.create()){this.dims=t,this.type=e,this.dataProvider=n,this.asyncDataProvider=r,this.cache=o,this.dataId=s,this.size=u.ShapeUtil.validateDimsAndCalcSize(t);const a=this.size,l=void 0===n&&void 0===r&&void 0===o;if(void 0!==o&&o.length!==a)throw new RangeError("Input dims doesn't match data length.");if("string"===e){if(!(void 0===o||Array.isArray(o)&&o.every(t=>"string"==typeof t)))throw new TypeError("cache should be a string array");l&&(this.cache=new Array(a))}else{if(void 0!==o){const t=h(e);if(!(o instanceof t))throw new TypeError(`cache should be type ${t.name}`)}if(l){const t=new ArrayBuffer(a*function(t){switch(t){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 ${t}`)}}(e));this.cache=function(t,e){return new(h(e))(t)}(t,e)}}}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");const e=u.ProtoUtil.tensorDataTypeFromProto(t.dataType),n=u.ProtoUtil.tensorDimsFromProto(t.dims),r=new c(n,e);if("string"===e)t.stringData.forEach((t,e)=>{r.data[e]=(0,u.decodeUtf8String)(t)});else if(t.rawData&&"number"==typeof t.rawData.byteLength&&t.rawData.byteLength>0){const e=r.data,n=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),i=d(t.dataType),o=t.rawData.byteLength/i;if(t.rawData.byteLength%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=f(n,t.dataType,r*i);e[r]=o}}else{let e;switch(t.dataType){case s.onnx.TensorProto.DataType.FLOAT:e=t.floatData;break;case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.INT16:case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.BOOL:e=t.int32Data;break;case s.onnx.TensorProto.DataType.INT64:e=t.int64Data;break;case s.onnx.TensorProto.DataType.DOUBLE:e=t.doubleData;break;case s.onnx.TensorProto.DataType.UINT32:case s.onnx.TensorProto.DataType.UINT64:e=t.uint64Data;break;default:throw new Error("unspecific error")}if(null==e)throw new Error("failed to populate data from a tensorproto value");const n=r.data;if(n.length!==e.length)throw new Error("array length mismatch");for(let r=0;r<e.length;r++){const i=e[r];o.default.isLong(i)?n[r]=p(i,t.dataType):n[r]=i}}return r}static fromData(t,e,n){return new c(e,n,void 0,void 0,t)}static fromOrtTensor(t){if(!t)throw new Error("cannot construct Value from an empty tensor");const e=u.ProtoUtil.tensorDimsFromORTFormat(t),n=u.ProtoUtil.tensorDataTypeFromProto(t.dataType()),r=new c(e,n);if("string"===n)for(let e=0;e<t.stringDataLength();e++)r.data[e]=t.stringData(e);else if(t.rawDataArray()&&"number"==typeof t.rawDataLength()&&t.rawDataLength()>0){const e=r.data,n=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),i=d(t.dataType()),o=t.rawDataLength()/i;if(t.rawDataLength()%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r<o;r++){const o=f(n,t.dataType(),r*i);e[r]=o}}return r}}function d(t){switch(t){case s.onnx.TensorProto.DataType.UINT8:case s.onnx.TensorProto.DataType.INT8:case s.onnx.TensorProto.DataType.BOOL:return 1;case s.onnx.TensorProto.DataType.UINT16:case s.onnx.TensorProto.DataType.INT16:return 2;case s.onnx.TensorProto.DataType.FLOAT:case s.onnx.TensorProto.DataType.INT32:case s.onnx.TensorProto.DataType.UINT32:return 4;case s.onnx.TensorProto.DataType.INT64:case s.onnx.TensorProto.DataType.DOUBLE:case s.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${s.onnx.TensorProto.DataType[t]}`)}}function h(t){switch(t){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function p(t,e){if(e===s.onnx.TensorProto.DataType.INT64||e===l.TensorDataType.INT64){if(t.greaterThanOrEqual(2147483648)||t.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else{if(e!==s.onnx.TensorProto.DataType.UINT32&&e!==l.TensorDataType.UINT32&&e!==s.onnx.TensorProto.DataType.UINT64&&e!==l.TensorDataType.UINT64)throw new TypeError(`not a LONG type: ${s.onnx.TensorProto.DataType[e]}`);if(t.greaterThanOrEqual(4294967296)||t.lessThan(0))throw new TypeError("uint64 is not supported")}return t.toNumber()}function f(t,e,n){switch(e){case s.onnx.TensorProto.DataType.BOOL:case s.onnx.TensorProto.DataType.UINT8:return t.getUint8(n);case s.onnx.TensorProto.DataType.INT8:return t.getInt8(n);case s.onnx.TensorProto.DataType.UINT16:return t.getUint16(n,!0);case s.onnx.TensorProto.DataType.INT16:return t.getInt16(n,!0);case s.onnx.TensorProto.DataType.FLOAT:return t.getFloat32(n,!0);case s.onnx.TensorProto.DataType.INT32:return t.getInt32(n,!0);case s.onnx.TensorProto.DataType.UINT32:return t.getUint32(n,!0);case s.onnx.TensorProto.DataType.INT64:return p(o.default.fromBits(t.getUint32(n,!0),t.getUint32(n+4,!0),!1),e);case s.onnx.TensorProto.DataType.DOUBLE:return t.getFloat64(n,!0);case s.onnx.TensorProto.DataType.UINT64:return p(o.default.fromBits(t.getUint32(n,!0),t.getUint32(n+4,!0),!0),e);default:throw new Error(`cannot read from DataView for type ${s.onnx.TensorProto.DataType[e]}`)}}e.Tensor=c},2517:function(t,e,n){var r=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.decodeUtf8String=e.MAX_CLIP=e.MIN_CLIP=e.PoolConvUtil=e.ReduceUtil=e.SplitUtil=e.MathUtil=e.ShapeUtil=e.LongUtil=e.ProtoUtil=e.GemmUtil=e.arrayCopyHelper=e.BroadcastUtil=e.MatMulUtil=e.ArrayUtil=e.assert=e.checkInputsShape=void 0;const i=n(5686),o=r(n(3720)),s=n(1446),a=n(9162);e.checkInputsShape=function(t,...e){if(!t||t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].dims||t[n].dims.length!==e[n])return!1;return!0},e.assert=function(t,e){if(!t)throw new Error("string"==typeof e?e:e())},e.ArrayUtil=class{static arraysEqual(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}};class u{static preprocessInputShapes(t,e){return[1===t.length?[1,t[0]]:t,1===e.length?[e[0],1]:e]}static postprocessOutputShape(t,e,n){1===e&&t.splice(t.length-2,1),1===n&&t.pop()}static calcMatMulShape(t,e){return t[1]!==e[0]?void 0:[t[0],e[1]]}}e.MatMulUtil=u;class l{static calcShape(t,e,n=!1){const r=t.length,i=e.length;if(0===r)return e;if(0===i)return t;const o=Math.max(t.length,e.length),s=new Array(o);if(n){if(r<2||i<2)return;const n=u.calcMatMulShape([t[r-2],t[r-1]],[e[i-2],e[i-1]]);if(void 0===n)return;[s[o-2],s[o-1]]=n}for(let a=n?3:1;a<=o;a++){const n=r-a<0?1:t[r-a],u=i-a<0?1:e[i-a];if(n!==u&&n>1&&u>1)return;s[o-a]=Math.max(n,u)}return s}static index(t,e){const n=new Array(e.length);return l.fillIndex(t,e,n),n}static fillIndex(t,e,n){const r=t.length-e.length;for(let i=0;i<e.length;i++)n[i]=t[r+i]%e[i]}static calc(t,e,n,r,i){const o=l.calcShape(t.dims,e.dims);if(o){if(r&&!h.areEqual(o,t.dims))return;const s=h.size(o),u=r?t:new a.Tensor(o,i||t.type);if(0===o.length)u.set([],n(t.get([]),e.get([])));else{const r=new Array(o.length),i=new Array(t.dims.length),a=new Array(e.dims.length);let c,d=0,h=0,p=!1,f=!1;0===t.dims.length&&(d=t.get([]),p=!0),0===e.dims.length&&(h=e.get([]),f=!0);for(let g=0;g<s;g++){c=g;for(let t=o.length-1;t>=0;t--)r[t]=c%o[t],c=Math.floor(c/o[t]);p||(l.fillIndex(r,t.dims,i),d=t.get(i)),f||(l.fillIndex(r,e.dims,a),h=e.get(a)),u.set(r,n(d,h))}}return u}}static isValidBroadcast(t,e){const n=t.length,r=e.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==t[n-i]&&t[n-i]!==e[r-i])return!1;return!0}static getBroadcastDims(t,e){const n=t.length,r=[];for(let i=0;i<n;i++){const o=n-1-i,s=t[o]||1;(e[e.length-1-i]||1)>1&&1===s&&r.unshift(o)}return r}}e.BroadcastUtil=l,e.arrayCopyHelper=function(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)t[n+o]=e[r+o]},e.GemmUtil=class{static getShapeOfGemmResult(t,e,n,r,i){if(2!==t.length||2!==n.length)throw new Error("shape need to be of size 2");let o,s,a;e?(o=t[1],s=t[0]):(o=t[0],s=t[1]);let u=-1;if(r?(a=n[0],u=1):(a=n[1],u=0),n[u]!==s)throw new Error("dimension mismatch");if(o<=0||a<=0||s<=0)throw new Error("invalid shape specified");if(i&&!l.isValidBroadcast(i,[o,a]))throw new Error("gemm: invalid bias shape for broadcast");return[o,a,s]}};class c{static tensorDataTypeFromProto(t){switch(t){case s.onnx.TensorProto.DataType.INT8:return"int8";case s.onnx.TensorProto.DataType.UINT8:return"uint8";case s.onnx.TensorProto.DataType.BOOL:return"bool";case s.onnx.TensorProto.DataType.INT16:return"int16";case s.onnx.TensorProto.DataType.UINT16:return"uint16";case s.onnx.TensorProto.DataType.INT32:return"int32";case s.onnx.TensorProto.DataType.UINT32:return"uint32";case s.onnx.TensorProto.DataType.FLOAT:return"float32";case s.onnx.TensorProto.DataType.DOUBLE:return"float64";case s.onnx.TensorProto.DataType.STRING:return"string";case s.onnx.TensorProto.DataType.INT64:return"int32";case s.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${s.onnx.TensorProto.DataType[t]}`)}}static tensorDataTypeStringToEnum(t){switch(t){case"int8":return s.onnx.TensorProto.DataType.INT8;case"uint8":return s.onnx.TensorProto.DataType.UINT8;case"bool":return s.onnx.TensorProto.DataType.BOOL;case"int16":return s.onnx.TensorProto.DataType.INT16;case"uint16":return s.onnx.TensorProto.DataType.UINT16;case"int32":return s.onnx.TensorProto.DataType.INT32;case"uint32":return s.onnx.TensorProto.DataType.UINT32;case"float32":return s.onnx.TensorProto.DataType.FLOAT;case"float64":return s.onnx.TensorProto.DataType.DOUBLE;case"string":return s.onnx.TensorProto.DataType.STRING;case"int64":return s.onnx.TensorProto.DataType.INT64;case"uint64":return s.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${t}`)}}static tensorDimsFromProto(t){return t.map(t=>o.default.isLong(t)?t.toNumber():t)}static tensorValueTypeFromProto(t){return{tensorType:c.tensorDataTypeFromProto(t.elemType),shape:{dims:c.tensorDimsFromProto(t.shape.dim.map(t=>t.dimValue))}}}static tensorDimsFromORTFormat(t){const e=[];for(let n=0;n<t.dimsLength();n++)e.push(d.longToNumber(t.dims(n)));return e}static tensorAttributesFromORTFormat(t){const e=[];for(let n=0;n<t.attributesLength();n++)e.push(t.attributes(n));return e}}e.ProtoUtil=c;class d{static longToNumber(t,e){return o.default.isLong(t)?t.toNumber():t instanceof i.flatbuffers.Long?o.default.fromValue({low:t.low,high:t.high,unsigned:null!=e&&e}).toNumber():t}static isLong(t){return o.default.isLong(t)||t instanceof i.flatbuffers.Long}}e.LongUtil=d;class h{static size(t){return h.getSizeFromDimensionRange(t,0,t.length)}static sizeFromDimension(t,e){if(e<0||e>t.length)throw new Error(`invalid dimension of ${e} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return h.getSizeFromDimensionRange(t,e,t.length)}static sizeToDimension(t,e){if(e<0||e>t.length)throw new Error(`invalid dimension of ${e} for sizeToDimension as Tensor has ${t.length} dimensions.`);return h.getSizeFromDimensionRange(t,0,e)}static getSizeFromDimensionRange(t,e,n){let r=1;for(let i=e;i<n;i++){if(t[i]<=0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");r*=t[i]}return r}static computeStrides(t){const e=t.length;if(0===e)return[];if(1===e)return[1];const n=new Array(e);n[e-1]=1,n[e-2]=t[e-1];for(let r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,e,n){void 0===n&&(n=t.length);let r=0;for(let i=0;i<n;++i)r+=e[i]*t[i];return r}static offsetToIndices(t,e){const n=e.length;if(0===n)return[];if(1===n)return[t*e[0]];const r=new Array(e.length);for(let n=0;n<r.length-1;++n)r[n]=Math.floor(t/e[n]),t-=r[n]*e[n];return r[r.length-1]=t,r}static normalizeAxis(t,e){if(t<-e&&t>=e)throw new Error("unsupported axis for this operation.");return t<0?t+e:t}static normalizeAxes(t,e){return t.map(t=>this.normalizeAxis(t,e))}static incrementIndex(t,e,n){if(0===e.length||0===t.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=e.length;else if(n<=0||n>e.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(t[r]++,!(t[r]<e[r]));--r)t[r]=0}static calculateReshapedDims(t,e){if(0===e.length){if(0===t.length||1===h.size(t))return[];throw new Error("cannot reshape to a scalar Tensor")}const n=e.length,r=new Array(n);let i=-1,o=1;for(let s=0;s<n;s++){if(e[s]<-1)throw new Error("a dimension in shape hints cannot be less than -1");if(-1===e[s]){if(-1!==i)throw new Error("at most one dimension in shape hints can be -1");i=s}else{if(0===e[s]){if(s>=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[s]=t[s]}else r[s]=e[s];o*=r[s]}}const s=h.size(t);if(-1!==i){if(s%o!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${e}]`);r[i]=s/o}else if(o!==s)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(t,e){return e?e.map(e=>t[e]):t.slice().reverse()}static padShape(t,e){const n=t.length;return t.map((t,r)=>t+e[r]+e[r+n])}static areEqual(t,e){return t.length===e.length&&t.every((t,n)=>t===e[n])}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let e=1;for(const n of t){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);e*=n}return e}static flattenShape(t,e){e<0&&(e+=t.length);const n=t.reduce((t,e)=>t*e,1),r=t.slice(e).reduce((t,e)=>t*e,1);return[n/r,r]}static squeezeShape(t,e){const n=new Array;e=h.normalizeAxes(e,t.length);for(let r=0;r<t.length;r++){const i=e.indexOf(r)>=0;if(i&&1!==t[r])throw new Error("squeeze an axis of size different than 1");(0===e.length&&t[r]>1||e.length>0&&!i)&&n.push(t[r])}return n}static unsqueezeShape(t,e){const n=new Array(t.length+e.length);n.fill(0);for(let t=0;t<e.length;t++){const r=h.normalizeAxis(e[t],n.length);if(r>=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let e=0;e<n.length;e++)0===n[e]&&(n[e]=t[r++]);if(r!==t.length)throw new Error("the unsqueezed dimension could not be established");return n}}e.ShapeUtil=h,e.MathUtil=class{static sqr(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)t[n+o]+=Math.pow(e[r+o],2)}static axpy(t,e,n,r,i,o){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let s=0;s<i;s++)t[n+s]+=o*e[r+s]}static powx(t,e,n,r,i,o){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let s=0;s<i;s++)t[n+s]=Math.pow(e[r+s],o)}static mul(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o<i;o++)t[n+o]=e[r+o]*t[n+o]}};class p{static splitShape(t,e,n,r){if(0===n.length){if(!r)throw new Error("need to know number of outputs when the 'split' attribute is not specified");p.determineSplit(t[e],r,n)}const i=[],o=[0];for(let r=0;r<n.length;++r){0!==r&&o.push(o[r-1]+n[r-1]);const s=t.slice();s[e]=n[r],i.push(s)}return[i,o]}static determineSplit(t,e,n){if(t%e!=0)throw new Error("cannot split tensor to equal sized parts");for(let r=0;r<e;++r)n.push(t/e)}}e.SplitUtil=p;class f{static calcReduce(t,e,n,r,i){const o=t.dims.slice(0);0===e.length&&o.forEach((t,n)=>e.push(n));const s=f.calcReduceShape(o,e,!0),u=h.size(s),c=new a.Tensor(s,t.type),d=h.computeStrides(s),p=h.computeStrides(o),g=new Array(o.length);for(let n=0;n<u;n++){const s=h.offsetToIndices(n,d);l.fillIndex(s,o,g),c.set(s,f.calcReduceByAxis(t.numberData,e,o,0,h.indicesToOffset(g,p),r,i))}return n?c:new a.Tensor(f.calcReduceShape(o,e,n),c.type,void 0,void 0,c.data,c.dataId)}static calcReduceByAxis(t,e,n,r,i,o,s){let a=0;if(r>=e.length)return o(t[i]);const u=e[r],l=u>=n.length?1:h.size(n.slice(u+1));for(let c=0;c<n[u];c++)a=0===c?f.calcReduceByAxis(t,e,n,r+1,i,o,s):s(a,f.calcReduceByAxis(t,e,n,r+1,i,o,s)),i+=l;return a}static calcReduceShape(t,e,n){const r=t.slice();for(let t=0;t<e.length;t++)r[e[t]]=n?1:0;return r.filter(t=>0!==t)}}e.ReduceUtil=f;class g{static adjustPoolAttributes(t,e,n,r,i,o){if(!t&&n.length!==e.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let t=0;t<e.length-2;t++)t>=n.length?n.push(e[t+2]):n[t]=e[t+2];for(let t=0;t<n.length;t++)if(t<r.length){if(r[t]<0)throw new Error("strides should be greater than or equal to 1")}else r.push(1);for(let t=0;t<n.length;t++)if(t<i.length){if(i[t]<0)throw new Error("dilations should be greater than or equal to 1")}else i.push(1);for(let t=0;t<2*n.length;t++)if(t<o.length){if(o[t]<0)throw new Error("pad should be greater than or equal to 1")}else o.push(0);for(let t=0;t<n.length;t++){if(n[t]<=0)throw new Error("kernel shapes need to be greater than 0");if(o[t]>=n[t]||o[t+n.length]>=n[t])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,e,n,r,i,o){if(o){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(e.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s<t.length-2;s++)g.adjustPadAndReturnShape(t[s+2],e[s],n[s],r[s],i,s,s+t.length-2,o)}}static computePoolOutputShape(t,e,n,r,i,o,s){if(e.length<=0)throw new Error("input shape must be of size greater than 0");const a=[e[0],e[1]];return g.computeShapeHelper(t,e,a,n,r,i,o,s),a}static computeConvOutputShape(t,e,n,r,i,o,s){if(t.length<=0||e.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");const a=[t[0],e[0]];return g.computeShapeHelper(!1,t,a,n,r,i,o,s),a}static computeShapeHelper(t,e,n,r,i,o,s,a){if(t)for(let t=0;t<e.length-2;t++)n.push(1);else for(let t=0;t<e.length-2;t++)n.push(g.adjustPadAndReturnShape(e[t+2],r[t],i[t],o[t],s,t,t+e.length-2,a))}static adjustPadAndReturnShape(t,e,n,r,i,o,s,a){const u=n*(r-1)+1;if(!a||"NOTSET"===a)return Math.floor((t+i[o]+i[s]-u)/e+1);switch(a){case"VALID":return i[o]=0,i[s]=0,Math.floor((t-u)/e+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{const n=((t+e-1)/e-1)*e+r-t;return i[o]="SAME_LOWER"===a?Math.floor((n+1)/2):Math.floor(n/2),i[s]=n-i[o],Math.floor((t+n-r)/e+1)}default:throw new Error("Unsupported AutoPad type")}}}e.PoolConvUtil=g,e.MIN_CLIP=-34028234663852886e22,e.MAX_CLIP=34028234663852886e22,e.decodeUtf8String=function(t){return(new TextDecoder).decode(t)}},7967:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,i)=>{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,o])=>{const s=n?n+t:t;if("object"==typeof o)(0,e.iterateExtraOptions)(o,s+".",r,i);else if("string"==typeof o||"number"==typeof o)i(s,o.toString());else{if("boolean"!=typeof o)throw new Error("Can't handle extra config type: "+typeof o);i(s,o?"1":"0")}})}},2157:function(t,e,n){var r,i=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),s=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)&&i(e,t,n);return o(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=e.initWasm=void 0;const a=n(1670),u=s(n(349)),l=n(6361),c=()=>!!a.env.wasm.proxy&&"undefined"!=typeof document;let d,h,p,f=!1,g=!1,m=!1;const b=[],y=[],_=[],w=[],v=[],x=[],T=()=>{if(f||!g||m||!d)throw new Error("worker not ready")},S=t=>{switch(t.data.type){case"init-wasm":f=!1,t.data.err?(m=!0,h[1](t.data.err)):(g=!0,h[0]());break;case"init-ort":t.data.err?p[1](t.data.err):p[0]();break;case"create_allocate":t.data.err?b.shift()[1](t.data.err):b.shift()[0](t.data.out);break;case"create_finalize":t.data.err?y.shift()[1](t.data.err):y.shift()[0](t.data.out);break;case"create":t.data.err?_.shift()[1](t.data.err):_.shift()[0](t.data.out);break;case"release":t.data.err?w.shift()[1](t.data.err):w.shift()[0]();break;case"run":t.data.err?v.shift()[1](t.data.err):v.shift()[0](t.data.out);break;case"end-profiling":t.data.err?x.shift()[1](t.data.err):x.shift()[0]()}},A="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;e.initWasm=async()=>{if(c()){if(g)return;if(f)throw new Error("multiple calls to 'initWasm()' detected.");if(m)throw new Error("previous call to 'initWasm()' failed.");return f=!0,void 0===a.env.wasm.wasmPaths&&A&&0!==A.indexOf("blob:")&&(a.env.wasm.wasmPaths=A.substr(0,+A.lastIndexOf("/")+1)),new Promise((t,e)=>{null==d||d.terminate(),d=n(9710).Z(),d.onmessage=S,h=[t,e];const r={type:"init-wasm",in:a.env.wasm};d.postMessage(r)})}return(0,l.initializeWebAssembly)(a.env.wasm)},e.initOrt=async(t,e)=>{if(c())return T(),new Promise((n,r)=>{p=[n,r];const i={type:"init-ort",in:{numThreads:t,loggingLevel:e}};d.postMessage(i)});u.initOrt(t,e)},e.createSessionAllocate=async t=>c()?(T(),new Promise((e,n)=>{b.push([e,n]);const r={type:"create_allocate",in:{model:t}};d.postMessage(r,[t.buffer])})):u.createSessionAllocate(t),e.createSessionFinalize=async(t,e)=>c()?(T(),new Promise((n,r)=>{y.push([n,r]);const i={type:"create_finalize",in:{modeldata:t,options:e}};d.postMessage(i)})):u.createSessionFinalize(t,e),e.createSession=async(t,e)=>c()?(T(),new Promise((n,r)=>{_.push([n,r]);const i={type:"create",in:{model:t,options:e}};d.postMessage(i,[t.buffer])})):u.createSession(t,e),e.releaseSession=async t=>{if(c())return T(),new Promise((e,n)=>{w.push([e,n]);const r={type:"release",in:t};d.postMessage(r)});u.releaseSession(t)},e.run=async(t,e,n,r,i)=>c()?(T(),new Promise((o,s)=>{v.push([o,s]);const a={type:"run",in:{sessionId:t,inputIndices:e,inputs:n,outputIndices:r,options:i}};d.postMessage(a,u.extractTransferableBuffers(n))})):u.run(t,e,n,r,i),e.endProfiling=async t=>{if(c())return T(),new Promise((e,n)=>{x.push([e,n]);const r={type:"end-profiling",in:t};d.postMessage(r)});u.endProfiling(t)}},586:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setRunOptions=t=>{const e=(0,o.getInstance)();let n=0;const s=[],a=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))a.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))a.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)&&(a.terminate=!1);let o=0;if(void 0!==(null==t?void 0:t.tag)&&(o=(0,i.allocWasmString)(t.tag,s)),n=e._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),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 o=(0,i.allocWasmString)(t,s),a=(0,i.allocWasmString)(r,s);if(0!==e._OrtAddRunConfigEntry(n,o,a))throw new Error(`Can't set a run config entry: ${t} - ${r}`)}),[n,s]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),s.forEach(e._free),t}}},2306:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),i=n(1670),o=n(2850),s=n(2157);let a;e.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(t){const e=await fetch(t),n=await e.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(n))}async loadModel(t,e){if(a||(await(0,s.initOrt)(i.env.wasm.numThreads,(t=>{switch(t){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: ${t}`)}})(i.env.logLevel)),a=!0),"string"==typeof t)if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(n,e)}else{const n=await this.createSessionAllocate(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(n,e)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(t,e)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(t,e,n){const r=[],o=[];Object.entries(t).forEach(t=>{const e=t[0],n=t[1],i=this.inputNames.indexOf(e);if(-1===i)throw new Error(`invalid input '${e}'`);r.push(n),o.push(i)});const a=[];Object.entries(e).forEach(t=>{const e=t[0],n=this.outputNames.indexOf(e);if(-1===n)throw new Error(`invalid output '${e}'`);a.push(n)});const u=await(0,s.run)(this.sessionId,o,r.map(t=>[t.type,t.dims,t.data]),a,n),l={};for(let t=0;t<u.length;t++)l[this.outputNames[a[t]]]=new i.Tensor(u[t][0],u[t][2],u[t][1]);return l}startProfiling(){}endProfiling(){(0,s.endProfiling)(this.sessionId)}}},4919:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setSessionOptions=t=>{const e=(0,o.getInstance)();let n=0;const s=[],a=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")})(a);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(a.graphOptimizationLevel="all");const u=(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}`)}})(a.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(a.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(a.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(a.executionMode="sequential");const l=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(a.executionMode);let c=0;if(void 0!==(null==t?void 0:t.logId)&&(c=(0,i.allocWasmString)(t.logId,s)),void 0===(null==t?void 0:t.logSeverityLevel))a.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))a.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)&&(a.enableProfiling=!1),n=e._OrtCreateSessionOptions(u,!!a.enableCpuMemArena,!!a.enableMemPattern,l,!!a.enableProfiling,0,c,a.logSeverityLevel,a.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 s=(0,i.allocWasmString)(e,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(t,s))throw new Error(`Can't append execution provider: ${e}`)}})(n,t.executionProviders,s),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,(t,r)=>{const o=(0,i.allocWasmString)(t,s),a=(0,i.allocWasmString)(r,s);if(0!==e._OrtAddSessionConfigEntry(n,o,a))throw new Error(`Can't set a session config entry: ${t} - ${r}`)}),[n,s]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),s.forEach(e._free),t}}},4983:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(6361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),i=n.lengthBytesUTF8(t)+1,o=n._malloc(i);return n.stringToUTF8(t,o,i),e.push(o),o}},349:(t,e,n)=>{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),i=n(4919),o=n(4983),s=n(6361);e.initOrt=(t,e)=>{const n=(0,s.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const a=new Map;e.createSessionAllocate=t=>{const e=(0,s.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,s.getInstance)();let r=0,o=0,u=[];try{if([o,u]=(0,i.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],o),0===r)throw new Error("Can't create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(o),u.forEach(n._free)}const l=n._OrtGetInputCount(r),c=n._OrtGetOutputCount(r),d=[],h=[],p=[],f=[];for(let t=0;t<l;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can't get an input name");h.push(e),d.push(n.UTF8ToString(e))}for(let t=0;t<c;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can't get an output name");f.push(e),p.push(n.UTF8ToString(e))}return a.set(r,[r,h,f]),[r,d,p]},e.createSession=(t,n)=>{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,s.getInstance)(),n=a.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=n[1],o=n[2];i.forEach(e._OrtFree),o.forEach(e._OrtFree),e._OrtReleaseSession(r),a.delete(t)};const u=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}`)}},l=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}`)}},c=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,i,d)=>{const h=(0,s.getInstance)(),p=a.get(t);if(!p)throw new Error("invalid session id");const f=p[0],g=p[1],m=p[2],b=e.length,y=i.length;let _=0,w=[];const v=[],x=[];try{[_,w]=(0,r.setRunOptions)(d);for(let t=0;t<b;t++){const e=n[t][0],r=n[t][1],i=n[t][2];let s,a;if(Array.isArray(i)){a=4*i.length,s=h._malloc(a),x.push(s);let t=s/4;for(let e=0;e<i.length;e++){if("string"!=typeof i[e])throw new TypeError(`tensor data at index ${e} is not a string`);h.HEAPU32[t++]=(0,o.allocWasmString)(i[e],x)}}else a=i.byteLength,s=h._malloc(a),x.push(s),h.HEAPU8.set(new Uint8Array(i.buffer,i.byteOffset,a),s);const l=h.stackSave(),c=h.stackAlloc(4*r.length);try{let t=c/4;r.forEach(e=>h.HEAP32[t++]=e);const n=h._OrtCreateTensor(u(e),s,a,c,r.length);if(0===n)throw new Error("Can't create a tensor");v.push(n)}finally{h.stackRestore(l)}}const t=h.stackSave(),s=h.stackAlloc(4*b),a=h.stackAlloc(4*b),p=h.stackAlloc(4*y),T=h.stackAlloc(4*y);try{let t=s/4,n=a/4,r=p/4,o=T/4;for(let r=0;r<b;r++)h.HEAPU32[t++]=v[r],h.HEAPU32[n++]=g[e[r]];for(let t=0;t<y;t++)h.HEAPU32[r++]=0,h.HEAPU32[o++]=m[i[t]];let u=h._OrtRun(f,a,s,b,T,y,p,_);const d=[];if(0===u)for(let t=0;t<y;t++){const e=h.HEAPU32[p/4+t],n=h.stackSave(),r=h.stackAlloc(16);let i,o=0;try{if(u=h._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==u)throw new Error(`Can't access output tensor data. error code = ${u}`);let t=r/4;const n=h.HEAPU32[t++];o=h.HEAPU32[t++];const s=h.HEAPU32[t++],a=h.HEAPU32[t++],p=[];for(let t=0;t<a;t++)p.push(h.HEAPU32[s/4+t]);h._OrtFree(s);const f=0===p.length?1:p.reduce((t,e)=>t*e);if(i=l(n),"string"===i){const t=[];let e=o/4;for(let n=0;n<f;n++){const r=h.HEAPU32[e++],i=n===f-1?void 0:h.HEAPU32[e]-r;t.push(h.UTF8ToString(r,i))}d.push([i,p,t])}else{const t=new(c(i))(f);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(h.HEAPU8.subarray(o,o+t.byteLength)),d.push([i,p,t])}}finally{h.stackRestore(n),"string"===i&&o&&h._free(o),h._OrtReleaseTensor(e)}}if(0===u)return d;throw new Error(`failed to call OrtRun(). error code = ${u}.`)}finally{h.stackRestore(t)}}finally{v.forEach(h._OrtReleaseTensor),x.forEach(h._free),h._OrtReleaseRunOptions(_),w.forEach(h._free)}},e.endProfiling=t=>{const e=(0,s.getInstance)(),n=a.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=e._OrtEndProfiling(r);if(0===i)throw new Error("Can't get an profile file name");e._OrtFree(i)},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}},6361:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=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 i(e,t),e},s=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 a=o(n(6449)),u=s(n(932)),l=n(3474);let c,d=!1,h=!1,p=!1;const f=(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(d)return Promise.resolve();if(h)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(p)throw new Error("previous call to 'initializeWebAssembly()' failed.");h=!0;const e=t.initTimeout,r=t.numThreads,i=t.simd,o=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}})(),s=i&&(()=>{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}})(),g="string"==typeof t.wasmPaths?t.wasmPaths:void 0,m=f(!1,o),b=f(s,o),y="object"==typeof t.wasmPaths?t.wasmPaths[b]:void 0;let _=!1;const w=[];if(e>0&&w.push(new Promise(t=>{setTimeout(()=>{_=!0,t()},e)})),w.push(new Promise((t,e)=>{const r=o?l:u.default,i={locateFile:(t,e)=>o&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):t===m?null!=y?y:(null!=g?g:e)+b:e+t};if(o)if("undefined"==typeof Blob)i.mainScriptUrlOrBlob=a.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;i.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(i).then(e=>{h=!1,d=!0,c=e,t()},t=>{h=!1,p=!0,e(t)})})),await Promise.race(w),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(d&&c)return c;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!d||h||p||(h=!0,null===(t=c.PThread)||void 0===t||t.terminateAllThreads(),c=void 0,h=!1,d=!1,p=!0)}},9710:(t,e,n)=>{n.d(e,{Z:()=>o});var r=n(477),i=n.n(r);function o(){return i()('/*!\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<process.argv.length&&(m=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof ct))throw t})),process.on("unhandledRejection",(function(t){throw t})),g=(t,e)=>{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<n-e&&t.buffer&&L)return L.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(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<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=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<t.length;++n){var r=t.charCodeAt(n);127>=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<t.length;)t.shift()(u)}function yt(t){var e=Ee();return t=t(),Me(e),t}function bt(t){if(O)return $t(2,0,t);try{pt(t)}catch(t){t instanceof ct||"unwind"==t||g(1,t)}}u.PThread=ht,u.establishStackSpace=function(){var t=he(),e=a()[t+44>>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<o?(i()[n>>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<n;u++){var c=r[2+u];o()[i+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<a.length;++u)e()[o++>>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<n;u++){var c=i()[e>>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l<s;l++)ae(t,r()[c+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.length<e;)t=n[0]+t;return t}function u(t,e){return o(t,e,"0")}function c(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function s(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function l(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ue(t.getFullYear())?ce:se)[n];if(!(e>r-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:12<t&&(t-=12),u(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(ue(t.Xb+1900)?ce:se)[n++]);return u(t.jc+e,3)},"%m":function(t){return u(t.ec+1,2)},"%M":function(t){return u(t.Kc,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.dc&&12>t.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;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},l: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;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},h: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;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},t:Tt,M:function(){var t=_t.pop();t||at("no exception to throw");var e=t.Zb;throw t.kc()||(_t.push(t),t.ic(!0),t.hc(!1),Ot++),At=e,e},c:function(t,e,n){throw new St(t).fc(e,n),At=t,Ot++,t},pa:function(){return Ot},Fa:function(t){ge(t,!w,1,!v),ht.pc()},T:function(t){O?postMessage({cmd:"cleanupThread",thread:t}):st(t)},xa:Mt,j:function(t){throw At||(At=t),t},H:Ct,Ma:xt,ua:Rt,wa:jt,oa:kt,Ka:Dt,Ca:Pt,Ja:Ut,V:Ft,va:It,sa:Wt,La:Ht,ta:Lt,Ta:function(){},X:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout((()=>zt(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<n!=(c==r)&&(o=Math.max(u,o),e.setTime(e.getTime()+6e4*((0<n?c:o)-r))),a()[t+24>>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<e;r++)Xt[r]=o()[n+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<t)return!1;for(var n=1;4>=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<a;i++)e()[r+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<et))if(O)c(u),O||dt(X),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)K();dt(q),0<et||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),t()}),1)):t())}}if(u.UTF8ToString=Y,u.stringToUTF8=function(t,e,n){return B(t,r(),e,n)},u.lengthBytesUTF8=G,u.keepRuntimeAlive=Q,u.wasmMemory=j,u.stackSave=Ee,u.stackRestore=Me,u.stackAlloc=Ce,u.ExitStatus=ct,u.PThread=ht,rt=function t(){ve||ze(),ve||(rt=t)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return ze(),t.ready});t.exports=r},932:(t,e,n)=>{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<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof J))throw t})),process.on("unhandledRejection",(function(t){throw t})),h=(t,e)=>{if(_||0<L)throw process.exitCode=t,e;e instanceof J||w("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(d||y)&&(y?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),_scriptDir&&(m=_scriptDir),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=t=>{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<n-e&&t.buffer&&x)return x.decode(t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(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<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=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<t.length;++n){var r=t.charCodeAt(n);127>=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<t.length;)t.shift()(e)}var Q=[],K=0,tt=0;function et(t){this.Db=t,this.zb=t-24,this.Ub=function(t){M[this.zb+4>>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.length<e;)t=n[0]+t;return t}function i(t,e){return a(t,e,"0")}function o(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function u(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function c(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(pt(t.getFullYear())?ht:dt)[n];if(!(e>r-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:12<t&&(t-=12),i(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(pt(t.Cb+1900)?ht:dt)[n++]);return i(t.Kb+e,3)},"%m":function(t){return i(t.Hb+1,2)},"%M":function(t){return i(t.Zb,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.Gb&&12>t.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<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},k: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<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},g: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<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},s:nt,L:function(){var t=Q.pop();t||V("no exception to throw");var e=t.Db;throw t.Lb()||(Q.push(t),t.Jb(!0),t.Ib(!1),K++),tt=e,e},b:function(t,e,n){throw new et(t).Rb(e,n),tt=t,K++,t},la:function(){return K},i:function(t){throw tt||(tt=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(M[t>>>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<n!=(u==r)&&(i=Math.max(o,i),e.setTime(e.getTime()+6e4*((0<n?u:i)-r))),E[t+24>>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<a?(M[n>>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<r.length;++i)S[a++>>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<L||(_t(),Z(W),wt(0),st[1].length&<(1,10),st[2].length&<(2,10)),_||0<L||(e.onExit&&e.onExit(t),C=!0),h(t,new J(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var a=0,i=0;i<n;i++){var o=M[e>>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c<u;c++)lt(t,T[o+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<r;a++)S[e+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<B)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)z();Z(F),0<B||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),t()}),1)):t())}}if(e.UTF8ToString=j,e.stringToUTF8=function(t,e,n){return k(t,T,e,n)},e.lengthBytesUTF8=D,e.stackSave=At,e.stackRestore=St,e.stackAlloc=Tt,N=function t(){mt||Wt(),mt||(N=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return Wt(),t.ready});t.exports=r},967:(t,e)=>{"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<s;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can\'t get an input name");p.push(e),f.push(n.UTF8ToString(e))}for(let t=0;t<l;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can\'t get an output name");d.push(e),h.push(n.UTF8ToString(e))}return u.set(r,[r,p,d]),[r,f,h]},e.createSession=(t,n)=>{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;t<m;t++){const e=n[t][0],r=n[t][1],a=n[t][2];let o,u;if(Array.isArray(a)){u=4*a.length,o=p._malloc(u),O.push(o);let t=o/4;for(let e=0;e<a.length;e++){if("string"!=typeof a[e])throw new TypeError(`tensor data at index ${e} is not a string`);p.HEAPU32[t++]=(0,i.allocWasmString)(a[e],O)}}else u=a.byteLength,o=p._malloc(u),O.push(o),p.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),o);const s=p.stackSave(),l=p.stackAlloc(4*r.length);try{let t=l/4;r.forEach((e=>p.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;t<m;t++)p.HEAPU32[n++]=_[t],p.HEAPU32[r++]=y[e[t]];for(let t=0;t<g;t++)p.HEAPU32[i++]=0,p.HEAPU32[c++]=b[a[t]];let f=p._OrtRun(d,u,o,m,A,g,h,v);const w=[];if(0===f)for(let t=0;t<g;t++){const e=p.HEAPU32[h/4+t],n=p.stackSave(),r=p.stackAlloc(16);let a,i=0;try{if(f=p._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==f)throw new Error(`Can\'t access output tensor data. error code = ${f}`);let t=r/4;const o=p.HEAPU32[t++];i=p.HEAPU32[t++];const u=p.HEAPU32[t++],c=p.HEAPU32[t++],h=[];for(let t=0;t<c;t++)h.push(p.HEAPU32[u/4+t]);p._OrtFree(u);const d=0===h.length?1:h.reduce(((t,e)=>t*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n<d;n++){const r=p.HEAPU32[e++],a=n===d-1?void 0:p.HEAPU32[e]-r;t.push(p.UTF8ToString(r,a))}w.push([a,h,t])}else{const t=new(l(a))(d);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(p.HEAPU8.subarray(i,i+t.byteLength)),w.push([a,h,t])}}finally{p.stackRestore(n),"string"===a&&i&&p._free(i),p._OrtReleaseTensor(e)}}if(0===f)return w;throw new Error(`failed to call OrtRun(). error code = ${f}.`)}finally{p.stackRestore(t)}}finally{_.forEach(p._OrtReleaseTensor),O.forEach(p._free),p._OrtReleaseRunOptions(v),w.forEach(p._free)}},e.endProfiling=t=>{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:t=>{t.exports=function(t,e,n,r){var i=self||window;try{try{var o;try{o=new i.Blob([t])}catch(e){(o=new(i.BlobBuilder||i.WebKitBlobBuilder||i.MozBlobBuilder||i.MSBlobBuilder)).append(t),o=o.getBlob()}var s=i.URL||i.webkitURL,a=s.createObjectURL(o),u=new i[e](a,n);return s.revokeObjectURL(a),u}catch(r){return new i[e]("data:application/javascript,".concat(encodeURIComponent(t)),n)}}catch(t){if(!r)throw Error("Inline worker is not supported");return new i[e](r,n)}}},4154:t=>{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'},1670:t=>{t.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(t,e,n)=>{n.r(e),n.d(e,{flatbuffers:()=>r});var r={};r.Offset,r.Table,r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(t,e){this.low=0|t,this.high=0|e},r.Long.create=function(t,e){return 0==t&&0==e?r.Long.ZERO:new r.Long(t,e)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(t){return this.low==t.low&&this.high==t.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(t){if(t)e=t;else var e=1024;this.bb=r.ByteBuffer.allocate(e),this.space=e,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},r.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},r.Builder.prototype.forceDefaults=function(t){this.force_defaults=t},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(t,e){t>this.minalign&&(this.minalign=t);for(var n=1+~(this.bb.capacity()-this.space+e)&t-1;this.space<n+t+e;){var i=this.bb.capacity();this.bb=r.Builder.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)},r.Builder.prototype.pad=function(t){for(var e=0;e<t;e++)this.bb.writeInt8(--this.space,0)},r.Builder.prototype.writeInt8=function(t){this.bb.writeInt8(this.space-=1,t)},r.Builder.prototype.writeInt16=function(t){this.bb.writeInt16(this.space-=2,t)},r.Builder.prototype.writeInt32=function(t){this.bb.writeInt32(this.space-=4,t)},r.Builder.prototype.writeInt64=function(t){this.bb.writeInt64(this.space-=8,t)},r.Builder.prototype.writeFloat32=function(t){this.bb.writeFloat32(this.space-=4,t)},r.Builder.prototype.writeFloat64=function(t){this.bb.writeFloat64(this.space-=8,t)},r.Builder.prototype.addInt8=function(t){this.prep(1,0),this.writeInt8(t)},r.Builder.prototype.addInt16=function(t){this.prep(2,0),this.writeInt16(t)},r.Builder.prototype.addInt32=function(t){this.prep(4,0),this.writeInt32(t)},r.Builder.prototype.addInt64=function(t){this.prep(8,0),this.writeInt64(t)},r.Builder.prototype.addFloat32=function(t){this.prep(4,0),this.writeFloat32(t)},r.Builder.prototype.addFloat64=function(t){this.prep(8,0),this.writeFloat64(t)},r.Builder.prototype.addFieldInt8=function(t,e,n){(this.force_defaults||e!=n)&&(this.addInt8(e),this.slot(t))},r.Builder.prototype.addFieldInt16=function(t,e,n){(this.force_defaults||e!=n)&&(this.addInt16(e),this.slot(t))},r.Builder.prototype.addFieldInt32=function(t,e,n){(this.force_defaults||e!=n)&&(this.addInt32(e),this.slot(t))},r.Builder.prototype.addFieldInt64=function(t,e,n){!this.force_defaults&&e.equals(n)||(this.addInt64(e),this.slot(t))},r.Builder.prototype.addFieldFloat32=function(t,e,n){(this.force_defaults||e!=n)&&(this.addFloat32(e),this.slot(t))},r.Builder.prototype.addFieldFloat64=function(t,e,n){(this.force_defaults||e!=n)&&(this.addFloat64(e),this.slot(t))},r.Builder.prototype.addFieldOffset=function(t,e,n){(this.force_defaults||e!=n)&&(this.addOffset(e),this.slot(t))},r.Builder.prototype.addFieldStruct=function(t,e,n){e!=n&&(this.nested(e),this.slot(t))},r.Builder.prototype.nested=function(t){if(t!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")},r.Builder.prototype.notNested=function(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")},r.Builder.prototype.slot=function(t){this.vtable[t]=this.offset()},r.Builder.prototype.offset=function(){return this.bb.capacity()-this.space},r.Builder.growByteBuffer=function(t){var e=t.capacity();if(3221225472&e)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");var n=e<<1,i=r.ByteBuffer.allocate(n);return i.setPosition(n-e),i.bytes().set(t.bytes(),n-e),i},r.Builder.prototype.addOffset=function(t){this.prep(r.SIZEOF_INT,0),this.writeInt32(this.offset()-t+r.SIZEOF_INT)},r.Builder.prototype.startObject=function(t){this.notNested(),null==this.vtable&&(this.vtable=[]),this.vtable_in_use=t;for(var e=0;e<t;e++)this.vtable[e]=0;this.isNested=!0,this.object_start=this.offset()},r.Builder.prototype.endObject=function(){if(null==this.vtable||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);for(var t=this.offset(),e=this.vtable_in_use-1;e>=0&&0==this.vtable[e];e--);for(var n=e+1;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);var i=(n+2)*r.SIZEOF_SHORT;this.addInt16(i);var o=0,s=this.space;t:for(e=0;e<this.vtables.length;e++){var a=this.bb.capacity()-this.vtables[e];if(i==this.bb.readInt16(a)){for(var u=r.SIZEOF_SHORT;u<i;u+=r.SIZEOF_SHORT)if(this.bb.readInt16(s+u)!=this.bb.readInt16(a+u))continue t;o=this.vtables[e];break}}return o?(this.space=this.bb.capacity()-t,this.bb.writeInt32(this.space,o-t)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-t,this.offset()-t)),this.isNested=!1,t},r.Builder.prototype.finish=function(t,e,n){var i=n?r.SIZE_PREFIX_LENGTH:0;if(e){var o=e;if(this.prep(this.minalign,r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH+i),o.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var s=r.FILE_IDENTIFIER_LENGTH-1;s>=0;s--)this.writeInt8(o.charCodeAt(s))}this.prep(this.minalign,r.SIZEOF_INT+i),this.addOffset(t),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(t,e){this.finish(t,e,!0)},r.Builder.prototype.requiredField=function(t,e){var n=this.bb.capacity()-t,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+e))throw new Error("FlatBuffers: field "+e+" must be set")},r.Builder.prototype.startVector=function(t,e,n){this.notNested(),this.vector_num_elems=e,this.prep(r.SIZEOF_INT,t*e),this.prep(n,t*e)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(t){if(t instanceof Uint8Array)var e=t;else{e=[];for(var n=0;n<t.length;){var r,i=t.charCodeAt(n++);(r=i<55296||i>=56320?i:(i<<10)+t.charCodeAt(n++)+-56613888)<128?e.push(r):(r<2048?e.push(r>>6&31|192):(r<65536?e.push(r>>12&15|224):e.push(r>>18&7|240,r>>12&63|128),e.push(r>>6&63|128)),e.push(63&r|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length),n=0;for(var o=this.space,s=this.bb.bytes();n<e.length;n++)s[o++]=e[n];return this.endVector()},r.Builder.prototype.createLong=function(t,e){return r.Long.create(t,e)},r.ByteBuffer=function(t){this.bytes_=t,this.position_=0},r.ByteBuffer.allocate=function(t){return new r.ByteBuffer(new Uint8Array(t))},r.ByteBuffer.prototype.clear=function(){this.position_=0},r.ByteBuffer.prototype.bytes=function(){return this.bytes_},r.ByteBuffer.prototype.position=function(){return this.position_},r.ByteBuffer.prototype.setPosition=function(t){this.position_=t},r.ByteBuffer.prototype.capacity=function(){return this.bytes_.length},r.ByteBuffer.prototype.readInt8=function(t){return this.readUint8(t)<<24>>24},r.ByteBuffer.prototype.readUint8=function(t){return this.bytes_[t]},r.ByteBuffer.prototype.readInt16=function(t){return this.readUint16(t)<<16>>16},r.ByteBuffer.prototype.readUint16=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8},r.ByteBuffer.prototype.readInt32=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24},r.ByteBuffer.prototype.readUint32=function(t){return this.readInt32(t)>>>0},r.ByteBuffer.prototype.readInt64=function(t){return new r.Long(this.readInt32(t),this.readInt32(t+4))},r.ByteBuffer.prototype.readUint64=function(t){return new r.Long(this.readUint32(t),this.readUint32(t+4))},r.ByteBuffer.prototype.readFloat32=function(t){return r.int32[0]=this.readInt32(t),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(t){return r.int32[r.isLittleEndian?0:1]=this.readInt32(t),r.int32[r.isLittleEndian?1:0]=this.readInt32(t+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeUint8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeInt16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeUint16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeInt32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeUint32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeInt64=function(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)},r.ByteBuffer.prototype.writeUint64=function(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)},r.ByteBuffer.prototype.writeFloat32=function(t,e){r.float32[0]=e,this.writeInt32(t,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(t,e){r.float64[0]=e,this.writeInt32(t,r.int32[r.isLittleEndian?0:1]),this.writeInt32(t+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length<this.position_+r.SIZEOF_INT+r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");for(var t="",e=0;e<r.FILE_IDENTIFIER_LENGTH;e++)t+=String.fromCharCode(this.readInt8(this.position_+r.SIZEOF_INT+e));return t},r.ByteBuffer.prototype.__offset=function(t,e){var n=t-this.readInt32(t);return e<this.readInt16(n)?this.readInt16(n+e):0},r.ByteBuffer.prototype.__union=function(t,e){return t.bb_pos=e+this.readInt32(e),t.bb=this,t},r.ByteBuffer.prototype.__string=function(t,e){t+=this.readInt32(t);var n=this.readInt32(t),i="",o=0;if(t+=r.SIZEOF_INT,e===r.Encoding.UTF8_BYTES)return this.bytes_.subarray(t,t+n);for(;o<n;){var s,a=this.readUint8(t+o++);if(a<192)s=a;else{var u=this.readUint8(t+o++);if(a<224)s=(31&a)<<6|63&u;else{var l=this.readUint8(t+o++);s=a<240?(15&a)<<12|(63&u)<<6|63&l:(7&a)<<18|(63&u)<<12|(63&l)<<6|63&this.readUint8(t+o++)}}s<65536?i+=String.fromCharCode(s):(s-=65536,i+=String.fromCharCode(55296+(s>>10),56320+(1023&s)))}return i},r.ByteBuffer.prototype.__indirect=function(t){return t+this.readInt32(t)},r.ByteBuffer.prototype.__vector=function(t){return t+this.readInt32(t)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(t){return this.readInt32(t+this.readInt32(t))},r.ByteBuffer.prototype.__has_identifier=function(t){if(t.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var e=0;e<r.FILE_IDENTIFIER_LENGTH;e++)if(t.charCodeAt(e)!=this.readInt8(this.position_+r.SIZEOF_INT+e))return!1;return!0},r.ByteBuffer.prototype.createLong=function(t,e){return r.Long.create(t,e)}}},__webpack_module_cache__={};function __nested_webpack_require_546802__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var n=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t].call(n.exports,n,n.exports,__nested_webpack_require_546802__),n.exports}__nested_webpack_require_546802__.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return __nested_webpack_require_546802__.d(e,{a:e}),e},__nested_webpack_require_546802__.d=(t,e)=>{for(var n in e)__nested_webpack_require_546802__.o(e,n)&&!__nested_webpack_require_546802__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__nested_webpack_require_546802__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),__nested_webpack_require_546802__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__nested_webpack_require_546802__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __nested_webpack_exports__=__nested_webpack_require_546802__(6018);return __nested_webpack_exports__})())},378:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.defaultModelFetcher=void 0,e.defaultModelFetcher=t=>fetch(t).then(t=>t.arrayBuffer())},450:(t,e,n)=>{n.d(e,{InferenceSession:()=>f,Tensor:()=>h,env:()=>s,registerBackend:()=>o}),n.r(e);const r={},i=[],o=(t,e,n)=>{if(e&&"function"==typeof e.init&&"function"==typeof e.createSessionHandler){const o=r[t];if(void 0===o)r[t]={backend:e,priority:n};else{if(o.priority>n)return;if(o.priority===n&&o.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${n}`)}if(n>=0){const e=i.indexOf(t);-1!==e&&i.splice(e,1);for(let e=0;e<i.length;e++)if(r[i[e]].priority<=n)return void i.splice(e,0,t);i.push(t)}return}throw new TypeError("not a valid backend")},s=new class{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(t){if(void 0!==t){if("string"!=typeof t||-1===["verbose","info","warning","error","fatal"].indexOf(t))throw new Error(`Unsupported logging level: ${t}`);this.logLevelInternal=t}}get logLevel(){return this.logLevelInternal}},a="undefined"!=typeof BigInt64Array&&"function"==typeof BigInt64Array.from,u="undefined"!=typeof BigUint64Array&&"function"==typeof BigUint64Array.from,l=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),c=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);a&&(l.set("int64",BigInt64Array),c.set(BigInt64Array,"int64")),u&&(l.set("uint64",BigUint64Array),c.set(BigUint64Array,"uint64"));class d{constructor(t,e,n){let r,i,o;if("string"==typeof t)if(r=t,o=n,"string"===t){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");i=e}else{const n=l.get(t);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(e))i=n.from(e);else{if(!(e instanceof n))throw new TypeError(`A ${r} tensor's data must be type of ${n}`);i=e}}else if(o=e,Array.isArray(t)){if(0===t.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");const e=typeof t[0];if("string"===e)r="string",i=t;else{if("boolean"!==e)throw new TypeError(`Invalid element type of data array: ${e}.`);r="bool",i=Uint8Array.from(t)}}else{const e=c.get(t.constructor);if(void 0===e)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);r=e,i=t}if(void 0===o)o=[i.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");const s=(t=>{let e=1;for(let n=0;n<t.length;n++){const r=t[n];if("number"!=typeof r||!Number.isSafeInteger(r))throw new TypeError(`dims[${n}] must be an integer, got: ${r}`);if(r<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${r}`);e*=r}return e})(o);if(s!==i.length)throw new Error(`Tensor's size(${s}) does not match data length(${i.length}).`);this.dims=o,this.type=r,this.data=i,this.size=s}static bufferToTensor(t,e){if(void 0===t)throw new Error("Image buffer must be defined");if(void 0===e.height||void 0===e.width)throw new Error("Image height and width must be defined");const{height:n,width:r}=e,i=e.norm;let o,s;o=void 0===i||void 0===i.mean?255:i.mean,s=void 0===i||void 0===i.bias?0:i.bias;const a=void 0!==e.bitmapFormat?e.bitmapFormat:"RGBA",u=void 0!==e.tensorFormat&&void 0!==e.tensorFormat?e.tensorFormat:"RGB",l=n*r,c="RGBA"===u?new Float32Array(4*l):new Float32Array(3*l);let h=4,p=0,f=1,g=2,m=3,b=0,y=l,_=2*l,w=-1;"RGB"===a&&(h=3,p=0,f=1,g=2,m=-1),"RGBA"===u?w=3*l:"RBG"===u?(b=0,_=l,y=2*l):"BGR"===u&&(_=0,y=l,b=2*l);for(let e=0;e<l;e++,p+=h,g+=h,f+=h,m+=h)c[b++]=(t[p]+s)/o,c[y++]=(t[f]+s)/o,c[_++]=(t[g]+s)/o,-1!==w&&-1!==m&&(c[w++]=(t[m]+s)/o);return new d("float32",c,"RGBA"===u?[1,4,n,r]:[1,3,n,r])}static async fromImage(t,e){const n="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement,r="undefined"!=typeof ImageData&&t instanceof ImageData,i="undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap,o="undefined"!=typeof String&&(t instanceof String||"string"==typeof t);let s,a={};if(n){const n=document.createElement("canvas"),r=n.getContext("2d");if(null==r)throw new Error("Can not access image data");{let i=t.naturalHeight,o=t.naturalWidth;if(void 0!==e&&void 0!==e.resizedHeight&&void 0!==e.resizedWidth&&(i=e.resizedHeight,o=e.resizedWidth),void 0!==e){if(a=e,void 0!==e.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");if(a.tensorFormat="RGBA",void 0!==e.height&&e.height!==i)throw new Error("Image input config height doesn't match HTMLImageElement height");if(a.height=i,void 0!==e.width&&e.width!==o)throw new Error("Image input config width doesn't match HTMLImageElement width");a.width=o}else a.tensorFormat="RGBA",a.height=i,a.width=o;n.width=o,n.height=i,r.drawImage(t,0,0,o,i),s=r.getImageData(0,0,o,i).data}}else{if(!r){if(i){if(void 0===e)throw new Error("Please provide image config with format for Imagebitmap");if(void 0!==e.bitmapFormat)throw new Error("Image input config format must be defined for ImageBitmap");const n=document.createElement("canvas").getContext("2d");if(null!=n){const r=t.height,i=t.width;if(n.drawImage(t,0,0,i,r),s=n.getImageData(0,0,i,r).data,void 0!==e){if(void 0!==e.height&&e.height!==r)throw new Error("Image input config height doesn't match ImageBitmap height");if(a.height=r,void 0!==e.width&&e.width!==i)throw new Error("Image input config width doesn't match ImageBitmap width");a.width=i}else a.height=r,a.width=i;return d.bufferToTensor(s,a)}throw new Error("Can not access image data")}if(o)return new Promise((n,r)=>{const i=document.createElement("canvas"),o=i.getContext("2d");if(!t||!o)return r();const s=new Image;s.crossOrigin="Anonymous",s.src=t,s.onload=()=>{i.width=s.width,i.height=s.height,o.drawImage(s,0,0,i.width,i.height);const t=o.getImageData(0,0,i.width,i.height);if(void 0!==e){if(void 0!==e.height&&e.height!==i.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(a.height=i.height,void 0!==e.width&&e.width!==i.width)throw new Error("Image input config width doesn't match ImageBitmap width");a.width=i.width}else a.height=i.height,a.width=i.width;n(d.bufferToTensor(t.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}{const n="RGBA";let r,i;if(void 0!==e&&void 0!==e.resizedWidth&&void 0!==e.resizedHeight?(r=e.resizedHeight,i=e.resizedWidth):(r=t.height,i=t.width),void 0!==e){if(a=e,void 0!==e.bitmapFormat&&e.bitmapFormat!==n)throw new Error("Image input config format must be RGBA for ImageData");a.bitmapFormat="RGBA"}else a.bitmapFormat="RGBA";if(a.height=r,a.width=i,void 0!==e){const e=document.createElement("canvas");e.width=i,e.height=r;const n=e.getContext("2d");if(null==n)throw new Error("Can not access image data");n.putImageData(t,0,0),s=n.getImageData(0,0,i,r).data}else s=t.data}}if(void 0!==s)return d.bufferToTensor(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(t){var e,n;const r=document.createElement("canvas").getContext("2d");let i;if(null==r)throw new Error("Can not access image data");{const o=this.dims[3],s=this.dims[2],a=this.dims[1],u=void 0!==t&&void 0!==t.format?t.format:"RGB",l=void 0!==t&&void 0!==(null===(e=t.norm)||void 0===e?void 0:e.mean)?t.norm.mean:255,c=void 0!==t&&void 0!==(null===(n=t.norm)||void 0===n?void 0:n.bias)?t.norm.bias:0,d=s*o;if(void 0!==t){if(void 0!==t.height&&t.height!==s)throw new Error("Image output config height doesn't match tensor height");if(void 0!==t.width&&t.width!==o)throw new Error("Image output config width doesn't match tensor width");if(void 0!==t.format&&4===a&&"RGBA"!==t.format||3===a&&"RGB"!==t.format&&"BGR"!==t.format)throw new Error("Tensor format doesn't match input tensor dims")}const h=4;let p=0,f=1,g=2,m=3,b=0,y=d,_=2*d,w=-1;"RGBA"===u?(b=0,y=d,_=2*d,w=3*d):"RGB"===u?(b=0,y=d,_=2*d):"RBG"===u&&(b=0,_=d,y=2*d),i=r.createImageData(o,s);for(let t=0;t<s*o;p+=h,f+=h,g+=h,m+=h,t++)i.data[p]=(this.data[b++]-c)*l,i.data[f]=(this.data[y++]-c)*l,i.data[g]=(this.data[_++]-c)*l,i.data[m]=-1===w?255:(this.data[w++]-c)*l}return i}reshape(t){return new d(this.type,this.data,t)}}const h=d;class p{constructor(t){this.handler=t}async run(t,e,n){const r={};let i={};if("object"!=typeof t||null===t||t instanceof h||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if("object"==typeof e){if(null===e)throw new TypeError("Unexpected argument[1]: cannot be null.");if(e instanceof h)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(e)){if(0===e.length)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const t of e){if("string"!=typeof t)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(t))throw new RangeError(`'fetches' contains invalid output name: ${t}.`);r[t]=null}if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else{let t=!1;const s=Object.getOwnPropertyNames(e);for(const n of this.outputNames)if(-1!==s.indexOf(n)){const i=e[n];(null===i||i instanceof h)&&(t=!0,o=!1,r[n]=i)}if(t){if("object"==typeof n&&null!==n)i=n;else if(void 0!==n)throw new TypeError("'options' must be an object.")}else i=e}}else if(void 0!==e)throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const e of this.inputNames)if(void 0===t[e])throw new Error(`input '${e}' is missing in 'feeds'.`);if(o)for(const t of this.outputNames)r[t]=null;const s=await this.handler.run(t,r,i),a={};for(const t in s)Object.hasOwnProperty.call(s,t)&&(a[t]=new h(s[t].type,s[t].data,s[t].dims));return a}static async create(t,e,n,o){let s,a={};if("string"==typeof t){if(s=t,"object"==typeof e&&null!==e)a=e;else if(void 0!==e)throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(s=t,"object"==typeof e&&null!==e)a=e;else if(void 0!==e)throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{const r=t;let i=0,u=t.byteLength;if("object"==typeof e&&null!==e)a=e;else if("number"==typeof e){if(i=e,!Number.isSafeInteger(i))throw new RangeError("'byteOffset' must be an integer.");if(i<0||i>=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(u=t.byteLength-i,"number"==typeof n){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||i+u>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-i}].`);if("object"==typeof o&&null!==o)a=o;else if(void 0!==o)throw new TypeError("'options' must be an object.")}else if(void 0!==n)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==e)throw new TypeError("'options' must be an object.");s=new Uint8Array(r,i,u)}}const u=(a.executionProviders||[]).map(t=>"string"==typeof t?t:t.name),l=await(async t=>{const e=0===t.length?i:t,n=[];for(const t of e){const e=r[t];if(e){if(e.initialized)return e.backend;if(e.aborted)continue;const r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init()),await e.initPromise,e.initialized=!0,e.backend}catch(i){r||n.push({name:t,err:i}),e.aborted=!0}finally{delete e.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map(t=>`[${t.name}] ${t.err}`).join(", ")}`)})(u),c=await l.createSessionHandler(s,a);return new p(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}const f=p},457:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FrameProcessor=e.validateOptions=e.defaultV5FrameProcessorOptions=e.defaultLegacyFrameProcessorOptions=void 0;const r=n(832),i=n(33),o=[512,1024,1536];e.defaultLegacyFrameProcessorOptions={positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,preSpeechPadFrames:1,redemptionFrames:8,frameSamples:1536,minSpeechFrames:3,submitUserSpeechOnPause:!1},e.defaultV5FrameProcessorOptions={positiveSpeechThreshold:.5,negativeSpeechThreshold:.35,preSpeechPadFrames:3,redemptionFrames:24,frameSamples:512,minSpeechFrames:9,submitUserSpeechOnPause:!1},e.validateOptions=function(t){o.includes(t.frameSamples)||r.log.warn("You are using an unusual frame size"),(t.positiveSpeechThreshold<0||t.positiveSpeechThreshold>1)&&r.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(t.negativeSpeechThreshold<0||t.negativeSpeechThreshold>t.positiveSpeechThreshold)&&r.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),t.preSpeechPadFrames<0&&r.log.error("preSpeechPadFrames should be positive"),t.redemptionFrames<0&&r.log.error("redemptionFrames should be positive")};const s=t=>{const e=t.reduce((t,e)=>(t.push(t.at(-1)+e.length),t),[0]),n=new Float32Array(e.at(-1));return t.forEach((t,r)=>{const i=e[r];n.set(t,i)}),n};e.FrameProcessor=class{constructor(t,e,n){this.modelProcessFunc=t,this.modelResetFunc=e,this.options=n,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=t=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(t):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=t=>{const e=this.audioBuffer;this.audioBuffer=[];const n=this.speaking;if(this.reset(),n)if(e.reduce((t,e)=>e.isSpeech?t+1:t,0)>=this.options.minSpeechFrames){const n=s(e.map(t=>t.frame));t({msg:i.Message.SpeechEnd,audio:n})}else t({msg:i.Message.VADMisfire});return{}},this.process=async(t,e)=>{if(!this.active)return;const n=await this.modelProcessFunc(t),r=n.isSpeech>=this.options.positiveSpeechThreshold;if(e({probs:n,msg:i.Message.FrameProcessed,frame:t}),this.audioBuffer.push({frame:t,isSpeech:r}),r&&(this.speechFrameCount++,this.redemptionCounter=0),r&&!this.speaking&&(this.speaking=!0,e({msg:i.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.options.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,e({msg:i.Message.SpeechRealStart})),n.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.options.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const t=this.audioBuffer;if(this.audioBuffer=[],t.reduce((t,e)=>e.isSpeech?t+1:t,0)>=this.options.minSpeechFrames){const n=s(t.map(t=>t.frame));e({msg:i.Message.SpeechEnd,audio:n})}else e({msg:i.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.options.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.reset()}}},461:(t,e,n)=>{var r;Object.defineProperty(e,"__esModule",{value:!0}),e.SileroLegacy=void 0;const i=n(832);class o{constructor(t,e,n,r,i){this.ortInstance=t,this._session=e,this._h=n,this._c=r,this._sr=i,this.reset_state=()=>{const t=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",t,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",t,[2,1,64])},this.process=async t=>{const e={input:new this.ortInstance.Tensor("float32",t,[1,t.length]),h:this._h,c:this._c,sr:this._sr},n=await this._session.run(e);this._h=n.hn,this._c=n.cn;const[r]=n.output?.data;return{notSpeech:1-r,isSpeech:r}}}}e.SileroLegacy=o,r=o,o.new=async(t,e)=>{i.log.debug("initializing vad");const n=await e(),o=await t.InferenceSession.create(n),s=new t.Tensor("int64",[16000n]),a=Array(128).fill(0),u=new t.Tensor("float32",a,[2,1,64]),l=new t.Tensor("float32",a,[2,1,64]);return i.log.debug("vad is initialized"),new r(t,o,u,l,s)}},463:(t,e,n)=>{var r;Object.defineProperty(e,"__esModule",{value:!0}),e.SileroV5=void 0;const i=n(832);function o(t){const e=Array(256).fill(0);return new t.Tensor("float32",e,[2,1,128])}class s{constructor(t,e,n,r){this._session=t,this._state=e,this._sr=n,this.ortInstance=r,this.reset_state=()=>{this._state=o(this.ortInstance)},this.process=async t=>{const e={input:new this.ortInstance.Tensor("float32",t,[1,t.length]),state:this._state,sr:this._sr},n=await this._session.run(e);this._state=n.stateN;const[r]=n.output?.data;return{notSpeech:1-r,isSpeech:r}}}}e.SileroV5=s,r=s,s.new=async(t,e)=>{i.log.debug("Loading VAD...");const n=await e(),s=await t.InferenceSession.create(n),a=new t.Tensor("int64",[16000n]),u=o(t);return i.log.debug("...finished loading VAD"),new r(s,u,a,t)}},587:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=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 i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.NonRealTimeVAD=e.defaultNonRealTimeVADOptions=void 0;const s=o(n(264)),a=n(61),u=n(378),l=n(457),c=n(33),d=n(28),h=n(702);e.defaultNonRealTimeVADOptions={...l.defaultLegacyFrameProcessorOptions,ortConfig:void 0,modelURL:a.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:u.defaultModelFetcher},e.NonRealTimeVAD=class{static async new(t={}){const n={...e.defaultNonRealTimeVADOptions,...t};(0,l.validateOptions)(n),void 0!==n.ortConfig&&n.ortConfig(s);const r=()=>n.modelFetcher(n.modelURL),i=await d.SileroLegacy.new(s,r),o=new l.FrameProcessor(i.process,i.reset_state,{frameSamples:n.frameSamples,positiveSpeechThreshold:n.positiveSpeechThreshold,negativeSpeechThreshold:n.negativeSpeechThreshold,redemptionFrames:n.redemptionFrames,preSpeechPadFrames:n.preSpeechPadFrames,minSpeechFrames:n.minSpeechFrames,submitUserSpeechOnPause:n.submitUserSpeechOnPause});return o.resume(),new this(r,s,n,o)}constructor(t,e,n,r){this.modelFetcher=t,this.ort=e,this.options=n,this.frameProcessor=r}async*run(t,e){const n={nativeSampleRate:e,targetSampleRate:16e3,targetFrameSize:this.options.frameSamples},r=new h.Resampler(n);let i=0,o=0,s=0,a=[];for await(const e of r.stream(t)){await this.frameProcessor.process(e,t=>{a.push(t)});for(const t of a)switch(t.msg){case c.Message.SpeechStart:i=s*this.options.frameSamples/16;break;case c.Message.SpeechEnd:o=(s+1)*this.options.frameSamples/16,yield{audio:t.audio,start:i,end:o}}s++}const{msg:u,audio:l}=this.frameProcessor.endSegment(t=>{a.push(t)});for(const t of a)t.msg===c.Message.SpeechEnd&&(yield{audio:t.audio,start:i,end:s*this.options.frameSamples/16})}}},685:function(t,e,n){var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=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 i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.AudioNodeVAD=e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;const s=o(n(264)),a=n(378),u=n(457),l=n(832),c=n(33),d=n(28),h=n(702);e.DEFAULT_MODEL="legacy",e.ort=s,e.getDefaultRealTimeVADOptions=t=>({..."v5"===t?u.defaultV5FrameProcessorOptions:u.defaultLegacyFrameProcessorOptions,onFrameProcessed:(t,e)=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.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:e.DEFAULT_MODEL,workletOptions:{}});class p{static async new(t={}){const n={...(0,e.getDefaultRealTimeVADOptions)(t.model??e.DEFAULT_MODEL),...t};let r;(0,u.validateOptions)(n),r=void 0===n.stream?await navigator.mediaDevices.getUserMedia({audio:{...n.additionalAudioConstraints,channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}):n.stream;const i=new AudioContext,o=new MediaStreamAudioSourceNode(i,{mediaStream:r}),s=await f.new(i,n);return s.receive(o),new p(n,i,r,s,o)}constructor(t,e,n,r,i,o=!1){this.options=t,this.audioContext=e,this.stream=n,this.audioNodeVAD=r,this.sourceNode=i,this.listening=o,this.pause=()=>{this.audioNodeVAD.pause(),this.listening=!1},this.start=()=>{this.audioNodeVAD.start(),this.listening=!0},this.destroy=()=>{this.listening&&this.pause(),void 0===this.options.stream&&this.stream.getTracks().forEach(t=>t.stop()),this.sourceNode.disconnect(),this.audioNodeVAD.destroy(),this.audioContext.close()},this.setOptions=t=>{this.audioNodeVAD.setFrameProcessorOptions(t)}}}e.MicVAD=p;class f{static async new(t,n={}){const r={...(0,e.getDefaultRealTimeVADOptions)(n.model??e.DEFAULT_MODEL),...n};(0,u.validateOptions)(r),e.ort.env.wasm.wasmPaths=r.onnxWASMBasePath,void 0!==r.ortConfig&&r.ortConfig(e.ort);const i="v5"===r.model?"silero_vad_v5.onnx":"silero_vad_legacy.onnx",o=r.baseAssetPath+i,s="v5"===r.model?d.SileroV5.new:d.SileroLegacy.new;let l;try{l=await s(e.ort,()=>(0,a.defaultModelFetcher)(o))}catch(t){throw console.error(`Encountered an error while loading model file ${o}`),t}const c=new u.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}),h=new f(t,r,c);return await h.setupAudioNode(),h}constructor(t,e,n){this.ctx=t,this.options=e,this.bufferIndex=0,this.pause=()=>{this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.start=()=>{this.frameProcessor.resume()},this.receive=t=>{t.connect(this.audioNode)},this.processFrame=async t=>{await this.frameProcessor.process(t,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=t=>{switch(t.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(t.probs,t.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(t.audio)}},this.destroy=()=>{this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:c.Message.SpeechStop}),this.audioNode.disconnect(),this.gainNode?.disconnect()},this.setFrameProcessorOptions=t=>{this.frameProcessor.options={...this.frameProcessor.options,...t}},this.frameProcessor=n}async setupAudioNode(){if("audioWorklet"in this.ctx&&"function"==typeof AudioWorkletNode)try{const t=this.options.baseAssetPath+"vad.worklet.bundle.min.js";await this.ctx.audioWorklet.addModule(t);const e=this.options.workletOptions??{};return e.processorOptions={...e.processorOptions??{},frameSamples:this.options.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",e),void(this.audioNode.port.onmessage=async t=>{if(t.data?.message===c.Message.AudioFrame){let e=t.data.data;e instanceof ArrayBuffer||(e=new ArrayBuffer(t.data.data.byteLength),new Uint8Array(e).set(new Uint8Array(t.data.data)));const n=new Float32Array(e);await this.processFrame(n)}})}catch(t){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",t)}this.resampler=new h.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.options.frameSamples??480}),this.audioNode=this.ctx.createScriptProcessor(4096,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let t=!1;this.audioNode.onaudioprocess=async e=>{if(!t){t=!0;try{const t=e.inputBuffer.getChannelData(0);if(e.outputBuffer.getChannelData(0).fill(0),this.resampler){const e=this.resampler.process(t);for(const t of e)await this.processFrame(t)}}catch(t){console.error("Error processing audio:",t)}finally{t=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}e.AudioNodeVAD=f},702:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Resampler=void 0;const r=n(832);e.Resampler=class{constructor(t){this.options=t,this.process=t=>{const e=[];for(const n of t)for(this.inputBuffer.push(n);this.hasEnoughDataForFrame();){const t=this.generateOutputFrame();e.push(t)}return e},t.nativeSampleRate<16e3&&r.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(t){for(const e of t)for(this.inputBuffer.push(e);this.hasEnoughDataForFrame();){const t=this.generateOutputFrame();yield t}}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const t=new Float32Array(this.options.targetFrameSize);let e=0,n=0;for(;e<this.options.targetFrameSize;){let r=0,i=0;for(;n<Math.min(this.inputBuffer.length,(e+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const t=this.inputBuffer[n];void 0!==t&&(r+=t,i++),n++}t[e]=r/i,e++}return this.inputBuffer=this.inputBuffer.slice(n),t}}},832:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.log=e.LOG_PREFIX=void 0,e.LOG_PREFIX="[VAD]";const n=["error","debug","warn"].reduce((t,n)=>(t[n]=function(t){return(...n)=>{console[t](e.LOG_PREFIX,...n)}}(n),t),{});e.log=n},937:(t,e,n)=>{e.Jl=void 0;n(61),n(378),n(457),n(33),n(587);const r=n(20);r.audioFileToArray,r.minFramesForTargetMS,r.arrayBufferToBase64,r.encodeWAV;var i=n(685);Object.defineProperty(e,"Jl",{enumerable:!0,get:function(){return i.MicVAD}})}},__webpack_module_cache__={};function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var n=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(t,e)=>{for(var n in e)__webpack_require__.o(e,n)&&!__webpack_require__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__webpack_require__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__={},common_utils_namespaceObject={};__webpack_require__.r(common_utils_namespaceObject),__webpack_require__.d(common_utils_namespaceObject,{hasBrowserEnv:()=>hasBrowserEnv,hasStandardBrowserEnv:()=>hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:()=>hasStandardBrowserWebWorkerEnv,navigator:()=>_navigator,origin:()=>origin});const StyleRed="color: #f44336; font-weight: bold; font-size: larger",StyleGreen="color: #4caf50; font-weight: bold; font-size: larger",StyleBlue="color: #2196f3; font-weight: bold; font-size: larger",StyleOrange="color: #ff9800; font-weight: bold; font-size: larger",StylePurple="color: #ab47bc; font-weight: bold; font-size: larger",StyleTeal="color: #009688; font-weight: bold; font-size: larger",StylePink="color: #e91e63; font-weight: bold; font-size: larger",StyleBrown="color: #795548; font-weight: bold; font-size: larger",StyleGrey="color: #607d8b; font-weight: bold; font-size: larger",StyleBlack="color: #222; font-weight: bold; font-size: larger";class DefaultLogger{category;style;constructor(t){this.category=t?.category,this.style=t?.style||"color: #2196f3; font-weight: bold; font-size: larger"}getTimestamp(){const t=new Date,e=(t,e=2)=>t.toString().padStart(e,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}`}log(t,e,...n){const r=this.getTimestamp();let i=e;const o=n.filter(t=>void 0!==t).map(t=>{if("object"==typeof t&&null!==t)try{return JSON.stringify(t,null,2)}catch(t){return"[Unserializable Object]"}return t});if(this.category){i.startsWith(`[${this.category}]`)||(i=`[${this.category}] ${i}`);const e=i.match(/^[[][^[\]]+[\]]\s?(.*)$/);if(e){const n=`%c${r} %c[${this.category}]%c ${e[1]}`,i="color: #888; font-size: smaller;",s="color: inherit;";return void(o.length>0?console[t](n,i,this.style,s,...o):console[t](n,i,this.style,s))}}o.length>0?console[t](`${r} ${i}`,...o):console[t](`${r} ${i}`)}info(t,...e){this.log("info",t,...e)}trace(t,...e){this.log("trace",t,...e)}debug(t,...e){this.log("debug",t,...e)}warn(t,...e){this.log("warn",t,...e)}error(t,...e){this.log("error",t,...e)}}class EventEmitter{eventListeners=new Map;logger;constructor(t){this.logger=t}on(t,e){this.eventListeners.has(t)||this.eventListeners.set(t,[]),this.eventListeners.get(t).push(e)}off(t,e){const n=this.eventListeners.get(t);if(n){const t=n.indexOf(e);t>-1&&n.splice(t,1)}}async emit(t,e){const n=this.eventListeners.get(t)||[];if(this.logger){const n=this.sanitizeForLogging(e);this.logger.debug(`Emitting event: ${String(t)}`,n?{data:n}:void 0)}await Promise.all(n.map(t=>Promise.resolve(t(e))))}sanitizeForLogging(t){if(!t)return t;if(t instanceof ArrayBuffer)return`<ArrayBuffer ${t.byteLength} bytes>`;if(ArrayBuffer.isView(t))return`<${t.constructor.name} ${t.byteLength} bytes>`;if("object"==typeof t&&null!==t&&"audio"in t&&"string"==typeof t.audio&&t.audio.length>20){const e=Object.assign({},t),n=e.audio.substring(0,20);return e.audio=`${n}... [${e.audio.length} chars total]`,e}return t}removeAllListeners(t){t?this.eventListeners.delete(t):this.eventListeners.clear()}}const ConversationNetworkEvents={Message:"message",Error:"error",Disconnected:"disconnected",Connected:"connected"};class AudioPlayerEvents{static Playing="playing";static Paused="paused";static Stopped="stopped";static Enqueued="enqueued";static Error="error";static Ready="ready";static Finished="finished";static AboutToComplete="aboutToComplete"}class VisemeSchedulerEvents{static Paused="paused";static Playing="playing";static Viseme="viseme"}class AvatarManagerEvents{static AnimationStopped="animation-stopped";static AnimationChanged="animation-changed"}class MP3FrameExtractor{buffer=[];static FrameSync=[255,251];static BitrateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0];static SamplingRateTable=[44100,48e3,32e3];getRemainingBufferSize(){return this.buffer.length}extractRemainingFrames(){const t=[];let e=0;for(;e+4<=this.buffer.length;)if(255!==this.buffer[e]||224&~this.buffer[e+1])e+=1;else{const n=this.buffer.slice(e,e+4),r=this.getFrameLength(n);if(r>0&&e+r<=this.buffer.length){const n=new Uint8Array(r);for(let t=0;t<r;t++)n[t]=this.buffer[e+t];t.push(n),e+=r}else{if(-1!==r)break;e+=1}}return this.buffer=this.buffer.slice(e),t}feedAndExtractCompleteFrames(t){const e=[],n=this.buffer.length;this.buffer.length=n+t.length;for(let e=0;e<t.length;e++)this.buffer[n+e]=t[e];let r=0;for(;r+4<=this.buffer.length;)if(255!==this.buffer[r]||224&~this.buffer[r+1])r+=1;else{const t=this.buffer.slice(r,r+4),n=this.getFrameLength(t);if(n>0&&r+n<=this.buffer.length){const t=new Uint8Array(n);for(let e=0;e<n;e++)t[e]=this.buffer[r+e];e.push(t),r+=n}else{if(-1!==n)break;r+=1}}const i=new Uint8Array(this.buffer.length-r);for(let t=0;t<i.length;t++)i[t]=this.buffer[r+t];return this.buffer=this.buffer.slice(r),{frames:e,remainingData:i}}getFrameLength(t){if(t.length<4)return-1;const e=t[1]>>3&3,n=t[1]>>1&3;if(3!==e||1!==n)return-1;const r=t[2]>>4&15,i=t[2]>>2&3,o=t[2]>>1&1;if(15===r||0===r||3===i)return-1;const s=1e3*MP3FrameExtractor.BitrateTable[r],a=MP3FrameExtractor.SamplingRateTable[i];return 0===s||0===a?-1:Math.floor(144*s/a)+o}}class AudioPlayerTimingEvents{static AboutToComplete="about-to-complete"}class AudioPlayerTiming extends EventEmitter{getCurrentTime;getQueueLength;getQueueDuration;aboutToCompleteThresholdMs;hasTriggeredAboutToComplete=!1;aboutToCompleteTimer=null;isAudioComplete=!1;constructor(t,e,n,r){super(new DefaultLogger({category:"🎵 AudioPlayerTiming",style:StyleTeal})),this.getCurrentTime=t,this.getQueueLength=e,this.getQueueDuration=n,this.aboutToCompleteThresholdMs=r}onAudioComplete(){this.isAudioComplete=!0,this.checkAboutToComplete()}onAudioEnqueued(){this.isAudioComplete&&!this.hasTriggeredAboutToComplete&&this.checkAboutToComplete()}checkAboutToComplete(){if(this.hasTriggeredAboutToComplete||!this.isAudioComplete)return;this.aboutToCompleteTimer&&(clearTimeout(this.aboutToCompleteTimer),this.aboutToCompleteTimer=null);const t=1e3*this.getQueueDuration();if(this.logger.debug(`checkAboutToComplete: remainingDurationMs=${t}, queueLength=${this.getQueueLength()}`),0!==t)if(this.logger.debug(`Remaining audio duration: ${t}ms, threshold: ${this.aboutToCompleteThresholdMs}ms`),t<=this.aboutToCompleteThresholdMs)this.triggerAboutToComplete();else{const e=t-this.aboutToCompleteThresholdMs;this.logger.debug(`Setting timer for ${e}ms`),this.aboutToCompleteTimer=window.setTimeout(()=>{this.triggerAboutToComplete()},e)}else this.triggerAboutToComplete()}async triggerAboutToComplete(){this.hasTriggeredAboutToComplete||(this.hasTriggeredAboutToComplete=!0,this.logger.debug(`Audio about to complete (${this.aboutToCompleteThresholdMs}ms threshold)`),await this.emit(AudioPlayerTimingEvents.AboutToComplete))}reset(){this.hasTriggeredAboutToComplete=!1,this.isAudioComplete=!1,this.aboutToCompleteTimer&&(clearTimeout(this.aboutToCompleteTimer),this.aboutToCompleteTimer=null)}}const t=(t,e=4294967295,n=79764919)=>{const r=new Int32Array(256);let i,o,s,a=e;for(i=0;i<256;i++){for(s=i<<24,o=8;o>0;--o)s=2147483648&s?s<<1^n:s<<1;r[i]=s}for(i=0;i<t.length;i++)a=a<<8^r[255&(a>>24^t[i])];return a},n=t=>{const e=[];for(const n of t){let t=(n+42)%256;0===t||10===t||13===t||61===t?e.push("="+String.fromCharCode((t+64)%256)):e.push(String.fromCharCode(t))}return e.join("")},e=(e,n=t)=>{const r=t=>new Uint8Array(t.length/2).map((e,n)=>parseInt(t.substring(2*n,2*(n+1)),16)),i=t=>r(t)[0],o=new Map;[,8364,,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,,381,,,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,,382,376].forEach((t,e)=>o.set(t,e));const s=new Uint8Array(e.length);let a,u,l,c=!1,d=0,h=42,p=e.length>13&&"dynEncode"===e.substring(0,9),f=0;p&&(f=11,u=i(e.substring(9,f)),u<=1&&(f+=2,h=i(e.substring(11,f))),1===u&&(f+=8,l=(t=>new DataView(r(t).buffer).getInt32(0,!0))(e.substring(13,f))));const g=256-h;for(let t=f;t<e.length;t++)if(a=e.charCodeAt(t),61!==a||c){if(92===a&&t<e.length-5&&p){const n=e.charCodeAt(t+1);117!==n&&85!==n||(a=parseInt(e.substring(t+2,t+6),16),t+=5)}if(a>255){const t=o.get(a);t&&(a=t+127)}c&&(c=!1,a-=64),s[d++]=a<h&&a>0?a+g:a-h}else c=!0;const m=s.subarray(0,d);if(p&&1===u){const t=n(m);if(t!==l){const e="Decode failed crc32 validation";throw console.error("`simple-yenc`\n",e+"\n","Expected: "+l+"; Got: "+t+"\n","Visit https://github.com/eshaz/simple-yenc for more information"),Error(e)}}return m},r=(e,n='"',r=t,i)=>{const o=(t,e)=>(t%e+e)%e,s=(t,e)=>e.push(String.fromCharCode(61,(t+64)%256)),a=t=>t.map(t=>t.toString(16).padStart(2,"0"));let u,l,c=[],d=1/0,h=Array(256).fill(0);if('"'===n?(l=[0,8,9,10,11,12,13,34,92,61],u=t=>0===t||8===t||9===t||10===t||11===t||12===t||13===t||34===t||92===t||61===t):"'"===n?(l=[0,8,9,10,11,12,13,39,92,61],u=t=>0===t||8===t||9===t||10===t||11===t||12===t||13===t||39===t||92===t||61===t):"`"===n&&(l=[13,61,96],c=[7,205,231],u=(t,e)=>13===t||36===t&&123===e||61===t||92===t&&(85===e||117===e)||96===t),void 0===i){i=0;for(let t=0;t<e.length;t++){const n=0|e[t];h[n]++;for(let r=0;r<c.length;r++){const i=c[r];o(n-e[t+1]|0,256)===i&&h[n]++}}for(let t=0;t<256;t++){let e=0;for(let n=0;n<l.length;n++)e+=h[o(l[n]-t,256)];e<d&&(d=e,i=t)}}const p=["dynEncode","01",a([i]),...a((t=>{const e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),[...e]})(r(e)))];for(let t=0;t<e.length;t++){const n=(e[t]+i)%256;u(n,(e[t+1]+i)%256)?s(n,p):p.push(String.fromCharCode(n))}return"\\"===p[p.length-1]&&(p.pop(),s(92,p)),p.join("")},o=t=>t.replace(/[\\]/g,"\\\\").replace(/[`]/g,"\\`").replace(/\${/g,"\\${");function WASMAudioDecoderCommon(){const t=Uint8Array,n=Float32Array;WASMAudioDecoderCommon.modules||Object.defineProperties(WASMAudioDecoderCommon,{modules:{value:new WeakMap},setModule:{value(t,e){WASMAudioDecoderCommon.modules.set(t,Promise.resolve(e))}},getModule:{value(t,n){let r=WASMAudioDecoderCommon.modules.get(t);return r||(n?r=WebAssembly.compile(e(n)):(n=t.wasm,r=WASMAudioDecoderCommon.inflateDynEncodeString(n).then(t=>WebAssembly.compile(t))),WASMAudioDecoderCommon.modules.set(t,r)),r}},concatFloat32:{value(t,e){let r=new n(e),i=0,o=0;for(;i<t.length;)r.set(t[i],o),o+=t[i++].length;return r}},getDecodedAudio:{value:(t,e,n,r,i)=>({errors:t,channelData:e,samplesDecoded:n,sampleRate:r,bitDepth:i})},getDecodedAudioMultiChannel:{value(t,e,n,r,i,o){let s,a,u=[];for(s=0;s<n;s++){const t=[];for(a=0;a<e.length;)t.push(e[a++][s]||[]);u.push(WASMAudioDecoderCommon.concatFloat32(t,r))}return WASMAudioDecoderCommon.getDecodedAudio(t,u,r,i,o)}},inflateDynEncodeString:{value:n=>(n=e(n),new Promise(e=>{const r=String.raw`dynEncode012804c7886d()((()>+*§§)§,§§§§)§+§§§)§+.-()(*)-+)(.7*§)i¸¸,3§(i¸¸,3/G+.¡*(,(,3+)2å:-),§H(P*DI*H(P*@I++hH)H*r,hH(H(P*<J,i)^*<H,H(P*4U((I-H(H*i0J,^*DH+H-H*I+H,I*4)33H(H*H)^*DH(H+H)^*@H+i§H)i§3æ*).§K(iHI/+§H,iHn,§H+i(H+i(rCJ0I,H*I-+hH,,hH(H-V)(i)J.H.W)(i)c)(H,i)I,H-i*I-4)33i(I.*hH(V)(H+n5(H(i*I-i(I,i)I.+hH,i*J+iHn,hi(I-i*I,+hH,H/H-c)(H,iFn,hi(I,+hH,H0n5-H*V)(J(,hH/H(i)J(H(V)(J(i)c)(H)H(i)H,c)(3H*i*I*H,i)I,4(3(-H(H,W)(H-I-H,i*I,4)3(3(3H,H-I1H+I,H.i)H1V)(J.i(v5(33H.-H(H,i(c)(H,i*I,4)333)-§i*I*+§H*iHn,hi73H,H(i)8(H+J+H)P*(H*V)(J-r,§H)P*,H.i)H+H,i)V)(-H*i*I*H+i)I+H-H.I.H,H-i)I,4)333Ã+)-§iø7i(^*(iü7I,*h+hH+iDn,h*hilI+i)I,+hH+,hH+iô7H,c)(i)H+i´8W)(H,I,H+i*I+4)-+hH(H)8*J-i(p5.*h*h*hH-i')u,hH(P*(J+,hH(P*0J,H(P*,n50H+H,H-b((3H(P*0i)I.4)3H-i¨*n5*H-iÅ*s,hi73H-i)J+V)&+I,H(H+V)æ,8(I.H(H*8*J-i(p51H-i)J+i¸7V)(H(H+iø7V)(8(J/H(P*0J+s,hi73H+H,H.J,I.H(P*(m5(H.H(P*,s5.+hH,m5*H(P*(J.H+H.H+H/U((b((H(H(P*0i)J+^*0H,i)I,4(3(3H(H.^*03H-i¨*o5)33i(73(3(3-H,H+i)c)(H,i*I,H+i)I+4)33i)I-3H-3!2)0§K(i2J,L(H,H(^*(H,H*^*4H,i(^*0H,i(^*DH,j(_*<H,H)P*(^*,H,H+P*(^*8*h*h+hH,i)8(I3i§I**h*h*h*h*h*h*hH,i*8(6+(),03H,j(_*@i*I-H,P*<J.i,J(H,P*8J/s50H,H.i+J0^*<i¦I*H.H,P*4J1J.U(*H.U((J2i')o5/H.U()I.H,H(^*<H0H1U((H.i0J.i§i0i')o5/H/H.H2J*H(J.q50H,P*0J/H*I-H,P*(J0,hH,P*,H-q,hi)I-423+hH*m5+H/H0H(H1U((b((H/i)I/H(i)I(H*i)I*4(3(3H,H.^*<H,H-^*04*3iØ1U((5+i(I(i¨7i1^*(i$6iè1^*(i°7iè6^*(i¬7iÈ6^*(+hH(iÈ*n,hiÈ*I(+hH(i¨,n,hi¨,I(+hH(iØ,n,hiØ,I(+hH(iè,o,hH,i-H(i0c)(H(i*I(4)33iè1i1H,i-iÈ*8)Bi(I(+hH(ido,hH,i-H(i-c)(H(i*I(4)33iÈ6iè6H,i-iF8)BiØ1i)b((41-H,i-H(i/c)(H(i*I(4)3(3(-H,i-H(i1c)(H(i*I(4)3(3(-H,i-H(i0c)(H(i*I(4)3(3(3H,H/^*0H,H(^*<3i(I*4*3H,H,i¸)^*TH,H,iø-^*PH,H,iX^*LH,H,i(^*HH,i-8(I(H,i-8(I-i¥I*H,i,8(I.H(iErH-iEr5)H(i©*I1H-i)I0i(i;H.i,J(i(H(i(rCJ(J*H*i;sCI*i¨1I-H(I/+hH/,hH,i-H-V)(i)H,i+8(c)(H/i)I/H-i*I-H*i)I*4)-H(i)i¨1I/+hH(H*o,hH,i-H/V)(i)i(c)(H/i*I/H(i)I(4)33i¤I*H,iø-H,i¸)H,i-i;8)5+H0H1I2i(I-+hH-H2p,hH,H,iP8*J*i(p5-H*i7u,hH,i-H-i)H*c)(H-i)I-4*3i(I/i+I.i+I(*h*h*hH*i86*(*)3H-m,hi£I*403H-i)H,W)-I/i*I(4)3i3I.i/I(3H2H,H(8(H.J(H-J.p,hi¢I*4.3H,i-H-i)I*+hH(,hH*H/c)(H*i*I*H(i)I(4)-H.I-4+3(3(33H,W)1m,hiI*4,3H,iø-H,i¸)H,i-H18)J(,hi¡I*H(i(p5,H1H,V)ú-H,V)ø-o5,3H,i(H,iXH,i-H1i)H08)J(,hi I*H(i(p5,H0H,V)H,V)o5,3H,H,iPH,iH8+I*4+3(3(3H,i$6i¬78+I*3H*H3m5(3i)I-H*i(r5)3H)H,P*0^*(H+H,P*<^*(H*I-3H,i2L(H-33Á)+(i¨03b+(,(-(.(/(0(1(2(3(5(7(9(;(?(C(G(K(S([(c(k({(((«(Ë(ë((*)(iø03O)()()()(*(*(*(*(+(+(+(+(,(,(,(,(-(-(-(-(i¨13M8(9(:(((0(/(1(.(2(-(3(,(4(+(5(*(6()(7(T7*S7US0U `;WASMAudioDecoderCommon.getModule(WASMAudioDecoderCommon,r).then(t=>WebAssembly.instantiate(t,{})).then(({exports:r})=>{const i=new Map(Object.entries(r)),o=i.get("puff"),s=i.get("memory").buffer,a=new t(s),u=new DataView(s);let l=i.get("__heap_base");const c=n.length,d=l;l+=4,u.setInt32(d,c,!0);const h=l;l+=c,a.set(n,h);const p=l;l+=4,u.setInt32(p,a.byteLength-l,!0),o(l,p,h,d),e(a.slice(l,l+u.getInt32(p,!0)))})}))}}),Object.defineProperty(this,"wasm",{enumerable:!0,get:()=>this._wasm}),this.getOutputChannels=(t,e,n)=>{let r=[],i=0;for(;i<e;)r.push(t.slice(i*n,i++*n+n));return r},this.allocateTypedArray=(t,e,n=!0)=>{const r=this._wasm.malloc(e.BYTES_PER_ELEMENT*t);return n&&this._pointers.add(r),{ptr:r,len:t,buf:new e(this._wasm.HEAP,r,t)}},this.free=()=>{this._pointers.forEach(t=>{this._wasm.free(t)}),this._pointers.clear()},this.codeToString=t=>{const e=[],n=new Uint8Array(this._wasm.HEAP);for(let r=n[t];0!==r;r=n[++t])e.push(r);return String.fromCharCode.apply(null,e)},this.addError=(t,e,n,r,i,o)=>{t.push({message:e,frameLength:n,frameNumber:r,inputBytes:i,outputSamples:o})},this.instantiate=(t,e)=>(e&&WASMAudioDecoderCommon.setModule(t,e),this._wasm=new t(WASMAudioDecoderCommon).instantiate(),this._pointers=new Set,this._wasm.ready.then(()=>this))}function EmscriptenWASM(t){var e,n,r,i=t=>console.log(t),o=t=>console.error(t);function s(){}function a(t){throw t}function u(){a("missing function: INT123_compat_close")}u.stub=!0;for(var l={},c=[null,[],[]],d=new TextDecoder,h=(t,e)=>{var n=c[t];0===e||10===e?((1===t?i:o)(((t,e=0,n=NaN)=>{for(var r=e+n,i=e;t[i]&&!(i>=r);)++i;return d.decode(t.buffer?t.subarray(e,i):new Uint8Array(t.slice(e,i)))})(n)),n.length=0):n.push(e)},p=new Uint8Array(123),f=25;f>=0;--f)p[48+f]=52+f,p[65+f]=f,p[97+f]=26+f;p[43]=62,p[47]=63;var g,m,b,y,_,w,v,x={j:u,c:()=>a(""),b:()=>{},d:(t,e)=>{if(l[t]&&(clearTimeout(l[t].id),delete l[t]),!e)return 0;var n=setTimeout(()=>{delete l[t],v(t,performance.now())},e);return l[t]={id:n,timeout_ms:e},0},e:t=>(e.length,!1),g:t=>52,h:(t,e,n,r)=>52,i:function(t,e,n,r){var i;return e=(i=e)<-9007199254740992||i>9007199254740992?NaN:Number(i),70},f:(t,r,i,o)=>{for(var s=0,a=0;a<i;a++){var u=n[r>>2],l=n[r+4>>2];r+=8;for(var c=0;c<l;c++)h(t,e[u+c]);s+=l}return n[o>>2]=s,0},a:t=>{throw`exit(${t})`}};EmscriptenWASM.wasm||Object.defineProperty(EmscriptenWASM,"wasm",{get:()=>String.raw`dynEncode01dd21c54d17j¢>¡-é!Dt 9&W U§®}»/6|ºì,ÜÐ*ÝÙÂ:C#ÈEÅõkµÄqÁ¹BCdq$GPPxÚý¾ýB{jð=M¸ìOÑ-Ia,¢áÅ Ó®µôEù= *f®Ø"þèÒ ËøÓÉÄà󫤡ù|þ«ôñ«´ÁÜú¤«ìe«p±§W6(¶¢ÏÑIZ»¥'T28òÞ6<±*h²ëHñ'q©ññ+9LÏ8n'!ò©åP.Þot__¹§ü 0J]ío Zï óÚºM´õjÈ¿n)å½ðN\]óÐÖ]±<¿_>»5Ûÿ-'2[HÕo×m}&xÎÿú&ôì¯ /ý§iÂÐÈRB÷¸M°G÷;;T8kB7ïQûzL´¨ÛÍD9$EnA¶¸ûÃv4òCû㨾YcÐ>t2çZéÂ{¬½«KØB6cvpR=}vªã4ÀP¿Ø»ä4ûwѽ®üªä~Ô±CÇJÓª±.NÉ\*±8jècª= |_VÃK×ã2)§}¼
gb/!ôÀV~:0-ÈÀu²Ì/@LO*ÃL1?çRMljÀw
|
|
2
|
+
var e={20:(e,t)=>{function n(e,t,n){for(let i=0;i<n.length;i++)e.setUint8(t+i,n.charCodeAt(i))}Object.defineProperty(t,"__esModule",{value:!0}),t.audioFileToArray=t.encodeWAV=t.arrayBufferToBase64=t.minFramesForTargetMS=void 0,t.minFramesForTargetMS=function(e,t,n=16e3){return Math.ceil(e*n/1e3/t)},t.arrayBufferToBase64=function(e){const t=new Uint8Array(e),n=t.byteLength,i=new Array(n);for(let e=0;e<n;e++){const n=t[e];if(void 0===n)break;i[e]=String.fromCharCode(n)}return btoa(i.join(""))},t.encodeWAV=function(e,t=3,i=16e3,r=1,s=32){const a=s/8,o=r*a,u=new ArrayBuffer(44+e.length*a),l=new DataView(u);return n(l,0,"RIFF"),l.setUint32(4,36+e.length*a,!0),n(l,8,"WAVE"),n(l,12,"fmt "),l.setUint32(16,16,!0),l.setUint16(20,t,!0),l.setUint16(22,r,!0),l.setUint32(24,i,!0),l.setUint32(28,i*o,!0),l.setUint16(32,o,!0),l.setUint16(34,s,!0),n(l,36,"data"),l.setUint32(40,e.length*a,!0),1===t?function(e,t,n){for(let i=0;i<n.length;i++,t+=2){const r=Math.max(-1,Math.min(1,n[i]));e.setInt16(t,r<0?32768*r:32767*r,!0)}}(l,44,e):function(e,t,n){for(let i=0;i<n.length;i++,t+=4)e.setFloat32(t,n[i],!0)}(l,44,e),u},t.audioFileToArray=async function(e){const t=new OfflineAudioContext(1,1,44100),n=new FileReader;let i=null;if(await new Promise(r=>{n.addEventListener("loadend",()=>{const e=n.result;t.decodeAudioData(e,e=>{i=e,t.startRendering().then(()=>{console.log("Rendering completed successfully"),r()}).catch(e=>{console.error("Rendering failed: ",e)})},e=>{console.log("Error with decoding audio data: ",e)})}),n.readAsArrayBuffer(e)}),null===i)throw Error("some shit");const r=i,s=new Float32Array(r.length);for(let e=0;e<r.length;e++)for(let t=0;t<r.numberOfChannels;t++){const n=r.getChannelData(t)[e],i=s[e];if(void 0===n||void 0===i)throw new Error("sample or out[i] is undefined");s[e]=i+n}return{audio:s,sampleRate:r.sampleRate}}},28:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.SileroV5=t.SileroLegacy=void 0,r(n(55),t);var s=n(461);Object.defineProperty(t,"SileroLegacy",{enumerable:!0,get:function(){return s.SileroLegacy}});var a=n(463);Object.defineProperty(t,"SileroV5",{enumerable:!0,get:function(){return a.SileroV5}})},33:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.Message=void 0,function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"}(n||(t.Message=n={}))},55:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},61:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baseAssetPath=void 0;const n="undefined"!=typeof window&&void 0!==window.document?window.document.currentScript:null;let i="/";n&&(i=n.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),t.baseAssetPath=i},378:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultModelFetcher=void 0,t.defaultModelFetcher=e=>fetch(e).then(e=>e.arrayBuffer())},457:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FrameProcessor=t.validateOptions=t.defaultFrameProcessorOptions=void 0;const i=n(832),r=n(33);t.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1},t.validateOptions=function(e){(e.positiveSpeechThreshold<0||e.positiveSpeechThreshold>1)&&i.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(e.negativeSpeechThreshold<0||e.negativeSpeechThreshold>e.positiveSpeechThreshold)&&i.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),e.preSpeechPadMs<0&&i.log.error("preSpeechPadMs should be positive"),e.redemptionMs<0&&i.log.error("redemptionMs should be positive"),e.minSpeechMs<0&&i.log.error("minSpeechMs should be positive")};const s=e=>{const t=e.reduce((e,t)=>(e.push(e.at(-1)+t.length),e),[0]),n=new Float32Array(t.at(-1));return e.forEach((e,i)=>{const r=t[i];n.set(e,r)}),n};function a(e,t){return{redemptionFrames:Math.floor(e.redemptionMs/t),preSpeechPadFrames:Math.floor(e.preSpeechPadMs/t),minSpeechFrames:Math.floor(e.minSpeechMs/t)}}t.FrameProcessor=class{constructor(e,t,n,i){this.modelProcessFunc=e,this.modelResetFunc=t,this.options=n,this.msPerFrame=i,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=e=>{this.options={...this.options,...e};const{redemptionFrames:t,preSpeechPadFrames:n,minSpeechFrames:i}=a(this.options,this.msPerFrame);this.redemptionFrames=t,this.preSpeechPadFrames=n,this.minSpeechFrames=i},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=e=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(e):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=e=>{const t=this.audioBuffer;this.audioBuffer=[];const n=this.speaking;if(this.reset(),n)if(t.reduce((e,t)=>t.isSpeech?e+1:e,0)>=this.minSpeechFrames){const n=s(t.map(e=>e.frame));e({msg:r.Message.SpeechEnd,audio:n})}else e({msg:r.Message.VADMisfire});return{}},this.process=async(e,t)=>{if(!this.active)return;const n=await this.modelProcessFunc(e),i=n.isSpeech>=this.options.positiveSpeechThreshold;if(t({probs:n,msg:r.Message.FrameProcessed,frame:e}),this.audioBuffer.push({frame:e,isSpeech:i}),i&&(this.speechFrameCount++,this.redemptionCounter=0),i&&!this.speaking&&(this.speaking=!0,t({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,t({msg:r.Message.SpeechRealStart})),n.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const e=this.audioBuffer;if(this.audioBuffer=[],e.reduce((e,t)=>t.isSpeech?e+1:e,0)>=this.minSpeechFrames){const n=s(e.map(e=>e.frame));t({msg:r.Message.SpeechEnd,audio:n})}else t({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:o,preSpeechPadFrames:u,minSpeechFrames:l}=a(this.options,this.msPerFrame);this.redemptionFrames=o,this.preSpeechPadFrames=u,this.minSpeechFrames=l,this.reset()}}},461:(e,t,n)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.SileroLegacy=void 0;const r=n(832);class s{constructor(e,t,n,i,r){this.ortInstance=e,this._session=t,this._h=n,this._c=i,this._sr=r,this.reset_state=()=>{const e=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",e,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",e,[2,1,64])},this.process=async e=>{const t={input:new this.ortInstance.Tensor("float32",e,[1,e.length]),h:this._h,c:this._c,sr:this._sr},n=await this._session.run(t);this._h=n.hn,this._c=n.cn;const[i]=n.output?.data;return{notSpeech:1-i,isSpeech:i}},this.release=async()=>{await this._session.release(),this._h.dispose(),this._c.dispose(),this._sr.dispose()}}}t.SileroLegacy=s,i=s,s.new=async(e,t)=>{r.log.debug("initializing vad");const n=await t(),s=await e.InferenceSession.create(n),a=new e.Tensor("int64",[16000n]),o=Array(128).fill(0),u=new e.Tensor("float32",o,[2,1,64]),l=new e.Tensor("float32",o,[2,1,64]);return r.log.debug("vad is initialized"),new i(e,s,u,l,a)}},463:(e,t,n)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.SileroV5=void 0;const r=n(832);function s(e){const t=Array(256).fill(0);return new e.Tensor("float32",t,[2,1,128])}class a{constructor(e,t,n,i){this._session=e,this._state=t,this._sr=n,this.ortInstance=i,this.reset_state=()=>{this._state=s(this.ortInstance)},this.process=async e=>{const t={input:new this.ortInstance.Tensor("float32",e,[1,e.length]),state:this._state,sr:this._sr},n=await this._session.run(t);if(!n.stateN)throw new Error("No state from model");if(this._state=n.stateN,!n.output?.data)throw new Error("No output from model");const i=n.output.data[0];if("number"!=typeof i)throw new Error("Weird output data");return{notSpeech:1-i,isSpeech:i}},this.release=async()=>{await this._session.release(),this._state.dispose(),this._sr.dispose()}}}t.SileroV5=a,i=a,a.new=async(e,t)=>{r.log.debug("Loading VAD...");const n=await t(),a=await e.InferenceSession.create(n),o=new e.Tensor("int64",[16000n]),u=s(e);return r.log.debug("...finished loading VAD"),new i(a,u,o,e)}},587:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.NonRealTimeVAD=t.defaultNonRealTimeVADOptions=void 0;const a=s(n(603)),o=n(61),u=n(378),l=n(457),d=n(33),h=n(28),c=n(702);t.defaultNonRealTimeVADOptions={...l.defaultFrameProcessorOptions,modelURL:o.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:u.defaultModelFetcher},t.NonRealTimeVAD=class{static async new(e={}){const n={...t.defaultNonRealTimeVADOptions,...e};(0,l.validateOptions)(n),void 0!==n.ortConfig&&n.ortConfig(a);const i=()=>n.modelFetcher(n.modelURL),r=await h.SileroLegacy.new(a,i),s=new l.FrameProcessor(r.process,r.reset_state,{positiveSpeechThreshold:n.positiveSpeechThreshold,negativeSpeechThreshold:n.negativeSpeechThreshold,redemptionMs:n.redemptionMs,preSpeechPadMs:n.preSpeechPadMs,minSpeechMs:n.minSpeechMs,submitUserSpeechOnPause:n.submitUserSpeechOnPause},96);return s.resume(),new this(i,a,n,s)}constructor(e,t,n,i){this.modelFetcher=e,this.ort=t,this.options=n,this.frameProcessor=i,this.frameSamples=1536}async*run(e,t){const n={nativeSampleRate:t,targetSampleRate:16e3,targetFrameSize:this.frameSamples},i=new c.Resampler(n);let r=0,s=0,a=0;for await(const t of i.stream(e)){const e=[];await this.frameProcessor.process(t,t=>{e.push(t)});for(const t of e)switch(t.msg){case d.Message.SpeechStart:r=a*this.frameSamples/16;break;case d.Message.SpeechEnd:s=(a+1)*this.frameSamples/16,yield{audio:t.audio,start:r,end:s}}a++}const o=[];this.frameProcessor.endSegment(e=>{o.push(e)});for(const e of o)e.msg===d.Message.SpeechEnd&&(yield{audio:e.audio,start:r,end:a*this.frameSamples/16})}}},593:(e,t,n)=>{var i=(()=>{var e,t,i,r,s,a,o,u,l,d,h,c,p,f,m,g,y,w,b,_,$,v,x,S,T,k,E,C,I,A,R,M,z,O=Object.defineProperty,P=Object.getOwnPropertyDescriptor,B=Object.getOwnPropertyNames,D=Object.prototype.hasOwnProperty,U=n(687),L=(e,t)=>()=>(e&&(t=e(e=0)),t),N=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})},H=e=>((e,t,n,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of B(t))!D.call(e,n)&&undefined!==n&&O(e,n,{get:()=>t[n],enumerable:!(i=P(t,n))||i.enumerable});return e})(O({},"__esModule",{value:!0}),e),F=L(()=>{e=new Map,t=[],i=(n,i,r)=>{if(i&&"function"==typeof i.init&&"function"==typeof i.createInferenceSessionHandler){let s=e.get(n);if(void 0===s)e.set(n,{backend:i,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==i)throw new Error(`cannot register backend "${n}" using priority ${r}`)}if(r>=0){let i=t.indexOf(n);-1!==i&&t.splice(i,1);for(let i=0;i<t.length;i++)if(e.get(t[i]).priority<=r)return void t.splice(i,0,n);t.push(n)}return}throw new TypeError("not a valid backend")},r=async t=>{let n=e.get(t);if(!n)return"backend not found.";if(n.initialized)return n.backend;if(n.aborted)return n.error;{let e=!!n.initPromise;try{return e||(n.initPromise=n.backend.init(t)),await n.initPromise,n.initialized=!0,n.backend}catch(t){return e||(n.error=`${t}`,n.aborted=!0),n.error}finally{delete n.initPromise}}},s=async e=>{let n,i=e.executionProviders||[],s=i.map(e=>"string"==typeof e?e:e.name),a=0===s.length?t:s,o=[],u=new Set;for(let e of a){let t=await r(e);"string"==typeof t?o.push({name:e,err:t}):(n||(n=t),n===t&&u.add(e))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(e=>`[${e.name}] ${e.err}`).join(", ")}`);for(let{name:e,err:t}of o)s.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let l=i.filter(e=>u.has("string"==typeof e?e:e.name));return[n,new Proxy(e,{get:(e,t)=>"executionProviders"===t?l:Reflect.get(e,t)})]}}),q=L(()=>{F()}),V=L(()=>{a="1.23.2"}),W=L(()=>{V(),o="warning",u={wasm:{},webgl:{},webgpu:{},versions:{common:a},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);o=e}},get logLevel(){return o}},Object.defineProperty(u,"logLevel",{enumerable:!0})}),j=L(()=>{W(),l=u}),G=L(()=>{d=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(null!=i){let r,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(r=e.dims[2],s=e.dims[3]):(r=e.dims[3],s=e.dims[2]);let a,o,u=void 0!==t?.format?t.format:"RGB",l=t?.norm;void 0===l||void 0===l.mean?a=[255,255,255,255]:"number"==typeof l.mean?a=[l.mean,l.mean,l.mean,l.mean]:(a=[l.mean[0],l.mean[1],l.mean[2],0],void 0!==l.mean[3]&&(a[3]=l.mean[3])),void 0===l||void 0===l.bias?o=[0,0,0,0]:"number"==typeof l.bias?o=[l.bias,l.bias,l.bias,l.bias]:(o=[l.bias[0],l.bias[1],l.bias[2],0],void 0!==l.bias[3]&&(o[3]=l.bias[3]));let d=s*r,h=0,c=d,p=2*d,f=-1;"RGBA"===u?(h=0,c=d,p=2*d,f=3*d):"RGB"===u?(h=0,c=d,p=2*d):"RBG"===u&&(h=0,p=d,c=2*d);for(let t=0;t<s;t++)for(let n=0;n<r;n++){let r=(e.data[h++]-o[0])*a[0],s=(e.data[c++]-o[1])*a[1],u=(e.data[p++]-o[2])*a[2],l=-1===f?255:(e.data[f++]-o[3])*a[3];i.fillStyle="rgba("+r+","+s+","+u+","+l+")",i.fillRect(n,t,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},h=(e,t)=>{let n,i=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(null==i)throw new Error("Can not access image data");{let r,s,a;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(r=e.dims[2],s=e.dims[1],a=e.dims[3]):(r=e.dims[3],s=e.dims[2],a=e.dims[1]);let o,u,l=void 0!==t&&void 0!==t.format?t.format:"RGB",d=t?.norm;void 0===d||void 0===d.mean?o=[255,255,255,255]:"number"==typeof d.mean?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],void 0!==d.mean[3]&&(o[3]=d.mean[3])),void 0===d||void 0===d.bias?u=[0,0,0,0]:"number"==typeof d.bias?u=[d.bias,d.bias,d.bias,d.bias]:(u=[d.bias[0],d.bias[1],d.bias[2],0],void 0!==d.bias[3]&&(u[3]=d.bias[3]));let h=s*r;if(void 0!==t&&(void 0!==t.format&&4===a&&"RGBA"!==t.format||3===a&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");let c=4,p=0,f=1,m=2,g=3,y=0,w=h,b=2*h,_=-1;"RGBA"===l?(y=0,w=h,b=2*h,_=3*h):"RGB"===l?(y=0,w=h,b=2*h):"RBG"===l&&(y=0,b=h,w=2*h),n=i.createImageData(r,s);for(let t=0;t<s*r;p+=c,f+=c,m+=c,g+=c,t++)n.data[p]=(e.data[y++]-u[0])*o[0],n.data[f]=(e.data[w++]-u[1])*o[1],n.data[m]=(e.data[b++]-u[2])*o[2],n.data[g]=-1===_?255:(e.data[_++]-u[3])*o[3]}return n}}),K=L(()=>{X(),c=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");let n,i,{height:r,width:s}=t,a=t.norm??{mean:255,bias:0};n="number"==typeof a.mean?[a.mean,a.mean,a.mean,a.mean]:[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],i="number"==typeof a.bias?[a.bias,a.bias,a.bias,a.bias]:[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];let o=void 0!==t.format?t.format:"RGBA",u=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",l=r*s,d="RGBA"===u?new Float32Array(4*l):new Float32Array(3*l),h=4,c=0,p=1,f=2,m=3,g=0,y=l,w=2*l,b=-1;"RGB"===o&&(h=3,c=0,p=1,f=2,m=-1),"RGBA"===u?b=3*l:"RBG"===u?(g=0,w=l,y=2*l):"BGR"===u&&(w=0,y=l,g=2*l);for(let t=0;t<l;t++,c+=h,f+=h,p+=h,m+=h)d[g++]=(e[c]+i[0])/n[0],d[y++]=(e[p]+i[1])/n[1],d[w++]=(e[f]+i[2])/n[2],-1!==b&&-1!==m&&(d[b++]=(e[m]+i[3])/n[3]);return new S("float32",d,"RGBA"===u?[1,4,r,s]:[1,3,r,s])},p=async(e,t)=>{let n,i=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,r=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a="string"==typeof e,o=t??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=e=>typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(i){let i=u();i.width=e.width,i.height=e.height;let r=l(i);if(null==r)throw new Error("Can not access image data");{let i=e.height,s=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(i=t.resizedHeight,s=t.resizedWidth),void 0!==t){if(o=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=i,o.width=s}else o.tensorFormat="RGBA",o.height=i,o.width=s;r.drawImage(e,0,0),n=r.getImageData(0,0,s,i).data}}else{if(!r){if(s){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");let i=u();i.width=e.width,i.height=e.height;let r=l(i);if(null!=r){let t=e.height,i=e.width;return r.drawImage(e,0,0,i,t),n=r.getImageData(0,0,i,t).data,o.height=t,o.width=i,c(n,o)}throw new Error("Can not access image data")}if(a)return new Promise((t,n)=>{let i=u(),r=l(i);if(!e||!r)return n();let s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=()=>{i.width=s.width,i.height=s.height,r.drawImage(s,0,0,i.width,i.height);let e=r.getImageData(0,0,i.width,i.height);o.height=i.height,o.width=i.width,t(c(e.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}{let i,r;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(i=t.resizedHeight,r=t.resizedWidth):(i=e.height,r=e.width),void 0!==t&&(o=t),o.format="RGBA",o.height=i,o.width=r,void 0!==t){let t=u();t.width=r,t.height=i;let s=l(t);if(null==s)throw new Error("Can not access image data");s.putImageData(e,0,0),n=s.getImageData(0,0,r,i).data}else n=e.data}}if(void 0!==n)return c(n,o);throw new Error("Input data provided is not supported - aborted tensor creation")},f=(e,t)=>{let{width:n,height:i,download:r,dispose:s}=t;return new S({location:"texture",type:"float32",texture:e,dims:[1,i,n,4],download:r,dispose:s})},m=(e,t)=>{let{dataType:n,dims:i,download:r,dispose:s}=t;return new S({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:r,dispose:s})},g=(e,t)=>{let{dataType:n,dims:i,download:r,dispose:s}=t;return new S({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:r,dispose:s})},y=(e,t,n)=>new S({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),Q=L(()=>{w=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),b=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),_=!1,$=()=>{if(!_){_=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(w.set("int64",BigInt64Array),b.set(BigInt64Array,"int64")),t&&(w.set("uint64",BigUint64Array),b.set(BigUint64Array,"uint64")),i?(w.set("float16",n),b.set(n,"float16")):w.set("float16",Uint16Array)}}}),J=L(()=>{X(),v=e=>{let t=1;for(let n=0;n<e.length;n++){let i=e[n];if("number"!=typeof i||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);t*=i}return t},x=(e,t)=>{switch(e.location){case"cpu":return new S(e.type,e.data,t);case"cpu-pinned":return new S({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new S({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new S({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new S({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),X=L(()=>{G(),K(),Q(),J(),S=class{constructor(e,t,n){let i,r;if($(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,i=e.type,r=e.dims,e.location){case"cpu-pinned":{let t=w.get(i);if(!t)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==i)throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==i&&"float16"!==i&&"int32"!==i&&"int64"!==i&&"uint32"!==i&&"uint8"!==i&&"bool"!==i&&"uint4"!==i&&"int4"!==i)throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==i&&"float16"!==i&&"int32"!==i&&"int64"!==i&&"uint32"!==i&&"uint64"!==i&&"int8"!==i&&"uint8"!==i&&"bool"!==i&&"uint4"!==i&&"int4"!==i)throw new TypeError(`unsupported type "${i}" 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 s,a;if("string"==typeof e)if(i=e,a=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{let n=w.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&n===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);s="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else if(t instanceof n)s=t;else if(t instanceof Uint8ClampedArray){if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");s=Uint8Array.from(t)}else{if(!("float16"===e&&t instanceof Uint16Array&&n!==Uint16Array))throw new TypeError(`A ${i} tensor's data must be type of ${n}`);s=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length)}}else if(a=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)i="string",s=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);i="bool",s=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)i="uint8",s=Uint8Array.from(e);else{let t=b.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=t,s=e}if(void 0===a)a=[s.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");r=a,this.cpuData=s,this.dataLocation="cpu"}let s=v(r);if(this.cpuData&&s!==this.cpuData.length&&("uint4"!==i&&"int4"!==i||Math.ceil(s/2)!==this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=r,this.size=s}static async fromImage(e,t){return p(e,t)}static fromTexture(e,t){return f(e,t)}static fromGpuBuffer(e,t){return m(e,t)}static fromMLTensor(e,t){return g(e,t)}static fromPinnedBuffer(e,t,n){return y(e,t,n)}toDataURL(e){return d(this,e)}toImageData(e){return h(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 t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&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("none"===this.dataLocation)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 x(this,e)}}}),Z=L(()=>{X(),T=S}),Y=L(()=>{W(),k=(e,t)=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||console.timeStamp(`${e}::ORT::${t}`)},E=(e,t)=>{let n=(new Error).stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let r=0;r<n.length;r++){if(i&&!n[r].includes("TRACE_FUNC")){let i=`FUNC_${e}::${n[r].trim().split(" ")[1]}`;return t&&(i+=`::${t}`),void k("CPU",i)}n[r].includes("TRACE_FUNC")&&(i=!0)}},C=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||E("BEGIN",e)},I=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||E("END",e)},A=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||console.time(`ORT::${e}`)},R=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||console.timeEnd(`ORT::${e}`)}}),ee=L(()=>{F(),Z(),Y(),M=class e{constructor(e){this.handler=e}async run(e,t,n){C(),A("InferenceSession.run");let i={},r={};if("object"!=typeof e||null===e||e instanceof T||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof T)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);i[e]=null}if("object"==typeof n&&null!==n)r=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,a=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==a.indexOf(n)){let r=t[n];(null===r||r instanceof T)&&(e=!0,s=!1,i[n]=r)}if(e){if("object"==typeof n&&null!==n)r=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else r=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of this.inputNames)if(typeof e[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(s)for(let e of this.outputNames)i[e]=null;let a=await this.handler.run(e,i,r),o={};for(let e in a)if(Object.hasOwnProperty.call(a,e)){let t=a[e];o[e]=t instanceof T?t:new T(t.type,t.data,t.dims)}return R("InferenceSession.run"),I(),o}async release(){return this.handler.dispose()}static async create(t,n,i,r){C(),A("InferenceSession.create");let a,o={};if("string"==typeof t){if(a=t,"object"==typeof n&&null!==n)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,"object"==typeof n&&null!==n)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let e=t,s=0,u=t.byteLength;if("object"==typeof n&&null!==n)o=n;else if("number"==typeof n){if(s=n,!Number.isSafeInteger(s))throw new RangeError("'byteOffset' must be an integer.");if(s<0||s>=e.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(u=t.byteLength-s,"number"==typeof i){if(u=i,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||s+u>e.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if("object"==typeof r&&null!==r)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(e,s,u)}}let[u,l]=await s(o),d=await u.createInferenceSessionHandler(a,l);return R("InferenceSession.create"),I(),new e(d)}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}}}),te=L(()=>{ee(),z=M}),ne=L(()=>{}),ie=L(()=>{}),re=L(()=>{}),se=L(()=>{}),ae={};N(ae,{InferenceSession:()=>z,TRACE:()=>k,TRACE_EVENT_BEGIN:()=>A,TRACE_EVENT_END:()=>R,TRACE_FUNC_BEGIN:()=>C,TRACE_FUNC_END:()=>I,Tensor:()=>T,env:()=>l,registerBackend:()=>i});var oe=L(()=>{q(),j(),te(),Z(),ne(),ie(),Y(),re(),se()}),ue=L(()=>{}),le={};N(le,{default:()=>ce});var de,he,ce,pe,fe,me,ge,ye,we,be,_e,$e,ve,xe,Se,Te,ke,Ee,Ce,Ie,Ae,Re,Me,ze,Oe,Pe,Be,De,Ue,Le,Ne,He,Fe,qe,Ve,We,je,Ge,Ke,Qe,Je,Xe,Ze,Ye,et,tt,nt,it,rt,st,at,ot,ut,lt,dt,ht,ct,pt,ft,mt,gt,yt,wt,bt,_t,$t,vt,xt,St,Tt,kt,Et,Ct,It,At,Rt,Mt,zt=L(()=>{Ht(),Pt(),Ot(),de="ort-wasm-proxy-worker",(he=globalThis.self?.name===de)&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Me(n.wasm).then(()=>{et(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case"init-ep":{let{epName:e,env:i}=n;tt(i,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case"copy-from":{let{buffer:e}=n,i=st(e);postMessage({type:t,out:i});break}case"create":{let{model:e,options:i}=n;at(e,i).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case"release":ot(n),postMessage({type:t});break;case"run":{let{sessionId:e,inputIndices:i,inputs:r,outputIndices:s,options:a}=n;lt(e,i,r,s,new Array(s.length).fill(null),a).then(e=>{e.some(e=>"cpu"!==e[3])?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:e},ht([...r,...e]))},e=>{postMessage({type:t,err:e})});break}case"end-profiling":dt(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),ce=he?null:e=>new Worker(e??fe,{type:"classic",name:de})}),Ot=L(()=>{ue(),pe=typeof location>"u"?void 0:location.origin,fe=typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,me=()=>{if(fe&&!fe.startsWith("blob:"))return fe.substring(0,fe.lastIndexOf("/")+1)},ge=(e,t)=>{try{let n=t??fe;return(n?new URL(e,n):new URL(e)).origin===pe}catch{return!1}},ye=(e,t)=>{let n=t??fe;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},we=(e,t)=>`${t??"./"}${e}`,be=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},_e=async e=>(await import(e)).default,$e=(zt(),H(le)).default,ve=async()=>{if(!fe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ge(fe))return[void 0,$e()];let e=await be(fe);return[e,$e(e)]},xe=void 0,Se=async(e,t,n,i)=>{let r=xe;if(r)if(fe)r=ge(fe);else{if(!i||n)throw new Error("cannot determine the script source URL.");r=!0}if(r)return[void 0,xe];{let i="ort-wasm-simd-threaded.mjs",r=e??ye(i,t),s=n&&r&&!ge(r,t),a=s?await be(r):r??we(i,t);return[s?a:void 0,await _e(a)]}}}),Pt=L(()=>{Ot(),ke=!1,Ee=!1,Ce=!1,Ie=()=>{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}},Ae=()=>{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}},Re=()=>{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}},Me=async e=>{if(ke)return Promise.resolve();if(Ee)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ce)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ee=!0;let t=e.initTimeout,n=e.numThreads;if(!1!==e.simd)if("relaxed"===e.simd){if(!Re())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ae())throw new Error("WebAssembly SIMD is not supported in the current environment.");let i=Ie();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", 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=n=1);let r=e.wasmPaths,s="string"==typeof r?r:void 0,a=r?.mjs,o=a?.href??a,u=r?.wasm,l=u?.href??u,d=e.wasmBinary,[h,c]=await Se(o,s,n>1,!!d||!!l),p=!1,f=[];if(t>0&&f.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),f.push(new Promise((e,t)=>{let i={numThreads:n};if(d)i.wasmBinary=d;else if(l||s)i.locateFile=e=>l??s+e;else if(o&&0!==o.indexOf("blob:"))i.locateFile=e=>new URL(e,o).href;else if(h){let e=me();e&&(i.locateFile=t=>e+t)}c(i).then(t=>{Ee=!1,ke=!0,Te=t,e(),h&&URL.revokeObjectURL(h)},e=>{Ee=!1,Ce=!0,t(e)})})),await Promise.race(f),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(ke&&Te)return Te;throw new Error("WebAssembly is not initialized yet.")}}),Bt=L(()=>{Pt(),Oe=(e,t)=>{let n=ze(),i=n.lengthBytesUTF8(e)+1,r=n._malloc(i);return n.stringToUTF8(e,r,i),t.push(r),r},Pe=(e,t,n,i)=>{if("object"==typeof e&&null!==e){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([e,r])=>{let s=t?t+e:e;if("object"==typeof r)Pe(r,s+".",n,i);else if("string"==typeof r||"number"==typeof r)i(s,r.toString());else{if("boolean"!=typeof r)throw new Error("Can't handle extra config type: "+typeof r);i(s,r?"1":"0")}})},Be=e=>{let t=ze(),n=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let r=Number(t.getValue(i,4===n?"i32":"i64")),s=t.getValue(i+n,"*"),a=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${r}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(n)}}}),Dt=L(()=>{Pt(),Bt(),De=e=>{let t=ze(),n=0,i=[],r=e||{};try{if(void 0===e?.logSeverityLevel)r.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(void 0===e?.logVerbosityLevel)r.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===e?.terminate&&(r.terminate=!1);let s=0;return void 0!==e?.tag&&(s=Oe(e.tag,i)),n=t._OrtCreateRunOptions(r.logSeverityLevel,r.logVerbosityLevel,!!r.terminate,s),0===n&&Be("Can't create run options."),void 0!==e?.extra&&Pe(e.extra,"",new WeakSet,(e,r)=>{let s=Oe(e,i),a=Oe(r,i);0!==t._OrtAddRunConfigEntry(n,s,a)&&Be(`Can't set a run config entry: ${e} - ${r}.`)}),[n,i]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),i.forEach(e=>t._free(e)),e}}}),Ut=L(()=>{Pt(),Bt(),Ue=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Le=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ne=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(e=>"webgpu"===("string"==typeof e?e:e.name))&&(e.enableMemPattern=!1)},He=(e,t,n,i)=>{let r=Oe(t,i),s=Oe(n,i);0!==ze()._OrtAddSessionConfigEntry(e,r,s)&&Be(`Can't set a session config entry: ${t} - ${n}.`)},Fe=async(e,t,n)=>{for(let i of t){let t="string"==typeof i?i:i.name,r=[];switch(t){case"webnn":if(t="WEBNN","string"!=typeof i){let t=i?.deviceType;t&&He(e,"deviceType",t,n)}break;case"webgpu":if(t="JS","string"!=typeof i){let t=i;if(t?.preferredLayout){if("NCHW"!==t.preferredLayout&&"NHWC"!==t.preferredLayout)throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${t.preferredLayout}`);He(e,"preferredLayout",t.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${t}`)}let s=Oe(t,n),a=r.length,o=0,u=0;if(a>0){o=ze()._malloc(a*ze().PTR_SIZE),n.push(o),u=ze()._malloc(a*ze().PTR_SIZE),n.push(u);for(let e=0;e<a;e++)ze().setValue(o+e*ze().PTR_SIZE,r[e][0],"*"),ze().setValue(u+e*ze().PTR_SIZE,r[e][1],"*")}0!==await ze()._OrtAppendExecutionProvider(e,s,o,u,a)&&Be(`Can't append execution provider: ${t}.`)}},qe=async e=>{let t=ze(),n=0,i=[],r=e||{};Ne(r);try{let e=Ue(r.graphOptimizationLevel??"all"),s=Le(r.executionMode??"sequential"),a="string"==typeof r.logId?Oe(r.logId,i):0,o=r.logSeverityLevel??2;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log severity level is not valid: ${o}`);let u=r.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let l="string"==typeof r.optimizedModelFilePath?Oe(r.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(e,!!r.enableCpuMemArena,!!r.enableMemPattern,s,!!r.enableProfiling,0,a,o,u,l),0===n&&Be("Can't create session options."),r.executionProviders&&await Fe(n,r.executionProviders,i),void 0!==r.enableGraphCapture){if("boolean"!=typeof r.enableGraphCapture)throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`);He(n,"enableGraphCapture",r.enableGraphCapture.toString(),i)}if(r.freeDimensionOverrides)for(let[e,s]of Object.entries(r.freeDimensionOverrides)){if("string"!=typeof e)throw new Error(`free dimension override name must be a string: ${e}`);if("number"!=typeof s||!Number.isInteger(s)||s<0)throw new Error(`free dimension override value must be a non-negative integer: ${s}`);let r=Oe(e,i);0!==t._OrtAddFreeDimensionOverride(n,r,s)&&Be(`Can't set a free dimension override: ${e} - ${s}.`)}return void 0!==r.extra&&Pe(r.extra,"",new WeakSet,(e,t)=>{He(n,e,t,i)}),[n,i]}catch(e){throw 0!==n&&0!==t._OrtReleaseSessionOptions(n)&&Be("Can't release session options."),i.forEach(e=>t._free(e)),e}}}),Lt=L(()=>{Ve=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}`)}},We=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}`)}},je=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i="number"==typeof t?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(i*n):void 0},Ge=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;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: ${e}`)}},Ke=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}`)}},Qe=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,Je=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint64"===e||"int8"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,Xe=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}`)}}}),Nt=L(()=>{ue(),Ze=async e=>{if("string"==typeof e){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n,r=t.body.getReader();try{n=new ArrayBuffer(i)}catch(e){if(!(e instanceof RangeError))throw e;{let e=Math.ceil(i/65536);n=new WebAssembly.Memory({initial:e,maximum:e}).buffer}}let s=0;for(;;){let{done:e,value:t}=await r.read();if(e)break;let i=t.byteLength;new Uint8Array(n,s,i).set(t),s+=i}return new Uint8Array(n,0,i)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ht=L(()=>{oe(),Dt(),Ut(),Lt(),Pt(),Bt(),Nt(),Ye=(e,t)=>{0!==ze()._OrtInit(e,t)&&Be("Can't initialize onnxruntime.")},et=async e=>{Ye(e.wasm.numThreads,Ke(e.logLevel))},tt=async(e,t)=>{ze().asyncInit?.();let n=e.webgpu.adapter;if("webgpu"===t){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if("object"!=typeof n.limits||"object"!=typeof n.features||"function"!=typeof n.requestDevice)throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(void 0!==t&&"low-power"!==t&&"high-performance"!==t)throw new Error(`Invalid powerPreference setting: "${t}"`);let i=e.webgpu.forceFallbackAdapter;if(void 0!==i&&"boolean"!=typeof i)throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if("webnn"===t&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},nt=new Map,it=e=>{let t=ze(),n=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);0!==t._OrtGetInputOutputCount(e,i,i+n)&&Be("Can't get session input/output count.");let r=4===n?"i32":"i64";return[Number(t.getValue(i,r)),Number(t.getValue(i+n,r))]}finally{t.stackRestore(n)}},rt=(e,t)=>{let n=ze(),i=n.stackSave(),r=0;try{let i=n.PTR_SIZE,s=n.stackAlloc(2*i);0!==n._OrtGetInputOutputMetadata(e,t,s,s+i)&&Be("Can't get session input/output metadata.");let a=Number(n.getValue(s,"*"));r=Number(n.getValue(s+i,"*"));let o=n.HEAP32[r/4];if(0===o)return[a,0];let u=n.HEAPU32[r/4+1],l=[];for(let e=0;e<u;e++){let t=Number(n.getValue(r+8+e*i,"*"));l.push(0!==t?n.UTF8ToString(t):Number(n.getValue(r+8+(e+u)*i,"*")))}return[a,o,l]}finally{n.stackRestore(i),0!==r&&n._OrtFree(r)}},st=e=>{let t=ze(),n=t._malloc(e.byteLength);if(0===n)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},at=async(e,t)=>{let n,i,r=ze();Array.isArray(e)?[n,i]=e:e.buffer===r.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=st(e);let s=0,a=0,o=[],u=[],l=[];try{if([a,o]=await qe(t),t?.externalData&&r.mountExternalData){let e=[];for(let n of t.externalData){let t="string"==typeof n?n:n.path;e.push(Ze("string"==typeof n?n:n.data).then(e=>{r.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if("webnn"===("string"==typeof e?e:e.name)){if(r.shouldTransferToMLTensor=!1,"string"!=typeof e){let t=e,n=t?.context,i=t?.gpuDevice,s=t?.deviceType,a=t?.powerPreference;r.currentContext=n||(i?await r.webnnCreateMLContext(i):await r.webnnCreateMLContext({deviceType:s,powerPreference:a}))}else r.currentContext=await r.webnnCreateMLContext();break}s=await r._OrtCreateSession(n,i,a),r.webgpuOnCreateSession?.(s),0===s&&Be("Can't create a session."),r.jsepOnCreateSession?.(),r.currentContext&&(r.webnnRegisterMLContext(s,r.currentContext),r.currentContext=void 0,r.shouldTransferToMLTensor=!0);let[e,d]=it(s),h=!!t?.enableGraphCapture,c=[],p=[],f=[],m=[];for(let t=0;t<e;t++){let[e,n,i]=rt(s,t);0===e&&Be("Can't get an input name."),u.push(e);let a=r.UTF8ToString(e);c.push(a),f.push(0===n?{name:a,isTensor:!1}:{name:a,isTensor:!0,type:We(n),shape:i})}for(let t=0;t<d;t++){let[n,i,a]=rt(s,t+e);0===n&&Be("Can't get an output name."),l.push(n);let o=r.UTF8ToString(n);p.push(o),m.push(0===i?{name:o,isTensor:!1}:{name:o,isTensor:!0,type:We(i),shape:a})}return nt.set(s,[s,u,l,null,h,!1]),[s,c,p,f,m]}catch(e){throw u.forEach(e=>r._OrtFree(e)),l.forEach(e=>r._OrtFree(e)),0!==s&&0!==r._OrtReleaseSession(s)&&Be("Can't release session."),e}finally{r._free(n),0!==a&&0!==r._OrtReleaseSessionOptions(a)&&Be("Can't release session options."),o.forEach(e=>r._free(e)),r.unmountExternalData?.()}},ot=e=>{let t=ze(),n=nt.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,r,s,a,o]=n;a&&(o&&0!==t._OrtClearBoundOutputs(a.handle)&&Be("Can't clear bound outputs."),0!==t._OrtReleaseBinding(a.handle)&&Be("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),r.forEach(e=>t._OrtFree(e)),s.forEach(e=>t._OrtFree(e)),0!==t._OrtReleaseSession(i)&&Be("Can't release session."),nt.delete(e)},ut=async(e,t,n,i,r,s,a=!1)=>{if(!e)return void t.push(0);let o,u,l=ze(),d=l.PTR_SIZE,h=e[0],c=e[1],p=e[3],f=p;if("string"===h&&("gpu-buffer"===p||"ml-tensor"===p))throw new Error("String tensor is not supported on GPU.");if(a&&"gpu-buffer"!==p)throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if("gpu-buffer"===p){let t=e[2].gpuBuffer;u=je(Ve(h),c);{let e=l.jsepRegisterBuffer;if(!e)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');o=e(i,s,t,u)}}else if("ml-tensor"===p){let t=e[2].mlTensor;u=je(Ve(h),c);let n=l.webnnRegisterMLTensor;if(!n)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');o=n(i,t,Ve(h),c)}else{let t=e[2];if(Array.isArray(t)){u=d*t.length,o=l._malloc(u),n.push(o);for(let e=0;e<t.length;e++){if("string"!=typeof t[e])throw new TypeError(`tensor data at index ${e} is not a string`);l.setValue(o+e*d,Oe(t[e],n),"*")}}else{let e=l.webnnIsGraphInput,s=l.webnnIsGraphOutput;if("string"!==h&&e&&s){let a=l.UTF8ToString(r);if(e(i,a)||s(i,a)){let e=Ve(h);u=je(e,c),f="ml-tensor";let n=l.webnnCreateTemporaryTensor,r=l.webnnUploadTensor;if(!n||!r)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let s=await n(i,e,c);r(s,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),o=s}else u=t.byteLength,o=l._malloc(u),n.push(o),l.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,u),o)}else u=t.byteLength,o=l._malloc(u),n.push(o),l.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,u),o)}}let m=l.stackSave(),g=l.stackAlloc(4*c.length);try{c.forEach((e,t)=>l.setValue(g+t*d,e,4===d?"i32":"i64"));let e=l._OrtCreateTensor(Ve(h),o,u,g,c.length,Xe(f));0===e&&Be(`Can't create tensor for input/output. session=${i}, index=${s}.`),t.push(e)}finally{l.stackRestore(m)}},lt=async(e,t,n,i,r,s)=>{let a=ze(),o=a.PTR_SIZE,u=nt.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let l=u[0],d=u[1],h=u[2],c=u[3],p=u[4],f=(u[5],t.length),m=i.length,g=0,y=[],w=[],b=[],_=[],$=a.stackSave(),v=a.stackAlloc(f*o),x=a.stackAlloc(f*o),S=a.stackAlloc(m*o),T=a.stackAlloc(m*o);try{[g,y]=De(s),A("wasm prepareInputOutputTensor");for(let i=0;i<f;i++)await ut(n[i],w,_,e,d[t[i]],t[i],p);for(let t=0;t<m;t++)await ut(r[t],b,_,e,h[i[t]],f+i[t],p);R("wasm prepareInputOutputTensor");for(let e=0;e<f;e++)a.setValue(v+e*o,w[e],"*"),a.setValue(x+e*o,d[t[e]],"*");for(let e=0;e<m;e++)a.setValue(S+e*o,b[e],"*"),a.setValue(T+e*o,h[i[e]],"*");let u;a.jsepOnRunStart?.(l),a.webnnOnRunStart?.(l),u=await a._OrtRun(l,x,v,f,T,m,S,g),0!==u&&Be("failed to call OrtRun().");let $=[],k=[];A("wasm ProcessOutputTensor");for(let t=0;t<m;t++){let n=Number(a.getValue(S+t*o,"*"));if(n===b[t]){$.push(r[t]);continue}let s,u=a.stackSave(),l=a.stackAlloc(4*o),d=!1,h=0;try{0!==a._OrtGetTensorData(n,l,l+o,l+2*o,l+3*o)&&Be(`Can't access output tensor data on index ${t}.`);let r=4===o?"i32":"i64",u=Number(a.getValue(l,r));h=a.getValue(l+o,"*");let p=a.getValue(l+2*o,"*"),f=Number(a.getValue(l+3*o,r)),m=[];for(let e=0;e<f;e++)m.push(Number(a.getValue(p+e*o,r)));0!==a._OrtFree(p)&&Be("Can't free memory for tensor dims.");let g=m.reduce((e,t)=>e*t,1);s=We(u);let y=c?.outputPreferredLocations[i[t]];if("string"===s){if("gpu-buffer"===y||"ml-tensor"===y)throw new Error("String tensor is not supported on GPU.");let e=[];for(let t=0;t<g;t++){let n=a.getValue(h+t*o,"*"),i=a.getValue(h+(t+1)*o,"*"),r=t===g-1?void 0:i-n;e.push(a.UTF8ToString(n,r))}$.push([s,m,e,"cpu"])}else if("gpu-buffer"===y&&g>0){let e=a.jsepGetBuffer;if(!e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let t=e(h),i=je(u,g);if(void 0===i||!Qe(s))throw new Error(`Unsupported data type: ${s}`);d=!0,$.push([s,m,{gpuBuffer:t,download:a.jsepCreateDownloader(t,i,s),dispose:()=>{0!==a._OrtReleaseTensor(n)&&Be("Can't release tensor.")}},"gpu-buffer"])}else if("ml-tensor"===y&&g>0){let t=a.webnnEnsureTensor,i=a.webnnIsGraphInputOutputTypeSupported;if(!t||!i)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(void 0===je(u,g)||!Je(s))throw new Error(`Unsupported data type: ${s}`);if(!i(e,s,!1))throw new Error(`preferredLocation "ml-tensor" for ${s} output is not supported by current WebNN Context.`);let r=await t(e,h,u,m,!1);d=!0,$.push([s,m,{mlTensor:r,download:a.webnnCreateMLTensorDownloader(h,s),dispose:()=>{a.webnnReleaseTensorId(h),a._OrtReleaseTensor(n)}},"ml-tensor"])}else if("ml-tensor-cpu-output"===y&&g>0){let e=a.webnnCreateMLTensorDownloader(h,s)(),t=$.length;d=!0,k.push((async()=>{let i=[t,await e];return a.webnnReleaseTensorId(h),a._OrtReleaseTensor(n),i})()),$.push([s,m,[],"cpu"])}else{let e=new(Ge(s))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(a.HEAPU8.subarray(h,h+e.byteLength)),$.push([s,m,e,"cpu"])}}finally{a.stackRestore(u),"string"===s&&h&&a._free(h),d||a._OrtReleaseTensor(n)}}c&&!p&&(0!==a._OrtClearBoundOutputs(c.handle)&&Be("Can't clear bound outputs."),nt.set(e,[l,d,h,c,p,!1]));for(let[e,t]of await Promise.all(k))$[e][2]=t;return R("wasm ProcessOutputTensor"),$}finally{a.webnnOnRunEnd?.(l),a.stackRestore($),w.forEach(e=>a._OrtReleaseTensor(e)),b.forEach(e=>a._OrtReleaseTensor(e)),_.forEach(e=>a._free(e)),0!==g&&a._OrtReleaseRunOptions(g),y.forEach(e=>a._free(e))}},dt=e=>{let t=ze(),n=nt.get(e);if(!n)throw new Error("invalid session id");let i=n[0],r=t._OrtEndProfiling(i);0===r&&Be("Can't get an profile file name."),t._OrtFree(r)},ht=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&"buffer"in e&&t.push(e.buffer)}return t}}),Ft=L(()=>{oe(),Ht(),Pt(),Ot(),ct=()=>!!l.wasm.proxy&&typeof document<"u",ft=!1,mt=!1,gt=!1,bt=new Map,_t=(e,t)=>{let n=bt.get(e);n?n.push(t):bt.set(e,[t])},$t=()=>{if(ft||!mt||gt||!pt)throw new Error("worker not ready")},vt=e=>{switch(e.data.type){case"init-wasm":ft=!1,e.data.err?(gt=!0,wt[1](e.data.err)):(mt=!0,wt[0]()),yt&&(URL.revokeObjectURL(yt),yt=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=bt.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},xt=async()=>{if(!mt){if(ft)throw new Error("multiple calls to 'initWasm()' detected.");if(gt)throw new Error("previous call to 'initWasm()' failed.");if(ft=!0,ct())return new Promise((e,t)=>{pt?.terminate(),ve().then(([n,i])=>{try{(pt=i).onerror=e=>t(e),pt.onmessage=vt,wt=[e,t];let r={type:"init-wasm",in:l};if(!r.in.wasm.wasmPaths&&n){let e=me();e&&(r.in.wasm.wasmPaths=e)}pt.postMessage(r),yt=n}catch(e){t(e)}},t)});try{await Me(l.wasm),await et(l),mt=!0}catch(e){throw gt=!0,e}finally{ft=!1}}},St=async e=>{if(ct())return $t(),new Promise((t,n)=>{_t("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:l}};pt.postMessage(i)});await tt(l,e)},Tt=async e=>ct()?($t(),new Promise((t,n)=>{_t("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};pt.postMessage(i,[e.buffer])})):st(e),kt=async(e,t)=>{if(ct()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $t(),new Promise((n,i)=>{_t("create",[n,i]);let r={type:"create",in:{model:e,options:{...t}}},s=[];e instanceof Uint8Array&&s.push(e.buffer),pt.postMessage(r,s)})}return at(e,t)},Et=async e=>{if(ct())return $t(),new Promise((t,n)=>{_t("release",[t,n]);let i={type:"release",in:e};pt.postMessage(i)});ot(e)},Ct=async(e,t,n,i,r,s)=>{if(ct()){if(n.some(e=>"cpu"!==e[3]))throw new Error("input tensor on GPU is not supported for proxy.");if(r.some(e=>e))throw new Error("pre-allocated output tensor is not supported for proxy.");return $t(),new Promise((r,a)=>{_t("run",[r,a]);let o=n,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:o,outputIndices:i,options:s}};pt.postMessage(u,ht(o))})}return lt(e,t,n,i,r,s)},It=async e=>{if(ct())return $t(),new Promise((t,n)=>{_t("end-profiling",[t,n]);let i={type:"end-profiling",in:e};pt.postMessage(i)});dt(e)}}),qt=L(()=>{oe(),Ft(),Lt(),ue(),Nt(),At=(e,t)=>{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 ${t()}`)}},Rt=e=>{switch(e[3]){case"cpu":return new T(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Qe(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:r}=e[2];return T.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:r})}case"ml-tensor":{let t=e[0];if(!Je(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:r}=e[2];return T.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:r})}default:throw new Error(`invalid data location: ${e[3]}`)}},Mt=class{async fetchModelAndCopyToWasmMemory(e){return Tt(await Ze(e))}async loadModel(e,t){let n;C(),n="string"==typeof e?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await kt(n,t),I()}async dispose(){return Et(this.sessionId)}async run(e,t,n){C();let i=[],r=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],s=this.inputNames.indexOf(t);if(-1===s)throw new Error(`invalid input '${t}'`);i.push(n),r.push(s)});let s=[],a=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],i=this.outputNames.indexOf(t);if(-1===i)throw new Error(`invalid output '${t}'`);s.push(n),a.push(i)});let o=i.map((e,t)=>At(e,()=>`input "${this.inputNames[r[t]]}"`)),u=s.map((e,t)=>e?At(e,()=>`output "${this.outputNames[a[t]]}"`):null),l=await Ct(this.sessionId,r,o,a,u,n),d={};for(let e=0;e<l.length;e++)d[this.outputNames[a[e]]]=s[e]??Rt(l[e]);return I(),d}startProfiling(){}endProfiling(){It(this.sessionId)}}}),Vt={};N(Vt,{OnnxruntimeWebAssemblyBackend:()=>jt,initializeFlags:()=>Wt,wasmBackend:()=>Gt});var Wt,jt,Gt,Kt=L(()=>{oe(),Ft(),qt(),Wt=()=>{("number"!=typeof l.wasm.initTimeout||l.wasm.initTimeout<0)&&(l.wasm.initTimeout=0);let e=l.wasm.simd;if("boolean"!=typeof e&&void 0!==e&&"fixed"!==e&&"relaxed"!==e&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),l.wasm.simd=!1),"boolean"!=typeof l.wasm.proxy&&(l.wasm.proxy=!1),"boolean"!=typeof l.wasm.trace&&(l.wasm.trace=!1),"number"!=typeof l.wasm.numThreads||!Number.isInteger(l.wasm.numThreads)||l.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)l.wasm.numThreads=1;else{let e=typeof navigator>"u"?U("node:os").cpus().length:navigator.hardwareConcurrency;l.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},jt=class{async init(e){Wt(),await xt(),await St(e)}async createInferenceSessionHandler(e,t){let n=new Mt;return await n.loadModel(e,t),n}},Gt=new jt}),Qt={};N(Qt,{InferenceSession:()=>z,TRACE:()=>k,TRACE_EVENT_BEGIN:()=>A,TRACE_EVENT_END:()=>R,TRACE_FUNC_BEGIN:()=>C,TRACE_FUNC_END:()=>I,Tensor:()=>T,default:()=>Jt,env:()=>l,registerBackend:()=>i}),oe(),oe(),oe();var Jt=ae;{let e=(Kt(),H(Vt)).wasmBackend;i("cpu",e,10),i("wasm",e,10)}return Object.defineProperty(l.versions,"web",{value:"1.23.2",enumerable:!0}),H(Qt)})();e.exports=i},603:(e,t,n)=>{var i=(()=>{var e,t,i,r,s,a,o,u,l,d,h,c,p,f,m,g,y,w,b,_,$,v,x,S,T,k,E,C,I,A,R,M,z,O=Object.defineProperty,P=Object.getOwnPropertyDescriptor,B=Object.getOwnPropertyNames,D=Object.prototype.hasOwnProperty,U=n(687),L=(e,t)=>()=>(e&&(t=e(e=0)),t),N=(e,t)=>{for(var n in t)O(e,n,{get:t[n],enumerable:!0})},H=e=>((e,t,n,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of B(t))!D.call(e,n)&&undefined!==n&&O(e,n,{get:()=>t[n],enumerable:!(i=P(t,n))||i.enumerable});return e})(O({},"__esModule",{value:!0}),e),F=L(()=>{e=new Map,t=[],i=(n,i,r)=>{if(i&&"function"==typeof i.init&&"function"==typeof i.createInferenceSessionHandler){let s=e.get(n);if(void 0===s)e.set(n,{backend:i,priority:r});else{if(s.priority>r)return;if(s.priority===r&&s.backend!==i)throw new Error(`cannot register backend "${n}" using priority ${r}`)}if(r>=0){let i=t.indexOf(n);-1!==i&&t.splice(i,1);for(let i=0;i<t.length;i++)if(e.get(t[i]).priority<=r)return void t.splice(i,0,n);t.push(n)}return}throw new TypeError("not a valid backend")},r=async t=>{let n=e.get(t);if(!n)return"backend not found.";if(n.initialized)return n.backend;if(n.aborted)return n.error;{let e=!!n.initPromise;try{return e||(n.initPromise=n.backend.init(t)),await n.initPromise,n.initialized=!0,n.backend}catch(t){return e||(n.error=`${t}`,n.aborted=!0),n.error}finally{delete n.initPromise}}},s=async e=>{let n,i=e.executionProviders||[],s=i.map(e=>"string"==typeof e?e:e.name),a=0===s.length?t:s,o=[],u=new Set;for(let e of a){let t=await r(e);"string"==typeof t?o.push({name:e,err:t}):(n||(n=t),n===t&&u.add(e))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(e=>`[${e.name}] ${e.err}`).join(", ")}`);for(let{name:e,err:t}of o)s.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let l=i.filter(e=>u.has("string"==typeof e?e:e.name));return[n,new Proxy(e,{get:(e,t)=>"executionProviders"===t?l:Reflect.get(e,t)})]}}),q=L(()=>{F()}),V=L(()=>{a="1.23.2"}),W=L(()=>{V(),o="warning",u={wasm:{},webgl:{},webgpu:{},versions:{common:a},set logLevel(e){if(void 0!==e){if("string"!=typeof e||-1===["verbose","info","warning","error","fatal"].indexOf(e))throw new Error(`Unsupported logging level: ${e}`);o=e}},get logLevel(){return o}},Object.defineProperty(u,"logLevel",{enumerable:!0})}),j=L(()=>{W(),l=u}),G=L(()=>{d=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(null!=i){let r,s;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(r=e.dims[2],s=e.dims[3]):(r=e.dims[3],s=e.dims[2]);let a,o,u=void 0!==t?.format?t.format:"RGB",l=t?.norm;void 0===l||void 0===l.mean?a=[255,255,255,255]:"number"==typeof l.mean?a=[l.mean,l.mean,l.mean,l.mean]:(a=[l.mean[0],l.mean[1],l.mean[2],0],void 0!==l.mean[3]&&(a[3]=l.mean[3])),void 0===l||void 0===l.bias?o=[0,0,0,0]:"number"==typeof l.bias?o=[l.bias,l.bias,l.bias,l.bias]:(o=[l.bias[0],l.bias[1],l.bias[2],0],void 0!==l.bias[3]&&(o[3]=l.bias[3]));let d=s*r,h=0,c=d,p=2*d,f=-1;"RGBA"===u?(h=0,c=d,p=2*d,f=3*d):"RGB"===u?(h=0,c=d,p=2*d):"RBG"===u&&(h=0,p=d,c=2*d);for(let t=0;t<s;t++)for(let n=0;n<r;n++){let r=(e.data[h++]-o[0])*a[0],s=(e.data[c++]-o[1])*a[1],u=(e.data[p++]-o[2])*a[2],l=-1===f?255:(e.data[f++]-o[3])*a[3];i.fillStyle="rgba("+r+","+s+","+u+","+l+")",i.fillRect(n,t,1,1)}if("toDataURL"in n)return n.toDataURL();throw new Error("toDataURL is not supported")}throw new Error("Can not access image data")},h=(e,t)=>{let n,i=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");if(null==i)throw new Error("Can not access image data");{let r,s,a;void 0!==t?.tensorLayout&&"NHWC"===t.tensorLayout?(r=e.dims[2],s=e.dims[1],a=e.dims[3]):(r=e.dims[3],s=e.dims[2],a=e.dims[1]);let o,u,l=void 0!==t&&void 0!==t.format?t.format:"RGB",d=t?.norm;void 0===d||void 0===d.mean?o=[255,255,255,255]:"number"==typeof d.mean?o=[d.mean,d.mean,d.mean,d.mean]:(o=[d.mean[0],d.mean[1],d.mean[2],255],void 0!==d.mean[3]&&(o[3]=d.mean[3])),void 0===d||void 0===d.bias?u=[0,0,0,0]:"number"==typeof d.bias?u=[d.bias,d.bias,d.bias,d.bias]:(u=[d.bias[0],d.bias[1],d.bias[2],0],void 0!==d.bias[3]&&(u[3]=d.bias[3]));let h=s*r;if(void 0!==t&&(void 0!==t.format&&4===a&&"RGBA"!==t.format||3===a&&"RGB"!==t.format&&"BGR"!==t.format))throw new Error("Tensor format doesn't match input tensor dims");let c=4,p=0,f=1,m=2,g=3,y=0,w=h,b=2*h,_=-1;"RGBA"===l?(y=0,w=h,b=2*h,_=3*h):"RGB"===l?(y=0,w=h,b=2*h):"RBG"===l&&(y=0,b=h,w=2*h),n=i.createImageData(r,s);for(let t=0;t<s*r;p+=c,f+=c,m+=c,g+=c,t++)n.data[p]=(e.data[y++]-u[0])*o[0],n.data[f]=(e.data[w++]-u[1])*o[1],n.data[m]=(e.data[b++]-u[2])*o[2],n.data[g]=-1===_?255:(e.data[_++]-u[3])*o[3]}return n}}),K=L(()=>{X(),c=(e,t)=>{if(void 0===e)throw new Error("Image buffer must be defined");if(void 0===t.height||void 0===t.width)throw new Error("Image height and width must be defined");if("NHWC"===t.tensorLayout)throw new Error("NHWC Tensor layout is not supported yet");let n,i,{height:r,width:s}=t,a=t.norm??{mean:255,bias:0};n="number"==typeof a.mean?[a.mean,a.mean,a.mean,a.mean]:[a.mean[0],a.mean[1],a.mean[2],a.mean[3]??255],i="number"==typeof a.bias?[a.bias,a.bias,a.bias,a.bias]:[a.bias[0],a.bias[1],a.bias[2],a.bias[3]??0];let o=void 0!==t.format?t.format:"RGBA",u=void 0!==t.tensorFormat&&void 0!==t.tensorFormat?t.tensorFormat:"RGB",l=r*s,d="RGBA"===u?new Float32Array(4*l):new Float32Array(3*l),h=4,c=0,p=1,f=2,m=3,g=0,y=l,w=2*l,b=-1;"RGB"===o&&(h=3,c=0,p=1,f=2,m=-1),"RGBA"===u?b=3*l:"RBG"===u?(g=0,w=l,y=2*l):"BGR"===u&&(w=0,y=l,g=2*l);for(let t=0;t<l;t++,c+=h,f+=h,p+=h,m+=h)d[g++]=(e[c]+i[0])/n[0],d[y++]=(e[p]+i[1])/n[1],d[w++]=(e[f]+i[2])/n[2],-1!==b&&-1!==m&&(d[b++]=(e[m]+i[3])/n[3]);return new S("float32",d,"RGBA"===u?[1,4,r,s]:[1,3,r,s])},p=async(e,t)=>{let n,i=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,r=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a="string"==typeof e,o=t??{},u=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},l=e=>typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext("2d"):null;if(i){let i=u();i.width=e.width,i.height=e.height;let r=l(i);if(null==r)throw new Error("Can not access image data");{let i=e.height,s=e.width;if(void 0!==t&&void 0!==t.resizedHeight&&void 0!==t.resizedWidth&&(i=t.resizedHeight,s=t.resizedWidth),void 0!==t){if(o=t,void 0!==t.tensorFormat)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=i,o.width=s}else o.tensorFormat="RGBA",o.height=i,o.width=s;r.drawImage(e,0,0),n=r.getImageData(0,0,s,i).data}}else{if(!r){if(s){if(void 0===t)throw new Error("Please provide image config with format for Imagebitmap");let i=u();i.width=e.width,i.height=e.height;let r=l(i);if(null!=r){let t=e.height,i=e.width;return r.drawImage(e,0,0,i,t),n=r.getImageData(0,0,i,t).data,o.height=t,o.width=i,c(n,o)}throw new Error("Can not access image data")}if(a)return new Promise((t,n)=>{let i=u(),r=l(i);if(!e||!r)return n();let s=new Image;s.crossOrigin="Anonymous",s.src=e,s.onload=()=>{i.width=s.width,i.height=s.height,r.drawImage(s,0,0,i.width,i.height);let e=r.getImageData(0,0,i.width,i.height);o.height=i.height,o.width=i.width,t(c(e.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}{let i,r;if(void 0!==t&&void 0!==t.resizedWidth&&void 0!==t.resizedHeight?(i=t.resizedHeight,r=t.resizedWidth):(i=e.height,r=e.width),void 0!==t&&(o=t),o.format="RGBA",o.height=i,o.width=r,void 0!==t){let t=u();t.width=r,t.height=i;let s=l(t);if(null==s)throw new Error("Can not access image data");s.putImageData(e,0,0),n=s.getImageData(0,0,r,i).data}else n=e.data}}if(void 0!==n)return c(n,o);throw new Error("Input data provided is not supported - aborted tensor creation")},f=(e,t)=>{let{width:n,height:i,download:r,dispose:s}=t;return new S({location:"texture",type:"float32",texture:e,dims:[1,i,n,4],download:r,dispose:s})},m=(e,t)=>{let{dataType:n,dims:i,download:r,dispose:s}=t;return new S({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:r,dispose:s})},g=(e,t)=>{let{dataType:n,dims:i,download:r,dispose:s}=t;return new S({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:r,dispose:s})},y=(e,t,n)=>new S({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),Q=L(()=>{w=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),b=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),_=!1,$=()=>{if(!_){_=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(w.set("int64",BigInt64Array),b.set(BigInt64Array,"int64")),t&&(w.set("uint64",BigUint64Array),b.set(BigUint64Array,"uint64")),i?(w.set("float16",n),b.set(n,"float16")):w.set("float16",Uint16Array)}}}),J=L(()=>{X(),v=e=>{let t=1;for(let n=0;n<e.length;n++){let i=e[n];if("number"!=typeof i||!Number.isSafeInteger(i))throw new TypeError(`dims[${n}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${n}] must be a non-negative integer, got: ${i}`);t*=i}return t},x=(e,t)=>{switch(e.location){case"cpu":return new S(e.type,e.data,t);case"cpu-pinned":return new S({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new S({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new S({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new S({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),X=L(()=>{G(),K(),Q(),J(),S=class{constructor(e,t,n){let i,r;if($(),"object"==typeof e&&"location"in e)switch(this.dataLocation=e.location,i=e.type,r=e.dims,e.location){case"cpu-pinned":{let t=w.get(i);if(!t)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw new TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case"texture":if("float32"!==i)throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case"gpu-buffer":if("float32"!==i&&"float16"!==i&&"int32"!==i&&"int64"!==i&&"uint32"!==i&&"uint8"!==i&&"bool"!==i&&"uint4"!==i&&"int4"!==i)throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case"ml-tensor":if("float32"!==i&&"float16"!==i&&"int32"!==i&&"int64"!==i&&"uint32"!==i&&"uint64"!==i&&"int8"!==i&&"uint8"!==i&&"bool"!==i&&"uint4"!==i&&"int4"!==i)throw new TypeError(`unsupported type "${i}" 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 s,a;if("string"==typeof e)if(i=e,a=n,"string"===e){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{let n=w.get(e);if(void 0===n)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if("float16"===e&&n===Uint16Array||"uint4"===e||"int4"===e)throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);s="uint64"===e||"int64"===e?n.from(t,BigInt):n.from(t)}else if(t instanceof n)s=t;else if(t instanceof Uint8ClampedArray){if("uint8"!==e)throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");s=Uint8Array.from(t)}else{if(!("float16"===e&&t instanceof Uint16Array&&n!==Uint16Array))throw new TypeError(`A ${i} tensor's data must be type of ${n}`);s=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length)}}else if(a=t,Array.isArray(e)){if(0===e.length)throw new TypeError("Tensor type cannot be inferred from an empty array.");let t=typeof e[0];if("string"===t)i="string",s=e;else{if("boolean"!==t)throw new TypeError(`Invalid element type of data array: ${t}.`);i="bool",s=Uint8Array.from(e)}}else if(e instanceof Uint8ClampedArray)i="uint8",s=Uint8Array.from(e);else{let t=b.get(e.constructor);if(void 0===t)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=t,s=e}if(void 0===a)a=[s.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");r=a,this.cpuData=s,this.dataLocation="cpu"}let s=v(r);if(this.cpuData&&s!==this.cpuData.length&&("uint4"!==i&&"int4"!==i||Math.ceil(s/2)!==this.cpuData.length))throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=r,this.size=s}static async fromImage(e,t){return p(e,t)}static fromTexture(e,t){return f(e,t)}static fromGpuBuffer(e,t){return m(e,t)}static fromMLTensor(e,t){return g(e,t)}static fromPinnedBuffer(e,t,n){return y(e,t,n)}toDataURL(e){return d(this,e)}toImageData(e){return h(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 t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&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("none"===this.dataLocation)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 x(this,e)}}}),Z=L(()=>{X(),T=S}),Y=L(()=>{W(),k=(e,t)=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||console.timeStamp(`${e}::ORT::${t}`)},E=(e,t)=>{let n=(new Error).stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let r=0;r<n.length;r++){if(i&&!n[r].includes("TRACE_FUNC")){let i=`FUNC_${e}::${n[r].trim().split(" ")[1]}`;return t&&(i+=`::${t}`),void k("CPU",i)}n[r].includes("TRACE_FUNC")&&(i=!0)}},C=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||E("BEGIN",e)},I=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||E("END",e)},A=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||console.time(`ORT::${e}`)},R=e=>{(typeof u.trace>"u"?!u.wasm.trace:!u.trace)||console.timeEnd(`ORT::${e}`)}}),ee=L(()=>{F(),Z(),Y(),M=class e{constructor(e){this.handler=e}async run(e,t,n){C(),A("InferenceSession.run");let i={},r={};if("object"!=typeof e||null===e||e instanceof T||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if("object"==typeof t){if(null===t)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof T)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(0===t.length)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let e of t){if("string"!=typeof e)throw new TypeError("'fetches' must be a string array or an object.");if(-1===this.outputNames.indexOf(e))throw new RangeError(`'fetches' contains invalid output name: ${e}.`);i[e]=null}if("object"==typeof n&&null!==n)r=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let e=!1,a=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(-1!==a.indexOf(n)){let r=t[n];(null===r||r instanceof T)&&(e=!0,s=!1,i[n]=r)}if(e){if("object"==typeof n&&null!==n)r=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else r=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let t of this.inputNames)if(typeof e[t]>"u")throw new Error(`input '${t}' is missing in 'feeds'.`);if(s)for(let e of this.outputNames)i[e]=null;let a=await this.handler.run(e,i,r),o={};for(let e in a)if(Object.hasOwnProperty.call(a,e)){let t=a[e];o[e]=t instanceof T?t:new T(t.type,t.data,t.dims)}return R("InferenceSession.run"),I(),o}async release(){return this.handler.dispose()}static async create(t,n,i,r){C(),A("InferenceSession.create");let a,o={};if("string"==typeof t){if(a=t,"object"==typeof n&&null!==n)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,"object"==typeof n&&null!==n)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{if(!(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer))throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");{let e=t,s=0,u=t.byteLength;if("object"==typeof n&&null!==n)o=n;else if("number"==typeof n){if(s=n,!Number.isSafeInteger(s))throw new RangeError("'byteOffset' must be an integer.");if(s<0||s>=e.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(u=t.byteLength-s,"number"==typeof i){if(u=i,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||s+u>e.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if("object"==typeof r&&null!==r)o=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(e,s,u)}}let[u,l]=await s(o),d=await u.createInferenceSessionHandler(a,l);return R("InferenceSession.create"),I(),new e(d)}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}}}),te=L(()=>{ee(),z=M}),ne=L(()=>{}),ie=L(()=>{}),re=L(()=>{}),se=L(()=>{}),ae={};N(ae,{InferenceSession:()=>z,TRACE:()=>k,TRACE_EVENT_BEGIN:()=>A,TRACE_EVENT_END:()=>R,TRACE_FUNC_BEGIN:()=>C,TRACE_FUNC_END:()=>I,Tensor:()=>T,env:()=>l,registerBackend:()=>i});var oe=L(()=>{q(),j(),te(),Z(),ne(),ie(),Y(),re(),se()}),ue=L(()=>{}),le={};N(le,{default:()=>ce});var de,he,ce,pe,fe,me,ge,ye,we,be,_e,$e,ve,xe,Se,Te,ke,Ee,Ce,Ie,Ae,Re,Me,ze,Oe,Pe,Be,De,Ue,Le,Ne,He,Fe,qe,Ve,We,je,Ge,Ke,Qe,Je,Xe,Ze,Ye,et,tt,nt,it,rt,st,at,ot,ut,lt,dt,ht,ct,pt,ft,mt,gt,yt,wt,bt,_t,$t,vt,xt,St,Tt,kt,Et,Ct,It,At,Rt,Mt,zt,Ot,Pt,Bt,Dt,Ut,Lt,Nt,Ht,Ft,qt,Vt,Wt,jt,Gt,Kt,Qt,Jt,Xt,Zt,Yt,en,tn,nn,rn,sn,an,on,un,ln,dn,hn,cn,pn,fn,mn,gn,yn,wn,bn,_n,$n,vn,xn,Sn,Tn,kn,En,Cn,In,An,Rn,Mn,zn,On,Pn,Bn,Dn,Un,Ln,Nn,Hn,Fn,qn,Vn,Wn,jn,Gn,Kn,Qn,Jn,Xn,Zn,Yn,ei,ti,ni,ii,ri,si,ai,oi,ui,li,di,hi,ci,pi,fi,mi,gi,yi,wi,bi,_i,$i,vi,xi,Si,Ti,ki,Ei,Ci,Ii,Ai,Ri,Mi,zi,Oi,Pi,Bi,Di,Ui,Li,Ni,Hi,Fi,qi,Vi,Wi,ji,Gi,Ki,Qi,Ji,Xi,Zi,Yi,er,tr,nr,ir,rr,sr,ar,or,ur,lr,dr,hr,cr,pr,fr,mr,gr,yr,wr,br,_r,$r,vr,xr,Sr,Tr,kr,Er,Cr,Ir,Ar,Rr,Mr,zr,Or,Pr,Br,Dr,Ur,Lr,Nr,Hr,Fr,qr,Vr,Wr,jr,Gr,Kr,Qr,Jr,Xr,Zr,Yr,es,ts,ns,is,rs,ss,as,os,us,ls,ds,hs,cs,ps,fs,ms,gs,ys,ws,bs,_s,$s,vs,xs,Ss,Ts,ks,Es,Cs,Is,As,Rs,Ms,zs,Os,Ps,Bs,Ds,Us,Ls,Ns,Hs,Fs,qs,Vs,Ws,js,Gs,Ks,Qs,Js,Xs,Zs,Ys,ea,ta,na,ia,ra,sa,aa,oa,ua,la,da,ha,ca,pa,fa,ma,ga,ya,wa,ba,_a,$a,va,xa,Sa,Ta,ka,Ea,Ca,Ia,Aa,Ra,Ma,za,Oa,Pa,Ba,Da,Ua,La,Na,Ha,Fa,qa,Va,Wa,ja,Ga,Ka,Qa,Ja,Xa,Za,Ya,eo,to,no,io,ro,so,ao,oo,uo,lo,ho,co,po,fo,mo,go,yo,wo,bo,_o,$o,vo,xo,So,To,ko,Eo,Co,Io,Ao,Ro,Mo,zo,Oo,Po,Bo,Do,Uo,Lo,No,Ho,Fo,qo,Vo,Wo,jo,Go,Ko,Qo,Jo,Xo,Zo,Yo,eu,tu,nu,iu,ru,su,au,ou,uu,lu,du,hu,cu,pu,fu,mu,gu,yu,wu,bu,_u,$u,vu,xu,Su,Tu,ku,Eu,Cu,Iu,Au,Ru,Mu,zu,Ou,Pu,Bu,Du,Uu,Lu,Nu,Hu,Fu,qu,Vu,Wu,ju,Gu=L(()=>{th(),Qu(),Ku(),de="ort-wasm-proxy-worker",(he=globalThis.self?.name===de)&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":Me(n.wasm).then(()=>{$d(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case"init-ep":{let{epName:e,env:i}=n;vd(i,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case"copy-from":{let{buffer:e}=n,i=kd(e);postMessage({type:t,out:i});break}case"create":{let{model:e,options:i}=n;Ed(e,i).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case"release":Cd(n),postMessage({type:t});break;case"run":{let{sessionId:e,inputIndices:i,inputs:r,outputIndices:s,options:a}=n;Ad(e,i,r,s,new Array(s.length).fill(null),a).then(e=>{e.some(e=>"cpu"!==e[3])?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:e},Md([...r,...e]))},e=>{postMessage({type:t,err:e})});break}case"end-profiling":Rd(n),postMessage({type:t})}}catch(e){postMessage({type:t,err:e})}}),ce=he?null:e=>new Worker(e??fe,{type:"classic",name:de})}),Ku=L(()=>{ue(),pe=typeof location>"u"?void 0:location.origin,fe=typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,me=()=>{if(fe&&!fe.startsWith("blob:"))return fe.substring(0,fe.lastIndexOf("/")+1)},ge=(e,t)=>{try{let n=t??fe;return(n?new URL(e,n):new URL(e)).origin===pe}catch{return!1}},ye=(e,t)=>{let n=t??fe;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},we=(e,t)=>`${t??"./"}${e}`,be=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},_e=async e=>(await import(e)).default,$e=(Gu(),H(le)).default,ve=async()=>{if(!fe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ge(fe))return[void 0,$e()];let e=await be(fe);return[e,$e(e)]},xe=void 0,Se=async(e,t,n,i)=>{let r=xe;if(r)if(fe)r=ge(fe);else{if(!i||n)throw new Error("cannot determine the script source URL.");r=!0}if(r)return[void 0,xe];{let i="ort-wasm-simd-threaded.jsep.mjs",r=e??ye(i,t),s=n&&r&&!ge(r,t),a=s?await be(r):r??we(i,t);return[s?a:void 0,await _e(a)]}}}),Qu=L(()=>{Ku(),ke=!1,Ee=!1,Ce=!1,Ie=()=>{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}},Ae=()=>{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}},Re=()=>{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}},Me=async e=>{if(ke)return Promise.resolve();if(Ee)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ce)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ee=!0;let t=e.initTimeout,n=e.numThreads;if(!1!==e.simd)if("relaxed"===e.simd){if(!Re())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ae())throw new Error("WebAssembly SIMD is not supported in the current environment.");let i=Ie();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", 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=n=1);let r=e.wasmPaths,s="string"==typeof r?r:void 0,a=r?.mjs,o=a?.href??a,u=r?.wasm,l=u?.href??u,d=e.wasmBinary,[h,c]=await Se(o,s,n>1,!!d||!!l),p=!1,f=[];if(t>0&&f.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),f.push(new Promise((e,t)=>{let i={numThreads:n};if(d)i.wasmBinary=d;else if(l||s)i.locateFile=e=>l??s+e;else if(o&&0!==o.indexOf("blob:"))i.locateFile=e=>new URL(e,o).href;else if(h){let e=me();e&&(i.locateFile=t=>e+t)}c(i).then(t=>{Ee=!1,ke=!0,Te=t,e(),h&&URL.revokeObjectURL(h)},e=>{Ee=!1,Ce=!0,t(e)})})),await Promise.race(f),p)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(ke&&Te)return Te;throw new Error("WebAssembly is not initialized yet.")}}),Ju=L(()=>{Qu(),Oe=(e,t)=>{let n=ze(),i=n.lengthBytesUTF8(e)+1,r=n._malloc(i);return n.stringToUTF8(e,r,i),t.push(r),r},Pe=(e,t,n,i)=>{if("object"==typeof e&&null!==e){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([e,r])=>{let s=t?t+e:e;if("object"==typeof r)Pe(r,s+".",n,i);else if("string"==typeof r||"number"==typeof r)i(s,r.toString());else{if("boolean"!=typeof r)throw new Error("Can't handle extra config type: "+typeof r);i(s,r?"1":"0")}})},Be=e=>{let t=ze(),n=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let r=Number(t.getValue(i,4===n?"i32":"i64")),s=t.getValue(i+n,"*"),a=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${r}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(n)}}}),Xu=L(()=>{Qu(),Ju(),De=e=>{let t=ze(),n=0,i=[],r=e||{};try{if(void 0===e?.logSeverityLevel)r.logSeverityLevel=2;else if("number"!=typeof e.logSeverityLevel||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(void 0===e?.logVerbosityLevel)r.logVerbosityLevel=0;else if("number"!=typeof e.logVerbosityLevel||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);void 0===e?.terminate&&(r.terminate=!1);let s=0;return void 0!==e?.tag&&(s=Oe(e.tag,i)),n=t._OrtCreateRunOptions(r.logSeverityLevel,r.logVerbosityLevel,!!r.terminate,s),0===n&&Be("Can't create run options."),void 0!==e?.extra&&Pe(e.extra,"",new WeakSet,(e,r)=>{let s=Oe(e,i),a=Oe(r,i);0!==t._OrtAddRunConfigEntry(n,s,a)&&Be(`Can't set a run config entry: ${e} - ${r}.`)}),[n,i]}catch(e){throw 0!==n&&t._OrtReleaseRunOptions(n),i.forEach(e=>t._free(e)),e}}}),Zu=L(()=>{Qu(),Ju(),Ue=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Le=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ne=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(e=>"webgpu"===("string"==typeof e?e:e.name))&&(e.enableMemPattern=!1)},He=(e,t,n,i)=>{let r=Oe(t,i),s=Oe(n,i);0!==ze()._OrtAddSessionConfigEntry(e,r,s)&&Be(`Can't set a session config entry: ${t} - ${n}.`)},Fe=async(e,t,n)=>{for(let i of t){let t="string"==typeof i?i:i.name,r=[];switch(t){case"webnn":if(t="WEBNN","string"!=typeof i){let t=i?.deviceType;t&&He(e,"deviceType",t,n)}break;case"webgpu":if(t="JS","string"!=typeof i){let t=i;if(t?.preferredLayout){if("NCHW"!==t.preferredLayout&&"NHWC"!==t.preferredLayout)throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${t.preferredLayout}`);He(e,"preferredLayout",t.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${t}`)}let s=Oe(t,n),a=r.length,o=0,u=0;if(a>0){o=ze()._malloc(a*ze().PTR_SIZE),n.push(o),u=ze()._malloc(a*ze().PTR_SIZE),n.push(u);for(let e=0;e<a;e++)ze().setValue(o+e*ze().PTR_SIZE,r[e][0],"*"),ze().setValue(u+e*ze().PTR_SIZE,r[e][1],"*")}0!==await ze()._OrtAppendExecutionProvider(e,s,o,u,a)&&Be(`Can't append execution provider: ${t}.`)}},qe=async e=>{let t=ze(),n=0,i=[],r=e||{};Ne(r);try{let e=Ue(r.graphOptimizationLevel??"all"),s=Le(r.executionMode??"sequential"),a="string"==typeof r.logId?Oe(r.logId,i):0,o=r.logSeverityLevel??2;if(!Number.isInteger(o)||o<0||o>4)throw new Error(`log severity level is not valid: ${o}`);let u=r.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let l="string"==typeof r.optimizedModelFilePath?Oe(r.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(e,!!r.enableCpuMemArena,!!r.enableMemPattern,s,!!r.enableProfiling,0,a,o,u,l),0===n&&Be("Can't create session options."),r.executionProviders&&await Fe(n,r.executionProviders,i),void 0!==r.enableGraphCapture){if("boolean"!=typeof r.enableGraphCapture)throw new Error(`enableGraphCapture must be a boolean value: ${r.enableGraphCapture}`);He(n,"enableGraphCapture",r.enableGraphCapture.toString(),i)}if(r.freeDimensionOverrides)for(let[e,s]of Object.entries(r.freeDimensionOverrides)){if("string"!=typeof e)throw new Error(`free dimension override name must be a string: ${e}`);if("number"!=typeof s||!Number.isInteger(s)||s<0)throw new Error(`free dimension override value must be a non-negative integer: ${s}`);let r=Oe(e,i);0!==t._OrtAddFreeDimensionOverride(n,r,s)&&Be(`Can't set a free dimension override: ${e} - ${s}.`)}return void 0!==r.extra&&Pe(r.extra,"",new WeakSet,(e,t)=>{He(n,e,t,i)}),[n,i]}catch(e){throw 0!==n&&0!==t._OrtReleaseSessionOptions(n)&&Be("Can't release session options."),i.forEach(e=>t._free(e)),e}}}),Yu=L(()=>{Ve=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}`)}},We=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}`)}},je=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i="number"==typeof t?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(i*n):void 0},Ge=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;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: ${e}`)}},Ke=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}`)}},Qe=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,Je=e=>"float32"===e||"float16"===e||"int32"===e||"int64"===e||"uint32"===e||"uint64"===e||"int8"===e||"uint8"===e||"bool"===e||"uint4"===e||"int4"===e,Xe=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}`)}}}),el=L(()=>{ue(),Ze=async e=>{if("string"==typeof e){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n,r=t.body.getReader();try{n=new ArrayBuffer(i)}catch(e){if(!(e instanceof RangeError))throw e;{let e=Math.ceil(i/65536);n=new WebAssembly.Memory({initial:e,maximum:e}).buffer}}let s=0;for(;;){let{done:e,value:t}=await r.read();if(e)break;let i=t.byteLength;new Uint8Array(n,s,i).set(t),s+=i}return new Uint8Array(n,0,i)}}return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),tl=L(()=>{Yu(),Ye=["V","I","W","E","F"],et=(e,t)=>{console.log(`[${Ye[e]},${(new Date).toISOString()}]${t}`)},it=(e,t)=>{tt=e,nt=t},rt=(e,t)=>{let n=Ke(e);n>=Ke(tt)&&et(n,"function"==typeof t?t():t)},st=(...e)=>{nt&&rt(...e)}}),nl=L(()=>{at=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ot=class{static calcShape(e,t,n=!1){let i=e.length,r=t.length;if(0===i)return t;if(0===r)return e;let s=Math.max(e.length,t.length),a=new Array(s);if(n){if(i<2||r<2)return;let n=at.calcMatMulShape([e[i-2],e[i-1]],[t[r-2],t[r-1]]);if(void 0===n)return;[a[s-2],a[s-1]]=n}for(let o=n?3:1;o<=s;o++){let n=i-o<0?1:e[i-o],u=r-o<0?1:t[r-o];if(n!==u&&n>1&&u>1)return;let l=Math.max(n,u);if(n&&u)a[s-o]=Math.max(n,u);else{if(l>1)return;a[s-o]=0}}return a}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let r=1;r<=n;r++)if(1!==e[n-r]&&e[n-r]!==t[i-r])return!1;return!0}},ut=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(e,t=4){let n=e.length;if(0===n)return[];let i=new Array(n),r=n-1;for(;r>=0;){if(e[r]%t===0){i[r]=e[r]/t;break}if(t%e[r]!==0)throw new Error("cannot convert shape");i[r]=1,t/=e[r],r--}for(r--;r>=0;r--)i[r]=e[r];return i}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(e,t,n){let i=1;for(let r=t;r<n;r++){if(e[r]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");i*=Number(e[r])}return i}static computeStrides(e){let t=e.length;if(0===t)return[];if(1===t)return[1];let n=new Array(t);n[t-1]=1,n[t-2]=e[t-1];for(let i=t-3;i>=0;--i)n[i]=n[i+1]*e[i+1];return n}static normalizeAxis(e,t){if(e<-t&&e>=t)throw new Error("unsupported axis for this operation.");return e<0?e+t:e}static normalizeAxes(e,t){return e.map(n=>this.normalizeAxis(n,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(t=>e[t]):e.slice().reverse()}static padShape(e,t){let n=e.length;return e.map((e,i)=>e+t[i]+t[i+n])}static areEqual(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}},lt=class e{static adjustPoolAttributes(e,t,n,i,r,s){if(!e&&n.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(e)for(let e=0;e<t.length-2;e++)e>=n.length?n.push(t[e+2]):n[e]=t[e+2];for(let e=0;e<n.length;e++)if(e<i.length){if(i[e]<0)throw new Error("strides should be greater than or equal to 1")}else i.push(1);for(let e=0;e<n.length;e++)if(e<r.length){if(r[e]<0)throw new Error("dilations should be greater than or equal to 1")}else r.push(1);for(let e=0;e<2*n.length;e++)if(e<s.length){if(s[e]<0)throw new Error("pad should be greater than or equal to 1")}else s.push(0);for(let e=0;e<n.length;e++){if(n[e]<=0)throw new Error("kernel shapes need to be greater than 0");if(s[e]>=n[e]||s[e+n.length]>=n[e])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,r,s,a,o){if(o){if(s.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let u=0;u<t.length-2;u++)e.adjustPadAndReturnShape(t[u+(a?1:2)],n[u],i[u],r[u],s,u,u+t.length-2,o)}}static computePoolOutputShape(t,n,i,r,s,a,o){if(n.length<=0)throw new Error("input shape must be of size greater than 0");let u=[n[0],n[1]];return e.computeShapeHelper(t,n,u,i,r,s,a,o),u}static computeConvOutputShape(t,n,i,r,s,a,o){if(t.length<=0||n.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let u=[t[0],n[0]];return e.computeShapeHelper(!1,t,u,i,r,s,a,o),u}static computeShapeHelper(t,n,i,r,s,a,o,u){if(t)for(let e=0;e<n.length-2;e++)i.push(1);else for(let t=0;t<n.length-2;t++)i.push(e.adjustPadAndReturnShape(n[t+2],r[t],s[t],a[t],o,t,t+n.length-2,u))}static adjustPadAndReturnShape(e,t,n,i,r,s,a,o){let u=n*(i-1)+1;if(!o||"NOTSET"===o)return Math.floor((e+r[s]+r[a]-u)/t+1);switch(o){case"VALID":return r[s]=0,r[a]=0,Math.floor((e-u)/t+1);case"SAME_LOWER":case"SAME_UPPER":if(1!==n)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let n=((e+t-1)/t-1)*t+i-e;return r[s]=Math.floor("SAME_LOWER"===o?(n+1)/2:n/2),r[a]=n-r[s],Math.floor((e+n-i)/t+1)}default:throw new Error("Unsupported AutoPad type")}}},dt=class{static getShapeOfGemmResult(e,t,n,i,r){if(2!==e.length||2!==n.length)throw new Error("shape need to be of size 2");let s,a,o;t?(s=e[1],a=e[0]):(s=e[0],a=e[1]);let u=-1;if(i?(o=n[0],u=1):(o=n[1],u=0),n[u]!==a)throw new Error("dimension mismatch");if(s<=0||o<=0||a<=0)throw new Error("invalid shape specified");if(r&&!ot.isValidBroadcast(r,[s,o]))throw new Error("gemm: invalid bias shape for broadcast");return[s,o,a]}},ht=-34028234663852886e22,ct=34028234663852886e22}),il=L(()=>{Yu(),pt=(e,t)=>new(Ge(t))(e)}),rl=L(()=>{Yu(),tl(),ft=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),mt=(e,t)=>{if("int32"===t)return e;let n=ft.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let r=e.byteLength/i,s=new(Ge(t))(e.buffer,e.byteOffset,r);switch(t){case"int64":case"uint64":{let e=new Int32Array(r);for(let t=0;t<r;t++){let n=s[t];if(n>2147483647n||n<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");e[t]=Number(n)}return new Uint8Array(e.buffer)}case"int8":case"uint8":case"uint32":{if("uint32"===t&&s.some(e=>e>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let e=Int32Array.from(s,Number);return new Uint8Array(e.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},gt=(e,t)=>{if("int32"===t)return e;if(e.byteLength%4!=0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let e=BigInt64Array.from(i,BigInt);return new Uint8Array(e.buffer)}case"uint64":{if(i.some(e=>e<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let e=BigUint64Array.from(i,BigInt);return new Uint8Array(e.buffer)}case"int8":{if(i.some(e=>e<-128||e>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let e=Int8Array.from(i,Number);return new Uint8Array(e.buffer)}case"uint8":if(i.some(e=>e<0||e>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number);case"uint32":{if(i.some(e=>e<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let e=Uint32Array.from(i,Number);return new Uint8Array(e.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},yt=1,wt=()=>yt++,bt=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),_t=(e,t)=>{let n=ft.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},$t=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:r,shape:s,fallbackDataType:a}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=r,this.tensorShape=s,this.fallbackDataType=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return _t(this.dataType,this.tensorShape)}destroy(){st("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=gt(new Uint8Array(t),this.dataType);return e?void(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n):n.buffer}return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},vt=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let r,s=this.tensorManager.getMLContext(e);if(!s.opSupportLimits().input.dataTypes.includes(t)){if(r=bt.get(t),!r||!s.opSupportLimits().input.dataTypes.includes(r))throw new Error(`WebNN backend does not support data type: ${t}`);st("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${r}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(s,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==_t(t,n))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,t,n,a,!0,!0,r),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType){if("int32"!==this.wrapper.fallbackType)throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);t=mt(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0)}if(e.byteLength===this.wrapper.byteLength)return void this.wrapper.write(t);st("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?gt(this.activeUpload,this.wrapper?.type):this.activeUpload;return e?void(e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t)):t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},xt=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}reserveTensorId(){let e=wt();return this.tensorTrackersById.set(e,new vt(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,r){st("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${r}}`);let s=this.tensorTrackersById.get(t);if(!s)throw new Error("Tensor not found.");return s.ensureTensor(e,n,i,r)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){st("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let r=this.getMLContext(e),s=wt(),a=new $t({sessionId:e,context:r,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(s,new vt(this,a)),this.externalTensors.add(a),s}async getCachedTensor(e,t,n,i,r,s,a){let o=this.getMLContext(e);for(let[i,r]of this.freeTensors.entries())if(r.canReuseTensor(o,t,n)){st("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${a?`fallbackDataType: ${a},`:""} shape: ${n}`);let r=this.freeTensors.splice(i,1)[0];return r.sessionId=e,r}st("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${a?`fallbackDataType: ${a},`:""} shape: ${n}}`);let u=await o.createTensor({dataType:a??t,shape:n,dimensions:n,usage:i,writable:r,readable:s});return new $t({sessionId:e,context:o,tensor:u,dataType:t,shape:n,fallbackDataType:a})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},St=(...e)=>new xt(...e)}),sl=L(()=>{Yu(),Qu(),il(),rl(),tl(),Tt=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),kt=(e,t)=>{if(e===t)return!0;if(void 0===e||void 0===t)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((n,r)=>n===i[r]&&e[n]===t[n])},Et=class{constructor(e){this.tensorManager=St(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,it(e.logLevel,!!e.debug)}get currentSessionId(){if(void 0===this.activeSessionId)throw new Error("No active session");return this.activeSessionId}onRunStart(e){st("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){st("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)st("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}if(void 0===e){let e=this.mlContextCache.findIndex(e=>void 0===e.options&&void 0===e.gpuDevice);if(-1!==e)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>kt(t.options,e));if(-1!==t)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),0===n.size){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);-1!==e&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){st("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,r){let s=Tt.get(n);if(!s)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,s,i,r)}async createTemporaryTensor(e,t,n){st("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=Tt.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let r=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,r,i,n,!1);let s=this.temporarySessionTensorIds.get(e);return s?s.push(r):this.temporarySessionTensorIds.set(e,[r]),r}uploadTensor(e,t){if(!ze().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");st("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return pt(n,t)}}registerMLTensor(e,t,n,i){let r=Tt.get(n);if(!r)throw new Error(`Unsupported ONNX data type: ${n}`);let s=this.tensorManager.registerTensor(e,t,r,i);return st("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${r}, dimensions: ${i}} -> {tensorId: ${s}}`),s}registerMLConstant(e,t,n,i,r,s,a=!1){if(!s)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let u=s.get(o);if(!u)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+n>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l,d=u.slice(t,t+n).buffer;switch(r.dataType){case"float32":l=new Float32Array(d);break;case"float16":l=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(d):new Uint16Array(d);break;case"int32":l=new Int32Array(d);break;case"uint32":l=new Uint32Array(d);break;case"int64":if(a){let e=mt(new Uint8Array(d),"int64");l=new Int32Array(e.buffer),r.dataType="int32"}else l=new BigInt64Array(d);break;case"uint64":l=new BigUint64Array(d);break;case"int8":l=new Int8Array(d);break;case"int4":case"uint4":case"uint8":l=new Uint8Array(d);break;default:throw new Error(`Unsupported data type: ${r.dataType} in creating WebNN Constant from external data.`)}return st("verbose",()=>`[WebNN] registerMLConstant {dataType: ${r.dataType}, shape: ${r.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(r,l)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return!!n&&n.includes(t)}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return!!n&&n.includes(t)}isGraphInputOutputTypeSupported(e,t,n=!0){let i=this.mlContextBySessionId.get(e),r=Tt.get(Ve(t));return!(typeof r>"u"||(n?!i?.opSupportLimits().input.dataTypes.includes(r):!i?.opSupportLimits().output.dataTypes.includes(r)))}flush(){}}}),al=L(()=>{}),ol=L(()=>{tl(),al(),Ct=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]]),It=[],At=e=>16*Math.ceil(Number(e)/16),Rt=e=>{for(let t=0;t<It.length;t++){let n=It[t];if(e<=n)return n}return 16*Math.ceil(e/16)},Mt=1,zt=()=>Mt++,Ot=async(e,t,n,i)=>{let r=At(n),s=e.device.createBuffer({size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,s,0,r),e.flush(),await s.mapAsync(GPUMapMode.READ);let o=s.getMappedRange();if(i){let e=i();return e.set(new Uint8Array(o,0,n)),e}return new Uint8Array(o.slice(0,n))}finally{s.destroy()}},Pt=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[e]of Ct)It.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,r=t.byteLength,s=At(r),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(Number(a.originalSize)!==r)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${r}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:s,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),u=o.getMappedRange();new Uint8Array(u).set(new Uint8Array(n,i,r)),o.unmap();let l=this.backend.device.createCommandEncoder();l.copyBufferToBuffer(o,0,a.gpuData.buffer,0,s),this.backend.device.queue.submit([l.finish()]),o.destroy(),st("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let r=At(n.originalSize),s=this.backend.getCommandEncoder();this.backend.endComputePass(),s.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,r)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return st("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error("Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!")}else i=zt();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),st("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){void 0!==e&&(this.storageCache.delete(e),st("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n,i=Rt(e),r=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,s=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(r||s){let e=(r?this.freeBuffers:this.freeUniformBuffers).get(i);n=e&&e.length>0?e.pop():this.backend.device.createBuffer({size:i,usage:t})}else n=this.backend.device.createBuffer({size:i,usage:t});let a={id:zt(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:Number(e)}),st("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t="bigint"==typeof e?Number(e):e,n=this.storageCache.get(t);if(!n){if(0===this.storageCache.size)return 0;throw new Error("releasing data does not exist")}return st("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await Ot(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(0!==this.buffersPending.length)if("default"===this.backend.sessionStatus){for(let e of this.buffersPending){let t=Ct.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];void 0===t||n.length>=t?e.destroy():n.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 t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(e=>{e.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(e=>{e.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,0===this.sessionCount&&(st("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Bt=(...e)=>new Pt(...e)}),ul=L(()=>{Dt=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}},Ut=e=>new Dt(e)}),ll=L(()=>{Yu(),nl(),Lt=64,Nt=(e,t)=>{if(3===t)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(4!==t)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ht=(e,t=1)=>{let n=Nt(e,t);return"string"==typeof n?n:n[0]},Ft=(e,t=1)=>{let n=Nt(e,t);return"string"==typeof n?n:n[1]},qt=(...e)=>{let t=[];return e.forEach(e=>{0!==e.length&&t.push({type:12,data:e},{type:12,data:ut.computeStrides(e)})}),t},Vt=e=>e%4==0?4:e%2==0?2:1,Wt=(e="f32",t,n="0")=>t&&1!==t?`vec${t}<${e}>(${n})`:`${e}(${n})`,jt=(e,t,n)=>"f32"===e?n:1===t?`f32(${n})`:`vec${t}<f32>(${n})`,Gt=(e,t)=>4===t?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:2===t?`(${e}.x + ${e}.y)`:3===t?`(${e}.x + ${e}.y + ${e}.z)`:e,Kt=(e,t,n,i)=>e.startsWith("uniforms.")&&n>4?"string"==typeof t?"f16"===i?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:"f16"===i?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,Qt=(e,t,n,i,r)=>{let s="number"==typeof n,a=s?n:n.length,o=[...new Array(a).keys()],u=a<2?"u32":a<=4?`vec${a}<u32>`:`array<u32, ${a}>`,l=Nt(t,r),d="string"==typeof l?l:l[1],h="string"==typeof l?l:l[0],c={indices:u,value:d,storage:h,tensor:t},p=e=>"string"==typeof e?e:`${e}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},m=s?"uniforms.":"",g=`${m}${e}_shape`,y=`${m}${e}_strides`,w="";for(let e=0;e<a-1;e++)w+=`\n let dim${e} = current / ${Kt(y,e,a)};\n let rest${e} = current % ${Kt(y,e,a)};\n indices[${e}] = dim${e};\n current = rest${e};\n `;w+=`indices[${a-1}] = current;`;let b=a<2?"":`\n fn o2i_${e}(offset: u32) -> ${c.indices} {\n var indices: ${c.indices};\n var current = offset;\n ${w}\n return indices;\n }`,_=[];if(a>=2)for(let e=a-1;e>=0;e--)_.push(`${Kt(y,e,a)} * (indices[${e}])`);let $=a<2?"":`\n fn i2o_${e}(indices: ${c.indices}) -> u32 {\n return ${_.join("+")};\n }`,v=(...e)=>0===a?"0u":`${c.indices}(${e.map(p).join(",")})`,x=(e,t)=>a<2?`${e}`:`${Kt(e,t,a)}`,S={},T=(t,n)=>(()=>{if(c.storage===c.value)return`${e}[${t}]=${n};`;if("vec2<u32>"===c.storage&&"i32"===c.value)return`${e}[${t}]=vec2<u32>(u32(${n}), select(0u, 0xFFFFFFFFu, ${n} < 0));`;if("vec2<u32>"===c.storage&&"u32"===c.value)return`${e}[${t}]=vec2<u32>(u32(${n}), 0u);`;if("u32"===c.storage&&"vec4<bool>"===c.value)return`${e}[${t}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${n}));`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),k=t=>(()=>{if(c.storage===c.value)return`${e}[${t}]`;if("vec2<u32>"===c.storage&&"i32"===c.value)return`i32(${e}[${t}].x)`;if("vec2<u32>"===c.storage&&"u32"===c.value)return`u32(${e}[${t}].x)`;if("u32"===c.storage&&"vec4<bool>"===c.value)return`vec4<bool>(bool(${e}[${t}] & 0xFFu), bool(${e}[${t}] & 0xFF00u), bool(${e}[${t}] & 0xFF0000u), bool(${e}[${t}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),E=a<2?"":`\n fn get_${e}ByIndices(indices: ${c.indices}) -> ${d} {\n return ${k(`i2o_${e}(indices)`)};\n }`,C=a<2?"":(()=>{let t=o.map(e=>`d${e}: u32`).join(", "),n=o.map(e=>`d${e}`).join(", ");return`\n fn get_${e}(${t}) -> ${d} {\n return get_${e}ByIndices(${v(n)});\n }`})(),I=a<2?"":`\n fn set_${e}ByIndices(indices: ${c.indices}, value: ${d}) {\n ${T(`i2o_${e}(indices)`,"value")}\n }`,A=a<2?"":(()=>{let t=o.map(e=>`d${e}: u32`).join(", "),n=o.map(e=>`d${e}`).join(", ");return`\n fn set_${e}(${t}, value: ${d}) {\n set_${e}ByIndices(${v(n)}, value);\n }`})();return{impl:()=>{let e=[],t=!1;return f.offsetToIndices&&(e.push(b),t=!0),f.indicesToOffset&&(e.push($),t=!0),f.broadcastedIndicesToOffset&&(Object.values(S).forEach(t=>e.push(t)),t=!0),f.set&&(e.push(A),t=!0),f.setByIndices&&(e.push(I),t=!0),f.get&&(e.push(C),t=!0),f.getByIndices&&(e.push(E),t=!0),!s&&t&&e.unshift(`const ${g} = ${c.indices}(${n.join(",")});`,`const ${y} = ${c.indices}(${ut.computeStrides(n).join(",")});`),e.join("\n")},type:c,offsetToIndices:t=>(f.offsetToIndices=!0,a<2?t:`o2i_${e}(${t})`),indicesToOffset:t=>(f.indicesToOffset=!0,a<2?t:`i2o_${e}(${t})`),broadcastedIndicesToOffset:(t,n)=>{f.broadcastedIndicesToOffset=!0;let i=`${n.name}broadcastedIndicesTo${e}Offset`;if(i in S)return`${i}(${t})`;let r=[];for(let e=a-1;e>=0;e--){let t=n.indicesGet("outputIndices",e+n.rank-a);r.push(`${x(y,e)} * (${t} % ${x(g,e)})`)}return S[i]=`fn ${i}(outputIndices: ${n.type.indices}) -> u32 {\n return ${r.length>0?r.join("+"):"0u"};\n }`,`${i}(${t})`},indices:v,indicesGet:x,indicesSet:(e,t,n)=>a<2?`${e}=${n};`:`${Kt(e,t,a)}=${n};`,set:(...t)=>{if(t.length!==a+1)throw new Error(`indices length must be ${a}`);let n=t[a];if("string"!=typeof n)throw new Error("value must be string");let i=t.slice(0,a).map(p).join(",");return 0===a?T("0u",n):1===a?T(i[0],n):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${i}, ${n})`)},setByOffset:T,setByIndices:(t,n)=>a<2?T(t,n):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${t}, ${n});`),get:(...t)=>{if(t.length!==a)throw new Error(`indices length must be ${a}`);let n=t.map(p).join(",");return 0===a?k("0u"):1===a?k(n[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${n})`)},getByOffset:k,getByIndices:t=>a<2?k(t):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${t})`),usage:i,name:e,strides:y,shape:g,rank:a}},Jt=(e,t,n,i=1)=>Qt(e,t,n,"input",i),Xt=(e,t,n,i=1)=>Qt(e,t,n,"output",i),Zt=(e,t,n)=>Qt(e,t,n,"atomicOutput",1),Yt=(e,t,n,i=1)=>Qt(e,t,n,"internal",i),en=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${"number"==typeof e?`${e}u`:e}) { return; }`}mainStart(e=Lt){let t="number"==typeof e?e:e[0],n="number"==typeof e?1:e[1],i="number"==typeof e?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let r=1===this.normalizedDispatchGroup[1]&&1===this.normalizedDispatchGroup[2];return`@compute @workgroup_size(${t}, ${n}, ${i})\n fn main(${r?"@builtin(global_invocation_id) global_id : vec3<u32>,\n @builtin(workgroup_id) workgroup_id : vec3<u32>,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(local_invocation_id) local_id : vec3<u32>":"@builtin(global_invocation_id) global_id : vec3<u32>,\n @builtin(local_invocation_id) local_id : vec3<u32>,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3<u32>,\n @builtin(num_workgroups) num_workgroups : vec3<u32>"}) {\n ${r?"let global_idx = global_id.x;\n let workgroup_index = workgroup_id.x;":`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x;\n let global_idx = workgroup_index * ${t*n*i}u + local_idx;`}\n `}appendVariableUniforms(e){0!==e.rank&&(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,t){if("internal"===e.usage)throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n="input"===e.usage?"read":"read_write",i="atomicOutput"===e.usage?"atomic<i32>":e.type.storage;return`@group(0) @binding(${t}) var<storage, ${n}> ${e.name}: array<${i}>;`}declareVariables(...e){return e.map(e=>this.declareVariable(e,this.variableIndex++)).join("\n")}registerInternalVariable(e){if("internal"!==e.usage)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(e=>this.registerInternalVariable(e)),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(0===this.uniforms.length)return"";let e=[];for(let{name:t,type:n,length:i}of this.uniforms)if(i&&i>4)"f16"===n?e.push(`@align(16) ${t}:array<mat2x4<${n}>, ${Math.ceil(i/8)}>`):e.push(`${t}:array<vec4<${n}>, ${Math.ceil(i/4)}>`);else{let r=null==i||1===i?n:`vec${i}<${n}>`;e.push(`${t}:${r}`)}return`\n struct Uniforms { ${e.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join("\n")+this.internalVariables.map(e=>e.impl()).join("\n")}get variablesInfo(){if(0===this.uniforms.length)return;let e=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},tn=(e,t)=>new en(e,t)}),dl=L(()=>{Yu(),nl(),ul(),ll(),nn=(e,t)=>{if(!e||1!==e.length)throw new Error("Transpose requires 1 input.");if(0!==t.length&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},rn=(e,t)=>0!==t.length?t:[...new Array(e).keys()].reverse(),sn=(e,t)=>ut.sortBasedOnPerm(e,rn(e.length,t)),an=(e,t,n,i)=>{let r=`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`;for(let n=0;n<t;++n)r+=`a[${e[n]}]=i[${n}];`;return r+"return a;}"},on=(e,t)=>{let n=[],i=[];for(let r=0;r<e.length;++r)1!==e[r]&&n.push(e[r]),1!==e[t[r]]&&i.push(t[r]);return{newShape:n,newPerm:i}},un=(e,t)=>{let n=0;for(let i=0;i<e.length;++i)if(1!==t[e[i]]){if(e[i]<n)return!1;n=e[i]}return!0},ln=(e,t)=>{let n,i=e.dataType,r=e.dims.length,s=rn(r,t),a=sn(e.dims,s),o=e.dims,u=a;if(r<2||un(s,e.dims))return n=e=>{let t=Jt("input",i,o,4),n=Xt("output",i,u,4);return`\n ${e.registerUniform("output_size","u32").declareVariables(t,n)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n output[global_idx] = input[global_idx];\n }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let t=ut.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64/4)},programUniforms:[{type:12,data:Math.ceil(t/4)}]}},getShaderSource:n};let{newShape:l,newPerm:d}=on(e.dims,s),h=ut.areEqual(d,[2,3,1]),c=ut.areEqual(d,[3,1,2]);if(2===l.length||h||c){o=h?[l[0],l[1]*l[2]]:c?[l[0]*l[1],l[2]]:l,u=[o[1],o[0]];let t=16;return n=e=>{let n=Jt("a",i,o.length),r=Xt("output",i,u.length);return`\n ${e.registerUniform("output_size","u32").declareVariables(n,r)}\n var<workgroup> tile : array<array<${r.type.value}, ${t+1}>, ${t}>;\n ${e.mainStart([t,t,1])}\n let stride = (uniforms.output_shape[1] - 1) / ${t} + 1;\n let workgroup_id_x = workgroup_index % stride;\n let workgroup_id_y = workgroup_index / stride;\n let input_col = workgroup_id_y * ${t}u + local_id.x;\n let input_row = workgroup_id_x * ${t}u + local_id.y;\n if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {\n tile[local_id.y][local_id.x] = ${n.getByIndices(`${n.type.indices}(input_row, input_col)`)};\n }\n workgroupBarrier();\n\n let output_col = workgroup_id_x * ${t}u + local_id.x;\n let output_row = workgroup_id_y * ${t}u + local_id.y;\n if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {\n ${r.setByIndices(`${r.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}\n }\n }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let n=ut.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/t),y:Math.ceil(u[0]/t)},programUniforms:[{type:12,data:n},...qt(o,u)]}},getShaderSource:n}}return n=e=>{let t=Jt("a",i,o.length),n=Xt("output",i,u.length);return`\n ${e.registerUniform("output_size","u32").declareVariables(t,n)}\n\n ${an(s,r,t,n)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${n.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${n.setByOffset("global_idx",t.getByIndices("aIndices"))}\n }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let t=ut.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:[{type:12,data:t},...qt(o,u)]}},getShaderSource:n}},dn=(e,t)=>{nn(e.inputs,t.perm),e.compute(ln(e.inputs[0],t.perm))},hn=e=>Ut({perm:e.perm})}),hl=L(()=>{Yu(),nl(),ll(),cl(),dl(),cn={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"},pn={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"},fn={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},mn={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},gn=(e,t)=>{let n=[];for(let i=t-e;i<t;++i)n.push(i);return n},yn=(e,t)=>{let n=[],i=e.length;for(let r=0;r<i;r++)-1===t.indexOf(r)&&n.push(e[r]);return[n,t.map(t=>e[t])]},wn=(e,t)=>{let n=e.length+t.length,i=[],r=0;for(let s=0;s<n;s++)-1===t.indexOf(s)?i.push(e[r++]):i.push(1);return i},bn=(e,t)=>{for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0},_n=(e,t)=>{let n=[];if(!bn(e,t)){for(let i=0;i<t;++i)-1===e.indexOf(i)&&n.push(i);e.forEach(e=>n.push(e))}return n},$n=(e,t,n,i,r,s,a)=>{let o=n[0].dims,u=ut.size(s),l=ut.size(a),d=Jt("_A",n[0].dataType,o),h=Xt("output",r,s),c=64;1===u&&(c=256);let p=`\n var<workgroup> aBestValues : array<f32, ${c}>;\n `;return{name:e,shaderCache:{hint:`${t};${c}`,inputDependencies:["type"]},getShaderSource:e=>`\n ${e.registerUniform("reduceSize","u32").declareVariables(d,h)}\n ${p}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${e.mainStart(c)}\n\n let outputIndex = global_idx / ${c};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${fn[i]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${c}) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${cn[i]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${c}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${pn[i]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${h.setByOffset("outputIndex","mean"===i?`${h.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${h.type.storage}(${mn[i]})`)};\n }\n }`,getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:{x:u},programUniforms:[{type:12,data:l}]})}},vn=(e,t,n,i)=>{let r=1===e.inputs.length?n:Bn(e.inputs,n),s=r.axes;0===s.length&&!r.noopWithEmptyAxes&&(s=e.inputs[0].dims.map((e,t)=>t));let a=ut.normalizeAxes(s,e.inputs[0].dims.length),o=a,u=e.inputs[0],l=_n(o,e.inputs[0].dims.length);l.length>0&&(u=e.compute(ln(e.inputs[0],l),{inputs:[0],outputs:[-1]})[0],o=gn(o.length,u.dims.length));let[d,h]=yn(u.dims,o),c=d;r.keepDims&&(c=wn(d,a)),e.compute($n(t,r.cacheKey,[u],i,e.inputs[0].dataType,c,h),{inputs:[u]})},xn=(e,t)=>{vn(e,"ReduceMeanShared",t,"mean")},Sn=(e,t)=>{vn(e,"ReduceL1Shared",t,"l1")},Tn=(e,t)=>{vn(e,"ReduceL2Shared",t,"l2")},kn=(e,t)=>{vn(e,"ReduceLogSumExpShared",t,"logSumExp")},En=(e,t)=>{vn(e,"ReduceMaxShared",t,"max")},Cn=(e,t)=>{vn(e,"ReduceMinShared",t,"min")},In=(e,t)=>{vn(e,"ReduceProdShared",t,"prod")},An=(e,t)=>{vn(e,"ReduceSumShared",t,"sum")},Rn=(e,t)=>{vn(e,"ReduceSumSquareShared",t,"sumSquare")},Mn=(e,t)=>{vn(e,"ReduceLogSumShared",t,"logSum")}}),cl=L(()=>{Yu(),nl(),ul(),ll(),hl(),zn=e=>{if(!e||0===e.length||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(2===e.length&&1!==e[1].dims.length)throw new Error("Invalid axes input dims.")},On=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Pn=(e,t,n,i,r,s,a=!1,o=!1)=>{let u=[],l=n[0].dims,d=l.length,h=ut.normalizeAxes(r,d),c=!o&&0===h.length;l.forEach((e,t)=>{c||h.indexOf(t)>=0?a&&u.push(1):u.push(e)});let p=u.length,f=ut.size(u);return{name:e,shaderCache:t,getShaderSource:e=>{let t=[],r=Jt("_A",n[0].dataType,d),o=Xt("output",s,p),u=i(r,o,h),f=u[2];for(let e=0,n=0;e<d;e++)c||h.indexOf(e)>=0?(a&&n++,f=`for(var j${e}: u32 = 0; j${e} < ${l[e]}; j${e}++) {\n ${u[2].includes("last_index")?`let last_index = j${e};`:""}\n ${r.indicesSet("input_indices",e,`j${e}`)}\n ${f}\n }`):(t.push(`${r.indicesSet("input_indices",e,o.indicesGet("output_indices",n))};`),n++);return`\n\n ${e.registerUniform("output_size","u32").declareVariables(r,o)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${r.type.indices};\n let output_indices = ${o.offsetToIndices("global_idx")};\n\n ${t.join("\n")}\n ${u[0]} // init ops for reduce max/min\n ${u[1]}\n ${f}\n ${u[3]}\n ${4===u.length?o.setByOffset("global_idx","value"):u.slice(4).join("\n")}\n }`},getRunData:()=>({outputs:[{dims:u,dataType:s}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...qt(l,u)]})}},Bn=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),Ut({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Dn=(e,t,n,i)=>{let r=e.inputs,s=1===r.length?n:Bn(r,n);e.compute(Pn(t,{hint:s.cacheKey,inputDependencies:["rank"]},[r[0]],s.noopWithEmptyAxes&&0===s.axes.length?On:i,s.axes,r[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},Un=(e,t)=>{zn(e.inputs),Dn(e,"ReduceLogSum",t,(e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,"value = log(value);"])},Ln=(e,t)=>{zn(e.inputs),Dn(e,"ReduceL1",t,(e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += abs(${e.getByIndices("input_indices")});`,""])},Nn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceL2",t,(e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Hn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceLogSumExp",t,(e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += exp(${e.getByIndices("input_indices")});`,"value = log(value);"])},Fn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceMax",t,(e,t,n)=>{let i=[];for(let t=0;t<e.rank;t++)(n.indexOf(t)>=0||0===n.length)&&i.push(e.indicesSet("input_indices",t,0));return[`${i.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = max(value, ${e.getByIndices("input_indices")});`,""]})},qn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceMean",t,(t,n,i)=>{let r=1;for(let n=0;n<t.rank;n++)(i.indexOf(n)>=0||0===i.length)&&(r*=e.inputs[0].dims[n]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${r});`]})},Vn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceMin",t,(e,t,n)=>{let i=[];for(let t=0;t<e.rank;t++)(n.indexOf(t)>=0||0===n.length)&&i.push(`input_indices[${t}] = 0;`);return[`${i.join("\n")}`,`var value = ${e.getByIndices("input_indices")};`,`value = min(value, ${e.getByIndices("input_indices")});`,""]})},Wn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceProd",t,(e,t)=>[`var value = ${t.type.storage}(1);`,"",`value *= ${e.getByIndices("input_indices")};`,""])},jn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceSum",t,(e,t)=>[`var value = ${t.type.storage}(0);`,"",`value += ${e.getByIndices("input_indices")};`,""])},Gn=(e,t)=>{zn(e.inputs),Dn(e,"ReduceSumSquare",t,(e,t)=>[`var t = ${t.type.value}(0); var value = ${t.type.value}(0);`,"",`t = ${e.getByIndices("input_indices")}; value += t * t;`,""])},Kn=(e,t,n)=>{if(0===t.length)return n;let i=1,r=1;for(let n=0;n<t.length;n++)-1===t.indexOf(n)?i*=e[n]:r*=e[n];return r<32&&i>1024},Qn=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qn(e,t):xn(e,t)},Jn=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ln(e,t):Sn(e,t)},Xn=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Nn(e,t):Tn(e,t)},Zn=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hn(e,t):kn(e,t)},Yn=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fn(e,t):En(e,t)},ei=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vn(e,t):Cn(e,t)},ti=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wn(e,t):In(e,t)},ni=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jn(e,t):An(e,t)},ii=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gn(e,t):Rn(e,t)},ri=(e,t)=>{Kn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Un(e,t):Mn(e,t)}}),pl=L(()=>{Yu(),ul(),cl(),si=e=>{if(!e||0===e.length||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(1!==e[0].dataType)throw new Error("Invalid input type.")},ai=(e,t)=>{si(e.inputs),e.compute(Pn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],(e,n,i)=>{let r=[];for(let t=0;t<e.rank;t++)(i.indexOf(t)>=0||0===i.length)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]},[t.axis],7,t.keepDims),{inputs:[0]})},oi=(e,t)=>{si(e.inputs),e.compute(Pn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],(e,n,i)=>{let r=[];for(let t=0;t<e.rank;t++)(i.indexOf(t)>=0||0===i.length)&&r.push(`input_indices[${t}] = 0;`);return[`${r.join("\n")}`,`var value = ${e.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${e.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${e.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]},[t.axis],7,t.keepDims),{inputs:[0]})},ui=e=>Ut(e)}),fl=L(()=>{Yu(),nl(),al(),ll(),li=(e,t)=>{let n=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5];if(a&&o)throw new Error("Attention cannot have both past and attention_bias");if(3!==n.dims.length)throw new Error('Input "input" must have 3 dimensions');let u=n.dims[0],l=n.dims[1],d=n.dims[2];if(1!==r.dims.length)throw new Error('Input "bias" is expected to have 1 dimensions');if(2!==i.dims.length)throw new Error('Input "weights" is expected to have 2 dimensions');if(i.dims[0]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(r.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let h=r.dims[0]/3,c=h,p=c;if(t.qkvHiddenSizes.length>0){if(3!==t.qkvHiddenSizes.length)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let e of t.qkvHiddenSizes)if(e%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");h=t.qkvHiddenSizes[0],c=t.qkvHiddenSizes[1],p=t.qkvHiddenSizes[2]}let f=l;if(h!==c)throw new Error("qkv_hidden_sizes first element should be same as the second");if(r.dims[0]!==h+c+p)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let m=0;if(a){if(c!==p)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(5!==a.dims.length)throw new Error('Input "past" must have 5 dimensions');if(2!==a.dims[0])throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==u)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==c/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(m=a.dims[3])}let g=f+m;if(s)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(o){if(4!==o.dims.length)throw new Error('Input "attention_bias" must have 4 dimensions');if(o.dims[0]!==u||o.dims[1]!==t.numHeads||o.dims[2]!==l||o.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:u,sequenceLength:l,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:g,maxSequenceLength:-1,inputHiddenSize:d,hiddenSize:h,vHiddenSize:p,headSize:Math.floor(h/t.numHeads),vHeadSize:Math.floor(p/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},di=(e,t,n)=>t&&e?`\n let total_sequence_length_input = u32(${t.getByOffset("0")});\n let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);\n let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;\n let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;\n total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1;\n var past_sequence_length: u32 = 0;\n if (is_first_prompt == false) {\n past_sequence_length = total_sequence_length - sequence_length;\n }\n `:`\n ${n?"let past_sequence_length = uniforms.past_sequence_length":""};\n let present_sequence_length = total_sequence_length;\n `,hi=(e,t,n,i,r,s,a,o)=>{let u=Vt(a?1:s),l=64,d=s/u;d<l&&(l=32);let h=Math.ceil(s/u/l),c=[{type:12,data:t},{type:12,data:n},{type:12,data:i},{type:12,data:r},{type:12,data:d},{type:12,data:h}],p=Ht(e.dataType,u),f=Ft(1,u),m=["type"];return a&&m.push("type"),o&&m.push("type"),{name:"AttentionProbsSoftmax",shaderCache:{hint:`${l};${p};${u}`,inputDependencies:m},getShaderSource:t=>{let n=Xt("x",e.dataType,e.dims,u),i=[n],r=a?Jt("seq_lens",a.dataType,a.dims):void 0;r&&i.push(r);let s=o?Jt("total_sequence_length_input",o.dataType,o.dims):void 0;s&&i.push(s);let d=Ft(e.dataType);return`\n var<workgroup> thread_max: array<f32, ${l}>;\n var<workgroup> thread_sum: array<f32, ${l}>;\n ${t.registerUniforms([{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"}]).declareVariables(...i)}\n ${t.mainStart([l,1,1])}\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let sequence_length = uniforms.sequence_length;\n var total_sequence_length = uniforms.total_sequence_length;\n ${di(r,s,!1)}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = (global_idx / ${l}) * uniforms.total_sequence_length + local_offset;\n let seq_causal_length = ${a?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};\n var thread_max_vector = ${f}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n thread_max_vector = max(${f}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(u){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: ${u}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${l}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${f}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n sum_vector += exp(${f}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(u){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: ${u}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${l}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n x[offset + i] = ${n.type.value}(${d}(1.0) / ${d}(seq_causal_length));\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {\n var f32input = ${f}(x[offset + i]);\n x[offset + i] = ${n.type.value}(exp(f32input - max_value) / sum);\n }\n }\n ${a?`\n for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {\n x[offset + total_seq_id] = ${n.type.value}(${d}(0));\n }`:""};\n }`},getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:r,z:t*n},programUniforms:c})}},ci=(e,t,n,i,r,s,a,o,u)=>{let l=a+s.kvSequenceLength,d=[s.batchSize,s.numHeads,s.sequenceLength,l],h=e>1&&i,c=s.kvNumHeads?s.kvNumHeads:s.numHeads,p=h?[s.batchSize,c,l,s.headSize]:void 0,f=s.nReps?s.nReps:1,m=0===s.scale?1/Math.sqrt(s.headSize):s.scale,g=Vt(s.headSize),y=s.headSize/g,w={x:Math.ceil(l/12),y:Math.ceil(s.sequenceLength/12),z:s.batchSize*s.numHeads},b=[{type:12,data:s.sequenceLength},{type:12,data:y},{type:12,data:l},{type:12,data:s.numHeads},{type:12,data:s.headSize},{type:1,data:m},{type:12,data:a},{type:12,data:s.kvSequenceLength},{type:12,data:f}],_=h&&i&&ut.size(i.dims)>0,$=["type","type"];_&&$.push("type"),r&&$.push("type"),o&&$.push("type"),u&&$.push("type");let v=[{dims:d,dataType:t.dataType,gpuDataType:0}];return h&&v.push({dims:p,dataType:t.dataType,gpuDataType:0}),{name:"AttentionProbs",shaderCache:{hint:`${g};${void 0!==r};${void 0!==i};${e}`,inputDependencies:$},getRunData:()=>({outputs:v,dispatchGroup:w,programUniforms:b}),getShaderSource:e=>{let s=Jt("q",t.dataType,t.dims,g),a=[s,Jt("key",n.dataType,n.dims,g)];if(_){let e=Jt("past_key",i.dataType,i.dims,g);a.push(e)}r&&a.push(Jt("attention_bias",r.dataType,r.dims));let l=o?Jt("seq_lens",o.dataType,o.dims):void 0;l&&a.push(l);let c=u?Jt("total_sequence_length_input",u.dataType,u.dims):void 0;c&&a.push(c);let m=Xt("output",t.dataType,d),y=[m];h&&y.push(Xt("present_key",t.dataType,p,g));let w=Ft(1,g);return`\n const TILE_SIZE = 12u;\n\n var<workgroup> tileQ: array<${s.type.storage}, 144>;\n var<workgroup> tileK: array<${s.type.storage}, 144>;\n ${e.registerUniforms([{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"}]).declareVariables(...a,...y)}\n ${e.mainStart([12,12,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let kvHeadIdx = ${1===f?"headIdx":"headIdx / uniforms.n_reps"};\n let kv_num_heads = ${1===f?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.N;\n ${di(l,c,!0)}\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;\n let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n ${_&&h?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};\n let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;\n ${h?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}\n var value = ${w}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${_&&h?"\n if (n + local_id.y < past_sequence_length) {\n tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];\n }":"\n if (n + local_id.y < uniforms.kv_sequence_length) {\n tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];\n }"}\n ${h?"if (n + local_id.y < present_sequence_length) {\n present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];\n }":""}\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${w}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {\n let headOffset = workgroup_id.z * uniforms.M * uniforms.N;\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(g){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: ${g}`)}})()};\n output[outputIdx] = ${m.type.value} (sum * uniforms.alpha) + ${r?"attention_bias[outputIdx]":"0.0"};\n }\n }`}}},pi=(e,t,n,i,r,s,a=void 0,o=void 0)=>{let u=s+r.kvSequenceLength,l=r.nReps?r.nReps:1,d=r.vHiddenSize*l,h=e>1&&i,c=r.kvNumHeads?r.kvNumHeads:r.numHeads,p=h?[r.batchSize,c,u,r.headSize]:void 0,f=[r.batchSize,r.sequenceLength,d],m={x:Math.ceil(r.vHeadSize/12),y:Math.ceil(r.sequenceLength/12),z:r.batchSize*r.numHeads},g=[{type:12,data:r.sequenceLength},{type:12,data:u},{type:12,data:r.vHeadSize},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:d},{type:12,data:s},{type:12,data:r.kvSequenceLength},{type:12,data:l}],y=h&&i&&ut.size(i.dims)>0,w=["type","type"];y&&w.push("type"),a&&w.push("type"),o&&w.push("type");let b=[{dims:f,dataType:t.dataType,gpuDataType:0}];return h&&b.push({dims:p,dataType:t.dataType,gpuDataType:0}),{name:"AttentionScore",shaderCache:{hint:`${void 0!==i};${e}`,inputDependencies:w},getRunData:()=>({outputs:b,dispatchGroup:m,programUniforms:g}),getShaderSource:e=>{let r=Jt("probs",t.dataType,t.dims),s=[r,Jt("v",n.dataType,n.dims)];y&&s.push(Jt("past_value",i.dataType,i.dims));let u=a?Jt("seq_lens",a.dataType,a.dims):void 0;a&&s.push(u);let d=o?Jt("total_sequence_length_input",o.dataType,o.dims):void 0;o&&s.push(d);let c=[Xt("output",t.dataType,f)];return h&&c.push(Xt("present_value",t.dataType,p)),`\n const TILE_SIZE = 12u;\n var<workgroup> tileQ: array<${r.type.value}, 144>;\n var<workgroup> tileV: array<${r.type.value}, 144>;\n ${e.registerUniforms([{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"}]).declareVariables(...s,...c)}\n ${e.mainStart([12,12,1])}\n let headIdx = workgroup_id.z % uniforms.num_heads;\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let kvHeadIdx = ${1===l?"headIdx":"headIdx / uniforms.n_reps"};\n let kv_num_heads = ${1===l?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};\n let m = global_id.y;\n let n = global_id.x;\n let sequence_length = uniforms.M;\n var total_sequence_length = uniforms.K;\n ${di(u,d,!0)}\n let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;\n let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch\n ${y&&h?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};\n let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;\n ${h?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}\n var value = ${r.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n var idx = TILE_SIZE * local_id.y + local_id.x;\n ${y&&h?"\n if (w + local_id.y < past_sequence_length) {\n tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];\n } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];\n }\n ":"\n if (w + local_id.y < uniforms.kv_sequence_length) {\n tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];\n }"}\n ${h?"\n if (w + local_id.y < present_sequence_length) {\n present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];\n }":""}\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + headIdx * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},fi=(e,t,n,i,r,s,a,o,u,l,d=void 0,h=void 0)=>{let c=Math.min(e.outputCount,1+(a?1:0)+(o?1:0)),p=c>1?l.pastSequenceLength:0,f=p+l.kvSequenceLength,m=u&&ut.size(u.dims)>0?u:void 0,g=[t,n];c>1&&a&&ut.size(a.dims)>0&&g.push(a),m&&g.push(m),d&&g.push(d),h&&g.push(h);let y=e.compute(ci(c,t,n,a,m,l,p,d,h),{inputs:g,outputs:c>1?[-1,1]:[-1]})[0];e.compute(hi(y,l.batchSize,l.numHeads,p,l.sequenceLength,f,d,h),{inputs:d&&h?[y,d,h]:[y],outputs:[]});let w=[y,i];c>1&&o&&ut.size(o.dims)>0&&w.push(o),d&&w.push(d),h&&w.push(h),e.compute(pi(c,y,i,o,l,p,d,h),{inputs:w,outputs:c>1?[0,2]:[0]})},mi=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,r=t.inputHiddenSize,s=t.headSize,a={x:Math.ceil(t.headSize/12),y:Math.ceil(t.sequenceLength/12),z:t.batchSize*t.numHeads},o=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:i},{type:12,data:r},{type:12,data:s},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}];return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:u}),getShaderSource:e=>{let t=Xt("output_q",o[0].dataType,n),i=Xt("output_k",o[0].dataType,n),r=Xt("output_v",o[0].dataType,n),s=Jt("input",o[0].dataType,o[0].dims),a=Jt("weight",o[1].dataType,o[1].dims),u=Jt("bias",o[2].dataType,o[2].dims),l=s.type.storage;return`\n const TILE_SIZE = 12u;\n var<workgroup> tileInput: array<${l}, 144>;\n var<workgroup> tileWeightQ: array<${l}, 144>;\n var<workgroup> tileWeightK: array<${l}, 144>;\n var<workgroup> tileWeightV: array<${l}, 144>;\n ${e.registerUniforms([{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"}]).declareVariables(s,a,u,t,i,r)}\n ${e.mainStart([12,12,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${l}(0);\n var valueK = ${l}(0);\n var valueV = ${l}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k<TILE_SIZE && w+k < uniforms.K; k++) {\n let inputTileOffset = TILE_SIZE * local_id.y + k;\n let weightTileOffset = TILE_SIZE * k + local_id.x;\n valueQ += tileInput[inputTileOffset] * tileWeightQ[weightTileOffset];\n valueK += tileInput[inputTileOffset] * tileWeightK[weightTileOffset];\n valueV += tileInput[inputTileOffset] * tileWeightV[weightTileOffset];\n }\n\n workgroupBarrier();\n }\n\n let headOffset = (m * uniforms.N + n) % uniforms.head_size;\n valueQ += bias[headOffset + biasOffsetQ];\n valueK += bias[headOffset + biasOffsetK];\n valueV += bias[headOffset + biasOffsetV];\n\n let offset = workgroup_id.z * uniforms.M * uniforms.N;\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = offset + m * uniforms.N + n;\n output_q[outputIdx] = valueQ;\n output_k[outputIdx] = valueK;\n output_v[outputIdx] = valueV;\n }\n }`}},{inputs:o,outputs:[-1,-1,-1]})},gi=(e,t)=>{let n=li(e.inputs,t),[i,r,s]=mi(e,n);return fi(e,i,r,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),ml=L(()=>{oe(),Yu(),nl(),ul(),ll(),yi=(e,t)=>{if(!e||5!==e.length)throw new Error("BatchNormalization requires 5 inputs");let n=(e,t,n)=>{let i=t.length;if(i!==e.length)throw new Error(`${n}: num dimensions != ${i}`);t.forEach((t,i)=>{if(t!==e[i])throw new Error(`${n}: dim[${i}] do not match`)})};if(e[0].dims.length>1){let i="NHWC"===t.format?t.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,t.spatial?2:void 0);n(e[1].dims,i,"Invalid input scale"),n(e[2].dims,i,"Invalid input B"),n(e[3].dims,i,"Invalid input mean"),n(e[4].dims,i,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},wi=(e,t)=>{let{epsilon:n,spatial:i,format:r}=t,s=e[0].dims,a=i?Vt(s[s.length-1]):1,o="NHWC"===r&&s.length>1?a:1,u=ut.size(s)/a,l=i,d=l?s.length:s,h=Jt("x",e[0].dataType,e[0].dims,a),c=Jt("scale",e[1].dataType,e[1].dims,o),p=Jt("bias",e[2].dataType,e[2].dims,o),f=Jt("inputMean",e[3].dataType,e[3].dims,o),m=Jt("inputVar",e[4].dataType,e[4].dims,o),g=Xt("y",e[0].dataType,d,a);return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${a}`,inputDependencies:l?["rank","type","type","type","type"]:void 0},getShaderSource:e=>`\n const epsilon = ${n};\n ${e.registerUniform("outputSize","u32").declareVariables(h,c,p,f,m,g)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${g.offsetToIndices(`global_idx * ${a}`)};\n ${(()=>{let e="";if(i)e=`let cOffset = ${1===s.length?"0u":"NHWC"===r?`outputIndices[${s.length-1}] / ${a}`:"outputIndices[1]"};`;else if("NCHW"===r)e=`\n ${g.indicesSet("outputIndices","0","0")}\n let cOffset = ${g.indicesToOffset("outputIndices")};`;else{e=`var cIndices = ${c.type.indices}(0);\n cIndices[0] = outputIndices[${s.length-1}];`;for(let t=1;t<c.rank;t++)e+=`cIndices[${t}] = outputIndices[${t}];`;e+=`let cOffset = ${c.indicesToOffset("cIndices")};`}return e})()}\n let scale = ${c.getByOffset("cOffset")};\n let bias = ${p.getByOffset("cOffset")};\n let inputMean = ${f.getByOffset("cOffset")};\n let inputVar = ${m.getByOffset("cOffset")};\n let x = ${h.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${g.setByOffset("global_idx","value")}\n }`,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l?[{type:12,data:u},...qt(s)]:[{type:12,data:u}]})}},bi=e=>Ut(e),_i=(e,t)=>{let{inputs:n,outputCount:i}=e,r=bi({...t,outputCount:i});if(l.webgpu.validateInputContent&&yi(n,r),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(wi(n,r))}}),gl=L(()=>{nl(),ll(),$i=e=>{if(3!==e[0].dims.length)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(1!==e[1].dims.length)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")},vi=e=>{let t=e[0].dims,n=e[0].dims[2],i=ut.size(t)/4,r=e[0].dataType,s=Jt("input",r,t,4),a=Jt("bias",r,[n],4),o=Jt("residual",r,t,4),u=Xt("output",r,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:e=>`\n const channels = ${n}u / 4;\n ${e.declareVariables(s,a,o,u)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(i)}\n let value = ${s.getByOffset("global_idx")}\n + ${a.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")};\n ${u.setByOffset("global_idx","value")}\n }`}},xi=e=>{$i(e.inputs),e.compute(vi(e.inputs))}}),yl=L(()=>{Yu(),nl(),ul(),ll(),Si=(e,t,n,i,r,s,a)=>{let o=Math.ceil(t/4),u="";u="string"==typeof r?`${r}(a)`:r("a");let l=Jt("inputData",n,[o],4),d=Xt("outputData",i,[o],4),h=[{name:"vec_size",type:"u32"}];return a&&h.push(...a),`\n ${e.registerUniforms(h).declareVariables(l,d)}\n\n ${s??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${l.getByOffset("global_idx")};\n ${d.setByOffset("global_idx",u)}\n }`},Ti=(e,t,n,i,r,s=e.dataType,a,o)=>{let u=[{type:12,data:Math.ceil(ut.size(e.dims)/4)}];return a&&u.push(...a),{name:t,shaderCache:{hint:r,inputDependencies:["type"]},getShaderSource:t=>Si(t,ut.size(e.dims),e.dataType,s,n,i,o),getRunData:t=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(ut.size(t[0].dims)/64/4)},programUniforms:u})}},ki=e=>{e.compute(Ti(e.inputs[0],"Abs","abs"))},Ei=e=>{e.compute(Ti(e.inputs[0],"Acos","acos"))},Ci=e=>{e.compute(Ti(e.inputs[0],"Acosh","acosh"))},Ii=e=>{e.compute(Ti(e.inputs[0],"Asin","asin"))},Ai=e=>{e.compute(Ti(e.inputs[0],"Asinh","asinh"))},Ri=e=>{e.compute(Ti(e.inputs[0],"Atan","atan"))},Mi=e=>{e.compute(Ti(e.inputs[0],"Atanh","atanh"))},zi=e=>Ut(e),Oi=(e,t)=>{let n;switch(t.to){case 10:n="vec4<f16>";break;case 1:n="vec4<f32>";break;case 12:n="vec4<u32>";break;case 6:n="vec4<i32>";break;case 9:n="vec4<bool>";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Ti(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},Pi=e=>{let t,n,i=e.length>=2&&0!==e[1].data,r=e.length>=3&&0!==e[2].data;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,n=r?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,n=r?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Ut({min:t,max:n})},Bi=(e,t)=>{let n=t||Pi(e.inputs),i=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"Clip",e=>`clamp(${e}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},Di=e=>{e.compute(Ti(e.inputs[0],"Ceil","ceil"))},Ui=e=>{e.compute(Ti(e.inputs[0],"Cos","cos"))},Li=e=>{e.compute(Ti(e.inputs[0],"Cosh","cosh"))},Ni=e=>Ut(e),Hi=(e,t)=>{let n=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"Elu",e=>`elu_vf32(${e})`,`\n const elu_alpha_ = ${n}(${t.alpha});\n\n fn elu_f32(a: ${n}) -> ${n} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Fi=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${e}> {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,qi=e=>{let t=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"Erf",e=>`erf_vf32(${e})`,Fi(t)))},Vi=e=>{e.compute(Ti(e.inputs[0],"Exp","exp"))},Wi=e=>{e.compute(Ti(e.inputs[0],"Floor","floor"))},ji=e=>{let t=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"Gelu",e=>`0.5 * ${e} * (1.0 + erf_vf32(${e} * 0.7071067811865475))`,Fi(t)))},Gi=(e,t)=>{let n=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"LeakyRelu",e=>`select(leaky_relu_alpha_ * ${e}, ${e}, ${e} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},Ki=e=>{e.compute(Ti(e.inputs[0],"Not",e=>`!${e}`))},Qi=e=>{e.compute(Ti(e.inputs[0],"Neg",e=>`-${e}`))},Ji=e=>{e.compute(Ti(e.inputs[0],"Reciprocal",e=>`1.0/${e}`))},Xi=e=>{let t=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"Relu",e=>`select(vec4<${t}>(0.0), ${e}, ${e} > vec4<${t}>(0.0))`))},Zi=e=>{e.compute(Ti(e.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},Yi=e=>Ut(e),er=(e,t)=>{let n=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"HardSigmoid",e=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${e} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},tr=e=>{e.compute(Ti(e.inputs[0],"Sin","sin"))},nr=e=>{e.compute(Ti(e.inputs[0],"Sinh","sinh"))},ir=e=>{e.compute(Ti(e.inputs[0],"Sqrt","sqrt"))},rr=e=>{e.compute(Ti(e.inputs[0],"Tan","tan"))},sr=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,ar=e=>{e.compute(Ti(e.inputs[0],"Tanh",sr))},or=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${sr("v")};\n}\n`,ur=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,lr=e=>{let t=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"FastGelu",ur,or(t),void 0,e.inputs[0].dataType))},dr=(e,t)=>{let n=Ft(e.inputs[0].dataType);return e.compute(Ti(e.inputs[0],"ThresholdedRelu",e=>`select(vec4<${n}>(0.0), ${e}, ${e} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},hr=e=>{e.compute(Ti(e.inputs[0],"Log","log"))},cr=(e,t)=>`\nconst alpha = vec4<${e}>(${t});\nconst one = ${e}(1.0);\nconst zero = ${e}(0.0);\n\nfn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> {\n let v = x *alpha;\n var x1 : vec4<${e}>;\n for (var i = 0; i < 4; i = i + 1) {\n if (v[i] >= zero) {\n x1[i] = one / (one + exp(-v[i]));\n } else {\n x1[i] = one - one / (one + exp(v[i]));\n }\n }\n return x * x1;\n}\n`,pr=e=>`quick_gelu_impl(${e})`,fr=(e,t)=>{let n=Ft(e.inputs[0].dataType);e.compute(Ti(e.inputs[0],"QuickGelu",pr,cr(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),wl=L(()=>{nl(),ll(),yl(),mr=e=>{if(3!==e[0].dims.length)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(1!==e[1].dims.length)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")},gr=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=Jt("input",e[0].dataType,e[0].dims,4),i=Jt("bias",e[0].dataType,[e[0].dims[2]],4),r=Xt("output",e[0].dataType,t,4),s=ut.size(t)/4,a=Ht(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:t=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${t.declareVariables(n,i,r)}\n\n ${Fi(a)}\n\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes(s)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${r.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},yr=e=>{mr(e.inputs),e.compute(gr(e.inputs))}}),bl=L(()=>{Yu(),nl(),ll(),wr=(e,t,n,i,r,s,a,o,u,l,d,h)=>{let c,p;"string"==typeof o?c=p=(e,t)=>`${o}((${e}),(${t}))`:"function"==typeof o?c=p=o:(c=o.scalar,p=o.vector);let f,m=Xt("outputData",d,i.length,4),g=Jt("aData",u,t.length,4),y=Jt("bData",l,n.length,4);if(r)if(s){let e=1===ut.size(t),i=1===ut.size(n),r=t.length>0&&t[t.length-1]%4==0,s=n.length>0&&n[n.length-1]%4==0;f=e||i?m.setByOffset("global_idx",p(e?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),i?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"))):`\n let outputIndices = ${m.offsetToIndices("global_idx * 4u")};\n let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",m)};\n let offsetB = ${y.broadcastedIndicesToOffset("outputIndices",m)};\n ${m.setByOffset("global_idx",p(a||r?g.getByOffset("offsetA / 4u"):`${g.type.value}(${g.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||s?y.getByOffset("offsetB / 4u"):`${y.type.value}(${y.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else f=m.setByOffset("global_idx",p(g.getByOffset("global_idx"),y.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let e=(e,t,n="")=>{let i=`aData[indexA${t}][componentA${t}]`,r=`bData[indexB${t}][componentB${t}]`;return`\n let outputIndices${t} = ${m.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offsetA${t} = ${g.broadcastedIndicesToOffset(`outputIndices${t}`,m)};\n let offsetB${t} = ${y.broadcastedIndicesToOffset(`outputIndices${t}`,m)};\n let indexA${t} = offsetA${t} / 4u;\n let indexB${t} = offsetB${t} / 4u;\n let componentA${t} = offsetA${t} % 4u;\n let componentB${t} = offsetB${t} % 4u;\n ${e}[${t}] = ${n}(${c(i,r)});\n `};f=9===d?`\n var data = vec4<u32>(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:`\n ${e("outputData[global_idx]",0)}\n ${e("outputData[global_idx]",1)}\n ${e("outputData[global_idx]",2)}\n ${e("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(g,y,m)}\n\n ${h??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${f}\n }`},br=(e,t,n,i,r,s,a=n.dataType)=>{let o=n.dims.map(e=>Number(e)??1),u=i.dims.map(e=>Number(e)??1),l=!ut.areEqual(o,u),d=o,h=ut.size(o),c=!1,p=!1,f=[l];if(l){let e=ot.calcShape(o,u,!1);if(!e)throw new Error("Can't perform binary op on the given tensors");d=e.slice(),h=ut.size(d);let t=1===ut.size(o),n=1===ut.size(u),i=o.length>0&&o[o.length-1]%4==0,r=u.length>0&&u[u.length-1]%4==0;f.push(t),f.push(n),f.push(i),f.push(r);let s=1;for(let e=1;e<d.length;e++){let t=o[o.length-e];if(t!==u[u.length-e])break;s*=t}s%4==0?(p=!0,c=!0):(t||n||i||r)&&(c=!0)}else c=!0;return f.push(c),{name:e,shaderCache:{hint:t+f.map(e=>e.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:e=>wr(e,o,u,d,c,l,p,r,n.dataType,i.dataType,a,s),getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(ut.size(d)/4)},...qt(o,u,d)]})}},_r=(e,t,n,i,r,s)=>{e.compute(br(t,r??"",e.inputs[0],e.inputs[1],n,i,s))},$r=e=>{_r(e,"Add",(e,t)=>`${e}+${t}`)},vr=e=>{_r(e,"Div",(e,t)=>`${e}/${t}`)},xr=e=>{_r(e,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4<u32>(${e}==${t})`},void 0,void 0,9)},Sr=e=>{_r(e,"Mul",(e,t)=>`${e}*${t}`)},Tr=e=>{let t=Jt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;_r(e,"Pow",{scalar:(e,t)=>`pow_custom(${e},${t})`,vector:(e,t)=>`pow_vector_custom(${e},${t})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${"i32"===t?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},kr=e=>{_r(e,"Sub",(e,t)=>`${e}-${t}`)},Er=e=>{_r(e,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4<u32>(${e}>${t})`},void 0,void 0,9)},Cr=e=>{_r(e,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4<u32>(${e}<${t})`},void 0,void 0,9)},Ir=e=>{_r(e,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4<u32>(${e}>=${t})`},void 0,void 0,9)},Ar=e=>{_r(e,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4<u32>(${e}<=${t})`},void 0,void 0,9)}}),_l=L(()=>{Yu(),nl(),ul(),ll(),Rr=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=e[0],i=n.dataType,r=n.dims.length;e.forEach((e,s)=>{if(0!==s){if(e.dataType!==i)throw new Error("input tensors should be one type");if(e.dims.length!==r)throw new Error("input tensors should have the same shape");e.dims.forEach((e,i)=>{if(i!==t&&e!==n.dims[i])throw new Error("non concat dimensions must match")})}})},Mr=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array<u32, ${e}u>(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,zr=(e,t)=>{let n=e.length,i=[];for(let r=0;r<n;++r){let s=t.setByOffset("global_idx",e[r].getByIndices("indices"));1===n?i.push(s):0===r?i.push(`if (inputIndex == ${r}u) { ${s} }`):r===n-1?i.push(`else { ${s} }`):i.push(`else if (inputIndex == ${r}) { ${s} }`)}return i.join("\n")},Or=(e,t,n,i)=>{let r=ut.size(n),s=new Array(e.length),a=new Array(e.length),o=0,u=[],l=[],d=[{type:12,data:r}];for(let n=0;n<e.length;++n)o+=e[n].dims[t],s[n]=o,l.push(e[n].dims.length),a[n]=Jt(`input${n}`,i,l[n]),u.push("rank"),d.push({type:12,data:s[n]});for(let t=0;t<e.length;++t)d.push(...qt(e[t].dims));d.push(...qt(n));let h=Xt("output",i,n.length),c=h.indicesGet("indices",t),p=Array.from(Array(s.length).keys()).map(e=>`uniforms.sizeInConcatAxis${e}`).join(",");return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:d}),getShaderSource:t=>`\n\n ${(()=>{t.registerUniform("outputSize","u32");for(let n=0;n<e.length;n++)t.registerUniform(`sizeInConcatAxis${n}`,"u32");return t.declareVariables(...a,h)})()}\n\n ${Mr(s.length,p)}\n\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n var indices = ${h.offsetToIndices("global_idx")};\n\n let inputIndex = calculateInputIndex(${c});\n if (inputIndex != 0u) {\n let sizeInConcatAxis = array<u32, ${s.length}u>(${p});\n ${c} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${zr(a,h)}\n }`}},Pr=(e,t)=>{let n=e.inputs,i=n[0].dims,r=ut.normalizeAxis(t.axis,i.length);Rr(n,r);let s=i.slice();s[r]=n.reduce((e,t)=>e+(t.dims.length>r?t.dims[r]:0),0);let a=n.filter(e=>ut.size(e.dims)>0);e.compute(Or(a,r,s,n[0].dataType),{inputs:a})},Br=e=>Ut({axis:e.axis})}),$l=L(()=>{Yu(),nl(),Dr=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return"let e2x = exp(-2.0 * abs(value));\n value = sign(value) * (1.0 - e2x) / (1.0 + e2x);\n ";case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Ur=(e,t)=>{"Clip"===e.activation?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):"HardSigmoid"===e.activation?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):"LeakyRelu"===e.activation&&t.push({type:1,data:e.alpha})},Lr=(e,t)=>{"Clip"===e.activation?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):"HardSigmoid"===e.activation?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):"LeakyRelu"===e.activation&&t.push({name:"alpha",type:"f32"})},Nr=e=>{let t=e?.activation||"";if("HardSigmoid"===t){let[n,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:i}}if("Clip"===t){let[n,i]=e?.activation_params||[ht,ct];return{activation:t,clipMax:i,clipMin:n}}if("LeakyRelu"===t){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),vl=L(()=>{Hr=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Fr=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `}),xl=L(()=>{qr=e=>`\nfn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {\n return dot(coords, vec4<i32>(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`}),Sl=L(()=>{Yu(),nl(),ll(),$l(),Vr=(e,t,n,i,r)=>{let s=i-n;return`\n ${Array.from({length:n}).map((n,a)=>`\n if (${Kt(t.shape,a,t.rank)} != 1) {\n ${t.indicesSet(e,a,Kt(r,a+s,i))}\n } else {\n ${t.indicesSet(e,a,0)}\n }`).join("")}\n`},Wr=(e,t,n,i,r=!1,s)=>{let a=e[0].dims,o=e[1].dims,u=a[a.length-2],l=o[o.length-1],d=a[a.length-1],h=Vt(l),c=Vt(d),p=Vt(u),f=ut.size(n)/h/p,m=e.length>2,g=i?i.slice(0,-2):n.slice(0,-2),y=[ut.size(g),u,l],w=[{type:12,data:f},{type:12,data:u},{type:12,data:l},{type:12,data:d}];return Ur(t,w),w.push(...qt(g,a,o)),m&&w.push(...qt(e[2].dims)),w.push(...qt(y)),{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${h};${c};${p};${r}`,inputDependencies:m?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:w}),getShaderSource:i=>{let s=Yt("batch_dims",e[0].dataType,g.length),u=Jt("a",e[0].dataType,a.length,c),l=Jt("b",e[1].dataType,o.length,h),d=Xt("output",e[0].dataType,y.length,h),f=Ht(d.type.tensor),w=Dr(t,d.type.value,f),b=[u,l],_="";if(m){let t=r?h:1;b.push(Jt("bias",e[2].dataType,e[2].dims.length,t)),_=r?`value += bias[col / ${t}];`:`value += ${d.type.value}(bias[row + i]);`}let $=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];return Lr(t,$),`\n ${i.registerUniforms($).registerInternalVariables(s).declareVariables(...b,d)}\n ${i.mainStart()}\n ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let col = (global_idx % (uniforms.N / ${h})) * ${h};\n var index1 = global_idx / (uniforms.N / ${h});\n let stride1 = uniforms.M / ${p};\n let row = (index1 % stride1) * ${p};\n let batch = index1 / stride1;\n\n ${2===n.length?"":`let batch_indices = ${s.offsetToIndices("batch")};`}\n\n var a_indices: ${u.type.indices};\n ${Vr("a_indices",u,u.rank-2,s.rank,"batch_indices")}\n ${u.indicesSet("a_indices",u.rank-2,0)}\n ${u.indicesSet("a_indices",u.rank-1,0)}\n let a_offset = ${u.indicesToOffset("a_indices")};\n\n var b_indices: ${l.type.indices};\n ${Vr("b_indices",l,l.rank-2,s.rank,"batch_indices")}\n ${l.indicesSet("b_indices",l.rank-2,0)}\n ${l.indicesSet("b_indices",l.rank-1,0)}\n let b_offset = ${l.indicesToOffset("b_indices")};\n var values: array<${d.type.value}, ${p}>;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${c}) {\n ${(()=>{let e=`var a_data: ${u.type.value};`;for(let t=0;t<c;t++)e+=`\n let b_data${t} = b[(b_offset + (k + ${t}) * uniforms.N + col) / ${h}];`;for(let t=0;t<p;t++){e+=`a_data = a[(a_offset + (row + ${t}) * uniforms.K + k) / ${c}];`;for(let n=0;n<c;n++)e+=`\n values[${t}] = fma(${l.type.value}(a_data${1===c?"":`[${n}]`}), b_data${n}, values[${t}]);\n`}return e})()}\n }\n for (var i = 0u; i < ${p}u; i++) {\n var value = values[i];\n ${_}\n ${w}\n let cur_indices = ${d.type.indices}(batch, row + i, col);\n let offset = ${d.indicesToOffset("cur_indices")};\n ${d.setByOffset(`offset / ${h}`,"value")};\n }\n }\n `}}}}),Tl=L(()=>{Yu(),nl(),ll(),$l(),Sl(),vl(),jr=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,Gr=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${3===t?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${3===t?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,Kr=(e,t,n="f32",i,r=!1,s=32,a=!1,o=32)=>{let u=t[1]*e[1],l=t[0]*e[0],d=r?u:s,h=r?s:u,c=d/t[0],p=s/t[1];if((!r||4!==c||4!==e[1])&&(r||3!==c&&4!==c)||d%t[0]!==0||s%t[1]!==0||4!==e[0])throw new Error(`If transposeA ${r} is true, innerElementSize ${c} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${c} must be 3 or 4.\n tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar<workgroup> mm_Asub: array<array<vec${c}<${n}>, ${d/c}>, ${h}>;\nvar<workgroup> mm_Bsub: array<array<vec4<${n}>, ${l/e[0]}>, ${s}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${c};\nconst tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n @builtin(global_invocation_id) globalId : vec3<u32>,\n @builtin(workgroup_id) workgroupId : vec3<u32>) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${a?"0":"i32(globalId.z)"};\n ${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${u};\n\n let num_tiles = ${a?`${Math.ceil(o/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${o}`:"0"};\n\n var acc: array<vec4<${n}>, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${p};\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${jr(r,i)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${p}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${3===c?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${Gr(r,c)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Qr=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,Jr=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Xr=(e,t,n="f32",i,r=!1,s=32,a=!1,o=32,u=!1)=>{let l=e[1]*t[1],d=e[0]*t[0],h=r?l:s,c=r?s:l;if(c%t[1]!==0||h%t[0]!==0||s%t[1]!==0)throw new Error(`tileAHight ${c} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${h} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let p=c/t[1],f=h/t[0],m=s/t[1],g=u?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${l};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${h}; inputCol = inputCol + ${t[0]}) {\n ${Qr(r,i)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${i?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${r?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${l};\n\nlet tileRowA = i32(localId.y) * ${p};\nlet tileColA = i32(localId.x) * ${f};\nlet tileRowB = i32(localId.y) * ${m};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${p}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Qr(r,i)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${m}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${i?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${n}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${Jr(r)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var<workgroup> mm_Asub : array<array<${n}, ${h}>, ${c}>;\n var<workgroup> mm_Bsub : array<array<${n}, ${d}>, ${s}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3<u32>,\n @builtin(global_invocation_id) globalId : vec3<u32>,\n @builtin(workgroup_id) workgroupId : vec3<u32>) {\n let batch = ${a?"0":"i32(globalId.z)"};\n ${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${a?`${Math.ceil(o/s)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${o}`:"0"};\n\n var acc : array<array<${n}, colPerThread>, rowPerThread>;\n ${g}\n }\n`},Zr=(e,t,n,i,r=!1)=>{let[s,a,o,u]=i,l=Ht(i[0].type.tensor);return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${s.type.indices}) -> ${Hr(e,l)} {\n var value = ${Hr(e,l)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n var aIndices: ${a.type.indices};\n ${Vr("aIndices",a,a.rank-2,s.rank,"batchIndices")}\n ${a.indicesSet("aIndices",a.rank-2,"u32(row)")}\n ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")}\n value = ${a.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${s.type.indices}) -> ${Hr(e,l)} {\n var value = ${Hr(e,l)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n var bIndices: ${o.type.indices};\n ${Vr("bIndices",o,o.rank-2,s.rank,"batchIndices")}\n ${o.indicesSet("bIndices",o.rank-2,"u32(row)")}\n ${o.indicesSet("bIndices",o.rank-1,"u32(colIn)")}\n value = ${o.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Hr(e,l)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3<i32>(batch, row, colIn);\n ${t?`value = value + ${r?"bias[colIn]":`${Hr(e,l)}(bias[row])`};`:""}\n ${n}\n ${u.setByIndices("vec3<u32>(coords)","value")}\n }\n }\n `},Yr=(e,t,n,i,r=!1,s)=>{let a=e[0].dims,o=e[1].dims,u=a.slice(0,-2),l=o.slice(0,-2),d=i?i.slice(0,-2):n.slice(0,-2),h=ut.size(d),c=a[a.length-2],p=a[a.length-1],f=o[o.length-1],m=p%4==0&&f%4==0,g=c<=8?[4,1,1]:[4,4,1],y=[8,8,1],w=[Math.ceil(f/y[0]/g[0]),Math.ceil(c/y[1]/g[1]),Math.ceil(h/y[2]/g[2])],b=m?4:1,_=[...u,c,p/b],$=_.length,v=[...l,p,f/b],x=v.length,S=[h,c,f/b],T=[{type:6,data:c},{type:6,data:f},{type:6,data:p}];Ur(t,T),T.push(...qt(d,_,v));let k=["rank","rank"],E=e.length>2;return E&&(T.push(...qt(e[2].dims)),k.push("rank")),T.push(...qt(S)),{name:"MatMul",shaderCache:{hint:`${g};${t.activation};${m};${r}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:s?s(n):n,dataType:e[0].dataType}],dispatchGroup:{x:w[0],y:w[1],z:w[2]},programUniforms:T}),getShaderSource:n=>{let i=d.length,s=Yt("batchDims",e[0].dataType,i,1),a=Ht(e[0].dataType),o=Jt("a",e[0].dataType,$,b),u=Jt("b",e[1].dataType,x,b),l=Xt("result",e[0].dataType,S.length,b),h=[o,u];if(E){let t=r?b:1;h.push(Jt("bias",e[2].dataType,e[2].dims.length,t))}let c=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Lr(t,c);let p=Ht(l.type.tensor),f=Dr(t,l.type.value,p),w=Zr(b,E,f,[s,o,u,l],r);return`\n ${n.registerUniforms(c).registerInternalVariables(s).declareVariables(...h,l)}\n ${w}\n ${m?Kr(g,y,a,s):Xr(g,y,a,s)}\n `}}}}),kl=L(()=>{Yu(),tl(),ll(),$l(),vl(),xl(),Tl(),es=(e,t,n,i,r=!1,s,a=4,o=4,u=4,l="f32")=>{let d=e=>{switch(e){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 ${e} is not supported.`)}},h=e?"\n let coord = vec4<i32>(batch, xRow, xCol, xCh);\n ":"\n let coord = vec4<i32>(batch, xCh, xRow, xCol);\n ",c=e?"\n let coords = vec4<i32>(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n ":"\n let coords = vec4<i32>(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n ",p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",f=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",m=e?"row":"col",g=e?"col":"row",y=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${m} / outWidth;\n let outCol = ${m} % outWidth;\n\n let WRow = ${g} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${g} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${g} % inChannels;\n var resData = ${Hr(a,l)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the 'same' padding type.\n if (xRow >= 0 && xRow < ${p} && xCol >= 0 && xCol < ${f}) {\n ${h}\n let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));\n ${(e=>{switch(e){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${l}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${e} is not supported.`)}})(a)}\n }\n return resData;`,w=e?t&&i?`\n let col = colIn * ${a};\n ${y}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${y}\n }\n return ${Hr(a,l)}(0.0);`:i&&n?`\n let col = colIn * ${a};\n ${y}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${y}\n }\n return ${Hr(a,l)}(0.0);`,b=e?i&&n?d(o):`\n let col = colIn * ${o};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${d(o)}\n }\n return ${Hr(o,l)}(0.0);`:`\n let col = colIn * ${o};\n if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {\n ${d(o)}\n }\n return ${Hr(o,l)}(0.0);`,_=Hr(u,l),$=Hr(e?a:o,l),v=Hr(e?o:a,l),x=Dr(s,_,l);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${$} {\n ${e?w:b}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${v} {\n ${e?b:w}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${_}) {\n let col = colIn * ${u};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${Fr(r)}\n ${x}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},ts=(e,t,n,i,r,s,a,o,u)=>{let l="NHWC"===t.format,d=l?e[0].dims[3]:e[0].dims[1],h=n[0],c=l?n[2]:n[3],p=l?n[1]:n[2],f=l?n[3]:n[1],m=l&&(d%4==0||d%3==0)&&f%4==0,g=l?f:c*p,y=l?c*p:f,w=[8,8,1],b=i<=8?[4,1,1]:[4,4,1],_=[Math.ceil(g/w[0]/b[0]),Math.ceil(y/w[1]/b[1]),Math.ceil(h/w[2]/b[2])];st("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${_}`);let $=m?l&&d%4!=0?3:4:1,v=w[1]*b[1],x=w[0]*b[0],S=Math.max(w[0]*$,w[1]),T=i%v===0,k=r%x===0,E=s%S===0,C=m?[$,4,4]:[1,1,1],I=[{type:6,data:i},{type:6,data:r},{type:6,data:s},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Ur(t,I),I.push(...qt(e[0].dims,e[1].dims));let A=["rank","rank"];return a&&(I.push(...qt(e[2].dims)),A.push("rank")),I.push(...qt(n)),{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${$};${m};${T};${k};${E};${v};${x};${S}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:u?u(n):n,dataType:e[0].dataType}],dispatchGroup:{x:_[0],y:_[1],z:_[2]},programUniforms:I}),getShaderSource:i=>{let r=[{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}];Lr(t,r);let s=m?4:1,u=Ht(e[0].dataType),d=`\n fn setOutputAtIndex(flatIndex : i32, value : ${m?`vec4<${u}>`:u}) {\n result[flatIndex] = ${m?`vec4<${u}>`:u}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${m?`vec4<${u}>`:u}) {\n let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${m?"/ 4":""}, value);\n }`,h=[Jt("x",e[0].dataType,e[0].dims.length,3===$?1:$),Jt("w",e[1].dataType,e[1].dims.length,s)],c=Xt("result",e[0].dataType,n.length,s);if(a){let t=Jt("bias",e[2].dataType,e[2].dims.length,s);h.push(t),d+=`\n fn getBiasByOutputCoords(coords : vec4<i32>) -> ${m?`vec4<${u}>`:u} {\n return bias[coords.${l?"w":"y"}${m?"/ 4":""}];\n }`}return`\n ${qr("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4<i32>, wShape : vec4<i32>, outShape : vec4<i32>,\n // outShapeStrides: vec3<i32>, filterDims : vec2<i32>, pad : vec2<i32>, stride : vec2<i32>,\n // dilation : vec2<i32>, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${i.registerUniforms(r).declareVariables(...h,c)}\n ${d}\n ${es(l,T,k,E,a,t,C[0],C[1],C[2],u)}\n ${m?Kr(b,w,u,void 0,!l,S):Xr(b,w,u,void 0,!l,S,!1,void 0,o)}`}}}}),El=L(()=>{Yu(),tl(),nl(),ll(),$l(),vl(),ns=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t},is=e=>"number"==typeof e?[e,e,e]:e,rs=(e,t)=>t<=1?e:e+(e-1)*(t-1),ss=(e,t,n,i=1)=>{let r=rs(t,i);return Math.floor((e[0]*(n-1)-n+r)/2)},as=(e,t,n,i,r)=>{null==r&&(r=ss(e,t[0],i[0]));let s=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*r>=t[n]&&(s[n]=Math.trunc((e[n]-t[n]+2*r)/i[n]+1));return s},os=(e,t,n,i,r,s,a,o,u,l)=>{let d,h,c,p;if("VALID"===e&&(e=0),"number"==typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=as([t,n,i,1],[o,u,l],1,[r,s,a],e);h=f[0],c=f[1],p=f[2]}else if(Array.isArray(e)){if(!e.every((e,t,n)=>e===n[0]))throw Error(`Unsupported padding parameter: ${e}`);d={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let f=as([t,n,i,1],[o,u,l],1,[r,s,a],e[0]);h=f[0],c=f[1],p=f[2]}else{if("SAME_UPPER"!==e)throw Error(`Unknown padding parameter: ${e}`);{h=Math.ceil(t/r),c=Math.ceil(n/s),p=Math.ceil(i/a);let e=(h-1)*r+o-t,f=(c-1)*s+u-n,m=(p-1)*a+l-i,g=Math.floor(e/2),y=e-g,w=Math.floor(f/2),b=f-w,_=Math.floor(m/2);d={top:w,bottom:b,left:_,right:m-_,front:g,back:y}}}return{padInfo:d,outDepth:h,outHeight:c,outWidth:p}},us=(e,t,n,i,r,s=!1,a="channelsLast")=>{let o,u,l,d,h;if("channelsLast"===a)[o,u,l,d,h]=e;else{if("channelsFirst"!==a)throw new Error(`Unknown dataFormat ${a}`);[o,h,u,l,d]=e}let[c,,p,f,m]=t,[g,y,w]=is(n),[b,_,$]=is(i),v=rs(p,b),x=rs(f,_),S=rs(m,$),{padInfo:T,outDepth:k,outHeight:E,outWidth:C}=os(r,u,l,d,g,y,w,v,x,S),I=s?c*h:c,A=[0,0,0,0,0];return"channelsFirst"===a?A=[o,I,k,E,C]:"channelsLast"===a&&(A=[o,k,E,C,I]),{batchSize:o,dataFormat:a,inDepth:u,inHeight:l,inWidth:d,inChannels:h,outDepth:k,outHeight:E,outWidth:C,outChannels:I,padInfo:T,strideDepth:g,strideHeight:y,strideWidth:w,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:v,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:b,dilationHeight:_,dilationWidth:$,inShape:e,outShape:A,filterShape:t}},ls=(e,t,n,i,r,s)=>{let a="channelsLast"===s,o=(a?e[0].dims[3]:e[0].dims[1],{x:n.map((e,t)=>t)}),u=[Math.ceil(ns(o.x.map(e=>n[e]))/64),1,1];st("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let l=[{type:12,data:ut.size(n)},{type:12,data:i},{type:12,data:r},{type:12,data:t.strides},{type:12,data:t.dilations}];Ur(t,l),l.push(...qt(e[0].dims,e[1].dims));let d=["rank","rank"],h=3===e.length;return h&&(l.push(...qt(e[2].dims)),d.push("rank")),l.push(...qt(n)),{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};1;${h}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:l}),getShaderSource:s=>{let o=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:r.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Lr(t,o);let u=Ht(e[0].dataType),l=Jt("x",e[0].dataType,e[0].dims.length,1),d=Jt("W",e[1].dataType,e[1].dims.length,1),c=[l,d],p=Xt("result",e[0].dataType,n.length,1),f="";if(h){let t=Jt("bias",e[2].dataType,e[2].dims.length,1);c.push(t),f+=`\n fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${u} {\n return bias[${Kt("coords",a?4:1,5)}];\n }`}let m=Hr(1,u),g=Dr(t,m,u);return`\n ${f}\n fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);\n return ${l.getByIndices("aIndices")};\n }\n fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {\n let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);\n return ${d.getByIndices("aIndices")};\n }\n ${s.registerUniforms(o).declareVariables(...c,p)}\n ${s.mainStart()}\n ${s.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let coords = ${p.offsetToIndices("global_idx")};\n let batch = ${Kt("coords",0,l.rank)};\n let d2 = ${Kt("coords",a?l.rank-1:1,l.rank)};\n let xFRCCorner = vec3<u32>(${Kt("coords",a?1:2,l.rank)},\n ${Kt("coords",a?2:3,l.rank)},\n ${Kt("coords",a?3:4,l.rank)}) * uniforms.strides - uniforms.pads;\n let xFCorner = xFRCCorner.x;\n let xRCorner = xFRCCorner.y;\n let xCCorner = xFRCCorner.z;\n let xShapeY = ${Kt("uniforms.x_shape",a?1:2,l.rank)};\n let xShapeZ = ${Kt("uniforms.x_shape",a?2:3,l.rank)};\n let xShapeW = ${Kt("uniforms.x_shape",a?3:4,l.rank)};\n let xShapeU = ${Kt("uniforms.x_shape",a?4:1,l.rank)};\n let inputDepthNearestVec4 = (xShapeU / 4) * 4;\n let inputDepthVec4Remainder = xShapeU % 4;\n\n var value = 0.0;\n for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) {\n let xF = xFCorner + wF * uniforms.dilations[0];\n if (xF < 0 || xF >= xShapeY) {\n continue;\n }\n\n for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) {\n let xR = xRCorner + wR * uniforms.dilations[1];\n if (xR < 0 || xR >= xShapeZ) {\n continue;\n }\n\n for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) {\n let xC = xCCorner + wC * uniforms.dilations[2];\n if (xC < 0 || xC >= xShapeW) {\n continue;\n }\n\n for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) {\n ${a?"let xValues = vec4<f32>(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3));\n ":"let xValues = vec4<f32>(\n getX(batch, d1, xF, xR, xC),\n getX(batch, d1 + 1, xF, xR, xC),\n getX(batch, d1 + 2, xF, xR, xC),\n getX(batch, d1 + 3, xF, xR, xC));\n "}\n let wValues = vec4<f32>(\n getW(d2, d1, wF, wR, wC),\n getW(d2, d1 + 1, wF, wR, wC),\n getW(d2, d1 + 2, wF, wR, wC),\n getW(d2, d1 + 3, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n if (inputDepthVec4Remainder == 1) {\n ${a?"value += getX(batch, xF, xR, xC, inputDepthNearestVec4)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);":"value += getX(batch, inputDepthNearestVec4, xF, xR, xC)\n * getW(d2, inputDepthNearestVec4, wF, wR, wC);"}\n } else if (inputDepthVec4Remainder == 2) {\n ${a?"let xValues = vec2<f32>(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1));\n ":"let xValues = vec2<f32>(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC));\n "}\n let wValues = vec2<f32>(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC));\n value += dot(xValues, wValues);\n } else if (inputDepthVec4Remainder == 3) {\n ${a?"let xValues = vec3<f32>(\n getX(batch, xF, xR, xC, inputDepthNearestVec4),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1),\n getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2));\n ":"let xValues = vec3<f32>(\n getX(batch, inputDepthNearestVec4, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC),\n getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC));\n "}\n let wValues = vec3<f32>(\n getW(d2, inputDepthNearestVec4, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC),\n getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC));\n value += dot(xValues, wValues);\n }\n }\n }\n }\n ${h?"value = value + getBiasByOutputCoords(coords)":""};\n ${g}\n result[global_idx] = f32(value);\n }`}}}}),Cl=L(()=>{Yu(),nl(),ll(),$l(),ds=(e,t,n,i)=>{let r=e.length>2,s=r?"value += b[output_channel];":"",a=e[0].dims,o=e[1].dims,u="NHWC"===t.format,l=u?n[3]:n[1],d=l/t.group,h=u&&d>=4?Vt(l):1,c=ut.size(n)/h,p=[{type:12,data:c},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:d}];Ur(t,p),p.push(...qt(a,[o[0],o[1],o[2],o[3]/h]));let f=r?["rank","rank","rank"]:["rank","rank"];return p.push(...qt([n[0],n[1],n[2],n[3]/h])),{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${h}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:i=>{let l=Xt("output",e[0].dataType,n.length,h),d=Ht(l.type.tensor),c=Dr(t,l.type.value,d),p=Jt("x",e[0].dataType,a.length),f=Jt("w",e[1].dataType,o.length,h),m=[p,f];r&&m.push(Jt("b",e[2].dataType,e[2].dims,h));let g=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Lr(t,g);let y=u?`\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n let xVal = ${p.get("batch","xHeight","xWidth","input_channel")};\n let wVal = ${f.get("wHeight","wWidth","wInChannel","output_channel")};\n value += xVal * wVal;\n }\n }\n }\n `:`\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = in_channel_offset + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) {\n continue;\n }\n\n let xVal = ${p.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${f.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal * wVal;\n }\n }\n }\n `;return`\n ${i.registerUniforms(g).declareVariables(...m,l)}\n\n ${i.mainStart()}\n ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${l.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${u?3:1}];\n let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${u?1:2}], outputIndices[${u?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel * ${h} / uniforms.output_channels_per_group;\n var in_channel_offset = group_id * uniforms.w_shape[${u?2:1}];\n\n var value: ${l.type.value} = ${l.type.value}(0);\n ${y}\n ${s}\n ${c}\n ${l.setByOffset("global_idx","value")}\n }`}}},hs=(e,t,n,i)=>{let r=e.length>2,s=Vt(n[3]),a=Vt(n[2]),o=ut.size(n)/s/a,u=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/s],l=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/s],d=[n[0],n[1],n[2],n[3]/s],h=[{type:12,data:o},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Ur(t,h),h.push(...qt(u,l,d));let c=(a-1)*t.strides[1]+l[1];return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${s};${a};${c};${l[0]};${l[1]}`,inputDependencies:r?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:h}),getShaderSource:n=>{let i=Xt("output",e[0].dataType,d.length,s),o=Ht(i.type.tensor),h=Dr(t,i.type.value,o),p=Jt("x",e[0].dataType,u.length,s),f=Jt("w",e[1].dataType,l.length,s),m=[p,f];r&&m.push(Jt("b",e[2].dataType,e[2].dims,s));let g=r?"value += b[output_channel];":"",y=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Lr(t,y),`\n ${n.registerUniforms(y).declareVariables(...m,i)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${a}u;\n let col = (index1 % width1) * ${a}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2<i32>(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${p.type.value}, ${c}>;\n var values: array<${i.type.value}, ${a}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w's height/width.\n for (var w_height: u32 = 0u; w_height < ${l[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${c}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${p.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${p.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) {\n let w_val = ${f.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${a}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${a}u; i++) {\n var value = values[i];\n ${g}\n ${h}\n ${i.set("batch","row","col + i","output_channel","value")};\n }\n }`}}}}),Il=L(()=>{nl(),kl(),El(),Tl(),Cl(),$l(),Sl(),dl(),cs=(e,t,n,i,r,s)=>{let a=e[0],o=e.slice(s?1:2,s?3:4),u=o.length,l=t[0],d=t.slice(2).map((e,t)=>e+(e-1)*(n[t]-1)),h=o.map((e,t)=>e+i[t]+i[t+u]).map((e,t)=>Math.floor((e-d[t]+r[t])/r[t]));return h.splice(0,0,a),h.splice(s?3:1,0,l),h},ps=[2,3,1,0],fs=(e,t)=>{if(!e||2!==e.length&&3!==e.length)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");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[1]*t.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===e.length&&(1!==e[2].dims.length||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ms=(e,t)=>{let n=e.kernelShape.slice();n.length<t[1].dims.length-2&&n.push(...Array(t[1].dims.length-2-n.length).fill(0));for(let e=2;e<t[1].dims.length;++e)0===n[e-2]&&(n[e-2]=t[1].dims[e]);let i=e.pads.slice();lt.adjustPadsBasedOnAutoPad(t[0].dims,e.strides,e.dilations,n,i,"NHWC"===e.format,e.autoPad);let r=Object.assign({},e);return Object.assign(r,{kernelShape:n,pads:i}),r},gs=e=>{let t=Nr(e),n=e.format;return{autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],format:n,dilations:e.dilations,group:e.group,kernelShape:e.kernel_shape,pads:e.pads,strides:e.strides,wIsConst:e.w_is_const(),...t,cacheKey:`${e.format};${t.activation};`}},ys=(e,t,n,i)=>{let r="NHWC"===n.format,s=cs(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,r);if(1!==n.group){let a=[t[0]];if(r){let i=e.kernelCustomData.wT??e.compute(ln(t[1],ps),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i),a.push(i)}else a.push(t[1]);return 3===t.length&&a.push(t[2]),void(!e.adapterInfo.isArchitecture("ampere")&&r&&t[1].dims[0]===n.group&&1===t[1].dims[1]&&1===n.dilations[0]&&1===n.dilations[1]?e.compute(hs(a,n,s,i),{inputs:a}):e.compute(ds(a,n,s,i),{inputs:a}))}let a=3===t.length,o=t[0].dims[r?1:2],u=t[0].dims[r?2:3],l=t[0].dims[r?3:1],d=t[1].dims[2],h=t[1].dims[3],c=s[r?1:2],p=s[r?2:3],f=s[r?3:1],m=r&&d===o&&h===u&&0===n.pads[0]&&0===n.pads[1];if(m||1===d&&1===h&&1===n.dilations[0]&&1===n.dilations[1]&&1===n.strides[0]&&1===n.strides[1]&&0===n.pads[0]&&0===n.pads[1]){let d,h,g,y=s[0],w=[];if(r){let i=e.kernelCustomData.wT??e.compute(ln(t[1],ps),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i),m){let e=o*u*l;d=t[0].reshape([1,y,e]),h=i.reshape([1,e,f]),g=[1,y,f]}else d=t[0].reshape([y,o*u,l]),h=i.reshape([1,l,f]),g=[y,c*p,f];w.push(d),w.push(h)}else d=t[0].reshape([y,l,o*u]),h=t[1].reshape([1,f,l]),g=[y,f,c*p],w.push(h),w.push(d);a&&w.push(t[2]);let b=g[2],_=w[0].dims[w[0].dims.length-1];return void(b<8&&_<8?e.compute(Wr(w,n,s,g,r,i),{inputs:w}):e.compute(Yr(w,n,s,g,r,i),{inputs:w}))}let g=e.kernelCustomData.wT??e.compute(ln(t[1],ps),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let y=[t[0],g];a&&y.push(t[2]);let w=r?c*p:f,b=r?f:c*p,_=d*h*l;e.compute(ts(y,n,s,w,b,_,a,!0,i),{inputs:y})},ws=(e,t)=>{let n="NHWC"===t.format,i=[e.inputs[0].reshape(n?[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]])];3===e.inputs.length&&i.push(e.inputs[2]);let r=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),a=[1].concat(t.dilations),o=[1].concat(t.kernelShape),u=ms({...t,pads:r,strides:s,dilations:a,kernelShape:o},i);ys(e,i,u,e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])},bs=(e,t,n)=>{let i="NHWC"===n.format?"channelsLast":"channelsFirst",r=ms(n,t),s="NOTSET"===n.autoPad?n.pads:n.autoPad,a=us(t[0].dims,t[1].dims,n.strides,n.dilations,s,!1,i);e.compute(ls(t,r,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],i))},_s=(e,t)=>{if(fs(e.inputs,t),3===e.inputs[0].dims.length)ws(e,t);else if(5===e.inputs[0].dims.length)bs(e,e.inputs,t);else{let n=ms(t,e.inputs);ys(e,e.inputs,n)}}}),Al=L(()=>{Yu(),tl(),nl(),ll(),$s=(e,t,n)=>{let i=e.length>2,r=t.outputShape,s="NHWC"===t.format,a=t.group,o=e[1].dims,u=o[2]/a,l=o[3],d=s?Vt(u):1,h=s&&1===l&&u>=4,c=h?4*Math.floor(u/4):Math.floor(u/d)*d,p=u-c,f=s?Vt(l):1,m=s?1===l?d:f:1,g=ut.size(r)/f,y=[Math.ceil(g/64),1,1];st("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${y}`);let w=["rank","rank"],b=[t.strides[0],t.strides[1]],_=[t.kernelShape[s?1:2],t.kernelShape[s?2:3]],$=[t.dilations[0],t.dilations[1]],v=[_[0]+(t.dilations[0]<=1?0:(t.kernelShape[s?1:2]-1)*(t.dilations[0]-1)),_[1]+(t.dilations[1]<=1?0:(t.kernelShape[s?2:3]-1)*(t.dilations[1]-1))],x=[v[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),v[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],S=[{type:12,data:g},{type:12,data:b},{type:12,data:_},{type:12,data:$},{type:12,data:v},{type:6,data:x},{type:12,data:c},{type:12,data:u},{type:12,data:l},...qt(e[0].dims,e[1].dims)];return i&&(S.push(...qt(e[2].dims)),w.push("rank")),S.push(...qt(r)),{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${d}${m}${f}${h}${p}`,inputDependencies:w},getRunData:()=>({dispatchGroup:{x:y[0],y:y[1],z:y[2]},outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:t=>{let n=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:b.length},{name:"filter_dims",type:"u32",length:_.length},{name:"dilations",type:"u32",length:_.length},{name:"effective_filter_dims",type:"u32",length:v.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"}],a=Ht(e[0].dataType),o=s?1:2,u=s?2:3,l=s?3:1,c=Jt("W",e[1].dataType,e[1].dims.length,m),g=Jt("Dy",e[0].dataType,e[0].dims.length,d),y=[g,c];i&&y.push(Jt("bias",e[2].dataType,[r[l]].length,f));let w=Xt("result",e[0].dataType,r.length,f),$=`\n let outputIndices = ${w.offsetToIndices(`global_idx * ${f}`)};\n let batch = ${w.indicesGet("outputIndices",0)};\n let d1 = ${w.indicesGet("outputIndices",l)};\n let r = ${w.indicesGet("outputIndices",o)};\n let c = ${w.indicesGet("outputIndices",u)};\n let dyCorner = vec2<i32>(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${w.type.value}(0.0);\n var wR: u32 = 0;\n if (uniforms.dilations.x == 1) {\n // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0\n wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);\n }\n for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${o}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n var wC: u32 = 0;\n if (uniforms.dilations.y == 1) {\n // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0\n wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);\n }\n for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${u}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n ${h?`\n var x_offset = ${g.indicesToOffset(`${g.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${d};\n var w_offset = ${c.indicesToOffset(`${c.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${m};\n `:""}\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${h?4:d}) {\n ${(()=>{let e="";if(h)4===d?e+=`\n let xValue = ${g.getByOffset("x_offset")};\n let wValue = ${c.getByOffset("w_offset")};\n dotProd = dotProd + dot(xValue, wValue);\n x_offset += 1u;\n w_offset += 1u;`:2===d?e+=`\n dotProd = dotProd + dot(vec4<${a}>(${g.getByOffset("x_offset")}, ${g.getByOffset("x_offset + 1u")}), vec4<${a}>(${c.getByOffset("w_offset")}, ${c.getByOffset("w_offset + 1u")}));\n x_offset += 2u;\n w_offset += 2u;`:1===d&&(e+=`\n dotProd = dotProd + dot(vec4<${a}>(${g.getByOffset("x_offset")}, ${g.getByOffset("x_offset + 1u")}, ${g.getByOffset("x_offset + 2u")}, ${g.getByOffset("x_offset + 3u")}), vec4<${a}>(${c.getByOffset("w_offset")}, ${c.getByOffset("w_offset + 1u")}, ${c.getByOffset("w_offset + 2u")}, ${c.getByOffset("w_offset + 3u")}));\n x_offset += 4u;\n w_offset += 4u;`);else if(e+=`\n let xValue = ${s?g.getByOffset(`${g.indicesToOffset(`${g.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${d}`):g.get("batch","inputChannel","idyR","idyC")};\n `,1===d)e+=`\n let w_offset = ${c.indicesToOffset(`${c.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};\n let wValue = ${c.getByOffset(`w_offset / ${m}`)};\n dotProd = dotProd + xValue * wValue;`;else for(let t=0;t<d;t++)e+=`\n let wValue${t} = ${c.getByOffset(`${c.indicesToOffset(`${c.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${t}, wOutChannel)`)} / ${m}`)};\n dotProd = dotProd + xValue[${t}] * wValue${t};`;return e})()}\n inputChannel = inputChannel + ${h?4:d};\n }\n ${(()=>{if(0===p)return"";if(!h)throw new Error(`packInputAs4 ${h} is not true.`);let e="";if(1===d){e+="dotProd = dotProd";for(let t=0;t<p;t++)e+=`\n + ${g.getByOffset(`x_offset + ${t}`)} * ${c.getByOffset(`w_offset + ${t}`)}`;e+=";"}else if(2===d){if(2!==p)throw new Error(`Invalid inputChannelsRemainder ${p}.`);e+=`\n let xValue = ${g.getByOffset("x_offset")};\n let wValue = ${c.getByOffset("w_offset")};\n dotProd = dotProd + dot(xValue, wValue);`}return e})()}\n wC = wC + uniforms.strides.y - 1;\n }\n wR = wR + uniforms.strides[0] - 1;\n }\n let value = dotProd${i?` + bias[d1 / ${f}]`:""};\n ${w.setByOffset("global_idx","value")};\n `;return`\n ${t.registerUniforms(n).declareVariables(...y,w)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${$}}`}}}}),Rl=L(()=>{Al(),$l(),dl(),vs=(e,t,n,i,r,s)=>(e-1)*t+n+(i-1)*r+1-s,xs=(e,t,n,i,r)=>{let s=Math.floor(e/2);"SAME_UPPER"===t?(n[i]=s,n[r]=e-s):"SAME_LOWER"===t&&(n[i]=e-s,n[r]=s)},Ss=(e,t,n,i,r,s,a,o,u,l)=>{let d=e.length-2,h=0===l.length;u.length<d&&u.push(...Array(d-u.length).fill(0));let c=e[0],p=t[o?3:1]*r;for(let r=0,c=e.length-d-(o?1:0);r<d;++r,++c){let o=e[c],p=h?o*a[r]:l[r],f=vs(o,a[r],s[r],t[c],n[r],p);xs(f,i,s,r,r+d),h&&l.push(a[r]*(o-1)+u[r]+(t[c]-1)*n[r]+1-s[r]-s[r+d])}l.splice(0,0,c),l.splice(o?3:1,0,p)},Ts=(e,t)=>{let n=e.kernelShape.slice();if(0===e.kernelShape.length||0===e.kernelShape.reduce((e,t)=>e*t,1)){n.length=0;for(let e=2;e<t[1].dims.length;++e)n.push(t[1].dims[e])}let i="NHWC"===e.format;n.splice(0,0,t[1].dims[0]),n.splice(i?3:1,0,t[1].dims[1]);let r=e.pads.slice(),s=e.outputShape.slice(),a=e.outputPadding.slice(),o=t[0].dims,u=e.dilations.slice();if(0===u.reduce((e,t)=>e+t,0)){let e=t[0].dims.length-2;u=new Array(e).fill(1)}let l=e.strides.slice();if(0===l.reduce((e,t)=>e+t,0)){let e=t[0].dims.length-2;l=new Array(e).fill(1)}Ss(o,n,u,e.autoPad,e.group,r,l,i,a,s);let d=Object.assign({},e);return Object.assign(d,{kernelShape:n,pads:r,outputPadding:a,outputShape:s,dilations:u,strides:l}),d},ks=e=>{let t=Nr(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],r=e.dilations,s=e.group,a=e.kernelShape,o=e.pads,u=e.strides,l=e.wIsConst();return{autoPad:i,format:n,dilations:r,group:s,kernelShape:a,outputPadding:e.outputPadding,outputShape:e.outputShape,pads:o,strides:u,wIsConst:l,...t,cacheKey:`${e.format};${t.activation};`}},Es=(e,t)=>{if(!e||2!==e.length&&3!==e.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==e[0].dims.length&&3!==e[0].dims.length)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");if(e[0].dims["NHWC"===t.format?e[0].dims.length-1:1]!==e[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(3===e.length&&(1!==e[2].dims.length||e[2].dims[0]!==n))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((e,t)=>e+t,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((e,t)=>e+t,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((e,t)=>e+t,0)>0&&t.pads.length!==2*i)throw new Error(`pads should be ${2*i}D`);if(t.outputPadding.length!==i&&0!==t.outputPadding.length)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((e,t)=>e+t,0)>0&&0!==t.kernelShape.length&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==t.outputShape.length&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Cs=(e,t,n,i)=>{let r=e.kernelCustomData.wT??e.compute(ln(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=r);let s=[t[0],r];3===t.length&&s.push(t[2]),e.compute($s(s,n,i),{inputs:s})},Is=(e,t)=>{let n="NHWC"===t.format,i=[e.inputs[0].reshape(n?[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]])];3===e.inputs.length&&i.push(e.inputs[2]);let r=t.kernelShape;(0===r.length||0===r[0])&&(r=[e.inputs[1].dims[2]]);let s=t.dilations;(0===s.length||0===s[0])&&(s=[1]);let a=t.strides;(0===a.length||0===a[0])&&(a=[1]);let o=t.pads;0===o.length&&(o=[0,0]),o=[0,o[0],0,o[1]],a=[1].concat(a),s=[1].concat(s),r=[1].concat(r);let u=t.outputPadding;u=[0].concat(u);let l=Ts({...t,pads:o,strides:a,dilations:s,kernelShape:r,outputPadding:u},i);Cs(e,i,l,e=>n?[e[0],e[2],e[3]]:[e[0],e[1],e[3]])},As=(e,t)=>{if(Es(e.inputs,t),3===e.inputs[0].dims.length)Is(e,t);else{let n=Ts(t,e.inputs);Cs(e,e.inputs,n)}}}),Ml=L(()=>{Yu(),nl(),ul(),ll(),Rs=(e,t,n,i)=>{let r=ut.size(t),s=t.length,a=Jt("input",e,s),o=Xt("output",e,s),u=6===n.dataType?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),l=ut.normalizeAxis(u,s);return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:[{type:12,data:r},{type:12,data:l},...qt(t,t)]}),getShaderSource:e=>{let t=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,n=Kt("uniforms.input_shape","uniforms.axis",s),r=i.reverse?t+(i.exclusive?" + 1":""):"0",u=i.reverse?n:t+(i.exclusive?"":" + 1");return`\n ${e.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,o)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${o.offsetToIndices("global_idx")};\n var sum = ${o.type.value}(0);\n let first : i32 = ${r};\n let last : i32 = ${u};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${a.getByIndices("inputIndices")};\n }\n ${o.setByOffset("global_idx","sum")};\n }`}}},Ms=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,r=e.inputs[1];e.compute(Rs(i,n,r,t),{inputs:[0]})},zs=e=>{let t=1===e.exclusive,n=1===e.reverse;return Ut({exclusive:t,reverse:n})}}),zl=L(()=>{Yu(),nl(),ul(),ll(),Os=e=>{if(!e||1!==e.length)throw new Error("DepthToSpace requires 1 input.");if(4!==e[0].dims.length)throw new Error("DepthToSpace requires 4D input.")},Ps=(e,t,n,i)=>{let r=[];r.push(`fn perm(i: ${i.type.indices}) -> ${n.type.indices} {\n var a: ${n.type.indices};`);for(let i=0;i<t;++i)r.push(n.indicesSet("a",e[i],`i[${i}]`));return r.push("return a;}"),r.join("\n")},Bs=(e,t)=>{let n,i,r,s,a,o,u="NHWC"===t.format,l=t.blocksize,d="DCR"===t.mode;u?([n,i,r,s]=e.dims,a=d?[n,i,r,l,l,s/l**2]:[n,i,r,s/l**2,l,l],o=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,r,s]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=d?[n,l,l,s/l**2,i,r]:[n,s/l**2,l,l,i,r],o=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let h=e.reshape(a),c=h.dims.length,p=e.dataType,f=Jt("a",p,c),m=Xt("output",p,c);return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:e=>{let t=u?[n,i*l,r*l,s/l**2]:[n,s/l**2,i*l,r*l],a=ut.size(t),d=h.dims,c=ut.sortBasedOnPerm(d,o);return{outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...qt(d,c)]}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(f,m)}\n\n ${Ps(o,c,f,m)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${m.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${m.setByOffset("global_idx",f.getByIndices("aIndices"))}\n }`}},Ds=(e,t)=>{Os(e.inputs),e.compute(Bs(e.inputs[0],t))},Us=e=>Ut({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ol=L(()=>{Yu(),nl(),ul(),ll(),Hs="^"+(Ns="("+(Ls="[a-zA-Z]|\\.\\.\\.")+")+")+"$",Fs="^("+Ns+",)*"+Ns+"$",qs=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);void 0===n?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},Vs=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,i]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(Fs)))throw new Error("Invalid LHS term");if(n.split(",").forEach((t,n)=>{let i=e[n].dims.slice();if(!t.match(RegExp(Hs)))throw new Error("Invalid LHS term");let r=this.processTerm(t,!0,i,n);this.lhs.push(r)}),""===i)i+=[...this.symbolToInfo.entries()].filter(([e,t])=>1===t.count||"..."===e).map(([e])=>e).join("");else if(!i.match(RegExp(Ns)))throw new Error("Invalid RHS");i.match(RegExp(Ls,"g"))?.forEach(e=>{if("..."===e)this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let t=this.symbolToInfo.get(e);if(void 0===t)throw new Error("Invalid RHS symbol");this.outputDims.push(t.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,t,n){let i=this.symbolToInfo.get(e);if(void 0!==i){if(i.dimValue!==t&&1!==i.count)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(n)}else i={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,i)}processTerm(e,t,n,i=-1){let r=n.length,s=!1,a=[],o=0;if(!e.match(RegExp(Hs))&&!t&&""!==e)throw new Error("Invalid LHS term");let u=e.match(RegExp(Ls,"g")),l=new qs(i);return u?.forEach((e,d)=>{if("..."===e){if(s)throw new Error("Only one ellipsis is allowed per input term");s=!0;let e=r-u.length+1;if(e<0)throw new Error("Ellipsis out of bounds");if(a=n.slice(o,o+e),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else{if(!t)throw new Error("Ellipsis must be specified in the LHS");this.hasEllipsis=!0,this.ellipsisDims=a}for(let e=0;e<a.length;e++){let t=String.fromCharCode(48+e);l.addSymbol(t,d+e),this.addSymbol(t,n[o++],i)}}else l.addSymbol(e,d+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(e,n[o++],i)}),l}},Ws=e=>e+"_max",js=(e,t,n,i)=>{let r=e.map(e=>e.length).map((e,n)=>Jt(`input${n}`,t,e)),s=ut.size(i),a=Xt("output",t,i.length),o=[...n.symbolToInfo.keys()].filter(e=>!n.rhs.symbolToIndices.has(e));return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let r=o.filter(e=>n.symbolToInfo.has(e)).map(e=>({type:12,data:n.symbolToInfo.get(e)?.dimValue||0}));r.push({type:12,data:s});let a=e.map((e,t)=>[...qt(e)]).reduce((e,t)=>e.concat(t),r);return a.push(...qt(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:a}},getShaderSource:e=>{let t=[],i=[],s=[],u=[],l=[],d=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((e,o)=>{if(n.rhs.symbolToIndices.has(o)){let i=n.rhs.symbolToIndices.get(o)?.[0];void 0!==i&&n.lhs.forEach((n,s)=>{if(e.inputIndices.includes(s)){let e=n.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach(e=>{t.push(`${r[s].indicesSet(`input${s}Indices`,e,a.indicesGet("outputIndices",i))}`)})}})}else n.lhs.forEach((t,n)=>{if(e.inputIndices.includes(n)){let e=t.symbolToIndices.get(o);if(void 0===e)throw new Error("Invalid symbol error");e.forEach(e=>{i.push(`${r[n].indicesSet(`input${n}Indices`,e,`${o}`)}`)}),l.push(`prod *= ${r[n].getByIndices(`input${n}Indices`)};`)}}),s.push(`for(var ${o}: u32 = 0; ${o} < uniforms.${Ws(o)}; ${o}++) {`),u.push("}")});let h=d?[...t,`let sum = ${r.map((e,t)=>e.getByIndices(`input${t}Indices`)).join(" * ")};`]:[...t,"var sum = 0.0;",...s,...i,"var prod = 1.0;",...l,"sum += prod;",...u];return`\n ${e.registerUniforms(o.map(e=>({name:`${Ws(e)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...r,a)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${a.offsetToIndices("global_idx")};\n ${r.map((e,t)=>`var input${t}Indices: ${r[t].type.indices};`).join("\n")}\n ${h.join("\n")};\n ${a.setByOffset("global_idx","sum")};\n }`}}},Gs=(e,t)=>{let n=new Vs(e.inputs,t.equation),i=n.outputDims,r=e.inputs.map((e,t)=>e.dims);e.compute(js(r,e.inputs[0].dataType,n,i))},Ks=e=>{let t=e.equation.replace(/\s+/g,"");return Ut({equation:t})}}),Pl=L(()=>{Yu(),nl(),ll(),Qs=e=>{if(!e||2!==e.length)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=n.length<t.length?0:n.length-t.length,r=t.length<n.length?0:t.length-n.length;for(;i<n.length&&r<t.length;++i,++r)if(n[i]!==t[r]&&1!==n[i]&&1!==t[r])throw new Error("Expand requires shape to be broadcastable to input")},Js=(e,t)=>{let n=e.length-t.length,i=[];for(let t=0;t<n;++t)i.push(e[t]);for(let r=0;r<t.length;++r)i.push(1===t[r]?e[r+n]:t[r]);return i},Xs=(e,t)=>e.length>t.length?Js(e,t):Js(t,e),Zs=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=Xs(t,n),r=e[0].dataType,s=9===r||1===ut.size(t),a=9===r||t.length>0&&t[t.length-1]%4==0?4:1,o=s||i.length>0&&i[i.length-1]%4==0?4:1,u=Math.ceil(ut.size(i)/o),l=[{type:12,data:u},...qt(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${a}${o}`,inputDependencies:["rank"]},getShaderSource:e=>{let n,s=Jt("input",r,t.length,a),u=Xt("output",r,i.length,o);if(9===r){let e=(e,t,n="")=>`\n let outputIndices${t} = ${u.offsetToIndices(`outputOffset + ${t}u`)};\n let offset${t} = ${s.broadcastedIndicesToOffset(`outputIndices${t}`,u)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${s.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${o};\n var data = vec4<u32>(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n ${u.setByOffset("global_idx","data")}\n }`}else n=`\n let outputIndices = ${u.offsetToIndices(`global_idx * ${o}`)};\n let inputOffset = ${s.broadcastedIndicesToOffset("outputIndices",u)};\n let data = ${u.type.value}(${s.getByOffset(`inputOffset / ${a}`)});\n ${u.setByOffset("global_idx","data")}\n }`;return`\n ${e.registerUniform("vec_size","u32").declareVariables(s,u)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${n}`},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l})}},Ys=e=>{Qs(e.inputs),e.compute(Zs(e.inputs),{inputs:[0]})}}),Bl=L(()=>{Yu(),nl(),ll(),yl(),ea=e=>{let t=e[0].dataType,n=ut.size(e[0].dims),i=ut.size(e[1].dims),r=i%4==0;return{name:"FastGeluWithBias",shaderCache:{hint:`${r}`,inputDependencies:["type","type"]},getShaderSource:e=>{let n=Jt("x",t,[1],4),i=Jt("bias",t,[1],4),s=Xt("y",t,[1],4),a=e=>`\n let bias${e}_offset: u32 = (global_idx * 4 + ${e}) % uniforms.bias_size;\n let bias${e} = ${i.getByOffset(`bias${e}_offset / 4`)}[bias${e}_offset % 4];`,o=r?`\n let bias = ${i.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${a(0)}${a(1)}${a(2)}${a(3)}\n let bias = ${n.type.value}(bias0, bias1, bias2, bias3);`;return`${e.registerUniforms([{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}]).declareVariables(n,i,s)}\n\n ${or(Ft(t))}\n\n ${e.mainStart(Lt)}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${n.getByOffset("global_idx")};\n ${o}\n let x_in = x + bias;\n ${s.setByOffset("global_idx",ur("x_in"))}\n }`},getRunData:e=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/Lt/4)}})}},ta=e=>{e.inputs.length<2||0===ut.size(e.inputs[1].dims)?lr(e):e.compute(ea(e.inputs))}}),Dl=L(()=>{Yu(),nl(),ul(),ll(),na=e=>{if(!e||2!==e.length)throw new Error("Gather requires 2 inputs.")},ia=(e,t)=>{let n=e[0].dims,i=e[1].dims,r=n.length,s=ut.normalizeAxis(t.axis,r),a=n.slice(0);a.splice(s,1,...i);let o=n[s],u=9===e[0].dataType?4:1,l=Math.ceil(ut.size(a)/u),d=[{type:12,data:l},{type:6,data:o},{type:12,data:s},...qt(e[0].dims,e[1].dims,a)];return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:t=>{let n,o=Jt("data",e[0].dataType,e[0].dims.length,u),l=Jt("inputIndices",e[1].dataType,e[1].dims.length),d=Xt("output",e[0].dataType,a.length,u),h=e=>{let t=i.length,n=`var indicesIndices${e} = ${l.type.indices}(0);`;for(let i=0;i<t;i++)n+=`${t>1?`indicesIndices${e}[${i}]`:`indicesIndices${e}`} = ${a.length>1?`outputIndices${e}[uniforms.axis + ${i}]`:`outputIndices${e}`};`;n+=`\n var idx${e} = ${l.getByIndices(`indicesIndices${e}`)};\n if (idx${e} < 0) {\n idx${e} = idx${e} + uniforms.axisDimLimit;\n }\n var dataIndices${e} : ${o.type.indices};\n `;for(let i=0,o=0;i<r;i++)i===s?(n+=`${r>1?`dataIndices${e}[${i}]`:`dataIndices${e}`} = u32(idx${e});`,o+=t):(n+=`${r>1?`dataIndices${e}[${i}]`:`dataIndices${e}`} = ${a.length>1?`outputIndices${e}[${o}]`:`outputIndices${e}`};`,o++);return n};if(9===e[0].dataType){let e=(e,t,n="")=>`\n let outputIndices${t} = ${d.offsetToIndices(`outputOffset + ${t}u`)};\n ${h(t)};\n let offset${t} = ${o.indicesToOffset(`dataIndices${t}`)};\n let index${t} = offset${t} / 4u;\n let component${t} = offset${t} % 4u;\n ${e}[${t}] = ${n}(${o.getByOffset(`index${t}`)}[component${t}]);\n `;n=`\n let outputOffset = global_idx * ${u};\n var value = vec4<u32>(0);\n ${e("value",0,"u32")}\n ${e("value",1,"u32")}\n ${e("value",2,"u32")}\n ${e("value",3,"u32")}\n ${d.setByOffset("global_idx","value")}\n `}else n=`\n let outputIndices = ${d.offsetToIndices("global_idx")};\n ${h("")};\n let value = ${o.getByIndices("dataIndices")};\n ${d.setByOffset("global_idx","value")};\n `;return`\n ${t.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(o,l,d)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${n}\n }`}}},ra=e=>Ut({axis:e.axis}),sa=(e,t)=>{let n=e.inputs;na(n),e.compute(ia(e.inputs,t))}}),Ul=L(()=>{Yu(),nl(),ll(),aa=(e,t,n,i,r,s,a,o,u)=>{let l=[{type:12,data:s},{type:12,data:i},{type:12,data:r},{type:12,data:n},{type:12,data:a},{type:12,data:o},{type:12,data:u}],d=[s];return l.push(...qt(t.dims,d)),e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${r.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l}),getShaderSource:e=>{let i=[Jt("indices_data",t.dataType,t.dims.length),Xt("input_slice_offsets_data",12,1,1)],s=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:r.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`\n ${e.registerUniforms(s).declareVariables(...i)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let batch_idx = global_idx / uniforms.num_slices_per_batch;\n let base_offset = batch_idx * uniforms.input_batch_stride;\n\n let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;\n var relative_slice_offset = 0;\n for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {\n var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);\n let input_dim_idx = uniforms.batch_dims + dim_idx;\n if (index < 0) {\n ${1===r.length?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}\n }\n ${1===n.length?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}\n }\n\n input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);\n }`}},{inputs:[t],outputs:[-1]})[0]},oa=(e,t)=>{let n=e.inputs,i=n[0].dims,r=n[0].dataType,s=n[1].dims,a=s[s.length-1],o=ut.sizeToDimension(s,s.length-1),u=ut.sizeFromDimension(i,t.batchDims+a),l=ut.sizeToDimension(i,t.batchDims),d=ut.sizeFromDimension(i,t.batchDims),h=o/l,c=new Array(a),p=u;for(let e=0;e<a;++e)c[a-1-e]=p,p*=i[t.batchDims+a-1-e];let f=aa(e,n[1],c,t.batchDims,i,o,h,d,a),m=t.batchDims+a;if(m>i.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let g=s.slice(0,-1).concat(i.slice(m)),y=ut.size(g),w=[{type:12,data:y},{type:12,data:u},...qt(n[0].dims,f.dims,g)];e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:g,dataType:r}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:w}),getShaderSource:e=>{let t=Jt("data",n[0].dataType,n[0].dims.length),i=Jt("slice_offsets",12,f.dims.length),r=Xt("output",n[0].dataType,g.length);return`\n ${e.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(t,i,r)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let slice_offset = slice_offsets[global_idx / uniforms.slice_size];\n output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];\n }`}},{inputs:[n[0],f]})},ua=e=>({batchDims:e.batch_dims,cacheKey:""})}),Ll=L(()=>{Yu(),nl(),ul(),ll(),la=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=ut.normalizeAxis(t.quantizeAxis,e[0].dims.length),i=t.blockSize,r=e[0],s=e[2],a=4===e.length?e[3]:void 0;if(s.dims.length!==r.dims.length||!r.dims.map((e,t)=>t===n?Math.ceil(e/i)===s.dims[t]:e===s.dims[t]).reduce((e,t)=>e&&t,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==r.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==s.dims.length||!a.dims.map((e,t)=>e===s.dims[t]).reduce((e,t)=>e&&t,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},da=(e,t)=>{let n=e[0].dims,i=e[1].dims,r=n.length,s=ut.normalizeAxis(t.gatherAxis,r),a=ut.normalizeAxis(t.quantizeAxis,r),o=n.slice(0);o.splice(s,1,...i);let u=ut.size(o),l=e[2].dataType,d=22===e[0].dataType,h=[{type:12,data:u},{type:12,data:a},{type:12,data:s},{type:12,data:t.blockSize},...qt(...e.map((e,t)=>e.dims),o)];return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((e,t)=>1!==t).map(e=>e.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(e,t)=>"rank")},getRunData:()=>({outputs:[{dims:o,dataType:l}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}),getShaderSource:t=>{let r=Jt("data",e[0].dataType,e[0].dims.length),a=Jt("inputIndices",e[1].dataType,e[1].dims.length),u=Jt("scales",e[2].dataType,e[2].dims.length),h=e.length>3?Jt("zeroPoint",e[3].dataType,e[3].dims.length):void 0,c=Xt("output",l,o.length),p=[r,a,u];return h&&p.push(h),`\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...p,c)}\n ${t.mainStart()}\n let output_indices = ${c.offsetToIndices("global_idx")};\n var indices_indices = ${a.type.indices}(0);\n ${i.length>1?`\n for (var i: u32 = 0; i < ${i.length}; i++) {\n let index = ${c.indicesGet("output_indices","uniforms.gather_axis + i")};\n ${a.indicesSet("indices_indices","i","index")};\n }`:`indices_indices = ${c.indicesGet("output_indices","uniforms.gather_axis")};`};\n var data_indices = ${r.type.indices}(0);\n for (var i: u32 = 0; i < uniforms.gather_axis; i++) {\n let index = ${c.indicesGet("output_indices","i")};\n ${r.indicesSet("data_indices","i","index")};\n }\n var index_from_indices = ${a.getByIndices("indices_indices")};\n if (index_from_indices < 0) {\n index_from_indices += ${n[s]};\n }\n ${r.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};\n for (var i = uniforms.gather_axis + 1; i < ${o.length}; i++) {\n let index = ${c.indicesGet("output_indices",`i + ${i.length} - 1`)};\n ${r.indicesSet("data_indices","i","index")};\n }\n let data_offset = ${r.indicesToOffset("data_indices")};\n let data_index = data_offset % 8;\n // Convert 4-bit packed data to 8-bit packed data.\n let packed_4bit_quantized_data = ${r.getByOffset("data_offset / 8")};\n let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;\n let quantized_data_vec = ${d?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));\n let quantized_data = quantized_data_vec[data_index / 2];\n var scale_indices = data_indices;\n let quantize_axis_index = ${u.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;\n ${u.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};\n var scale = ${u.getByIndices("scale_indices")};\n ${h?`\n let zero_point_indices = scale_indices;\n let zero_point_offset = ${h.indicesToOffset("zero_point_indices")};\n let zero_point_index = zero_point_offset % 8;\n let packed_4bit_zero_points = ${h.getByOffset("zero_point_offset / 8")};\n let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;\n let zero_point_vec = ${d?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));\n let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};\n let dequantized_data = ${Ft(l)}(quantized_data - zero_point) * scale;\n ${c.setByOffset("global_idx","dequantized_data")};\n }`}}},ha=(e,t)=>{let n=e.inputs;la(n,t),e.compute(da(e.inputs,t))},ca=e=>Ut({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Nl=L(()=>{Yu(),nl(),ul(),ll(),pa=e=>{if(!e||2!==e.length)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\n indices input tensors be of same rank.")},fa=(e,t)=>{let n=e[0].dims,i=e[0].dataType,r=n.length,s=e[1].dims,a=e[1].dataType,o=ut.normalizeAxis(t.axis,r),u=n[o],l=s.slice(0),d=ut.size(l),h=Jt("input",i,r),c=Jt("indicesInput",a,s.length),p=Xt("output",i,l.length),f=[{type:12,data:d},{type:6,data:u},{type:12,data:o}];return f.push(...qt(n,s,l)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}),getShaderSource:e=>`\n ${e.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(h,c,p)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${p.offsetToIndices("global_idx")};\n\n var idx = ${c.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${h.type.indices}(outputIndices);\n ${h.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${h.getByIndices("inputIndices")};\n\n ${p.setByOffset("global_idx","value")};\n }`}},ma=e=>Ut({axis:e.axis}),ga=(e,t)=>{let n=e.inputs;pa(n),e.compute(fa(e.inputs,t))}}),Hl=L(()=>{Yu(),nl(),ll(),ya=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(3===e.length&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},wa=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[r,s,a]=dt.getShapeOfGemmResult(n,t.transA,i,t.transB,3===e.length?e[2].dims:void 0),o=[r,s];if(!o)throw new Error("Can't use gemm on the given tensors");let u=Math.ceil(s/16),l=Math.ceil(r/16),d=(ut.size(o),[{type:12,data:u},{type:12,data:r},{type:12,data:s},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}]),h=["type","type"];return 3===e.length&&(d.push(...qt(e[2].dims)),h.push("rank")),d.push(...qt(o)),{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:u*l},programUniforms:d}),getShaderSource:n=>{let i=Jt("a",e[0].dataType,e[0].dims),r=Jt("b",e[1].dataType,e[1].dims),s=null,a=[i,r];3===e.length&&(s=Jt("c",e[2].dataType,e[2].dims.length),a.push(s));let u=Xt("output",e[0].dataType,o.length);a.push(u);let l="",d="";t.transA&&t.transB?(d=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n `,l="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(d=`\n var col = tile_row_start + local_id.x;\n var row = k_start + local_id.y;\n if (col < uniforms.M && row < uniforms.K) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n `,l="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(d=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n\n col = k_start + local_id.x;\n row = tile_col_start + local_id.y;\n if (col < uniforms.K && row < uniforms.N) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n `,l="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(d=`\n var col = k_start + local_id.x;\n var row = tile_row_start + local_id.y;\n if (col < uniforms.K && row < uniforms.M) {\n tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];\n } else {\n tile_a[local_id.y][local_id.x] = ${i.type.value}(0);\n }\n\n col = tile_col_start + local_id.x;\n row = k_start + local_id.y;\n if (col < uniforms.N && row < uniforms.K) {\n tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];\n } else {\n tile_b[local_id.y][local_id.x] = ${r.type.value}(0);\n }\n `,l="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let h=1===t.alpha?"":"value *= uniforms.alpha;";return`\n ${n.registerUniforms([{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"}]).declareVariables(...a)}\n var<workgroup> tile_a: array<array<${i.type.storage}, 16>, 16>;\n var<workgroup> tile_b: array<array<${r.type.storage}, 16>, 16>;\n ${n.mainStart([16,16,1])}\n let tile_col_start = (workgroup_index % uniforms.num_tile_n) * 16;\n let tile_row_start = (workgroup_index / uniforms.num_tile_n) * 16;\n let num_tiles = (uniforms.K - 1) / 16 + 1;\n var k_start = 0u;\n var value = ${u.type.value}(0);\n for (var t: u32 = 0u; t < num_tiles; t++) {\n ${d}\n k_start = k_start + 16;\n workgroupBarrier();\n\n for (var k: u32 = 0u; k < 16; k++) {\n ${l}\n }\n workgroupBarrier();\n }\n\n ${h}\n let m = tile_row_start + local_id.y;\n let n = tile_col_start + local_id.x;\n ${null!=s?`let cOffset = ${s.broadcastedIndicesToOffset("vec2(m, n)",u)}; value += ${u.type.value}(uniforms.beta) * ${s.getByOffset("cOffset")};`:""}\n if (m < uniforms.M && n < uniforms.N) {\n output[m * uniforms.N + n] = value;\n }\n }`}}},ba=e=>({transA:e.transA,transB:e.transB,alpha:e.alpha,beta:e.beta,cacheKey:`${e.transA};${e.transB};${1===e.alpha}`}),_a=(e,t)=>{ya(e.inputs),e.compute(wa(e.inputs,t))}}),Fl=L(()=>{Yu(),nl(),ul(),ll(),[$a,va,xa,Sa]=[0,1,2,3],Ta=e=>{if(4!==e[0].dims.length)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")},ka=e=>`\n fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} {\n var v: vec4<f32>;\n var coeffs = gs_get_cubic_coeffs(x);\n for (var i = 0; i < 4; i++) {\n v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];\n }\n coeffs = gs_get_cubic_coeffs(y);\n let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);\n return pixel;\n }\n`,Ea=e=>`\n fn gs_denormalize(n: f32, length: i32) -> f32 {\n ${0===e.alignCorners?"\n // alignCorners: false => [-1, 1] to [-0.5, length - 0.5]\n return ((n + 1.0) * f32(length) - 1.0) / 2.0;\n ":"\n // alignCorners: true => [-1, 1] to [0, length - 1]\n return (n + 1.0) / 2.0 * (f32(length - 1));\n "}\n }\n`,Ca=e=>`\n ${"reflection"===e.paddingMode?"\n fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {\n var dx = 0.0;\n var fx = f32(x);\n let range = x_max - x_min;\n if (fx < x_min) {\n dx = x_min - fx;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_min + r;\n } else {\n fx = x_max - r;\n }\n } else if (fx > x_max) {\n dx = fx - x_max;\n let n = u32(dx / range);\n let r = dx - f32(n) * range;\n if (n % 2 == 0) {\n fx = x_max - r;\n } else {\n fx = x_min + r;\n }\n }\n return u32(fx);\n }":""}\n`,Ia=(e,t,n)=>`\n fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${t} {\n var pixel = ${t}(0);\n var indices = vec4<u32>(0);\n indices[${$a}] = batch;\n indices[${va}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return`\n if (r >= 0 && r < H && c >=0 && c < W) {\n indices[${xa}] = u32(r);\n indices[${Sa}] = u32(c);\n } else {\n return ${t}(0);\n }\n `;case"border":return`\n indices[${xa}] = u32(clamp(r, 0, H - 1));\n indices[${Sa}] = u32(clamp(c, 0, W - 1));\n `;case"reflection":return`\n indices[${xa}] = gs_reflect(r, border[1], border[3]);\n indices[${Sa}] = gs_reflect(c, border[0], border[2]);\n `;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+`\n return ${e.getByIndices("indices")};\n }\n`,Aa=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return`\n let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${$a}], indices[${va}], border);\n `;case"bilinear":return`\n let x1 = i32(floor(x));\n let y1 = i32(floor(y));\n let x2 = x1 + 1;\n let y2 = y1 + 1;\n\n let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${$a}], indices[${va}], border);\n let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${$a}], indices[${va}], border);\n let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${$a}], indices[${va}], border);\n let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${$a}], indices[${va}], border);\n\n let dx2 = ${t}(f32(x2) - x);\n let dx1 = ${t}(x - f32(x1));\n let dy2 = ${t}(f32(y2) - y);\n let dy1 = ${t}(y - f32(y1));\n let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);\n `;case"bicubic":return`\n let x0 = i32(floor(x)) - 1;\n let y0 = i32(floor(y)) - 1;\n var p: mat4x4<${t}>;\n for (var h = 0; h < 4; h++) {\n for (var w = 0; w < 4; w++) {\n p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${$a}], indices[${va}], border);\n }\n }\n\n let dx = x - f32(x0 + 1);\n let dy = y - f32(y0 + 1);\n let result = gs_bicubic_interpolate(p, dx, dy);\n `;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Ra=(e,t)=>{let n=Jt("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],r=Jt("grid",e[1].dataType,i.length,2),s=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];"NHWC"===t.format&&(s=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[$a,va,xa,Sa]=[0,3,1,2]);let a=Xt("output",e[0].dataType,s.length),o=n.type.value,u=[{type:12,data:ut.size(s)},...qt(e[0].dims,i,s)];return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:e=>{let t=ut.size(s);return{outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(t/64)},programUniforms:u}},getShaderSource:e=>`\n ${e.registerUniform("output_size","u32").declareVariables(n,r,a)}\n \n fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {\n let cubic_alpha = -0.75f;\n let x_abs = abs(x);\n var coeffs: vec4<f32>;\n coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);\n coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);\n coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);\n coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);\n return coeffs;\n }\n\n ${ka(o)}\n ${Ea(t)}\n ${Ca(t)}\n ${Ia(n,o,t)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let H_in = i32(uniforms.x_shape[${xa}]);\n let W_in = i32(uniforms.x_shape[${Sa}]);\n\n ${0===t.alignCorners?"\n let x_min = -0.5;\n let x_max = f32(W_in) - 0.5;\n let y_min = -0.5;\n let y_max = f32(H_in) - 0.5;\n ":"\n let x_min = 0.0;\n let x_max = f32(W_in) - 1.0;\n let y_min = 0.0;\n let y_max = f32(H_in) - 1.0;\n "};\n let border = vec4<f32>(x_min, y_min, x_max, y_max);\n\n let indices = ${a.offsetToIndices("global_idx")};\n var grid_indices = vec3<u32>(indices[${$a}], indices[${xa}], indices[${Sa}]);\n let nxy = ${r.getByIndices("grid_indices")};\n var x = gs_denormalize(f32(nxy[0]), W_in);\n var y = gs_denormalize(f32(nxy[1]), H_in);\n\n ${Aa(a,o,t)}\n }`}},Ma=(e,t)=>{Ta(e.inputs),e.compute(Ra(e.inputs,t))},za=e=>Ut({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),ql=L(()=>{Yu(),nl(),ul(),al(),fl(),ll(),dl(),Oa=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Pa=(e,t)=>{let n=e[0],i=Oa(e,1),r=Oa(e,2),s=Oa(e,3),a=Oa(e,4),o=Oa(e,5),u=Oa(e,6),l=Oa(e,7);if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let d,h=n.dims[0],c=n.dims[1],p=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],f=c,m=0,g=0,y=Math.floor(p/t.numHeads);if(u&&l&&ut.size(u.dims)&&ut.size(l.dims)){if(4!==u.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(u.dims[0]!==h||u.dims[1]!==t.numHeads||u.dims[3]!==y)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[0]!==h||l.dims[1]!==t.numHeads||l.dims[3]!==y)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[2]!==l.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(4!==l.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');m=u.dims[2],g=u.dims[2]}else if(u&&ut.size(u.dims)||l&&ut.size(l.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');if(i&&ut.size(i.dims)>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===i.dims.length){if(i.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');d=2,f=i.dims[1]}else if(5===i.dims.length){if(i.dims[2]!==t.numHeads||2!==i.dims[3]||i.dims[4]!==y)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(r)throw new Error('Expect "value" be none when "key" has packed kv format.');d=5,f=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=0,f=i.dims[2]}}else{if(5!==n.dims.length)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||3!==n.dims[3])throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');d=3}if(s&&ut.size(s.dims)>0){if(1!==s.dims.length)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&5===i.dims.length&&2===i.dims[3])throw new Error("bias is not allowed for packed kv.")}let w=m+f,b=0;if(a&&ut.size(a.dims)>0){b=8;let e=a.dims;throw 1===e.length?e[0]===h?b=1:e[0]===3*h+2&&(b=3):2===e.length&&e[0]===h&&e[1]===w&&(b=5),8===b?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let _=!1,$=p;if(r&&ut.size(r.dims)>0){if(3!==r.dims.length&&4!==r.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===r.dims.length){if(f!==r.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');$=r.dims[2]}else{if(f!==r.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');$=r.dims[1]*r.dims[3],_=!0}}if(a&&ut.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(o&&ut.size(o.dims)>0){if(4!==o.dims.length)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(o.dims[0]!==h||o.dims[1]!==t.numHeads||o.dims[2]!==c||o.dims[3]!==w)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:h,sequenceLength:c,pastSequenceLength:m,kvSequenceLength:f,totalSequenceLength:w,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:p,vHiddenSize:$,headSize:y,vHeadSize:Math.floor($/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:b,scale:t.scale,broadcastResPosBias:!1,passPastInKv:_,qkvFormat:d}},Ba=e=>Ut({...e}),Da=Ut({perm:[0,2,1,3]}),Ua=(e,t,n,i,r,s,a)=>{let o=[i,r,s],u=ut.size(o),l=[{type:12,data:u},{type:12,data:a},{type:12,data:s}];return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:l}),getShaderSource:e=>{let i=Xt("qkv_with_bias",t.dataType,o),r=Jt("qkv",t.dataType,o),s=Jt("bias",n.dataType,o);return`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}]).declareVariables(r,s,i)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`}},{inputs:[t,n],outputs:[-1]})[0]},La=(e,t,n,i,r,s,a,o)=>{let u=s;if(a&&ut.size(a.dims)>0){if(1===i)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return u=Ua(e,s,a,t,i,n*r,o),u=u.reshape([t,i,n,r]),1===n||1===i?u:e.compute(ln(u,Da.perm),{inputs:[u],outputs:[-1]})[0]}return 3===s.dims.length&&(u=s.reshape([t,i,n,r])),1===n||1===i?u:e.compute(ln(u,Da.perm),{inputs:[u],outputs:[-1]})[0]},Na=(e,t)=>{let n=Pa(e.inputs,t),i=e.inputs[0],r=Oa(e.inputs,1),s=Oa(e.inputs,2),a=Oa(e.inputs,3),o=Oa(e.inputs,4),u=Oa(e.inputs,5),l=Oa(e.inputs,6),d=Oa(e.inputs,7);if(5===i.dims.length)throw new Error("Packed QKV is not implemented");if(5===r?.dims.length)throw new Error("Packed KV is not implemented");let h=r&&s&&4===r.dims.length&&4===s.dims.length,c=La(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,i,a,0);if(h)return fi(e,c,r,s,o,void 0,l,d,u,n);if(!r||!s)throw new Error("key and value must be provided");let p=La(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,r,a,n.hiddenSize),f=La(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,s,a,2*n.hiddenSize);fi(e,c,p,f,o,void 0,l,d,u,n)}}),Vl=L(()=>{Yu(),nl(),ul(),ll(),Ha=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Fa=(e,t)=>{let n=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(e=>n.push(Number(e))),i=n.length),Ut({numOutputs:i,axis:t.axis,splitSizes:n})},qa=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${Kt("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Va=e=>{let t=e.length,n=[];for(let i=0;i<t;++i){let r=e[i].setByIndices("indices","input[global_idx]");1===t?n.push(r):0===i?n.push(`if (output_number == ${i}u) { ${r} }`):i===t-1?n.push(`else { ${r} }`):n.push(`else if (output_number == ${i}) { ${r} }`)}return`\n fn writeBufferData(output_number: u32, indices: ${e[0].type.indices}, global_idx: u32) {\n ${n.join("\n")}\n }`},Wa=(e,t)=>{let n=e[0].dims,i=ut.size(n),r=e[0].dataType,s=ut.normalizeAxis(t.axis,n.length),a=new Array(t.numOutputs),o=Jt("input",r,n.length),u=new Array(t.numOutputs),l=[],d=[],h=0,c=[{type:12,data:i}];for(let i=0;i<t.numOutputs;i++){h+=t.splitSizes[i],u[i]=h;let o=n.slice();o[s]=t.splitSizes[i],d.push(o),a[i]=Xt(`output${i}`,r,o.length),l.push({dims:d[i],dataType:e[0].dataType})}return c.push({type:12,data:u},...qt(n,...d)),{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:e=>`\n ${e.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",u.length).declareVariables(o,...a)}\n ${qa(u.length)}\n ${Va(a)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${o.offsetToIndices("global_idx")};\n var index = ${o.indicesGet("indices",s)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${Kt("uniforms.size_in_split_axis","output_number - 1u",u.length)};\n ${o.indicesSet("indices",s,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`,getRunData:()=>({outputs:l,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c})}},ja=(e,t)=>{Ha(e.inputs);let n=1===e.inputs.length?t:Fa(e.inputs,t);e.compute(Wa(e.inputs,n),{inputs:[0]})},Ga=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return Ut({axis:t,numOutputs:i,splitSizes:n})}}),Wl=L(()=>{Yu(),nl(),ul(),ll(),Ka=(e,t)=>{let[n,i,r,s]=e,{numHeads:a,rotaryEmbeddingDim:o}=t;if(3!==n.dims.length&&4!==n.dims.length)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!ut.areEqual(i.dims,[])&&!ut.areEqual(i.dims,[1])&&2!==i.dims.length)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${i.dims.length}`);if(2!==r.dims.length)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${r.dims.length}`);if(2!==s.dims.length)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(!ut.areEqual(r.dims,s.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(o>0&&0===a)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let u=n.dims[0],l=n.dims[n.dims.length-2],d=r.dims[0],h=ut.sizeFromDimension(n.dims,1)/l,c=0===o?2*r.dims[1]:h/a;if(o>c)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(2===i.dims.length){if(u!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(l!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(c/2!==r.dims[1]&&o/2!==r.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${r.dims[1]}`);if(l>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Qa=(e,t)=>{let{interleaved:n,numHeads:i,rotaryEmbeddingDim:r,scale:s}=t,a=e[0].dims[0],o=ut.sizeFromDimension(e[0].dims,1),u=e[0].dims[e[0].dims.length-2],l=o/u,d=e[2].dims[1],h=0===r?2*d:l/i,c=new Array(a,u,l/h,h-d),p=ut.computeStrides(c),f=[{type:1,data:s},{type:12,data:c},{type:12,data:p},...3===e[0].dims.length?new Array({type:12,data:[o,l,h,1]}):[],...4===e[0].dims.length?new Array({type:12,data:[o,h,u*h,1]}):[],...qt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)];return{name:"RotaryEmbedding",shaderCache:{hint:Ut({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:t=>{let i=Jt("input",e[0].dataType,e[0].dims.length),r=Jt("position_ids",e[1].dataType,e[1].dims.length),s=Jt("cos_cache",e[2].dataType,e[2].dims.length),a=Jt("sin_cache",e[3].dataType,e[3].dims.length),o=Xt("output",e[0].dataType,e[0].dims.length);return t.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:c.length},{name:"global_strides",type:"u32",length:p.length},{name:"input_output_strides",type:"u32",length:p.length}]),`\n ${t.declareVariables(i,r,s,a,o)}\n\n ${t.mainStart(Lt)}\n let half_rotary_emb_dim = uniforms.${s.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${r.broadcastedIndicesToOffset("bsnh.xy",Xt("",r.type.tensor,2))};\n let position_id =\n u32(${r.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${n});\n let j = i + select(half_rotary_emb_dim, 1, ${n});\n let re = ${i.getByOffset("i")} * ${s.get("position_id","bsnh[3]")} -\n ${i.getByOffset("j")} * ${a.get("position_id","bsnh[3]")};\n ${o.setByOffset("i","re")}\n let im = ${i.getByOffset("i")} * ${a.get("position_id","bsnh[3]")} +\n ${i.getByOffset("j")} * ${s.get("position_id","bsnh[3]")};\n ${o.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${o.setByOffset("k",i.getByOffset("k"))}\n }\n }`},getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ut.size(c)/Lt)},programUniforms:f})}},Ja=(e,t)=>{Ka(e.inputs,t),e.compute(Qa(e.inputs,t))}}),jl=L(()=>{ul(),Yu(),fl(),ql(),Vl(),dl(),Wl(),ll(),Xa=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],i=e[1],r=e[2],s=e[3],a=e[4];if(0!==t.doRotary&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(-1!==t.localWindowSize)throw new Error("Local attention is not supported");if(0!==t.softcap)throw new Error("Softcap is not supported");if(0!==t.rotaryInterleaved)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(3!==n.dims.length&&5!==n.dims.length)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=n.dims[0],u=n.dims[1],l=3===n.dims.length?n.dims[2]:t.numHeads*n.dims[4],d=u,h=0,c=!i||0===i.dims.length,p=Math.floor(c?l/(t.numHeads+2*t.kvNumHeads):l/t.numHeads);c&&(l=p*t.numHeads);let f=s&&0!==s.dims.length,m=a&&0!==a.dims.length;if(f&&4===s.dims.length&&s.dims[0]===o&&s.dims[1]!==t.kvNumHeads&&s.dims[2]===t.kvNumHeads&&s.dims[3]===p)throw new Error("BSNH pastKey/pastValue is not supported");if(f&&m){if(4!==s.dims.length)throw new Error('Input "past_key" is expected to have 4 dimensions');if(4!==a.dims.length)throw new Error('Input "past_value" is expected to have 4 dimensions');h=s.dims[2]}else if(f||m)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(i&&i.dims.length>0){if(3!==n.dims.length)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(3===i.dims.length){if(n.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=i.dims[1]}else if(5===i.dims.length){if(i.dims[2]!==t.numHeads||2!==i.dims[3]||i.dims[4]!==p)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(r)throw new Error('Expect "value" be none when "key" has packed kv format.');d=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==p)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=i.dims[2]}}else{if(3!==n.dims.length&&5!==n.dims.length)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(5===n.dims.length&&(n.dims[2]!==t.numHeads||3!==n.dims[3]))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');g=3}let y=!1,w=t.kvNumHeads?p*t.kvNumHeads:l;if(r&&r.dims.length>0){if(3!==r.dims.length&&4!==r.dims.length)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(3===r.dims.length){if(d!==r.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');w=r.dims[2]}else{if(d!==r.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');w=r.dims[1]*r.dims[3],y=!0}}let b=e.length>4?e[5]:void 0;if(b&&1!==b.dims.length&&b.dims[0]!==o)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:o,sequenceLength:u,pastSequenceLength:h,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:l,vHiddenSize:w,headSize:p,vHeadSize:Math.floor(w/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:0,scale:t.scale,broadcastResPosBias:!1,passPastInKv:y,qkvFormat:g}},Za=Ut({perm:[0,2,1,3]}),Ya=(e,t,n)=>{let i=t,r=n.kvNumHeads;return 3===t.dims.length&&0!==n.kvSequenceLength&&(i=t.reshape([n.batchSize,n.kvSequenceLength,r,n.headSize]),i=e.compute(ln(i,Za.perm),{inputs:[i],outputs:[-1]})[0]),i},eo=(e,t,n,i)=>{let r=[e*t],s=e*t,a=[{type:12,data:s},{type:12,data:t},{type:12,data:e}];return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:r,dataType:7}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:a}),getShaderSource:e=>{let t=Jt("seq_lens",n.dataType,n.dims),s=Jt("total_seq_lens",i.dataType,i.dims),a=Xt("pos_ids",7,r);return`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}]).declareVariables(t,s,a)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let total_sequence_length = u32(${s.getByOffset("0")});\n let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;\n let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;\n let batch_idx = global_idx / uniforms.sequence_length;\n let sequence_idx = i32(global_idx % uniforms.sequence_length);\n var pos_id: i32 = 0;\n let seqlen = ${t.getByOffset("batch_idx")};\n let total_seqlen = seqlen + 1;\n if (is_first_prompt) {\n if (sequence_idx < total_seqlen) {\n pos_id = sequence_idx;\n } else {\n pos_id = 1;\n }\n ${a.setByOffset("global_idx","pos_id")}\n } else if (is_subsequent_prompt) {\n let past_seqlen = total_seqlen - i32(uniforms.sequence_length);\n if (past_seqlen + sequence_idx < total_seqlen) {\n pos_id = past_seqlen + sequence_idx;\n } else {\n pos_id = 1;\n }\n ${a.setByOffset("global_idx","pos_id")}\n } else if (global_idx < uniforms.batch_size) {\n ${a.setByOffset("global_idx","seqlen")}\n };\n }\n `}}},to=(e,t)=>{let n=Xa(e.inputs,t);if(5===e.inputs[0].dims.length)throw new Error("Packed QKV is not implemented");if(5===e.inputs[1]?.dims.length)throw new Error("Packed KV is not implemented");let i,r,s=e.inputs[0],a=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,u=e.inputs[3]&&0!==e.inputs[3].dims.length?e.inputs[3]:void 0,l=e.inputs[4]&&0!==e.inputs[4].dims.length?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,c=n.kvNumHeads?n.kvNumHeads:n.numHeads,p=Ut({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,c*n.headSize,c*n.headSize]}),[f,m,g]=a||o?[s,a,o]:e.compute(Wa([s],p),{inputs:[s],outputs:[-1,-1,-1]});if(t.doRotary){let s=e.compute(eo(n.batchSize,n.sequenceLength,d,h),{inputs:[d,h],outputs:[-1]})[0],a=e.inputs[7],o=e.inputs[8],u=Ut({interleaved:0!==t.rotaryInterleaved,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),l=[f,s,a,o],c=[-1];i=e.compute(Qa(l,u),{inputs:l,outputs:c})[0],l.splice(0,1,m);let p=Ut({interleaved:0!==t.rotaryInterleaved,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});r=e.compute(Qa(l,p),{inputs:l,outputs:c})[0]}let y=La(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?i:f,void 0,0),w=Ya(e,t.doRotary?r:m,n),b=Ya(e,g,n);fi(e,y,w,b,void 0,void 0,u,l,void 0,n,d,h)}}),Gl=L(()=>{Yu(),nl(),dl(),ll(),no=(e,t,n,i,r,s,a,o)=>{let u=Vt(s),l=1===u?"f32":`vec${u}f`,d=1===u?"vec2f":`mat2x${u}f`,h=r*a,c=64;1===h&&(c=256);let p=[r,a,s/u],f=[r,a,2],m=[];return m.push(...qt(p,f)),e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${u};${o};${c}`,inputDependencies:["rank","type","type"]},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:h},programUniforms:m}),getShaderSource:e=>{let r=Jt("x",t.dataType,3,u),s=[r,Jt("scale",n.dataType,n.dims),Jt("bias",i.dataType,i.dims),Xt("output",1,3,2)];return`\n var<workgroup> workgroup_shared : array<${d}, ${c}>;\n const workgroup_size = ${c}u;\n ${e.declareVariables(...s)}\n ${e.mainStart(c)}\n let batch = workgroup_index / uniforms.x_shape[1];\n let channel = workgroup_index % uniforms.x_shape[1];\n let hight = uniforms.x_shape[2];\n // initialize workgroup memory\n var sum = ${l}(0);\n var squared_sum = ${l}(0);\n for (var h = local_idx; h < hight; h += workgroup_size) {\n let value = ${l}(${r.get("batch","channel","h")});\n sum += value;\n squared_sum += value * value;\n }\n workgroup_shared[local_idx] = ${d}(sum, squared_sum);\n workgroupBarrier();\n\n for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {\n if (local_idx < currSize) {\n workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];\n }\n workgroupBarrier();\n }\n if (local_idx == 0) {\n let sum_final = ${Gt("workgroup_shared[0][0]",u)} / f32(hight * ${u});\n let squared_sum_final = ${Gt("workgroup_shared[0][1]",u)} / f32(hight * ${u});\n\n let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${o}));\n let channel_scale = inv_std_dev * f32(scale[channel]);\n let channel_shift = f32(bias[channel]) - sum_final * channel_scale;\n output[workgroup_index] = vec2f(channel_scale, channel_shift);\n }\n }`}},{inputs:[t,n,i],outputs:[-1]})[0]},io=(e,t,n)=>{let i=t[0].dims,r=i,s=i[0],a=i[1],o=ut.sizeFromDimension(i,2),u=Vt(o),l=ut.size(r)/u,d=no(e,t[0],t[1],t[2],s,o,a,n.epsilon),h=[s,a,o/u],c=[s,a];e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:["type","none"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...qt(h,c,h)]}),getShaderSource:e=>{let n=Jt("x",t[0].dataType,h.length,u),i=Jt("scale_shift",1,c.length,2),r=Xt("output",t[0].dataType,h.length,u),s=[n,i,r];return`\n ${e.registerUniform("output_size","u32").declareVariables(...s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let outputIndices = ${r.offsetToIndices("global_idx")};\n let batch = outputIndices[0];\n let channel = outputIndices[1];\n let scale_shift = ${i.getByIndices("vec2<u32>(batch, channel)")};\n let value = ${n.getByOffset("global_idx")} * ${r.type.value}(scale_shift.x) + ${r.type.value}(scale_shift.y);\n ${r.setByOffset("global_idx","value")};\n }`}},{inputs:[t[0],d]})},ro=(e,t,n)=>{let i=t[0].dims,r=i,s=i[0],a=i[i.length-1],o=ut.sizeFromDimension(i,1)/a,u=Vt(a),l=ut.size(r)/u,d=[{type:12,data:o},{type:12,data:Math.floor(a/u)}],h=!1,c=[0,i.length-1];for(let e=0;e<i.length-2;e++)h=h||1!==i[e+1],c.push(e+1);h=h&&1!==i[i.length-1];let p=h?e.compute(ln(e.inputs[0],c),{inputs:[e.inputs[0]],outputs:[-1]})[0]:e.inputs[0].reshape(Array.from({length:i.length},(e,t)=>i[c[t]])),f=no(e,p,t[1],t[2],s,o,a,n.epsilon);e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${u}`,inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:r,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:e=>{let n=Ht(t[0].dataType),i=1===u?"vec2f":`mat${u}x2f`,s=e=>{let t=0===e?"x":"y",i=1===u?"f32":`vec${u}f`;switch(u){case 1:return`${n}(${i}(scale.${t}))`;case 2:return`vec2<${n}>(${i}(scale[0].${t}, scale[1].${t}))`;case 4:return`vec4<${n}>(${i}(scale[0].${t}, scale[1].${t}, scale[2].${t}, scale[3].${t}))`;default:throw new Error(`Not supported compoents ${u}`)}},a=Jt("input",t[0].dataType,t[0].dims,u),o=Xt("output",t[0].dataType,r,u);return`\n @group(0) @binding(0) var<storage, read> input : array<${a.type.storage}>;\n @group(0) @binding(1) var<storage, read> scale_input : array<${i}>;\n @group(0) @binding(2) var<storage, read_write> output : array<${o.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var<uniform> uniforms: Uniforms;\n\n ${e.mainStart()}\n let current_image_number = global_idx / (uniforms.C * uniforms.H);\n let current_channel_number = global_idx % uniforms.C;\n\n let scale_offset = current_image_number * uniforms.C + current_channel_number;\n let scale = scale_input[scale_offset];\n output[global_idx] = fma(input[global_idx], ${s(0)}, ${s(1)});\n }`}},{inputs:[t[0],f]})},so=(e,t)=>{"NHWC"===t.format?ro(e,e.inputs,t):io(e,e.inputs,t)}}),Kl=L(()=>{Yu(),nl(),ll(),ao=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},oo=(e,t,n)=>{let i=t.simplified,r=e[0].dims,s=e[1],a=!i&&e[2],o=r,u=ut.normalizeAxis(t.axis,r.length),l=ut.sizeToDimension(r,u),d=ut.sizeFromDimension(r,u),h=ut.size(s.dims),c=a?ut.size(a.dims):0;if(h!==d||a&&c!==d)throw new Error(`Size of X.shape()[axis:] == ${d}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${h} and bias size of ${c}`);let p=[];for(let e=0;e<r.length;++e)e<u?p.push(r[e]):p.push(1);let f=Vt(d),m=["type","type"],g=[{type:12,data:l},{type:1,data:d},{type:12,data:Math.floor(d/f)},{type:1,data:t.epsilon}];a&&m.push("type");let y=n>1,w=n>2,b=[{dims:o,dataType:e[0].dataType}];return y&&b.push({dims:p,dataType:1}),w&&b.push({dims:p,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${n};${i}`,inputDependencies:m},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:g}),getShaderSource:t=>{let n=Ht(e[0].dataType),r=[Jt("x",e[0].dataType,e[0].dims,f),Jt("scale",s.dataType,s.dims,f)];return a&&r.push(Jt("bias",a.dataType,a.dims,f)),r.push(Xt("output",e[0].dataType,o,f)),y&&r.push(Xt("mean_data_output",1,p)),w&&r.push(Xt("inv_std_output",1,p)),`\n ${t.registerUniforms([{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...r)}\n ${t.mainStart()}\n ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${Wt("f32",f)};\n var mean_square_vector = ${Wt("f32",f)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${jt(n,f,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${Gt("mean_vector",f)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${Gt("mean_square_vector",f)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${jt(n,f,"x[j + offset]")};\n let f32scale = ${jt(n,f,"scale[j]")};\n output[j + offset] = ${r[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale\n ${a?`+ ${jt(n,f,"bias[j]")}`:""}\n );\n }\n\n ${y?"mean_data_output[global_idx] = mean":""};\n ${w?"inv_std_output[global_idx] = inv_std_dev":""};\n }`}}},uo=(e,t)=>{ao(e.inputs),e.compute(oo(e.inputs,t,e.outputCount))}}),Ql=L(()=>{nl(),Sl(),Tl(),lo=e=>{if(!e||2!==e.length)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.")},ho=e=>{lo(e.inputs);let t=ot.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&i<8)e.compute(Wr(e.inputs,{activation:""},t));else{let r=t[t.length-2],s=ut.size(e.inputs[0].dims.slice(0,-2)),a=ut.size(e.inputs[1].dims.slice(0,-2));if(1!==s&&1===r&&1===a){let r=[1,s,n],a=[e.inputs[0].reshape([1,s,i]),e.inputs[1].reshape([1,i,n])];e.compute(Yr(a,{activation:""},t,r),{inputs:a})}else e.compute(Yr(e.inputs,{activation:""},t))}}}),Jl=L(()=>{Yu(),nl(),ul(),ll(),co=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],i=n.dims.length;if(n.dims[i-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let r=Math.floor((t.k+t.blockSize-1)/t.blockSize),s=t.blockSize/8*t.bits,a=e[1];if(!ut.areEqual(a.dims,[t.n,r,s]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let o=e[2].dims;if(ut.size(o)!==t.n*r)throw new Error("scales input size error.");if(4===e.length){let n=e[3].dims,i=t.n*(8===t.bits?r:Math.floor((r*t.bits+7)/8));if(ut.size(n)!==i)throw new Error("zeroPoints input size error.")}},po=(e,t)=>{let n=e[0].dims,i=n.length,r=n[i-2],s=t.k,a=t.n,o=n.slice(0,i-2),u=ut.size(o),l=e[1].dims[2]/4,d=e[0].dataType,h=Vt(t.k),c=Vt(l),p=Vt(a),f=o.concat([r,a]),m=r>1&&a/p%2==0?2:1,g=ut.size(f)/p/m,y=[],w=[u,r,s/h],b=ut.convertShape(e[1].dims).slice();b.splice(-1,1,l/c),y.push(...qt(w)),y.push(...qt(b)),y.push(...qt(e[2].dims)),4===e.length&&y.push(...qt(ut.convertShape(e[3].dims)));let _=[u,r,a/p];return y.push(...qt(_)),{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${h};${c};${p};${m};64`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:d}],dispatchGroup:{x:g},programUniforms:y}),getShaderSource:n=>{let i=w.length,r=Jt("a",e[0].dataType,i,h),s=Jt("b",12,b.length,c),a=Jt("scales",e[2].dataType,e[2].dims.length),o=[r,s,a],u=4===e.length?Jt("zero_points",12,e[3].dims.length):void 0;u&&o.push(u);let d=_.length,f=Xt("output",e[0].dataType,d,p),g=Ht(e[0].dataType),y=(()=>{switch(h){case 1:return`array<${g}, 8>`;case 2:return`mat4x2<${g}>`;case 4:return`mat2x4<${g}>`;default:throw new Error(`${h}-component is not supported.`)}})();return`\n var<workgroup> workgroup_shared: array<${f.type.value}, ${64*m}>;\n ${n.declareVariables(...o,f)}\n ${n.mainStart([64,1,1])}\n let output_indices = ${f.offsetToIndices(`(global_idx / 64) * ${m}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let nBlocksPerCol = uniforms.b_shape[1];\n\n for (var block = local_id.x; block < nBlocksPerCol; block += 64) {\n //process one block\n var word_offset: u32 = block * ${t.blockSize/h};\n ${(()=>{let e=`\n var col_index = col * ${p};\n ${u?"\n let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2;\n var zero_point_byte_count: u32;\n var zero_point_word_index: u32;\n var zero_point_byte_offset: u32;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32;\n var zero_point_word: u32;":`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${g}(8);`}\n `;for(let t=0;t<p*m;t++)e+=`\n let scale${t} = ${a.getByOffset("col_index * nBlocksPerCol + block")};\n ${u?`\n zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u);\n zero_point_word_index = zero_point_byte_count >> 0x2u;\n zero_point_byte_offset = zero_point_byte_count & 0x3u;\n zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n zero_point_word = ${u.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n let zero_point${t} = ${g}((zero_point_word) & 0xFu);`:""}\n col_index += 1;`;return e})()}\n for (var word: u32 = 0; word < ${l}; word += ${c}) {\n ${(()=>{let e=`col_index = col * ${p};`;for(let t=0;t<p*m;t++)e+=`\n let b${t}_data = ${s.getByIndices(`${s.type.indices}(col_index, block, word)`)};\n col_index += 1;`;return e+=`\n var b_value: u32;\n let b_mask: u32 = 0x0F0F0F0Fu;\n var b_value_lower: vec4<u32>;\n var b_value_upper: vec4<u32>;\n var b_quantized_values: ${y};\n var b_dequantized_values: ${y};`,e})()}\n for (var i: u32 = 0; i < ${c}; i++) {\n ${(()=>{let e=`\n // reuse a data\n var input_offset = ${r.indicesToOffset(`${r.type.indices}(batch, row, word_offset)`)};\n var a_data: ${y};\n for (var j: u32 = 0; j < ${8/h}; j++) {\n a_data[j] = ${r.getByOffset("input_offset")};\n input_offset++;\n }\n `;for(let t=0;t<p*m;t++)e+=`\n b_value = ${1===c?`b${t}_data`:`b${t}_data[i]`};\n b_value_lower = unpack4xU8(b_value & b_mask);\n b_value_upper = unpack4xU8((b_value >> 4) & b_mask);\n b_quantized_values = ${y}(${Array.from({length:4},(e,t)=>`${g}(b_value_lower[${t}]), ${g}(b_value_upper[${t}])`).join(", ")});\n b_dequantized_values = ${1===h?`${y}(${Array.from({length:8},(e,n)=>`(b_quantized_values[${n}] - ${u?`zero_point${t}`:"zero_point"}) * scale${t}`).join(", ")});`:`(b_quantized_values - ${y}(${Array(8).fill(u?`zero_point${t}`:"zero_point").join(",")})) * scale${t};`};\n workgroup_shared[local_id.x * ${m} + ${Math.floor(t/p)}]${p>1?`[${t%p}]`:""} += ${Array.from({length:8/h},(e,t)=>1===h?`a_data[${t}] * b_dequantized_values[${t}]`:`dot(a_data[${t}], b_dequantized_values[${t}])`).join(" + ")};\n `;return e})()}\n word_offset += ${8/h};\n }\n }\n }\n workgroupBarrier();\n\n if (local_id.x < ${m}) {\n var output_value: ${f.type.value} = ${f.type.value}(0);\n var workgroup_shared_offset: u32 = local_id.x;\n for (var b: u32 = 0u; b < 64u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${m};\n }\n ${f.setByIndices(`${f.type.indices}(batch, row, col + local_id.x)`,"output_value")};\n }\n }`}}},fo=(e,t)=>{let n=e[0].dims,i=n.length,r=n[i-2],s=t.k,a=t.n,o=n.slice(0,i-2),u=ut.size(o),l=e[1].dims[2]/4,d=e[0].dataType,h=Vt(t.k),c=Vt(l),p=o.concat([r,a]),f=a%8==0?8:a%4==0?4:1,m=128/f,g=m*c*8,y=g/h,w=g/t.blockSize,b=ut.size(p)/f,_=[],$=[u,r,s/h],v=ut.convertShape(e[1].dims).slice();v.splice(-1,1,l/c),_.push(...qt($)),_.push(...qt(v)),_.push(...qt(e[2].dims)),4===e.length&&_.push(...qt(ut.convertShape(e[3].dims)));let x=[u,r,a];return _.push(...qt(x)),{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${h};${c};${m};${f}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:p,dataType:d}],dispatchGroup:{x:b},programUniforms:_}),getShaderSource:n=>{let i=$.length,r=Jt("a",e[0].dataType,i,h),s=Jt("b",12,v.length,c),a=Jt("scales",e[2].dataType,e[2].dims.length),o=[r,s,a],u=4===e.length?Jt("zero_points",12,e[3].dims.length):void 0;u&&o.push(u);let l=x.length,d=Xt("output",e[0].dataType,l),p=Ht(e[0].dataType);return`\n var<workgroup> sub_a: array<${r.type.value}, ${y}>;\n var<workgroup> inter_results: array<array<${d.type.value}, ${m}>, ${f}>;\n ${n.declareVariables(...o,d)}\n ${n.mainStart([m,f,1])}\n let output_indices = ${d.offsetToIndices(`workgroup_index * ${f}`)};\n let col = output_indices[2];\n let row = output_indices[1];\n let batch = output_indices[0];\n let n_blocks_per_col = uniforms.b_shape[1];\n let num_tiles = (n_blocks_per_col - 1) / ${w} + 1;\n\n // Loop over shared dimension.\n for (var tile: u32 = 0; tile < num_tiles; tile += 1) {\n let a_col_start = tile * ${y};\n // load one tile A data into shared memory.\n for (var a_offset = local_idx; a_offset < ${y}; a_offset += 128)\n {\n let a_col = a_col_start + a_offset;\n if (a_col < uniforms.a_shape[2])\n {\n sub_a[a_offset] = ${r.getByIndices(`${r.type.indices}(batch, row, a_col)`)};\n } else {\n sub_a[a_offset] = ${r.type.value}(0);\n }\n }\n workgroupBarrier();\n\n // each thread process one block\n let b_row = col + local_id.y;\n let block = tile * ${w} + local_id.x;\n ${u?`\n let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2;\n let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u);\n let zero_point_word_index = zero_point_byte_count >> 0x2u;\n let zero_point_byte_offset = zero_point_byte_count & 0x3u;\n let zero_point_nibble_offset: u32 = block & 0x1u;\n let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n let zero_point_word = ${u.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;\n let zero_point = ${p}((zero_point_word) & 0xFu);`:`\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${p}(8);`}\n let scale = ${a.getByOffset("b_row * n_blocks_per_col + block")};\n let b_data = ${s.getByIndices(`${s.type.indices}(b_row, block, 0)`)};\n var word_offset = local_id.x * ${t.blockSize/h};\n for (var i: u32 = 0; i < ${c}; i++) {\n ${(()=>{switch(h){case 1:return`\n let a_data0 = vec4<${p}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);\n let a_data1 = vec4<${p}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`\n let a_data0 = vec4<${p}>(sub_a[word_offset], sub_a[word_offset + 1]);\n let a_data1 = vec4<${p}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return"\n let a_data0 = sub_a[word_offset];\n let a_data1 = sub_a[word_offset + 1];";default:throw new Error(`${h}-component is not supported.`)}})()}\n let b_value = ${1===c?"b_data":"b_data[i]"};\n let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu);\n let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu);\n let b_quantized_values = mat2x4<${p}>(${Array.from({length:4},(e,t)=>`${p}(b_value_lower[${t}]), ${p}(b_value_upper[${t}])`).join(", ")});\n let b_dequantized_values = (b_quantized_values - mat2x4<${p}>(${Array(8).fill("zero_point").join(",")})) * scale;\n inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(e,t)=>`dot(a_data${t}, b_dequantized_values[${t}])`).join(" + ")};\n word_offset += ${8/h};\n }\n workgroupBarrier();\n }\n\n if (local_idx < ${f}) {\n var output_value: ${d.type.value} = ${d.type.value}(0);\n for (var b = 0u; b < ${m}; b++) {\n output_value += inter_results[local_idx][b];\n }\n if (col + local_idx < uniforms.output_shape[2])\n {\n ${d.setByIndices(`${d.type.indices}(batch, row, col + local_idx)`,"output_value")}\n }\n }\n }`}}},mo=(e,t)=>{co(e.inputs,t),32===t.blockSize&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(fo(e.inputs,t)):e.compute(po(e.inputs,t))},go=e=>Ut(e)}),Xl=L(()=>{Yu(),nl(),ll(),yo=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(1!==e[0].dataType&&10!==e[0].dataType)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=2*e[0].dims.length===e[1].dims[0];if(4===e.length&&(t=2*e[3].dims[0]===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},wo=(e,t,n)=>{let i="";for(let r=t-1;r>=0;--r)i+=`\n k = i32(${e.indicesGet("indices",r)}) - ${Kt("uniforms.pads",r,n)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${Kt("uniforms.x_shape",r,t)})) {\n break;\n }\n offset += k * i32(${Kt("uniforms.x_strides",r,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${i}\n value = x[offset];\n }\n `},bo=(e,t,n)=>{let i="";for(let r=t-1;r>=0;--r)i+=`\n k = i32(${e.indicesGet("indices",r)}) - ${Kt("uniforms.pads",r,n)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${Kt("uniforms.x_shape",r,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${Kt("uniforms.x_shape",r,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${Kt("uniforms.x_strides",r,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${i}\n value = x[offset];\n `},_o=(e,t,n)=>{let i="";for(let r=t-1;r>=0;--r)i+=`\n k = i32(${e.indicesGet("indices",r)}) - ${Kt("uniforms.pads",r,n)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${Kt("uniforms.x_shape",r,t)})) {\n k = i32(${Kt("uniforms.x_shape",r,t)}) - 1;\n }\n offset += k * i32(${Kt("uniforms.x_strides",r,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${i}\n value = x[offset];\n `},$o=(e,t,n)=>{let i="";for(let r=t-1;r>=0;--r)i+=`\n k = i32(${e.indicesGet("indices",r)}) - ${Kt("uniforms.pads",r,n)};\n if (k < 0) {\n k += i32(${Kt("uniforms.x_shape",r,t)}]);\n }\n if (k >= i32(${Kt("uniforms.x_shape",r,t)})) {\n k -= i32(${Kt("uniforms.x_shape",r,t)});\n }\n offset += k * i32(${Kt("uniforms.x_strides",r,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${i}\n value = x[offset];\n `},vo=(e,t,n)=>{switch(n.mode){case 0:return wo(e,t,n.pads.length);case 1:return bo(e,t,n.pads.length);case 2:return _o(e,t,n.pads.length);case 3:return $o(e,t,n.pads.length);default:throw new Error("Invalid mode")}},xo=(e,t)=>{let n=ut.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,r=[{type:12,data:ut.size(n)},{type:6,data:t.pads}],s=e.length>=3&&e[2].data;return 0===t.mode&&r.push({type:s?e[2].dataType:1,data:t.value}),r.push(...qt(e[0].dims,n)),{name:"Pad",shaderCache:{hint:`${t.mode}${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ut.size(n)/64)},programUniforms:r}),getShaderSource:r=>{let a=Xt("output",e[0].dataType,n.length),o=Jt("x",e[0].dataType,i.length),u=o.type.value,l=vo(a,i.length,t),d=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return 0===t.mode&&d.push({name:"constant_value",type:s?u:"f32"}),`\n ${r.registerUniforms(d).declareVariables(o,a)}\n ${r.mainStart()}\n ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${a.offsetToIndices("global_idx")};\n\n var value = ${u}(0);\n ${l}\n output[global_idx] = value;\n }`}}},So=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?10===e[2].dataType?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,r=e[0].dims.length,s=new Int32Array(2*r).fill(0);if(e.length>=4){let t=e[3].getBigInt64Array();for(let e=0;e<t.length;e++)s[Number(t[e])]=Number(n[e]),s[Number(t[e])+r]=Number(n[e+t.length])}else n.forEach((e,t)=>s[Number(t)]=Number(e));let a=[];return s.forEach(e=>a.push(e)),{mode:t.mode,value:i,pads:a}}return t},To=(e,t)=>{yo(e.inputs);let n=So(e.inputs,t);e.compute(xo(e.inputs,n),{inputs:[0]})}}),Zl=L(()=>{oe(),Yu(),nl(),ll(),ko=e=>{if(l.webgpu.validateInputContent&&(!e||1!==e.length))throw new Error("Pool ops requires 1 input.")},Eo=(e,t,n)=>{let i="NHWC"===t.format,r=e.dims.slice();i&&r.splice(1,0,r.pop());let s=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),o=t.strides.slice(),u=s?t.dilations.slice():[],l=t.pads.slice();lt.adjustPoolAttributes(n,r,a,o,u,l);let d=lt.computePoolOutputShape(n,r,o,u,a,l,t.autoPad),h=Object.assign({},t);s?Object.assign(h,{kernelShape:a,strides:o,pads:l,dilations:u,cacheKey:t.cacheKey}):Object.assign(h,{kernelShape:a,strides:o,pads:l,cacheKey:t.cacheKey});let c=d.slice();return c.push(c.splice(1,1)[0]),[h,i?c:d]},Co=(e,t)=>{let n="NHWC"===t.format,i=[{type:12,data:ut.size(e)},{type:12,data:ut.size(t.kernelShape)}],r=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let e=t.kernelShape[t.kernelShape.length-1],n=t.strides[t.strides.length-1],s=t.pads[t.pads.length/2-1],a=t.pads[t.pads.length-1],o=!!(s+a);i.push({type:12,data:e},{type:12,data:n},{type:12,data:s},{type:12,data:a}),r.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(2===t.kernelShape.length){let e=t.kernelShape[t.kernelShape.length-2],n=t.strides[t.strides.length-2],s=t.pads[t.pads.length/2-2],a=t.pads[t.pads.length-2];u=!!(s+a),i.push({type:12,data:e},{type:12,data:n},{type:12,data:s},{type:12,data:a}),r.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,r,!0,o,u]}{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let e=ut.computeStrides(t.kernelShape);return i.push({type:12,data:e},{type:12,data:t.pads},{type:12,data:t.strides}),r.push({name:"kernelStrides",type:"u32",length:e.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length}),[i,r,!!t.pads.reduce((e,t)=>e+t),!1,!1]}},Io=(e,t,n,i,r,s,a,o,u,l,d,h)=>{let c="NHWC"===r.format,p=t.type.value,f=Xt("output",t.type.tensor,i);if(r.kernelShape.length<=2){let i="",l="",m="",g=n-(c?2:1);if(i=d?`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${g}] < 0 || xIndices[${g}]\n >= uniforms.x_shape[${g}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`,2===r.kernelShape.length){let e=n-(c?3:2);l=h?`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${e}] < 0 || xIndices[${e}] >= uniforms.x_shape[${e}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${e}] = indices[${e}] * uniforms.sh - uniforms.phStart + j;\n `,m="\n }\n "}return`\n ${e.registerUniforms(u).declareVariables(t,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${f.offsetToIndices("global_idx")};\n var xIndices = ${f.offsetToIndices("global_idx")};\n\n var value = ${p}(${o});\n var pad = 0;\n ${l}\n ${i}\n ${m}\n ${a}\n\n output[global_idx] = value;\n }`}{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let i=r.kernelShape.length,d=r.pads.length,h="";return h=l?`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n `,`\n ${e.registerUniforms(u).declareVariables(t,f)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${f.offsetToIndices("global_idx")};\n var xIndices = ${f.offsetToIndices("global_idx")};\n\n var offsets: array<u32, ${i}>;\n\n var value = ${p}(${o});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${i-1}u; j++) {\n offsets[j] = offset / ${Kt("uniforms.kernelStrides","j",i)};\n offset -= offsets[j] * ${Kt("uniforms.kernelStrides","j",i)};\n }\n offsets[${i-1}] = offset;\n\n isPad = false;\n for (var j = ${n-i}u; j < ${n}u; j++) {\n xIndices[j] = indices[j] * ${Kt("uniforms.strides",`j - ${n-i}u`,i)}\n + offsets[j - ${n-i}u] - ${Kt("uniforms.pads","j - 2u",d)};\n ${h}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},Ao=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Ro=e=>`${Ao(e)};${e.countIncludePad}`,Mo=e=>`${Ao(e)};${e.storageOrder};${e.dilations}`,zo=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}),Oo=(e,t,n,i)=>{let[r,s]=Eo(t,i,n),a=Jt("x",t.dataType,t.dims.length),o=a.type.value,u="";r.countIncludePad?u+=`value /= ${o}(uniforms.kernelSize);`:u+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[l,d,h,c,p]=Co(s,r);return l.push(...qt(t.dims,s)),{name:e,shaderCache:{hint:`${i.cacheKey};${h};${c};${p}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ut.size(s)/64)},programUniforms:l}),getShaderSource:e=>Io(e,a,t.dims.length,s.length,r,"value += x_val;",u,0,d,h,c,p)}},Po=e=>{let t=0!==e.count_include_pad,n=zo(e);if(0!==n.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let i={countIncludePad:t,...n,cacheKey:""};return{...i,cacheKey:Ro(i)}},Bo=(e,t)=>{ko(e.inputs),e.compute(Oo("AveragePool",e.inputs[0],!1,t))},Do={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Uo=e=>{let t=e.format;return{format:t,...Do,cacheKey:t}},Lo=(e,t)=>{ko(e.inputs),e.compute(Oo("GlobalAveragePool",e.inputs[0],!0,t))},No=(e,t,n,i)=>{let[r,s]=Eo(t,i,n),a=Jt("x",t.dataType,t.dims.length),[o,u,l,d,h]=Co(s,r);return o.push(...qt(t.dims,s)),{name:e,shaderCache:{hint:`${i.cacheKey};${l};${d};${h}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ut.size(s)/64)},programUniforms:o}),getShaderSource:e=>Io(e,a,t.dims.length,s.length,r,"\n value = max(x_val, value);\n ","",10===t.dataType?-65504:-1e5,u,l,d,h)}},Ho=(e,t)=>{ko(e.inputs),e.compute(No("MaxPool",e.inputs[0],!1,t))},Fo=e=>{let t=e.storage_order,n=e.dilations,i=zo(e);if(0!==t)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==i.ceilMode)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let r={storageOrder:t,dilations:n,...i,cacheKey:""};return{...r,cacheKey:Mo(r)}},qo=e=>{let t=e.format;return{format:t,...Do,cacheKey:t}},Vo=(e,t)=>{ko(e.inputs),e.compute(No("GlobalMaxPool",e.inputs[0],!0,t))}}),Yl=L(()=>{Yu(),nl(),ul(),ll(),Wo=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(3===e.length&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(3===e.length&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(6===e[0].dataType&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(0!==e[1].dims.length&&1!==e[1].dims.length&&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,n)=>t===e[2].dims[n]).reduce((e,t)=>e&&t,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(0===e[1].dims.length||1===e[1].dims.length&&1===e[1].dims[0])throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((n,i)=>i===t.axis||n===e[0].dims[i]).reduce((e,t)=>e&&t,!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 n=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSize<Math.ceil(n/i)||t.blockSize>Math.ceil(n/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},jo=(e,t)=>{let n=ut.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,r=3===i,s=e[0].dims,a=e[1].dataType,o=ut.size(s),u=3===i||2===i,l=u?[Math.ceil(ut.size(e[0].dims)/4)]:e[0].dims,d=e[1].dims,h=e.length>2?e[2]:void 0,c=h?u?[Math.ceil(ut.size(h.dims)/4)]:h.dims:void 0,p=0===d.length||1===d.length&&1===d[0],f=!1===p&&1===d.length,m=Vt(o),g=p&&(!u||4===m),y=g?m:1,w=g&&!u?m:1,b=Jt("input",u?12:i,l.length,w),_=Jt("scale",a,d.length),$=h?Jt("zero_point",u?12:i,c.length):void 0,v=Xt("output",a,s.length,y),x=[b,_];$&&x.push($);let S=[l,d];h&&S.push(c);let T=[{type:12,data:o/y},{type:12,data:n},{type:12,data:t.blockSize},...qt(...S,s)];return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:$?["rank","rank","rank"]:["rank","rank"]},getShaderSource:e=>`\n ${e.registerUniforms([{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}]).declareVariables(...x,v)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${v.offsetToIndices("global_idx")};\n\n // Set input x\n ${u?`\n let input = ${b.getByOffset("global_idx / 4")};\n let x_vec = ${r?"unpack4xI8(input)":"unpack4xU8(input)"};\n let x_value = ${1===y?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${b.getByOffset("global_idx")};`};\n\n // Set scale input\n ${p?`let scale_value= ${_.getByOffset("0")}`:f?`\n let scale_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let scale_value= ${_.getByOffset("scale_index")};`:`\n var scale_indices: ${_.type.indices} = output_indices;\n let index = ${_.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;\n ${_.indicesSet("scale_indices","uniforms.axis","index")};\n let scale_value= ${_.getByIndices("scale_indices")};`};\n\n // Set zero-point input\n ${$?p?u?`\n let zero_point_input = ${$.getByOffset("0")};\n let zero_point_vec = ${r?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${$.getByOffset("0")}`:f?u?`\n let zero_point_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let zero_point_input = ${$.getByOffset("zero_point_index / 4")};\n let zero_point_vec = ${r?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value = zero_point_vec[zero_point_index % 4]`:`\n let zero_point_index = ${v.indicesGet("output_indices","uniforms.axis")};\n let zero_point_value = ${$.getByOffset("zero_point_index")};`:u?`\n let zero_point_offset = ${_.indicesToOffset("scale_indices")};\n let zero_point_input = ${$.getByOffset("zero_point_offset / 4")};\n let zero_point_vec = ${r?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};\n let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${$.getByIndices("scale_indices")};`:`let zero_point_value = ${u?r?"i32":"u32":b.type.value}(0);`};\n // Compute and write output\n ${v.setByOffset("global_idx",`${v.type.value}(x_value - zero_point_value) * scale_value`)};\n }`,getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:Math.ceil(o/y/64),y:1,z:1},programUniforms:T})}},Go=(e,t)=>{Wo(e.inputs,t),e.compute(jo(e.inputs,t))},Ko=e=>Ut({axis:e.axis,blockSize:e.blockSize})}),ed=L(()=>{oe(),Yu(),ll(),Qo=(e,t,n)=>{if(e===t||e<t&&n<0||e>t&&n>0)throw new Error("Range these inputs' contents are invalid.")},Jo=(e,t,n,i)=>{let r=Math.abs(Math.ceil((t-e)/n)),s=[r],a=r,o=[{type:12,data:a},{type:i,data:e},{type:i,data:n},...qt(s)];return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:e=>{let t=Xt("output",i,s.length),n=t.type.value,r=[{name:"outputSize",type:"u32"},{name:"start",type:n},{name:"delta",type:n}];return`\n ${e.registerUniforms(r).declareVariables(t)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${n}(global_idx) * uniforms.delta;\n }`},getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:o})}},Xo=e=>{let t=0,n=0,i=0;6===e.inputs[0].dataType?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):1===e.inputs[0].dataType&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),l.webgpu.validateInputContent&&Qo(t,n,i),e.compute(Jo(t,n,i,e.inputs[0].dataType),{inputs:[]})}}),td=L(()=>{Yu(),nl(),ul(),ll(),Zo=(e,t,n,i)=>{if("none"!==e&&"i32"!==i&&"u32"!==i&&"f32"!==i)throw new Error(`Input ${i} is not supported with reduction ${e}.`);let r="{\n var oldValue = 0;\n loop {\n let newValueF32 =",s=`;\n let newValue = bitcast<i32>(newValueF32);\n let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue);\n if res.exchanged {\n break;\n }\n oldValue = res.old_value;\n }\n }`;switch(e){case"none":return`${t}=${n};`;case"add":return"i32"===i||"u32"===i?`atomicAdd(&${t}, bitcast<${i}>(${n}));`:`\n ${r}bitcast<${i}>(oldValue) + (${n})${s}`;case"max":return"i32"===i||"u32"===i?`atomicMax(&${t}, bitcast<${i}>(${n}));`:`\n ${r}max(bitcast<f32>(oldValue), (${n}))${s}`;case"min":return"i32"===i||"u32"===i?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${r}min(bitcast<${i}>(oldValue), (${n}))${s}`;case"mul":return`${r}(bitcast<${i}>(oldValue) * (${n}))${s}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Yo=(e,t)=>{let n=e[0].dims,i=e[1].dims,r=n,s=Math.ceil(ut.sizeToDimension(i,i.length-1)/1),a=i[i.length-1],o=ut.sizeFromDimension(n,a),u=[{type:12,data:s},{type:12,data:a},{type:12,data:o},...qt(e[1].dims,e[2].dims,r)];return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u}),getShaderSource:n=>{let i=Jt("indices",e[1].dataType,e[1].dims.length),s=Jt("updates",e[2].dataType,e[2].dims.length,1),a="none"!==t.reduction&&""!==t.reduction?Zt("output",e[0].dataType,r.length):Xt("output",e[0].dataType,r.length,1);return`\n ${n.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(i,s,a)}\n ${n.mainStart()}\n ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var data_offset = 0u;\n let indices_start = uniforms.last_index_dimension * global_idx;\n let indices_end = indices_start + uniforms.last_index_dimension;\n for (var i = indices_start; i < indices_end; i++) {\n var index = i32(indices[i].x);\n ${1===e[0].dims.length?"\n let element_count_dim = uniforms.output_strides;\n let dim_value = uniforms.output_shape;":"\n let element_count_dim = uniforms.output_strides[i - indices_start];\n let dim_value = uniforms.output_shape[i - indices_start];"}\n if (index >= 0) {\n if (index >= i32(dim_value)) {\n index = i32(dim_value - 1);\n }\n } else {\n if (index < -i32(dim_value)) {\n index = 0;\n } else {\n index += i32(dim_value);\n }\n }\n data_offset += u32((u32(index) * element_count_dim));\n }\n\n for (var i = 0u; i < uniforms.num_updates_elements; i++) {\n let value = updates[uniforms.num_updates_elements * global_idx + i];\n ${Zo(t.reduction,"output[data_offset + i]","value",a.type.value)}\n }\n\n }`}}},eu=e=>Ut({reduction:e.reduction}),tu=(e,t)=>{e.compute(Yo(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),nd=L(()=>{Yu(),nl(),ul(),ll(),nu=(e,t)=>{if(e.every(e=>e>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0)if("linear"===t.mode){if(!(2===e.length||3===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]||5===e.length&&1===e[0]&&1===e[1]))throw new Error("For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1")}else if("cubic"===t.mode&&!(2===e.length||4===e.length&&1===e[0]&&1===e[1]||4===e.length&&1===e[0]&&1===e[3]))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")},iu=(e,t,n)=>{t.every(e=>e>=0&&e<n||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(n).fill(1);return t.forEach((t,n)=>i[t]=e[n]),i},ru=(e,t,n,i,r,s)=>{let[a,o,u]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],l=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(e=>s.push(e));else if("tf_crop_and_resize"===t.coordinateTransformMode)throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&e.length>o&&1===e[o].dims.length&&e[o].dims[0]>0){if(e[o].getFloat32Array().forEach(e=>i.push(e)),0!==i.length&&i.length!==l&&n>=18&&i.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");nu(i,t),t.axes.length>0&&iu(i,t.axes,l).forEach((e,t)=>i[t]=e)}if(u>0&&e.length>u&&1===e[u].dims.length&&e[u].dims[0]>0&&(e[u].getBigInt64Array().forEach(e=>r.push(Number(e))),0!==r.length&&r.length!==l&&n>=18&&r.length!==t.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(t.axes.length>0){if(0!==i.length&&i.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(0!==r.length&&r.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof i<"u"&&typeof r<"u"&&i.length>0&&r.length>l)throw new Error("Resize requires only of scales or sizes to be specified")},su=(e,t,n,i)=>`\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let big = (${e}) * (${t});\n let whole = ${i}(big / (${n}));\n let fract = ${i}(big % (${n})) / ${i}(${n});\n return whole + fract;\n`,au=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`\n if (xScale < 1.0 || floor(xScale) != xScale) {\n return ${t}(xResized) / ${t}(xScale);\n } else {\n ${su("xResized","lengthOriginal","lengthResized",t)}\n }\n `;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n ${su("xResized","lengthOriginal - 1","lengthResized - 1",t)}\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ou=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{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); }";default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",uu=(e,t,n)=>{let i=new Array(n).fill(0).concat(new Array(n).fill(1)),r=0===e.length?i:e.slice();return t.length>0?(t.forEach((e,s)=>{i[e]=r[s],i[s+n]=r[t.length+s]}),i):r},lu=(e,t,n,i)=>{let r=[];if(n.length>0)if(i.length>0){if(e.forEach(e=>r.push(e)),Math.max(...i)>e.length)throw new Error("axes is out of bound");i.forEach((e,t)=>r[e]=n[t])}else n.forEach(e=>r.push(e));else{if(0===t.length)throw new Error("Resize requires either scales or sizes.");r=e.map((e,n)=>Math.round(e*t[n]))}return r},du=(e,t,n)=>{let i=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(e=>t[e]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(e=>t[e]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let r=e.slice();return n.axes.length>0?(n.axes.forEach(e=>t[e]=i),n.axes.forEach(n=>r[n]=Math.round(e[n]*t[n]))):(t.fill(i,0,t.length),r.forEach((e,n)=>r[n]=Math.round(e*t[n]))),r},hu=(e,t,n,i,r)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> {\n var original_indices: array<${e.type.value}, ${n.length}>;\n for (var i:u32 = 0; i < ${n.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${Kt("uniforms.scales","i",i)};\n var roi_low = ${Kt("uniforms.roi","i",r)};\n var roi_hi = ${Kt("uniforms.roi",`i + ${t.length}`,r)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${Kt("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${Kt("uniforms.output_shape","i",n.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,cu=(e,t,n,i,r,s,a)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${i.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${Kt("uniforms.scales","i",r)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${Kt("uniforms.roi","i",s)};\n var roi_hi = ${Kt("uniforms.roi",`i + ${n.length}`,s)};\n var input_shape_i = ${Kt("uniforms.input_shape","i",n.length)};\n var output_shape_i = ${Kt("uniforms.output_shape","i",i.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i","input_index")}\n }\n return input_indices;\n }`,pu=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${Kt("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,fu=(e,t,n,i)=>e.rank>i?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",n,"batch")};\n`:"",mu=(e,t,n,i,r)=>{let[s,a,o,u]=2===n.length?[-1,0,1,-1]:[0,2,3,1],l=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${l} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",a,`max(0, min(row, ${n[a]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)};\n ${fu(e,u,s,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${l} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${l} = originalIndices[${a}];\n var col:${l} = originalIndices[${o}];\n ${i?`if (row < 0 || row > (${n[a]} - 1) || col < 0 || col > (${n[o]} - 1)) {\n return ${r};\n }`:""};\n row = max(0, min(row, ${n[a]} - 1));\n col = max(0, min(col, ${n[o]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${n.length>2?`u32(originalIndices[${u}])`:"0"};\n var batch: u32 = ${n.length>2?`u32(originalIndices[${s}])`:"0"};\n var x11: ${l} = getInputValue(batch, channel, row1, col1);\n var x12: ${l} = getInputValue(batch, channel, row1, col2);\n var x21: ${l} = getInputValue(batch, channel, row2, col1);\n var x22: ${l} = getInputValue(batch, channel, row2, col2);\n var dx1: ${l} = abs(row - ${l}(row1));\n var dx2: ${l} = abs(${l}(row2) - row);\n var dy1: ${l} = abs(col - ${l}(col1));\n var dy2: ${l} = abs(${l}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},gu=(e,t,n,i,r,s,a,o,u,l)=>{let d=2===n.length,[h,c]=d?[0,1]:[2,3],p=e.type.value,f=a=>{let d=a===h?"row":"col";return`\n fn ${d}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${p} {\n var output_index = ${t.indicesGet("output_indices",a)};\n var originalIdx: ${p} = getOriginalCoordinateFromResizedCoordinate(output_index, ${r[a]},\n ${i[a]}, ${n[a]}, ${s[a]}, ${s[a]} + ${n.length});\n var fractOriginalIdx: ${p} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${o} && (originalIdx < 0 || originalIdx > (${n[a]} - 1))) {\n return ${u};\n }\n var data: array<${p}, 4> = array<${p}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${d}: ${p} = originalIdx + ${p}(i);\n if (${d} < 0 || ${d} >= ${n[a]}) {\n ${l?"coefs[i + 1] = 0.0;\n continue;":o?`return ${u};`:`${d} = max(0, min(${d}, ${n[a]} - 1));`};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",a,`u32(${d})`)};\n data[i + 1] = ${a===h?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${f(h)};\n ${f(c)};\n fn getCubicInterpolationCoefs(s: ${p}) -> array<${p}, 4> {\n var absS = abs(s);\n var coeffs: array<${p}, 4> = array<${p}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${p} = 1.0 - absS;\n var twoMinusAbsS: ${p} = 2.0 - absS;\n var onePlusAbsS: ${p} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${p}, 4>, coefs: array<${p}, 4>) -> ${p} {\n var coefsSum: ${p} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${p} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},yu=(e,t,n,i,r)=>{let[s,a,o,u,l]=3===n.length?[-1,0,1,2,-1]:[0,2,3,4,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",a,`max(0, min(depth, ${n[a]} - 1))`)};\n ${e.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)};\n ${e.indicesSet("input_indices",u,`max(0, min(width, ${n[u]} - 1))`)};\n ${fu(e,l,s,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${d} = originalIndices[${a}];\n var height:${d} = originalIndices[${o}];\n var width:${d} = originalIndices[${u}];\n ${i?`if (depth < 0 || depth > (${n[a]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[u]} - 1)) {\n return ${r};\n }`:""};\n\n depth = max(0, min(depth, ${n[a]} - 1));\n height = max(0, min(height, ${n[o]} - 1));\n width = max(0, min(width, ${n[u]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${n.length>3?`u32(originalIndices[${l}])`:"0"};\n var batch: u32 = ${n.length>3?`u32(originalIndices[${s}])`:"0"};\n\n var x111: ${d} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${d} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${d} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${d} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${d} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${d} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${d} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${d} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${d} = abs(depth - ${d}(depth1));\n var dx2: ${d} = abs(${d}(depth2) - depth);\n var dy1: ${d} = abs(height - ${d}(height1));\n var dy2: ${d} = abs(${d}(height2) - height);\n var dz1: ${d} = abs(width - ${d}(width1));\n var dz2: ${d} = abs(${d}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},wu=(e,t,n,i,r,s)=>{let a=e.dims,o=uu(s,t.axes,a.length),u=lu(a,i,r,t.axes),l=i.slice();0===i.length&&(l=a.map((e,t)=>0===e?1:u[t]/e),"stretch"!==t.keepAspectRatioPolicy&&(u=du(a,l,t)));let d=Xt("output",e.dataType,u.length),h=Jt("input",e.dataType,a.length),c=ut.size(u),p=a.length===u.length&&a.every((e,t)=>e===u[t]),f="tf_crop_and_resize"===t.coordinateTransformMode,m=t.extrapolationValue,g=h.type.value;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${l.length>0?"cubic"===t.mode?l:l.length:""}|${r.length>0?r:""}|${o.length>0?o:""}|${p}|${"nearest"===t.mode?a.length:a}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${p?"":`\n ${au(t.coordinateTransformMode,g)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${pu(h,a)};\n ${ou(t.nearestMode,n,g)};\n ${cu(h,d,a,u,l.length,o.length,f)};\n `;case"linear":return`\n ${hu(d,a,u,l.length,o.length)};\n ${(()=>{if(2===a.length||4===a.length)return`${mu(h,d,a,f,m)}`;if(3===a.length||5===a.length)return`${yu(h,d,a,f,m)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(2===a.length||4===a.length)return`${gu(h,d,a,u,l,o,t.cubicCoeffA,f,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${e.registerUniform("output_size","u32").registerUniform("scales","f32",l.length).registerUniform("roi","f32",o.length).declareVariables(h,d)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${p?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${h.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${h.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${2===a.length||4===a.length?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`,getRunData:()=>({outputs:[{dims:u,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:1,data:l},{type:1,data:o},...qt(a,u)]})}},bu=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},_u=(e,t)=>{let n=[],i=[],r=[],s=bu(e);if(0!==t.antialias)throw Error("Only default value (0) for Antialias attribute is supported");ru(e.inputs,t,s,n,i,r),e.compute(wu(e.inputs[0],t,s,n,i,r),{inputs:[0]})},$u=e=>{let t=e.antialias,n=e.axes,i=e.coordinateTransformMode,r=e.cubicCoeffA,s=0!==e.excludeOutside,a=e.extrapolationValue,o=e.keepAspectRatioPolicy,u=e.mode,l=""===e.nearestMode?"simple":e.nearestMode;return Ut({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:r,excludeOutside:s,extrapolationValue:a,keepAspectRatioPolicy:o,mode:u,nearestMode:l})}}),id=L(()=>{Yu(),nl(),ll(),vu=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dataType!==n.dataType||t.dataType!==i.dataType)throw new Error("All inputs must have the same data type");if(3!==t.dims.length&&2!==t.dims.length)throw new Error("Input must be 2D or 3D");if(3!==n.dims.length&&2!==n.dims.length)throw new Error("Skip must be 2D or 3D");let r=t.dims[t.dims.length-1],s=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==r)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(1!==i.dims.length)throw new Error("Gamma must be 1D");if(i.dims[i.dims.length-1]!==r)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let t=e[3];if(1!==t.dims.length)throw new Error("Beta must be 1D");if(t.dims[t.dims.length-1]!==r)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let t=e[4];if(1!==t.dims.length)throw new Error("Bias must be 1D");if(t.dims[t.dims.length-1]!==r)throw new Error("Bias must have the same hidden size as input")}},xu=(e,t,n,i)=>{let r=t.simplified,s=e[0].dims,a=ut.size(s),o=s,u=a,l=s.slice(-1)[0],d=i?s.slice(0,-1).concat(1):[],h=!r&&e.length>3,c=e.length>4,p=i&&n>1,f=i&&n>2,m=n>3,g=Vt(l),y=[{type:12,data:u},{type:12,data:g},{type:12,data:l},{type:1,data:t.epsilon}],w=[{dims:o,dataType:e[0].dataType}];return n>1&&w.push({dims:d,dataType:1}),n>2&&w.push({dims:d,dataType:1}),n>3&&w.push({dims:s,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${g};${p};${f};${m}`,inputDependencies:e.map((e,t)=>"type")},getShaderSource:t=>{let n=[Jt("x",e[0].dataType,e[0].dims,g),Jt("skip",e[1].dataType,e[1].dims,g),Jt("gamma",e[2].dataType,e[2].dims,g)];h&&n.push(Jt("beta",e[3].dataType,e[3].dims,g)),c&&n.push(Jt("bias",e[4].dataType,e[4].dims,g)),n.push(Xt("output",e[0].dataType,o,g)),p&&n.push(Xt("mean_output",1,d)),f&&n.push(Xt("inv_std_output",1,d)),m&&n.push(Xt("input_skip_bias_sum",e[0].dataType,o,g));let i=Ht(e[0].dataType),s=Ht(1,g);return`\n\n ${t.registerUniforms([{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}]).declareVariables(...n)}\n var<workgroup> sum_shared : array<${s}, 64>;\n var<workgroup> sum_squared_shared : array<${s}, 64>;\n\n ${t.mainStart([64,1,1])}\n let ix = local_id.x;\n let iy = global_id.x / 64;\n\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n var stride = hidden_size_vectorized / 64;\n let offset = ix * stride + iy * hidden_size_vectorized;\n let offset1d = stride * ix;\n if (ix == 63) {\n stride = hidden_size_vectorized - stride * ix;\n }\n for (var i: u32 = 0; i < stride; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${c?"bias[offset1d + i]":i+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${m?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${jt(i,g,"value")};\n sum_shared[ix] += f32_value;\n sum_squared_shared[ix] += f32_value * f32_value;\n }\n workgroupBarrier();\n\n var reduce_size : u32 = 64;\n for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {\n reduce_size = curr_size + (reduce_size & 1);\n if (ix < curr_size) {\n sum_shared[ix] += sum_shared[ix + reduce_size];\n sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];\n }\n workgroupBarrier();\n }\n\n let sum = sum_shared[0];\n let square_sum = sum_squared_shared[0];\n let mean = ${Gt("sum",g)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${Gt("square_sum",g)} / f32(uniforms.hidden_size) ${r?"":"- mean * mean"} + uniforms.epsilon);\n ${p?"mean_output[global_idx] = mean;":""}\n ${f?"inv_std_output[global_idx] = inv_std_dev;":""}\n\n for (var i: u32 = 0; i < stride; i++) {\n output[offset + i] = (output[offset + i] ${r?"":`- ${i}(mean)`}) *\n ${i}(inv_std_dev) * gamma[offset1d + i]\n ${h?"+ beta[offset1d + i]":""};\n }\n }`},getRunData:()=>({outputs:w,dispatchGroup:{x:Math.ceil(u/l)},programUniforms:y})}},Su=(e,t)=>{vu(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(xu(e.inputs,t,e.outputCount,!1),{outputs:n})}}),rd=L(()=>{Yu(),nl(),ul(),ll(),Tu=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(0!==t.axes.length){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,n)=>{if(6!==e[n+1].dataType&&7!==e[n+1].dataType)throw new Error(`Input ${n} must be an array of int32 or int64`)})},ku=(e,t)=>{let n=[];if(e.length>t)if(7===e[t].dataType)e[t].getBigInt64Array().forEach(e=>n.push(Number(e)));else{if(6!==e[t].dataType)throw new Error(`Input ${t} must be an array of int32 or int64`);e[t].getInt32Array().forEach(e=>n.push(Number(e)))}return n},Eu=(e,t)=>{if(e.length>1){let t=ku(e,1),n=ku(e,2),i=ku(e,3);return 0===i.length&&(i=[...Array(e[0].dims.length).keys()]),Ut({starts:t,ends:n,axes:i})}return t},Cu=(e,t,n,i,r)=>{let s=e;return e<0&&(s+=n[i[t]]),r[t]<0?Math.max(0,Math.min(s,n[i[t]]-1)):Math.max(0,Math.min(s,n[i[t]]))},Iu=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${n.length-1}; i >= 0; i--) {\n let input_shape_i = ${Kt("uniforms.input_shape","i",n.length)};\n let steps_i = ${Kt("uniforms.steps","i",n.length)};\n let signs_i = ${Kt("uniforms.signs","i",n.length)};\n let starts_i = ${Kt("uniforms.starts","i",n.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,Au=(e,t)=>{let n=e[0].dims,i=ut.size(n),r=t.axes.length>0?ut.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],s=ku(e,4);s.forEach(e=>0!==e||(()=>{throw new Error("step cannot be 0")})),0===s.length&&(s=Array(r.length).fill(1));let a=t.starts.map((e,t)=>Cu(e,t,n,r,s)),o=t.ends.map((e,t)=>Cu(e,t,n,r,s));if(r.length!==a.length||r.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(r.length!==n.length)for(let e=0;e<n.length;++e)r.includes(e)||(a.splice(e,0,0),o.splice(e,0,n[e]),s.splice(e,0,1));let u=s.map(e=>Math.sign(e));s.forEach((e,t,n)=>{if(e<0){let i=(o[t]-a[t])/e,r=a[t],u=r+i*s[t];a[t]=u,o[t]=r,n[t]=-e}});let l=n.slice(0);r.forEach((e,t)=>{l[e]=Math.ceil((o[e]-a[e])/s[e])});let d={dims:l,dataType:e[0].dataType},h=Xt("output",e[0].dataType,l.length),c=Jt("input",e[0].dataType,e[0].dims.length),p=ut.size(l),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:u.length},{name:"steps",type:"u32",length:s.length}],m=[{type:12,data:p},{type:12,data:a},{type:6,data:u},{type:12,data:s},...qt(e[0].dims,l)];return{name:"Slice",shaderCache:{hint:`${u.length}_${a.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:e=>`\n ${e.registerUniforms(f).declareVariables(c,h)}\n ${Iu(c,h,n)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${h.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${h.setByOffset("global_idx",c.getByIndices("input_indices"))}\n }`,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:m})}},Ru=(e,t)=>{Tu(e.inputs,t);let n=Eu(e.inputs,t);e.compute(Au(e.inputs,n),{inputs:[0]})},Mu=e=>{let t=e.starts,n=e.ends,i=e.axes;return Ut({starts:t,ends:n,axes:i})}}),sd=L(()=>{Yu(),nl(),ul(),dl(),ll(),zu=e=>{if(!e||1!==e.length)throw new Error("Softmax op requires 1 input.")},Ou=(e,t)=>{let n,i=e.inputs[0],r=i.dims,s=ut.size(r),a=r.length,o=ut.normalizeAxis(t.axis,a),u=o<r.length-1,l=[];u?(l=Array.from({length:a},(e,t)=>t),l[o]=a-1,l[a-1]=o,n=e.compute(ln(i,l),{inputs:[i],outputs:[-1]})[0]):n=i;let d=n.dims,h=d[a-1],c=s/h,p=Vt(h),f=h/p,m=64;1===c&&(m=256);let g=Jt("x",n.dataType,n.dims,p),y=Xt("result",n.dataType,n.dims,p),w=g.type.value,b="f32"===Ht(n.dataType)?`var threadMax = ${w}(-3.402823e+38f);`:`var threadMax = ${w}(-65504.0h);`,_=e.compute({name:"Softmax",shaderCache:{hint:`${p};${m}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:d,dataType:n.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:f}]}),getShaderSource:e=>`\n var<workgroup> rowMaxShared : ${w};\n var<workgroup> rowSumShared : ${w};\n var<workgroup> threadShared : array<${w}, ${m}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${e.registerUniform("packedCols","i32").declareVariables(g,y)}\n ${e.mainStart(m)}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${m};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${b}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${w}(${((e,t)=>4===t?`max(max(${e}.x, ${e}.y), max(${e}.z, ${e}.w))`:2===t?`max(${e}.x, ${e}.y)`:3===t?`max(max(${e}.x, ${e}.y), ${e}.z)`:e)("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${w}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${w}(${Gt("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n var value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n // max operation protects against NaN since all values should be >=0\n value = max(value, ${w}(0.0));\n setValue(row, col, row_stride, value);\n }\n }`},{inputs:[n],outputs:[u?-1:0]})[0];u&&e.compute(ln(_,l),{inputs:[_]})},Pu=(e,t)=>{zu(e.inputs),Ou(e,t)},Bu=e=>Ut({axis:e.axis})}),ad=L(()=>{Yu(),nl(),ll(),Du=e=>Array.from(e.getBigInt64Array(),Number),Uu=e=>{if(!e||2!==e.length)throw new Error("Tile requires 2 inputs.");if(1!==e[0].dataType&&10!==e[0].dataType&&6!==e[0].dataType&&12!==e[0].dataType)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(7!==e[1].dataType)throw new Error("Tile `repeats` input should be of int64 data type");if(1!==e[1].dims.length)throw new Error("Tile `repeats` input should be 1-D");if(Du(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")},Lu=(e,t)=>{let n=[];for(let i=0;i<e.length;++i)n.push(e[i]*t[i]);return n},Nu=(e,t)=>{let n=e[0].dims,i=t??Du(e[1]),r=Lu(n,i),s=ut.size(r),a=e[0].dataType,o=Jt("input",a,n.length),u=Xt("output",a,r.length);return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},...qt(e[0].dims,r)]}),getShaderSource:e=>`\n const inputShape = ${o.indices(...n)};\n ${e.registerUniform("output_size","u32").declareVariables(o,u)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${u.offsetToIndices("global_idx")};\n var input_indices: ${o.type.indices};\n for (var i = 0; i < ${n.length}; i++) {\n let input_dim_i = ${o.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${u.indicesGet("output_indices","i")} % input_dim_i;\n\n ${o.indicesSet("input_indices","i","input_dim_value")}\n }\n ${u.setByOffset("global_idx",o.getByIndices("input_indices"))}\n }`}},Hu=e=>{Uu(e.inputs),e.compute(Nu(e.inputs),{inputs:[0]})}}),od=L(()=>{Yu(),nl(),ll(),Fu=(e,t,n,i,r)=>{let s,a=Xt("output_data",r,n.length,4),o=Jt("a_data",t[1].dataType,t[1].dims.length,4),u=Jt("b_data",t[2].dataType,t[2].dims.length,4),l=Jt("c_data",t[0].dataType,t[0].dims.length,4),d=(e,t,n)=>`select(${t}, ${e}, ${n})`;if(i){let e=(e,t,n="")=>{let i=`a_data[index_a${t}][component_a${t}]`,r=`b_data[index_b${t}][component_b${t}]`,s=`bool(c_data[index_c${t}] & (0xffu << (component_c${t} * 8)))`;return`\n let output_indices${t} = ${a.offsetToIndices(`global_idx * 4u + ${t}u`)};\n let offset_a${t} = ${o.broadcastedIndicesToOffset(`output_indices${t}`,a)};\n let offset_b${t} = ${u.broadcastedIndicesToOffset(`output_indices${t}`,a)};\n let offset_c${t} = ${l.broadcastedIndicesToOffset(`output_indices${t}`,a)};\n let index_a${t} = offset_a${t} / 4u;\n let index_b${t} = offset_b${t} / 4u;\n let index_c${t} = offset_c${t} / 4u;\n let component_a${t} = offset_a${t} % 4u;\n let component_b${t} = offset_b${t} % 4u;\n let component_c${t} = offset_c${t} % 4u;\n ${e}[${t}] = ${n}(${d(i,r,s)});\n `};s=9===r?`\n var data = vec4<u32>(0);\n ${e("data",0,"u32")}\n ${e("data",1,"u32")}\n ${e("data",2,"u32")}\n ${e("data",3,"u32")}\n output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:`\n ${e("output_data[global_idx]",0)}\n ${e("output_data[global_idx]",1)}\n ${e("output_data[global_idx]",2)}\n ${e("output_data[global_idx]",3)}\n `}else s=a.setByOffset("global_idx",d(o.getByOffset("global_idx"),u.getByOffset("global_idx"),l.getByOffset("global_idx")));return`\n ${e.registerUniform("vec_size","u32").declareVariables(l,o,u,a)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${s}\n }`},qu=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,r=e[1].dataType,s=!(ut.areEqual(t,n)&&ut.areEqual(n,i)),a=t,o=ut.size(t);if(s){let e=ot.calcShape(ot.calcShape(t,n,!1),i,!1);if(!e)throw new Error("Can't perform where op on the given tensors");a=e,o=ut.size(a)}let u=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:t=>Fu(t,e,a,s,r),getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:12,data:u},...qt(i,t,n,a)]})}},Vu=e=>{e.compute(qu(e.inputs))}}),ud=L(()=>{pl(),fl(),ml(),gl(),wl(),bl(),_l(),Il(),Rl(),Ml(),zl(),Ol(),Pl(),Bl(),Dl(),Ul(),Ll(),Nl(),Hl(),Fl(),jl(),Gl(),Kl(),Ql(),Jl(),ql(),Xl(),Zl(),Yl(),ed(),td(),cl(),nd(),Wl(),id(),rd(),sd(),Vl(),ad(),dl(),yl(),od(),Wu=new Map([["Abs",[ki]],["Acos",[Ei]],["Acosh",[Ci]],["Add",[$r]],["ArgMax",[oi,ui]],["ArgMin",[ai,ui]],["Asin",[Ii]],["Asinh",[Ai]],["Atan",[Ri]],["Atanh",[Mi]],["Attention",[gi]],["AveragePool",[Bo,Po]],["BatchNormalization",[_i]],["BiasAdd",[xi]],["BiasSplitGelu",[yr]],["Cast",[Oi,zi]],["Ceil",[Di]],["Clip",[Bi]],["Concat",[Pr,Br]],["Conv",[_s,gs]],["ConvTranspose",[As,ks]],["Cos",[Ui]],["Cosh",[Li]],["CumSum",[Ms,zs]],["DepthToSpace",[Ds,Us]],["DequantizeLinear",[Go,Ko]],["Div",[vr]],["Einsum",[Gs,Ks]],["Elu",[Hi,Ni]],["Equal",[xr]],["Erf",[qi]],["Exp",[Vi]],["Expand",[Ys]],["FastGelu",[ta]],["Floor",[Wi]],["FusedConv",[_s,gs]],["Gather",[sa,ra]],["GatherElements",[ga,ma]],["GatherBlockQuantized",[ha,ca]],["GatherND",[oa,ua]],["Gelu",[ji]],["Gemm",[_a,ba]],["GlobalAveragePool",[Lo,Uo]],["GlobalMaxPool",[Vo,qo]],["Greater",[Er]],["GreaterOrEqual",[Ir]],["GridSample",[Ma,za]],["GroupQueryAttention",[to]],["HardSigmoid",[er,Yi]],["InstanceNormalization",[so]],["LayerNormalization",[uo]],["LeakyRelu",[Gi,Ni]],["Less",[Cr]],["LessOrEqual",[Ar]],["Log",[hr]],["MatMul",[ho]],["MatMulNBits",[mo,go]],["MaxPool",[Ho,Fo]],["Mul",[Sr]],["MultiHeadAttention",[Na,Ba]],["Neg",[Qi]],["Not",[Ki]],["Pad",[To]],["Pow",[Tr]],["QuickGelu",[fr,Ni]],["Range",[Xo]],["Reciprocal",[Ji]],["ReduceMin",[ei]],["ReduceMean",[Qn]],["ReduceMax",[Yn]],["ReduceSum",[ni]],["ReduceProd",[ti]],["ReduceL1",[Jn]],["ReduceL2",[Xn]],["ReduceLogSum",[ri]],["ReduceLogSumExp",[Zn]],["ReduceSumSquare",[ii]],["Relu",[Xi]],["Resize",[_u,$u]],["RotaryEmbedding",[Ja]],["ScatterND",[tu,eu]],["Sigmoid",[Zi]],["Sin",[tr]],["Sinh",[nr]],["Slice",[Ru,Mu]],["SkipLayerNormalization",[Su]],["Split",[ja,Ga]],["Sqrt",[ir]],["Softmax",[Pu,Bu]],["Sub",[kr]],["Tan",[rr]],["Tanh",[ar]],["ThresholdedRelu",[dr,Ni]],["Tile",[Hu]],["Transpose",[dn,hn]],["Where",[Vu]]])}),ld=L(()=>{oe(),tl(),ll(),ju=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,i,r){C(e.programInfo.name);let s=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber);let o=[];for(let e of t)o.push({binding:o.length,resource:{buffer:e.buffer}});for(let e of n)o.push({binding:o.length,resource:{buffer:e.buffer}});r&&o.push({binding:o.length,resource:r});let u=s.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:o,label:e.programInfo.name});if("capturing"===this.backend.sessionStatus){let t={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:u,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(t)}a.setPipeline(e.computePipeline),a.setBindGroup(0,u),a.dispatchWorkgroups(...i),this.backend.writeTimestamp(2*this.backend.pendingDispatchNumber+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||"at-passes"===this.backend.queryType)&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),I(e.programInfo.name)}dispose(){}build(e,t){C(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(e=>{n.features.has(e.feature)&&i.push(`enable ${e.extension};`)});let r=tn(t,this.backend.device.limits),s=e.getShaderSource(r),a=`${i.join("\n")}\n${r.additionalImplementations}\n${s}`,o=n.createShaderModule({code:a,label:e.name});st("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let u=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:e.name});return I(e.name),{programInfo:e,computePipeline:u,uniformVariablesInfo:r.variablesInfo}}normalizeDispatchGroupSize(e){let t="number"==typeof e?e:e.x,n="number"==typeof e?1:e.y||1,i="number"==typeof e?1:e.z||1,r=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=r&&n<=r&&i<=r)return[t,n,i];let s=t*n*i,a=Math.ceil(Math.sqrt(s));if(a>r){if(a=Math.ceil(Math.cbrt(s)),a>r)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}return[a,a,1]}}}),dd={};N(dd,{WebGpuBackend:()=>fd});var hd,cd,pd,fd,md=L(()=>{oe(),Yu(),tl(),il(),ol(),ud(),ld(),hd=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i<e.length;++i){let r=e[i].dataType;switch(t[i]){case"none":n.push("");break;case"type":n.push(`${r}`);break;case"rank":{let t=e[i].dims.length;n.push(`${r};${t}`);break}case"dims":{let t=e[i].dims.join(",");n.push(`${r};${t}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return n.join("|")},cd=(e,t,n)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${hd(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},pd=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},fd=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(null===this.currentKernelId)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,t){this.env=e;let n=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},r=e=>t.features.has(e)&&n.push(e)&&!0;r("chromium-experimental-timestamp-query-inside-passes")||r("timestamp-query"),r("shader-f16"),r("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new pd(t.info||await t.requestAdapterInfo()),this.gpuDataManager=Bt(this),this.programManager=new ju(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,it(e.logLevel,!!e.debug),this.device.onuncapturederror=e=>{e.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${e.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,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(),t={};"at-passes"===this.queryType&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:2*this.pendingDispatchNumber,endOfPassWriteIndex:2*this.pendingDispatchNumber+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;let e;C(),this.endComputePass(),"none"!==this.queryType&&(this.commandEncoder.resolveQuerySet(this.querySet,0,2*this.pendingDispatchNumber,this.queryResolveBuffer,0),e=this.device.createBuffer({size:2*this.pendingDispatchNumber*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,2*this.pendingDispatchNumber*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,"none"!==this.queryType&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let e=0;e<t.length/2;e++){let i=n[e],r=i.kernelId,s=this.kernels.get(r),a=s.kernelType,o=s.kernelName,u=i.programName,l=i.inputTensorViews,d=i.outputTensorViews,h=t[2*e],c=t[2*e+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=h);let p=Number(h-this.queryTimeBase),f=Number(c-this.queryTimeBase);if(!Number.isSafeInteger(p)||!Number.isSafeInteger(f))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:l.map(e=>({dims:e.dims,dataType:We(e.dataType)})),outputsMetadata:d.map(e=>({dims:e.dims,dataType:We(e.dataType)})),kernelId:r,kernelType:a,kernelName:o,programName:u,startTime:p,endTime:f});else{let e="";l.forEach((t,n)=>{e+=`input[${n}]: [${t.dims}] | ${We(t.dataType)}, `});let t="";d.forEach((e,n)=>{t+=`output[${n}]: [${e.dims}] | ${We(e.dataType)}, `}),console.log(`[profiling] kernel "${r}|${a}|${o}|${u}" ${e}${t}start time: ${p} ns, execution time: ${f-p} ns`)}k("GPU",`${u}::${h}::${c}`)}e.unmap(),this.pendingQueries.delete(e)}),I()}run(e,t,n,i,r,s){C(e.name);let a=[];for(let e=0;e<t.length;++e){let n=t[e].data;if(0===n)continue;let i=this.gpuDataManager.get(n);if(!i)throw new Error(`no GPU data for input: ${n}`);a.push(i)}let{outputs:o,dispatchGroup:u,programUniforms:l}=e.getRunData(t),d=0===n.length?o.map((e,t)=>t):n;if(d.length!==o.length)throw new Error(`Output size ${d.length} must be equal to ${o.length}.`);let h,c=[],p=[];for(let e=0;e<o.length;++e){if(!Number.isInteger(d[e])||d[e]<-3||d[e]>=s)throw new Error(`Invalid output index: ${d[e]}`);if(-3===d[e])continue;let t=-1===d[e],n=-2===d[e],a=t||n?r(o[e].dataType,o[e].dims):i(d[e],o[e].dataType,o[e].dims);if(c.push(a),0===a.data)continue;let u=this.gpuDataManager.get(a.data);if(!u)throw new Error(`no GPU data for output: ${a.data}`);if(t&&this.temporaryData.push(u),n){let e=this.kernelPersistentData.get(this.currentKernelId);e||(e=[],this.kernelPersistentData.set(this.currentKernelId,e)),e.push(u)}p.push(u)}if(a.length!==t.length||p.length!==c.length){if(0===p.length)return I(e.name),c;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}if(l){let e=0,t=[];l.forEach(n=>{let i="number"==typeof n.data?[n.data]:n.data;if(0===i.length)return;let r,s,a=10===n.type?2:4;10===n.type?(s=i.length>4?16:i.length>2?8:i.length*a,r=i.length>4?16:a*i.length):(s=i.length<=2?i.length*a:16,r=16),e=Math.ceil(e/s)*s,t.push(e);let o=10===n.type?8:4;e+=i.length>4?Math.ceil(i.length/o)*r:i.length*a});let n=16;e=Math.ceil(e/n)*n;let i=new ArrayBuffer(e);l.forEach((e,n)=>{let r=t[n],s="number"==typeof e.data?[e.data]:e.data;if(6===e.type)new Int32Array(i,r,s.length).set(s);else if(12===e.type)new Uint32Array(i,r,s.length).set(s);else if(10===e.type)new Uint16Array(i,r,s.length).set(s);else{if(1!==e.type)throw new Error(`Unsupported uniform type: ${We(e.type)}`);new Float32Array(i,r,s.length).set(s)}});let r=this.gpuDataManager.create(e,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(r.buffer,0,i,0,e),this.gpuDataManager.release(r.id),h={offset:0,size:e,buffer:r.buffer}}let f=this.programManager.normalizeDispatchGroupSize(u),m=1===f[1]&&1===f[2],g=cd(e,t,m),y=this.programManager.getArtifact(g);if(y||(y=this.programManager.build(e,f),this.programManager.setArtifact(g,y),st("info",()=>`[artifact] key: ${g}, programName: ${e.name}`)),l&&y.uniformVariablesInfo){if(l.length!==y.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${y.uniformVariablesInfo.length}, got ${l.length} in program "${y.programInfo.name}".`);for(let e=0;e<l.length;e++){let t=l[e],n=t.type,i="number"==typeof t.data?1:t.data.length,[r,s]=y.uniformVariablesInfo[e];if(n!==r||i!==s)throw new Error(`Uniform variable ${e} mismatch: expect type ${r} with size ${s}, got type ${n} with size ${i} in program "${y.programInfo.name}".`)}}if(st("info",()=>`[ProgramManager] run "${e.name}" (key=${g}) with ${f[0]}x${f[1]}x${f[2]}`),"none"!==this.queryType||"capturing"===this.sessionStatus){let e={kernelId:this.currentKernelId,programName:y.programInfo.name,inputTensorViews:t,outputTensorViews:c};this.pendingKernels.push(e),"capturing"===this.sessionStatus&&this.capturedPendingKernels.get(this.currentSessionId).push(e)}return this.programManager.run(y,a,p,f,h),I(e.name),c}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,i){let r=Wu.get(e);if(!r)throw new Error(`kernel not implemented: ${e}`);let s={kernelType:e,kernelName:i,kernelEntry:r[0],attributes:[r[1],n]};this.kernels.set(t,s)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let e of t)this.gpuDataManager.release(e.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let r=i.kernelType,s=i.kernelName,a=i.kernelEntry,o=i.attributes;if(null!==this.currentKernelId)throw new Error(`kernel "[${r}] ${s}" is not allowed to be called recursively`);this.currentKernelId=e,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),st("info",()=>`[WebGPU] Start to run kernel "[${r}] ${s}"...`);let u=this.env.debug;this.temporaryData=[];try{return u&&this.device.pushErrorScope("validation"),a(t,o[1]),0}catch(e){return n.push(Promise.resolve(`[WebGPU] Kernel "[${r}] ${s}" failed. ${e}`)),1}finally{u&&n.push(this.device.popErrorScope().then(e=>e?`GPU validation error for kernel "[${r}] ${s}": ${e.message}`:null));for(let e of this.temporaryData)this.gpuDataManager.release(e.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let r=this.sessionExternalDataMapping.get(e);r||(r=new Map,this.sessionExternalDataMapping.set(e,r));let s=r.get(t),a=this.gpuDataManager.registerExternalBuffer(n,i,s);return r.set(t,[a,n]),a}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(e=>this.gpuDataManager.unregisterExternalBuffer(e[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Ot(this,e,t);return pt(i.buffer,n)}}writeTimestamp(e){"inside-passes"===this.queryType&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",("default"===this.env.webgpu.profiling?.mode||(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"),"none"!==this.queryType&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2*this.maxDispatchNumber}),this.queryResolveBuffer=this.device.createBuffer({size:2*this.maxDispatchNumber*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){st("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){st("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){st("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i<n;i++){let n=this.getComputePassEncoder(),r=e[i];this.writeTimestamp(2*this.pendingDispatchNumber),n.setPipeline(r.computePipeline),n.setBindGroup(0,r.bindGroup),n.dispatchWorkgroups(...r.dispatchGroup),this.writeTimestamp(2*this.pendingDispatchNumber+1),this.pendingDispatchNumber++,"none"!==this.queryType&&this.pendingKernels.push(t[i]),(this.pendingDispatchNumber>=this.maxDispatchNumber||"at-passes"===this.queryType)&&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()}}}),gd={};N(gd,{init:()=>bd});var yd,wd,bd,_d,$d,vd,xd,Sd,Td,kd,Ed,Cd,Id,Ad,Rd,Md,zd,Od,Pd,Bd,Dd,Ud,Ld,Nd,Hd,Fd,qd,Vd,Wd,jd,Gd,Kd,Qd,Jd,Xd,Zd,Yd,eh=L(()=>{Yu(),tl(),nl(),sl(),yd=class e{constructor(e,t,n,i){this.module=e,this.dataType=t,this.data=n,this.dims=i}getFloat32Array(){if(1!==this.dataType)throw new Error("Invalid data type");let e=ut.size(this.dims);return 0===e?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(7!==this.dataType)throw new Error("Invalid data type");let e=ut.size(this.dims);return 0===e?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(6!==this.dataType)throw new Error("Invalid data type");let e=ut.size(this.dims);return 0===e?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(10!==this.dataType&&4!==this.dataType)throw new Error("Invalid data type");let e=ut.size(this.dims);return 0===e?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(t){if(ut.size(t)!==ut.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},wd=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,r=n/e.PTR_SIZE,s=4===i?"i32":"i64";this.opKernelContext=Number(e.getValue(i*r++,s));let a=Number(e.getValue(i*r++,s));this.outputCount=Number(e.getValue(i*r++,s)),this.customDataOffset=Number(e.getValue(i*r++,"*")),this.customDataSize=Number(e.getValue(i*r++,s));let o=[];for(let t=0;t<a;t++){let t=Number(e.getValue(i*r++,s)),n=Number(e.getValue(i*r++,"*")),a=Number(e.getValue(i*r++,s)),u=[];for(let t=0;t<a;t++)u.push(Number(e.getValue(i*r++,s)));o.push(new yd(e,t,n,u))}this.inputs=o}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let n=t?.inputs?.map(e=>"number"==typeof e?this.inputs[e]:e)??this.inputs,i=t?.outputs??[];return this.backend.run(e,n,i,(e,t,n)=>new yd(this.module,t,this.output(e,n),n),(e,t)=>{let n=je(e,t);if(!n)throw new Error(`Unsupported data type: ${e}`);let i=n>0?this.backend.gpuDataManager.create(n).id:0;return new yd(this.module,e,i,t)},this.outputCount)}output(e,t){let n=this.module.stackSave();try{let n=this.module.PTR_SIZE,i=4===n?"i32":"i64",r=this.module.stackAlloc((1+t.length)*n);this.module.setValue(r,t.length,i);for(let e=0;e<t.length;e++)this.module.setValue(r+n*(e+1),t[e],i);return this.module._JsepOutput(this.opKernelContext,e,r)}catch(n){throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${n}`)}finally{this.module.stackRestore(n)}}},bd=async(e,t,n,i)=>{let r=t.jsepInit;if(!r)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if("webgpu"===e){let e=new(0,(md(),H(dd)).WebGpuBackend);await e.initialize(n,i),r("webgpu",[e,t=>e.alloc(Number(t)),t=>e.free(t),(n,i,r,s=!1)=>{if(s)st("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(n)}, dst=${Number(i)}, size=${Number(r)}`),e.memcpy(Number(n),Number(i));else{st("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(n)}, gpuDataId=${Number(i)}, size=${Number(r)}`);let s=t.HEAPU8.subarray(Number(n>>>0),Number(n>>>0)+Number(r));e.upload(Number(i),s)}},async(n,i,r)=>{st("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${n}, dataOffset=${i}, size=${r}`),await e.download(Number(n),()=>t.HEAPU8.subarray(Number(i)>>>0,Number(i+r)>>>0))},(n,i,r)=>e.createKernel(n,Number(i),r,t.UTF8ToString(t._JsepGetNodeName(Number(i)))),t=>e.releaseKernel(t),(n,i,r,s)=>{st("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${n}, contextDataOffset=${i}`);let a=new wd(t,e,Number(i));return e.computeKernel(Number(n),a,s)},()=>e.captureBegin(),()=>e.captureEnd(),()=>e.replay()])}else{let e=new Et(n);r("webnn",[e,()=>e.reserveTensorId(),t=>e.releaseTensorId(t),async(t,n,i,r,s)=>e.ensureTensor(t,n,i,r,s),(t,n)=>{e.uploadTensor(t,n)},async(t,n)=>e.downloadTensor(t,n),(t,n)=>e.registerMLContext(t,n),!!n.trace])}}}),th=L(()=>{oe(),Xu(),Zu(),Yu(),Qu(),Ju(),el(),_d=(e,t)=>{0!==ze()._OrtInit(e,t)&&Be("Can't initialize onnxruntime.")},$d=async e=>{_d(e.wasm.numThreads,Ke(e.logLevel))},vd=async(e,t)=>{ze().asyncInit?.();let n=e.webgpu.adapter;if("webgpu"===t){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if("object"!=typeof n.limits||"object"!=typeof n.features||"function"!=typeof n.requestDevice)throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(void 0!==t&&"low-power"!==t&&"high-performance"!==t)throw new Error(`Invalid powerPreference setting: "${t}"`);let i=e.webgpu.forceFallbackAdapter;if(void 0!==i&&"boolean"!=typeof i)throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if("webnn"===t&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(eh(),H(gd)).init;"webgpu"===t&&await i("webgpu",ze(),e,n),"webnn"===t&&await i("webnn",ze(),e)}},xd=new Map,Sd=e=>{let t=ze(),n=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);0!==t._OrtGetInputOutputCount(e,i,i+n)&&Be("Can't get session input/output count.");let r=4===n?"i32":"i64";return[Number(t.getValue(i,r)),Number(t.getValue(i+n,r))]}finally{t.stackRestore(n)}},Td=(e,t)=>{let n=ze(),i=n.stackSave(),r=0;try{let i=n.PTR_SIZE,s=n.stackAlloc(2*i);0!==n._OrtGetInputOutputMetadata(e,t,s,s+i)&&Be("Can't get session input/output metadata.");let a=Number(n.getValue(s,"*"));r=Number(n.getValue(s+i,"*"));let o=n.HEAP32[r/4];if(0===o)return[a,0];let u=n.HEAPU32[r/4+1],l=[];for(let e=0;e<u;e++){let t=Number(n.getValue(r+8+e*i,"*"));l.push(0!==t?n.UTF8ToString(t):Number(n.getValue(r+8+(e+u)*i,"*")))}return[a,o,l]}finally{n.stackRestore(i),0!==r&&n._OrtFree(r)}},kd=e=>{let t=ze(),n=t._malloc(e.byteLength);if(0===n)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Ed=async(e,t)=>{let n,i,r=ze();Array.isArray(e)?[n,i]=e:e.buffer===r.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=kd(e);let s=0,a=0,o=0,u=[],l=[],d=[];try{if([a,u]=await qe(t),t?.externalData&&r.mountExternalData){let e=[];for(let n of t.externalData){let t="string"==typeof n?n:n.path;e.push(Ze("string"==typeof n?n:n.data).then(e=>{r.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if("webnn"===("string"==typeof e?e:e.name)){if(r.shouldTransferToMLTensor=!1,"string"!=typeof e){let t=e,n=t?.context,i=t?.gpuDevice,s=t?.deviceType,a=t?.powerPreference;r.currentContext=n||(i?await r.webnnCreateMLContext(i):await r.webnnCreateMLContext({deviceType:s,powerPreference:a}))}else r.currentContext=await r.webnnCreateMLContext();break}s=await r._OrtCreateSession(n,i,a),r.webgpuOnCreateSession?.(s),0===s&&Be("Can't create a session."),r.jsepOnCreateSession?.(),r.currentContext&&(r.webnnRegisterMLContext(s,r.currentContext),r.currentContext=void 0,r.shouldTransferToMLTensor=!0);let[e,h]=Sd(s),c=!!t?.enableGraphCapture,p=[],f=[],m=[],g=[],y=[];for(let t=0;t<e;t++){let[e,n,i]=Td(s,t);0===e&&Be("Can't get an input name."),l.push(e);let a=r.UTF8ToString(e);p.push(a),m.push(0===n?{name:a,isTensor:!1}:{name:a,isTensor:!0,type:We(n),shape:i})}for(let n=0;n<h;n++){let[i,a,o]=Td(s,n+e);0===i&&Be("Can't get an output name."),d.push(i);let u=r.UTF8ToString(i);f.push(u),g.push(0===a?{name:u,isTensor:!1}:{name:u,isTensor:!0,type:We(a),shape:o});{if(c&&void 0===t?.preferredOutputLocation){y.push("gpu-buffer");continue}let e="string"==typeof t?.preferredOutputLocation?t.preferredOutputLocation:t?.preferredOutputLocation?.[u]??"cpu",n=r.webnnIsGraphOutput;if("cpu"===e&&n&&n(s,u)){y.push("ml-tensor-cpu-output");continue}if("cpu"!==e&&"cpu-pinned"!==e&&"gpu-buffer"!==e&&"ml-tensor"!==e)throw new Error(`Not supported preferred output location: ${e}.`);if(c&&"gpu-buffer"!==e)throw new Error(`Not supported preferred output location: ${e}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);y.push(e)}}let w=null;return y.some(e=>"gpu-buffer"===e||"ml-tensor"===e||"ml-tensor-cpu-output"===e)&&(o=r._OrtCreateBinding(s),0===o&&Be("Can't create IO binding."),w={handle:o,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(e=>"ml-tensor-cpu-output"===e?"ml-tensor":e).map(e=>Xe(e))}),xd.set(s,[s,l,d,w,c,!1]),[s,p,f,m,g]}catch(e){throw l.forEach(e=>r._OrtFree(e)),d.forEach(e=>r._OrtFree(e)),0!==o&&0!==r._OrtReleaseBinding(o)&&Be("Can't release IO binding."),0!==s&&0!==r._OrtReleaseSession(s)&&Be("Can't release session."),e}finally{r._free(n),0!==a&&0!==r._OrtReleaseSessionOptions(a)&&Be("Can't release session options."),u.forEach(e=>r._free(e)),r.unmountExternalData?.()}},Cd=e=>{let t=ze(),n=xd.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,r,s,a,o]=n;a&&(o&&0!==t._OrtClearBoundOutputs(a.handle)&&Be("Can't clear bound outputs."),0!==t._OrtReleaseBinding(a.handle)&&Be("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),r.forEach(e=>t._OrtFree(e)),s.forEach(e=>t._OrtFree(e)),0!==t._OrtReleaseSession(i)&&Be("Can't release session."),xd.delete(e)},Id=async(e,t,n,i,r,s,a=!1)=>{if(!e)return void t.push(0);let o,u,l=ze(),d=l.PTR_SIZE,h=e[0],c=e[1],p=e[3],f=p;if("string"===h&&("gpu-buffer"===p||"ml-tensor"===p))throw new Error("String tensor is not supported on GPU.");if(a&&"gpu-buffer"!==p)throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if("gpu-buffer"===p){let t=e[2].gpuBuffer;u=je(Ve(h),c);{let e=l.jsepRegisterBuffer;if(!e)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');o=e(i,s,t,u)}}else if("ml-tensor"===p){let t=e[2].mlTensor;u=je(Ve(h),c);let n=l.webnnRegisterMLTensor;if(!n)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');o=n(i,t,Ve(h),c)}else{let t=e[2];if(Array.isArray(t)){u=d*t.length,o=l._malloc(u),n.push(o);for(let e=0;e<t.length;e++){if("string"!=typeof t[e])throw new TypeError(`tensor data at index ${e} is not a string`);l.setValue(o+e*d,Oe(t[e],n),"*")}}else{let e=l.webnnIsGraphInput,s=l.webnnIsGraphOutput;if("string"!==h&&e&&s){let a=l.UTF8ToString(r);if(e(i,a)||s(i,a)){let e=Ve(h);u=je(e,c),f="ml-tensor";let n=l.webnnCreateTemporaryTensor,r=l.webnnUploadTensor;if(!n||!r)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let s=await n(i,e,c);r(s,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),o=s}else u=t.byteLength,o=l._malloc(u),n.push(o),l.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,u),o)}else u=t.byteLength,o=l._malloc(u),n.push(o),l.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,u),o)}}let m=l.stackSave(),g=l.stackAlloc(4*c.length);try{c.forEach((e,t)=>l.setValue(g+t*d,e,4===d?"i32":"i64"));let e=l._OrtCreateTensor(Ve(h),o,u,g,c.length,Xe(f));0===e&&Be(`Can't create tensor for input/output. session=${i}, index=${s}.`),t.push(e)}finally{l.stackRestore(m)}},Ad=async(e,t,n,i,r,s)=>{let a=ze(),o=a.PTR_SIZE,u=xd.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let l=u[0],d=u[1],h=u[2],c=u[3],p=u[4],f=u[5],m=t.length,g=i.length,y=0,w=[],b=[],_=[],$=[],v=a.stackSave(),x=a.stackAlloc(m*o),S=a.stackAlloc(m*o),T=a.stackAlloc(g*o),k=a.stackAlloc(g*o);try{[y,w]=De(s),A("wasm prepareInputOutputTensor");for(let i=0;i<m;i++)await Id(n[i],b,$,e,d[t[i]],t[i],p);for(let t=0;t<g;t++)await Id(r[t],_,$,e,h[i[t]],m+i[t],p);R("wasm prepareInputOutputTensor");for(let e=0;e<m;e++)a.setValue(x+e*o,b[e],"*"),a.setValue(S+e*o,d[t[e]],"*");for(let e=0;e<g;e++)a.setValue(T+e*o,_[e],"*"),a.setValue(k+e*o,h[i[e]],"*");if(c&&!f){let{handle:n,outputPreferredLocations:s,outputPreferredLocationsEncoded:o}=c;if(d.length!==m)throw new Error(`input count from feeds (${m}) is expected to be always equal to model's input count (${d.length}).`);A("wasm bindInputsOutputs");for(let i=0;i<m;i++){let r=t[i];0!==await a._OrtBindInput(n,d[r],b[i])&&Be(`Can't bind input[${i}] for session=${e}.`)}for(let t=0;t<g;t++){let u=i[t];r[t]?.[3]?0!==a._OrtBindOutput(n,h[u],_[t],0)&&Be(`Can't bind pre-allocated output[${t}] for session=${e}.`):0!==a._OrtBindOutput(n,h[u],0,o[u])&&Be(`Can't bind output[${t}] to ${s[t]} for session=${e}.`)}R("wasm bindInputsOutputs"),xd.set(e,[l,d,h,c,p,!0])}let u;a.jsepOnRunStart?.(l),a.webnnOnRunStart?.(l),u=c?await a._OrtRunWithBinding(l,c.handle,g,T,y):await a._OrtRun(l,S,x,m,k,g,T,y),0!==u&&Be("failed to call OrtRun().");let v=[],E=[];A("wasm ProcessOutputTensor");for(let t=0;t<g;t++){let n=Number(a.getValue(T+t*o,"*"));if(n===_[t]){v.push(r[t]);continue}let s,u=a.stackSave(),l=a.stackAlloc(4*o),d=!1,h=0;try{0!==a._OrtGetTensorData(n,l,l+o,l+2*o,l+3*o)&&Be(`Can't access output tensor data on index ${t}.`);let r=4===o?"i32":"i64",u=Number(a.getValue(l,r));h=a.getValue(l+o,"*");let p=a.getValue(l+2*o,"*"),f=Number(a.getValue(l+3*o,r)),m=[];for(let e=0;e<f;e++)m.push(Number(a.getValue(p+e*o,r)));0!==a._OrtFree(p)&&Be("Can't free memory for tensor dims.");let g=m.reduce((e,t)=>e*t,1);s=We(u);let y=c?.outputPreferredLocations[i[t]];if("string"===s){if("gpu-buffer"===y||"ml-tensor"===y)throw new Error("String tensor is not supported on GPU.");let e=[];for(let t=0;t<g;t++){let n=a.getValue(h+t*o,"*"),i=a.getValue(h+(t+1)*o,"*"),r=t===g-1?void 0:i-n;e.push(a.UTF8ToString(n,r))}v.push([s,m,e,"cpu"])}else if("gpu-buffer"===y&&g>0){let e=a.jsepGetBuffer;if(!e)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let t=e(h),i=je(u,g);if(void 0===i||!Qe(s))throw new Error(`Unsupported data type: ${s}`);d=!0,v.push([s,m,{gpuBuffer:t,download:a.jsepCreateDownloader(t,i,s),dispose:()=>{0!==a._OrtReleaseTensor(n)&&Be("Can't release tensor.")}},"gpu-buffer"])}else if("ml-tensor"===y&&g>0){let t=a.webnnEnsureTensor,i=a.webnnIsGraphInputOutputTypeSupported;if(!t||!i)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(void 0===je(u,g)||!Je(s))throw new Error(`Unsupported data type: ${s}`);if(!i(e,s,!1))throw new Error(`preferredLocation "ml-tensor" for ${s} output is not supported by current WebNN Context.`);let r=await t(e,h,u,m,!1);d=!0,v.push([s,m,{mlTensor:r,download:a.webnnCreateMLTensorDownloader(h,s),dispose:()=>{a.webnnReleaseTensorId(h),a._OrtReleaseTensor(n)}},"ml-tensor"])}else if("ml-tensor-cpu-output"===y&&g>0){let e=a.webnnCreateMLTensorDownloader(h,s)(),t=v.length;d=!0,E.push((async()=>{let i=[t,await e];return a.webnnReleaseTensorId(h),a._OrtReleaseTensor(n),i})()),v.push([s,m,[],"cpu"])}else{let e=new(Ge(s))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(a.HEAPU8.subarray(h,h+e.byteLength)),v.push([s,m,e,"cpu"])}}finally{a.stackRestore(u),"string"===s&&h&&a._free(h),d||a._OrtReleaseTensor(n)}}c&&!p&&(0!==a._OrtClearBoundOutputs(c.handle)&&Be("Can't clear bound outputs."),xd.set(e,[l,d,h,c,p,!1]));for(let[e,t]of await Promise.all(E))v[e][2]=t;return R("wasm ProcessOutputTensor"),v}finally{a.webnnOnRunEnd?.(l),a.stackRestore(v),b.forEach(e=>a._OrtReleaseTensor(e)),_.forEach(e=>a._OrtReleaseTensor(e)),$.forEach(e=>a._free(e)),0!==y&&a._OrtReleaseRunOptions(y),w.forEach(e=>a._free(e))}},Rd=e=>{let t=ze(),n=xd.get(e);if(!n)throw new Error("invalid session id");let i=n[0],r=t._OrtEndProfiling(i);0===r&&Be("Can't get an profile file name."),t._OrtFree(r)},Md=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&"buffer"in e&&t.push(e.buffer)}return t}}),nh=L(()=>{oe(),th(),Qu(),Ku(),zd=()=>!!l.wasm.proxy&&typeof document<"u",Pd=!1,Bd=!1,Dd=!1,Nd=new Map,Hd=(e,t)=>{let n=Nd.get(e);n?n.push(t):Nd.set(e,[t])},Fd=()=>{if(Pd||!Bd||Dd||!Od)throw new Error("worker not ready")},qd=e=>{switch(e.data.type){case"init-wasm":Pd=!1,e.data.err?(Dd=!0,Ld[1](e.data.err)):(Bd=!0,Ld[0]()),Ud&&(URL.revokeObjectURL(Ud),Ud=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Nd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Vd=async()=>{if(!Bd){if(Pd)throw new Error("multiple calls to 'initWasm()' detected.");if(Dd)throw new Error("previous call to 'initWasm()' failed.");if(Pd=!0,zd())return new Promise((e,t)=>{Od?.terminate(),ve().then(([n,i])=>{try{(Od=i).onerror=e=>t(e),Od.onmessage=qd,Ld=[e,t];let r={type:"init-wasm",in:l};if(!r.in.wasm.wasmPaths&&n){let e=me();e&&(r.in.wasm.wasmPaths=e)}Od.postMessage(r),Ud=n}catch(e){t(e)}},t)});try{await Me(l.wasm),await $d(l),Bd=!0}catch(e){throw Dd=!0,e}finally{Pd=!1}}},Wd=async e=>{if(zd())return Fd(),new Promise((t,n)=>{Hd("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:l}};Od.postMessage(i)});await vd(l,e)},jd=async e=>zd()?(Fd(),new Promise((t,n)=>{Hd("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};Od.postMessage(i,[e.buffer])})):kd(e),Gd=async(e,t)=>{if(zd()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Fd(),new Promise((n,i)=>{Hd("create",[n,i]);let r={type:"create",in:{model:e,options:{...t}}},s=[];e instanceof Uint8Array&&s.push(e.buffer),Od.postMessage(r,s)})}return Ed(e,t)},Kd=async e=>{if(zd())return Fd(),new Promise((t,n)=>{Hd("release",[t,n]);let i={type:"release",in:e};Od.postMessage(i)});Cd(e)},Qd=async(e,t,n,i,r,s)=>{if(zd()){if(n.some(e=>"cpu"!==e[3]))throw new Error("input tensor on GPU is not supported for proxy.");if(r.some(e=>e))throw new Error("pre-allocated output tensor is not supported for proxy.");return Fd(),new Promise((r,a)=>{Hd("run",[r,a]);let o=n,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:o,outputIndices:i,options:s}};Od.postMessage(u,Md(o))})}return Ad(e,t,n,i,r,s)},Jd=async e=>{if(zd())return Fd(),new Promise((t,n)=>{Hd("end-profiling",[t,n]);let i={type:"end-profiling",in:e};Od.postMessage(i)});Rd(e)}}),ih=L(()=>{oe(),nh(),Yu(),ue(),el(),Xd=(e,t)=>{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 ${t()}`)}},Zd=e=>{switch(e[3]){case"cpu":return new T(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Qe(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:r}=e[2];return T.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:r})}case"ml-tensor":{let t=e[0];if(!Je(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:r}=e[2];return T.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:r})}default:throw new Error(`invalid data location: ${e[3]}`)}},Yd=class{async fetchModelAndCopyToWasmMemory(e){return jd(await Ze(e))}async loadModel(e,t){let n;C(),n="string"==typeof e?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Gd(n,t),I()}async dispose(){return Kd(this.sessionId)}async run(e,t,n){C();let i=[],r=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],s=this.inputNames.indexOf(t);if(-1===s)throw new Error(`invalid input '${t}'`);i.push(n),r.push(s)});let s=[],a=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],i=this.outputNames.indexOf(t);if(-1===i)throw new Error(`invalid output '${t}'`);s.push(n),a.push(i)});let o=i.map((e,t)=>Xd(e,()=>`input "${this.inputNames[r[t]]}"`)),u=s.map((e,t)=>e?Xd(e,()=>`output "${this.outputNames[a[t]]}"`):null),l=await Qd(this.sessionId,r,o,a,u,n),d={};for(let e=0;e<l.length;e++)d[this.outputNames[a[e]]]=s[e]??Zd(l[e]);return I(),d}startProfiling(){}endProfiling(){Jd(this.sessionId)}}}),rh={};N(rh,{OnnxruntimeWebAssemblyBackend:()=>ah,initializeFlags:()=>sh,wasmBackend:()=>oh});var sh,ah,oh,uh=L(()=>{oe(),nh(),ih(),sh=()=>{("number"!=typeof l.wasm.initTimeout||l.wasm.initTimeout<0)&&(l.wasm.initTimeout=0);let e=l.wasm.simd;if("boolean"!=typeof e&&void 0!==e&&"fixed"!==e&&"relaxed"!==e&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),l.wasm.simd=!1),"boolean"!=typeof l.wasm.proxy&&(l.wasm.proxy=!1),"boolean"!=typeof l.wasm.trace&&(l.wasm.trace=!1),"number"!=typeof l.wasm.numThreads||!Number.isInteger(l.wasm.numThreads)||l.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)l.wasm.numThreads=1;else{let e=typeof navigator>"u"?U("node:os").cpus().length:navigator.hardwareConcurrency;l.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},ah=class{async init(e){sh(),await Vd(),await Wd(e)}async createInferenceSessionHandler(e,t){let n=new Yd;return await n.loadModel(e,t),n}},oh=new ah}),lh={};N(lh,{InferenceSession:()=>z,TRACE:()=>k,TRACE_EVENT_BEGIN:()=>A,TRACE_EVENT_END:()=>R,TRACE_FUNC_BEGIN:()=>C,TRACE_FUNC_END:()=>I,Tensor:()=>T,default:()=>dh,env:()=>l,registerBackend:()=>i}),oe(),oe(),oe();var dh=ae;{let e=(uh(),H(rh)).wasmBackend;i("webgpu",e,5),i("webnn",e,5),i("cpu",e,10),i("wasm",e,10)}return Object.defineProperty(l.versions,"web",{value:"1.23.2",enumerable:!0}),H(lh)})();e.exports=i},685:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.MicVAD=t.getDefaultRealTimeVADOptions=t.ort=t.DEFAULT_MODEL=void 0;const a=s(n(593)),o=n(378),u=n(457),l=n(832),d=n(33),h=n(28),c=n(702);t.DEFAULT_MODEL="legacy",t.ort=a,t.getDefaultRealTimeVADOptions=e=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:e,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async e=>{e.getTracks().forEach(e=>{e.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:e=>{e.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});class p{constructor(e,t,n,i,r=!1,s=null,a=null,o=null,u=null,h=null,p=null,f="uninitialized",m=!1){this.options=e,this.frameProcessor=t,this.model=n,this.frameSamples=i,this.listening=r,this.errored=s,this._stream=a,this._audioContext=o,this._vadNode=u,this._mediaStreamAudioSourceNode=h,this._audioProcessorAdapterType=p,this.initializationState=f,this.ownsAudioContext=m,this.getAudioInstances=()=>{if(null===this._stream||null===this._audioContext||null==this._vadNode||null==this._mediaStreamAudioSourceNode)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=e=>{this.initializationState="errored",this.errored=e},this.start=async()=>{switch(this.initializationState){case"uninitialized":l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(e){throw e instanceof Error?this.setErrored(e.message):this.setErrored(String(e)),e}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType="auto"==this.options.processorType?"audioWorklet"in this._audioContext&&"function"==typeof AudioWorkletNode?"AudioWorklet":"ScriptProcessor":this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await async function(e,t,n,i,r){await n.audioWorklet.addModule(e),t.processorOptions={...t.processorOptions??{},frameSamples:i};const s=new AudioWorkletNode(n,"vad-helper-worklet",t);return s.port.onmessage=async e=>{const t=e.data;if("object"==typeof t&&t&&"message"in t)switch(t.message){case d.Message.AudioFrame:{if(!("data"in t&&t.data instanceof ArrayBuffer))return void console.log("Audio frame message has no data");const e=new Float32Array(t.data);await r(e);break}}else console.error("Invalid message event",t)},s}(this.options.baseAssetPath+"vad.worklet.bundle.min.js",this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await async function(e,t,n){const i=new c.Resampler({nativeSampleRate:e.sampleRate,targetSampleRate:16e3,targetFrameSize:t});l.log.debug("using script processor");const r=e.createScriptProcessor(4096,1,1);let s=!1;return r.onaudioprocess=async e=>{if(!s){s=!0;try{const t=e.inputBuffer.getChannelData(0);e.outputBuffer.getChannelData(0).fill(0);const r=i.process(t);for(const e of r)await n(e)}catch(e){console.error("Error processing audio:",e)}finally{s=!1}}},r.connect(e.destination),r}(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break;case"initializing":l.log.warn("start called while initializing");break;case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:e,audioContext:t,vadNode:n}=this.getAudioInstances();this._stream=await this.options.resumeStream(e);const i=new MediaStreamAudioSourceNode(t,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=i,i.connect(n);break}case"destroyed":l.log.warn("start called after destroyed");break;case"errored":l.log.error("start called after errored");break;default:l.log.warn("weird initialization state")}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:e,mediaStreamAudioSourceNode:t}=this.getAudioInstances();await this.options.pauseStream(e),t.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:e}=this.getAudioInstances();e instanceof AudioWorkletNode&&e.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await(this._audioContext?.close())},this.setOptions=e=>{this.frameProcessor.setOptions(e)},this.processFrame=async e=>{await this.frameProcessor.process(e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=e=>{switch(e.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(e.probs,e.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(e.audio)}}}static async new(e={}){const n={...(0,t.getDefaultRealTimeVADOptions)(e.model??t.DEFAULT_MODEL),...e};(0,u.validateOptions)(n),t.ort.env.wasm.wasmPaths=n.onnxWASMBasePath,void 0!==n.ortConfig&&n.ortConfig(t.ort);const i="v5"===n.model?"silero_vad_v5.onnx":"silero_vad_legacy.onnx",r=n.baseAssetPath+i,s="v5"===n.model?h.SileroV5.new:h.SileroLegacy.new;let a;try{a=await s(t.ort,()=>(0,o.defaultModelFetcher)(r))}catch(e){throw console.error(`Encountered an error while loading model file ${r}`),e}const l="v5"===n.model?512:1536,d=l/16,c=new u.FrameProcessor(a.process,a.reset_state,{positiveSpeechThreshold:n.positiveSpeechThreshold,negativeSpeechThreshold:n.negativeSpeechThreshold,redemptionMs:n.redemptionMs,preSpeechPadMs:n.preSpeechPadMs,minSpeechMs:n.minSpeechMs,submitUserSpeechOnPause:n.submitUserSpeechOnPause},d),f=new p(n,c,a,l);if(n.startOnLoad)try{await f.start()}catch(e){throw console.error("Error starting micVad",e),e}return f}}t.MicVAD=p},687:e=>{function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=687,e.exports=t},702:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Resampler=void 0;const i=n(832);t.Resampler=class{constructor(e){this.options=e,this.process=e=>{const t=[];for(const n of e)for(this.inputBuffer.push(n);this.hasEnoughDataForFrame();){const e=this.generateOutputFrame();t.push(e)}return t},e.nativeSampleRate<16e3&&i.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(e){for(const t of e)for(this.inputBuffer.push(t);this.hasEnoughDataForFrame();){const e=this.generateOutputFrame();yield e}}hasEnoughDataForFrame(){return this.inputBuffer.length*this.options.targetSampleRate/this.options.nativeSampleRate>=this.options.targetFrameSize}generateOutputFrame(){const e=new Float32Array(this.options.targetFrameSize);let t=0,n=0;for(;t<this.options.targetFrameSize;){let i=0,r=0;for(;n<Math.min(this.inputBuffer.length,(t+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const e=this.inputBuffer[n];void 0!==e&&(i+=e,r++),n++}e[t]=i/r,t++}return this.inputBuffer=this.inputBuffer.slice(n),e}}},832:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.log=void 0;const n=e=>t=>{console.log(`VAD | ${e} >`,t)};t.log={error:n("error"),debug:n("debug"),warn:n("warn")}},937:(e,t,n)=>{t.Jl=void 0;n(61),n(378),n(457),n(33),n(587);const i=n(20);i.audioFileToArray,i.minFramesForTargetMS,i.arrayBufferToBase64,i.encodeWAV;var r=n(685);Object.defineProperty(t,"Jl",{enumerable:!0,get:function(){return r.MicVAD}})}},t={};function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};n.r(i),n.d(i,{hasBrowserEnv:()=>st,hasStandardBrowserEnv:()=>ot,hasStandardBrowserWebWorkerEnv:()=>ut,navigator:()=>at,origin:()=>lt});const r="color: #ff9800; font-weight: bold; font-size: larger",s="color: #ab47bc; font-weight: bold; font-size: larger",a="color: #795548; font-weight: bold; font-size: larger";class o{category;style;constructor(e){this.category=e?.category,this.style=e?.style||"color: #2196f3; font-weight: bold; font-size: larger"}getTimestamp(){const e=new Date,t=(e,t=2)=>e.toString().padStart(t,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}log(e,t,...n){const i=this.getTimestamp();let r=t;const s=n.filter(e=>void 0!==e).map(e=>{if("object"==typeof e&&null!==e)try{return JSON.stringify(e,null,2)}catch(e){return"[Unserializable Object]"}return e});if(this.category){r.startsWith(`[${this.category}]`)||(r=`[${this.category}] ${r}`);const t=r.match(/^[[][^[\]]+[\]]\s?(.*)$/);if(t){const n=`%c${i} %c[${this.category}]%c ${t[1]}`,r="color: #888; font-size: smaller;",a="color: inherit;";return void(s.length>0?console[e](n,r,this.style,a,...s):console[e](n,r,this.style,a))}}s.length>0?console[e](`${i} ${r}`,...s):console[e](`${i} ${r}`)}info(e,...t){this.log("info",e,...t)}trace(e,...t){this.log("trace",e,...t)}debug(e,...t){this.log("debug",e,...t)}warn(e,...t){this.log("warn",e,...t)}error(e,...t){this.log("error",e,...t)}}class u{eventListeners=new Map;logger;constructor(e){this.logger=e}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){const n=this.eventListeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}async emit(e,t){const n=this.eventListeners.get(e)||[];if(this.logger){const n=this.sanitizeForLogging(t);this.logger.debug(`Emitting event: ${String(e)}`,n?{data:n}:void 0)}await Promise.all(n.map(e=>Promise.resolve(e(t))))}sanitizeForLogging(e){if(!e)return e;if(e instanceof ArrayBuffer)return`<ArrayBuffer ${e.byteLength} bytes>`;if(ArrayBuffer.isView(e))return`<${e.constructor.name} ${e.byteLength} bytes>`;if("object"==typeof e&&null!==e&&"audio"in e&&"string"==typeof e.audio&&e.audio.length>20){const t=Object.assign({},e),n=t.audio.substring(0,20);return t.audio=`${n}... [${t.audio.length} chars total]`,t}return e}removeAllListeners(e){e?this.eventListeners.delete(e):this.eventListeners.clear()}}const l="message",d="error",h="disconnected",c="connected";class p{static Playing="playing";static Paused="paused";static Stopped="stopped";static Enqueued="enqueued";static Error="error";static Ready="ready";static Finished="finished";static AboutToComplete="aboutToComplete"}class f{static Paused="paused";static Playing="playing";static Viseme="viseme"}class m{static AnimationStopped="animation-stopped";static AnimationChanged="animation-changed"}class g{buffer=[];static FrameSync=[255,251];static BitrateTable=[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0];static SamplingRateTable=[44100,48e3,32e3];getRemainingBufferSize(){return this.buffer.length}extractRemainingFrames(){const e=[];let t=0;for(;t+4<=this.buffer.length;)if(255!==this.buffer[t]||224&~this.buffer[t+1])t+=1;else{const n=this.buffer.slice(t,t+4),i=this.getFrameLength(n);if(i>0&&t+i<=this.buffer.length){const n=new Uint8Array(i);for(let e=0;e<i;e++)n[e]=this.buffer[t+e];e.push(n),t+=i}else{if(-1!==i)break;t+=1}}return this.buffer=this.buffer.slice(t),e}feedAndExtractCompleteFrames(e){const t=[],n=this.buffer.length;this.buffer.length=n+e.length;for(let t=0;t<e.length;t++)this.buffer[n+t]=e[t];let i=0;for(;i+4<=this.buffer.length;)if(255!==this.buffer[i]||224&~this.buffer[i+1])i+=1;else{const e=this.buffer.slice(i,i+4),n=this.getFrameLength(e);if(n>0&&i+n<=this.buffer.length){const e=new Uint8Array(n);for(let t=0;t<n;t++)e[t]=this.buffer[i+t];t.push(e),i+=n}else{if(-1!==n)break;i+=1}}const r=new Uint8Array(this.buffer.length-i);for(let e=0;e<r.length;e++)r[e]=this.buffer[i+e];return this.buffer=this.buffer.slice(i),{frames:t,remainingData:r}}getFrameLength(e){if(e.length<4)return-1;const t=e[1]>>3&3,n=e[1]>>1&3;if(3!==t||1!==n)return-1;const i=e[2]>>4&15,r=e[2]>>2&3,s=e[2]>>1&1;if(15===i||0===i||3===r)return-1;const a=1e3*g.BitrateTable[i],o=g.SamplingRateTable[r];return 0===a||0===o?-1:Math.floor(144*a/o)+s}}class y{static AboutToComplete="about-to-complete"}class w extends u{getCurrentTime;getQueueLength;getQueueDuration;aboutToCompleteThresholdMs;hasTriggeredAboutToComplete=!1;aboutToCompleteTimer=null;isAudioComplete=!1;constructor(e,t,n,i){super(new o({category:"🎵 AudioPlayerTiming",style:"color: #009688; font-weight: bold; font-size: larger"})),this.getCurrentTime=e,this.getQueueLength=t,this.getQueueDuration=n,this.aboutToCompleteThresholdMs=i}onAudioComplete(){this.isAudioComplete=!0,this.checkAboutToComplete()}onAudioEnqueued(){this.isAudioComplete&&!this.hasTriggeredAboutToComplete&&this.checkAboutToComplete()}checkAboutToComplete(){if(this.hasTriggeredAboutToComplete||!this.isAudioComplete)return;this.aboutToCompleteTimer&&(clearTimeout(this.aboutToCompleteTimer),this.aboutToCompleteTimer=null);const e=1e3*this.getQueueDuration();if(this.logger.debug(`checkAboutToComplete: remainingDurationMs=${e}, queueLength=${this.getQueueLength()}`),0!==e)if(this.logger.debug(`Remaining audio duration: ${e}ms, threshold: ${this.aboutToCompleteThresholdMs}ms`),e<=this.aboutToCompleteThresholdMs)this.triggerAboutToComplete();else{const t=e-this.aboutToCompleteThresholdMs;this.logger.debug(`Setting timer for ${t}ms`),this.aboutToCompleteTimer=window.setTimeout(()=>{this.triggerAboutToComplete()},t)}else this.triggerAboutToComplete()}async triggerAboutToComplete(){this.hasTriggeredAboutToComplete||(this.hasTriggeredAboutToComplete=!0,this.logger.debug(`Audio about to complete (${this.aboutToCompleteThresholdMs}ms threshold)`),await this.emit(y.AboutToComplete))}reset(){this.hasTriggeredAboutToComplete=!1,this.isAudioComplete=!1,this.aboutToCompleteTimer&&(clearTimeout(this.aboutToCompleteTimer),this.aboutToCompleteTimer=null)}}const b=(e,t=4294967295,n=79764919)=>{const i=new Int32Array(256);let r,s,a,o=t;for(r=0;r<256;r++){for(a=r<<24,s=8;s>0;--s)a=2147483648&a?a<<1^n:a<<1;i[r]=a}for(r=0;r<e.length;r++)o=o<<8^i[255&(o>>24^e[r])];return o},_=(e,t=b)=>{const n=e=>new Uint8Array(e.length/2).map((t,n)=>parseInt(e.substring(2*n,2*(n+1)),16)),i=e=>n(e)[0],r=new Map;[,8364,,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,,381,,,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,,382,376].forEach((e,t)=>r.set(e,t));const s=new Uint8Array(e.length);let a,o,u,l=!1,d=0,h=42,c=e.length>13&&"dynEncode"===e.substring(0,9),p=0;c&&(p=11,o=i(e.substring(9,p)),o<=1&&(p+=2,h=i(e.substring(11,p))),1===o&&(p+=8,u=(e=>new DataView(n(e).buffer).getInt32(0,!0))(e.substring(13,p))));const f=256-h;for(let t=p;t<e.length;t++)if(a=e.charCodeAt(t),61!==a||l){if(92===a&&t<e.length-5&&c){const n=e.charCodeAt(t+1);117!==n&&85!==n||(a=parseInt(e.substring(t+2,t+6),16),t+=5)}if(a>255){const e=r.get(a);e&&(a=e+127)}l&&(l=!1,a-=64),s[d++]=a<h&&a>0?a+f:a-h}else l=!0;const m=s.subarray(0,d);if(c&&1===o){const e=t(m);if(e!==u){const t="Decode failed crc32 validation";throw console.error("`simple-yenc`\n",t+"\n","Expected: "+u+"; Got: "+e+"\n","Visit https://github.com/eshaz/simple-yenc for more information"),Error(t)}}return m};function $(){const e=Uint8Array,t=Float32Array;$.modules||Object.defineProperties($,{modules:{value:new WeakMap},setModule:{value(e,t){$.modules.set(e,Promise.resolve(t))}},getModule:{value(e,t){let n=$.modules.get(e);return n||(t?n=WebAssembly.compile(_(t)):(t=e.wasm,n=$.inflateDynEncodeString(t).then(e=>WebAssembly.compile(e))),$.modules.set(e,n)),n}},concatFloat32:{value(e,n){let i=new t(n),r=0,s=0;for(;r<e.length;)i.set(e[r],s),s+=e[r++].length;return i}},getDecodedAudio:{value:(e,t,n,i,r)=>({errors:e,channelData:t,samplesDecoded:n,sampleRate:i,bitDepth:r})},getDecodedAudioMultiChannel:{value(e,t,n,i,r,s){let a,o,u=[];for(a=0;a<n;a++){const e=[];for(o=0;o<t.length;)e.push(t[o++][a]||[]);u.push($.concatFloat32(e,i))}return $.getDecodedAudio(e,u,i,r,s)}},inflateDynEncodeString:{value:t=>(t=_(t),new Promise(n=>{const i=String.raw`dynEncode012804c7886d()((()>+*§§)§,§§§§)§+§§§)§+.-()(*)-+)(.7*§)i¸¸,3§(i¸¸,3/G+.¡*(,(,3+)2å:-),§H(P*DI*H(P*@I++hH)H*r,hH(H(P*<J,i)^*<H,H(P*4U((I-H(H*i0J,^*DH+H-H*I+H,I*4)33H(H*H)^*DH(H+H)^*@H+i§H)i§3æ*).§K(iHI/+§H,iHn,§H+i(H+i(rCJ0I,H*I-+hH,,hH(H-V)(i)J.H.W)(i)c)(H,i)I,H-i*I-4)33i(I.*hH(V)(H+n5(H(i*I-i(I,i)I.+hH,i*J+iHn,hi(I-i*I,+hH,H/H-c)(H,iFn,hi(I,+hH,H0n5-H*V)(J(,hH/H(i)J(H(V)(J(i)c)(H)H(i)H,c)(3H*i*I*H,i)I,4(3(-H(H,W)(H-I-H,i*I,4)3(3(3H,H-I1H+I,H.i)H1V)(J.i(v5(33H.-H(H,i(c)(H,i*I,4)333)-§i*I*+§H*iHn,hi73H,H(i)8(H+J+H)P*(H*V)(J-r,§H)P*,H.i)H+H,i)V)(-H*i*I*H+i)I+H-H.I.H,H-i)I,4)333Ã+)-§iø7i(^*(iü7I,*h+hH+iDn,h*hilI+i)I,+hH+,hH+iô7H,c)(i)H+i´8W)(H,I,H+i*I+4)-+hH(H)8*J-i(p5.*h*h*hH-i')u,hH(P*(J+,hH(P*0J,H(P*,n50H+H,H-b((3H(P*0i)I.4)3H-i¨*n5*H-iÅ*s,hi73H-i)J+V)&+I,H(H+V)æ,8(I.H(H*8*J-i(p51H-i)J+i¸7V)(H(H+iø7V)(8(J/H(P*0J+s,hi73H+H,H.J,I.H(P*(m5(H.H(P*,s5.+hH,m5*H(P*(J.H+H.H+H/U((b((H(H(P*0i)J+^*0H,i)I,4(3(3H(H.^*03H-i¨*o5)33i(73(3(3-H,H+i)c)(H,i*I,H+i)I+4)33i)I-3H-3!2)0§K(i2J,L(H,H(^*(H,H*^*4H,i(^*0H,i(^*DH,j(_*<H,H)P*(^*,H,H+P*(^*8*h*h+hH,i)8(I3i§I**h*h*h*h*h*h*hH,i*8(6+(),03H,j(_*@i*I-H,P*<J.i,J(H,P*8J/s50H,H.i+J0^*<i¦I*H.H,P*4J1J.U(*H.U((J2i')o5/H.U()I.H,H(^*<H0H1U((H.i0J.i§i0i')o5/H/H.H2J*H(J.q50H,P*0J/H*I-H,P*(J0,hH,P*,H-q,hi)I-423+hH*m5+H/H0H(H1U((b((H/i)I/H(i)I(H*i)I*4(3(3H,H.^*<H,H-^*04*3iØ1U((5+i(I(i¨7i1^*(i$6iè1^*(i°7iè6^*(i¬7iÈ6^*(+hH(iÈ*n,hiÈ*I(+hH(i¨,n,hi¨,I(+hH(iØ,n,hiØ,I(+hH(iè,o,hH,i-H(i0c)(H(i*I(4)33iè1i1H,i-iÈ*8)Bi(I(+hH(ido,hH,i-H(i-c)(H(i*I(4)33iÈ6iè6H,i-iF8)BiØ1i)b((41-H,i-H(i/c)(H(i*I(4)3(3(-H,i-H(i1c)(H(i*I(4)3(3(-H,i-H(i0c)(H(i*I(4)3(3(3H,H/^*0H,H(^*<3i(I*4*3H,H,i¸)^*TH,H,iø-^*PH,H,iX^*LH,H,i(^*HH,i-8(I(H,i-8(I-i¥I*H,i,8(I.H(iErH-iEr5)H(i©*I1H-i)I0i(i;H.i,J(i(H(i(rCJ(J*H*i;sCI*i¨1I-H(I/+hH/,hH,i-H-V)(i)H,i+8(c)(H/i)I/H-i*I-H*i)I*4)-H(i)i¨1I/+hH(H*o,hH,i-H/V)(i)i(c)(H/i*I/H(i)I(4)33i¤I*H,iø-H,i¸)H,i-i;8)5+H0H1I2i(I-+hH-H2p,hH,H,iP8*J*i(p5-H*i7u,hH,i-H-i)H*c)(H-i)I-4*3i(I/i+I.i+I(*h*h*hH*i86*(*)3H-m,hi£I*403H-i)H,W)-I/i*I(4)3i3I.i/I(3H2H,H(8(H.J(H-J.p,hi¢I*4.3H,i-H-i)I*+hH(,hH*H/c)(H*i*I*H(i)I(4)-H.I-4+3(3(33H,W)1m,hiI*4,3H,iø-H,i¸)H,i-H18)J(,hi¡I*H(i(p5,H1H,V)ú-H,V)ø-o5,3H,i(H,iXH,i-H1i)H08)J(,hi I*H(i(p5,H0H,V)H,V)o5,3H,H,iPH,iH8+I*4+3(3(3H,i$6i¬78+I*3H*H3m5(3i)I-H*i(r5)3H)H,P*0^*(H+H,P*<^*(H*I-3H,i2L(H-33Á)+(i¨03b+(,(-(.(/(0(1(2(3(5(7(9(;(?(C(G(K(S([(c(k({(((«(Ë(ë((*)(iø03O)()()()(*(*(*(*(+(+(+(+(,(,(,(,(-(-(-(-(i¨13M8(9(:(((0(/(1(.(2(-(3(,(4(+(5(*(6()(7(T7*S7US0U `;$.getModule($,i).then(e=>WebAssembly.instantiate(e,{})).then(({exports:i})=>{const r=new Map(Object.entries(i)),s=r.get("puff"),a=r.get("memory").buffer,o=new e(a),u=new DataView(a);let l=r.get("__heap_base");const d=t.length,h=l;l+=4,u.setInt32(h,d,!0);const c=l;l+=d,o.set(t,c);const p=l;l+=4,u.setInt32(p,o.byteLength-l,!0),s(l,p,c,h),n(o.slice(l,l+u.getInt32(p,!0)))})}))}}),Object.defineProperty(this,"wasm",{enumerable:!0,get:()=>this._wasm}),this.getOutputChannels=(e,t,n)=>{let i=[],r=0;for(;r<t;)i.push(e.slice(r*n,r++*n+n));return i},this.allocateTypedArray=(e,t,n=!0)=>{const i=this._wasm.malloc(t.BYTES_PER_ELEMENT*e);return n&&this._pointers.add(i),{ptr:i,len:e,buf:new t(this._wasm.HEAP,i,e)}},this.free=()=>{this._pointers.forEach(e=>{this._wasm.free(e)}),this._pointers.clear()},this.codeToString=e=>{const t=[],n=new Uint8Array(this._wasm.HEAP);for(let i=n[e];0!==i;i=n[++e])t.push(i);return String.fromCharCode.apply(null,t)},this.addError=(e,t,n,i,r,s)=>{e.push({message:t,frameLength:n,frameNumber:i,inputBytes:r,outputSamples:s})},this.instantiate=(e,t)=>(t&&$.setModule(e,t),this._wasm=new e($).instantiate(),this._pointers=new Set,this._wasm.ready.then(()=>this))}function v(e){var t,n,i,r=e=>console.log(e),s=e=>console.error(e);function a(){}function o(e){throw e}function u(){o("missing function: INT123_compat_close")}u.stub=!0;for(var l={},d=[null,[],[]],h=new TextDecoder,c=(e,t)=>{var n=d[e];0===t||10===t?((1===e?r:s)(((e,t=0,n=NaN)=>{for(var i=t+n,r=t;e[r]&&!(r>=i);)++r;return h.decode(e.buffer?e.subarray(t,r):new Uint8Array(e.slice(t,r)))})(n)),n.length=0):n.push(t)},p=new Uint8Array(123),f=25;f>=0;--f)p[48+f]=52+f,p[65+f]=f,p[97+f]=26+f;p[43]=62,p[47]=63;var m,g,y,w,b,_,$,x={j:u,c:()=>o(""),b:()=>{},d:(e,t)=>{if(l[e]&&(clearTimeout(l[e].id),delete l[e]),!t)return 0;var n=setTimeout(()=>{delete l[e],$(e,performance.now())},t);return l[e]={id:n,timeout_ms:t},0},e:e=>(t.length,!1),g:e=>52,h:(e,t,n,i)=>52,i:function(e,t,n,i){var r;return t=(r=t)<-9007199254740992||r>9007199254740992?NaN:Number(r),70},f:(e,i,r,s)=>{for(var a=0,o=0;o<r;o++){var u=n[i>>2],l=n[i+4>>2];i+=8;for(var d=0;d<l;d++)c(e,t[u+d]);a+=l}return n[s>>2]=a,0},a:e=>{throw`exit(${e})`}};v.wasm||Object.defineProperty(v,"wasm",{get:()=>String.raw`dynEncode01dd21c54d17j¢>¡-é!Dt 9&W U§®}»/6|ºì,ÜÐ*ÝÙÂ:C#ÈEÅõkµÄqÁ¹BCdq$GPPxÚý¾ýB{jð=M¸ìOÑ-Ia,¢áÅ Ó®µôEù= *f®Ø"þèÒ ËøÓÉÄà󫤡ù|þ«ôñ«´ÁÜú¤«ìe«p±§W6(¶¢ÏÑIZ»¥'T28òÞ6<±*h²ëHñ'q©ññ+9LÏ8n'!ò©åP.Þot__¹§ü 0J]ío Zï óÚºM´õjÈ¿n)å½ðN\]óÐÖ]±<¿_>»5Ûÿ-'2[HÕo×m}&xÎÿú&ôì¯ /ý§iÂÐÈRB÷¸M°G÷;;T8kB7ïQûzL´¨ÛÍD9$EnA¶¸ûÃv4òCû㨾YcÐ>t2çZéÂ{¬½«KØB6cvpR=}vªã4ÀP¿Ø»ä4ûwѽ®üªä~Ô±CÇJÓª±.NÉ\*±8jècª= |_VÃK×ã2)§}¼
gb/!ôÀV~:0-ÈÀu²Ì/@LO*ÃL1?çRMljÀw
|
|
3
3
|
K<î ¼G$ý¿¸É´g¢ô°rTªS¨Ð²éfªm½y
|
|
4
4
|
|~¦À?Ä;Ä¡gmjê'IhÅüO0b¢¹1ÜÎhj÷ÓÚ:rþ^KÓYٺʹ«IÚ
|
|
5
5
|
Ú©»WõªÁÞ\vvw+Ô^¤hÄ|´Dl*6¹2ÌðPF¼)\HQcQu%Ê,Jd¾7«Ô=Mº®nø½ÞÈö6×Á?ì EôQÞ¡éRÝ¡W*muú®¨ ñsÊWÂÌ5Î= v[x¨}\¦Æã£Q>wÀBÁ×(~;Þcí¹«
|
|
@@ -181,4 +181,4 @@ g¹¯´ì±Ñp·¯Æúj!Ùê3û|©Ña°9èóPSàj¨ÎZ®%WçÇ&Õ¹
|
|
|
181
181
|
CU¡ÍÌ]Âuf¸i^ÍN¸<ößiIÒzWHÈDkòPëKã.í»+{J¸
V0¸J¸J¸Ã³J#Ä8+KÉA¥NAú¬Í)ô¼¡%°|ù(JPsS±E¯j=M-2Þ[6+Ïû¿²h$ɳ0= êL,§D1ÌJÈBrÚ YÏxSòRFx¤ÚK+ÐÃ:&öôêGº´;ÌúÏà7Ðr´Í6I)ó÷~~àrOyE\ÔfËøª¬ÓFܧìpQ¯{¨EO:.ÆÔEÊm¢Ä¹#{±
|
|
182
182
|
r÷|ú
|
|
183
183
|
*ÔàñT' 8KpLjúwù@Q(HÎj{¥¦SÙ01TÀ7F<â<$êÐÉSLVa·ËEk´&[[Ê×zôEtF@Ë9KV©ÇEÙK¬)G4WÛWv3ýn§ÁçÂxârjz= phxdtl|\=}-M¥ìÉÜ\¾Ù%Á?vq³¾Ãð6æøÇ]\C"
3ú¹ï5ÞÞçpXç)z²^Rû÷üoõ{µ(âw]WT½Ïm§Cö4&t]Ât[bìÓ®\%óêëÌÔfìW´@¨ÁÚ_ª÷n xV½é9]MàËàUßÍ/»äµÝ<½äÙÝåáýõaY¿DÅìZÀìØüÛ£üÞÿÍ$Z-×8Ò\ Üb½RLhuñ®äâøþsBV_»ë»Um3
|
|
184
|
-
½ÇaztÅò¬¼Åâ`});var T={a:x};this.setModule=e=>{t.setModule(EmscriptenWASM,e)},this.getModule=()=>t.getModule(EmscriptenWASM),this.instantiate=()=>(this.getModule().then(t=>WebAssembly.instantiate(t,T)).then(t=>{const i=t.exports;var o;!function(t){g=t.m,m=t.n,b=t.p,y=t.q,_=t.r,w=t.s,v=t.t}(i),o=(r=i.k).buffer,new Int8Array(o),new Int16Array(o),e=new Uint8Array(o),new Uint16Array(o),new Int32Array(o),n=new Uint32Array(o),new Float32Array(o),new Float64Array(o),new BigInt64Array(o),new BigUint64Array(o),function(t){t.l()}(i),s()}),this.ready=new Promise(t=>{s=t}).then(()=>{this.HEAP=r.buffer,this.malloc=g,this.free=m,this.mpeg_decoder_feed=y,this.mpeg_decoder_read=_,this.mpeg_frame_decoder_create=b,this.mpeg_frame_decoder_destroy=w}),this)}function MPEGDecoder(t={}){return this._init=()=>(new this._WASMAudioDecoderCommon).instantiate(this._EmscriptenWASM,this._module).then(e=>{this._common=e,this._sampleRate=0,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputSize,Float32Array);const n=this._common.allocateTypedArray(1,Uint32Array);this._samplesDecodedPtr=this._common.allocateTypedArray(1,Uint32Array),this._sampleRatePtr=this._common.allocateTypedArray(1,Uint32Array),this._errorStringPtr=this._common.allocateTypedArray(1,Uint32Array);const r=this._common.wasm.mpeg_frame_decoder_create(n.ptr,!1===t.enableGapless?0:1);if(r)throw Error(this._getErrorMessage(r));this._decoder=n.buf[0]}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this._getErrorMessage=t=>t+" "+this._common.codeToString(this._errorStringPtr.buf[0]),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.mpeg_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder),this._common.free()},this.decode=t=>{let e=[],n=[],r=0;if(!(t instanceof Uint8Array))throw Error("Data to decode must be Uint8Array. Instead got "+typeof t);t:for(let i=0,o=0;i<t.length;i+=o){const s=t.subarray(i,this._input.len+i);o=s.length,this._inputBytes+=o,this._input.buf.set(s);let a=this._common.wasm.mpeg_decoder_feed(this._decoder,this._input.ptr,o);if(-10!==a)for(;;){this._samplesDecodedPtr.buf[0]=0,a=this._common.wasm.mpeg_decoder_read(this._decoder,this._output.ptr,this._output.len,this._samplesDecodedPtr.ptr,this._sampleRatePtr.ptr,this._errorStringPtr.ptr);const t=this._samplesDecodedPtr.buf[0];if(this._outputSamples+=t,t&&(r+=t,e.push([this._output.buf.slice(0,t),this._output.buf.slice(t,2*t)])),-11!=a){if(-10===a)continue t;if(a){const t=this._getErrorMessage(a);console.error("mpg123-decoder: "+t),this._common.addError(n,t,0,this._frameNumber,this._inputBytes,this._outputSamples)}}}}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,e,2,r,this._sampleRatePtr.buf[0])},this.decodeFrame=t=>{const e=this.decode(t);return this._frameNumber++,e},this.decodeFrames=t=>{let e=[],n=[],r=0,i=0;for(;i<t.length;){const o=this.decodeFrame(t[i++]);e.push(o.channelData),n=n.concat(o.errors),r+=o.samplesDecoded}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,e,2,r,this._sampleRatePtr.buf[0])},this._isWebWorker=MPEGDecoder.isWebWorker,this._WASMAudioDecoderCommon=MPEGDecoder.WASMAudioDecoderCommon||WASMAudioDecoderCommon,this._EmscriptenWASM=MPEGDecoder.EmscriptenWASM||EmscriptenWASM,this._module=MPEGDecoder.module,this._inputSize=65536,this._outputSize=92448,this._ready=this._init(),this}class AudioPlayer extends EventEmitter{MIN_CHUNKS_TO_PROCESS=2;FLUSH_DELAY_MS=450;audioContext;currentSource=null;playbackQueue=[];mp3Decoder=null;scheduledPlayTime=0;playbackStartTime=0;chunkQueue=[];isProcessingQueue=!1;frameExtractor=new MP3FrameExtractor;totalFramesDecoded=0;totalFramesFailed=0;totalFramesExtracted=0;isPlayingState=!1;isPausedState=!1;stopped=!1;frameBuffer=[];chunkAccumulator=[];flushTimeout=null;isAudioComplete=!1;timing;isScheduling=!1;allAudioPlayed=!1;constructor(){super(new DefaultLogger({category:"🎵 AudioPlayer",style:StyleGreen})),this.audioContext=new AudioContext,this.timing=new AudioPlayerTiming(()=>this.getCurrentTime(),()=>this.getQueueLength(),()=>this.getRemainingAudioSeconds(),1e3),this.setupTimingListeners()}setupTimingListeners(){this.timing.on("about-to-complete",async()=>{await this.emit(AudioPlayerEvents.AboutToComplete)})}async initialize(){this.audioContext||(this.audioContext=new AudioContext,this.logger.debug("AudioContext created by user gesture")),"suspended"===this.audioContext.state&&(this.audioContext.resume(),this.logger.debug("AudioContext resumed by user gesture")),this.mp3Decoder||(this.logger.debug("Initializing MP3 decoder..."),this.mp3Decoder=new MPEGDecoder,await this.mp3Decoder.ready,this.logger.debug("MP3 decoder ready")),this.resetState()}resetState(){this.currentSource&&(this.currentSource.onended=null,this.currentSource.stop(),this.currentSource=null),this.playbackQueue=[],this.scheduledPlayTime=0,this.playbackStartTime=0,this.chunkQueue=[],this.isProcessingQueue=!1,this.frameExtractor=new MP3FrameExtractor,this.isPlayingState=!1,this.isPausedState=!1,this.stopped=!1,this.frameBuffer=[],this.chunkAccumulator=[],this.isAudioComplete=!1,this.totalFramesDecoded=0,this.totalFramesFailed=0,this.totalFramesExtracted=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.reset(),this.allAudioPlayed=!1}reset(){this.resetState()}enqueue(t){this.logger.debug("Enqueue: received chunk"),this.allAudioPlayed=!1,this.chunkQueue.push({base64String:t}),this.processChunkQueue(),this.isAudioComplete||(this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(()=>{this.logger.debug("auto-flush timer fired"),this.flush()},this.FLUSH_DELAY_MS))}markComplete(){this.logger.debug("markComplete: no more audio will be added"),this.isAudioComplete=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.onAudioComplete(),this.flush();const t=this.frameExtractor.extractRemainingFrames();t.length>0&&(this.logger.debug("markComplete: Found additional frames after flush",{count:t.length}),this.totalFramesExtracted+=t.length,this.decodeAudioFrames(t).then(e=>{if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),this.emit(AudioPlayerEvents.Enqueued,{duration:e.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?this.emit(AudioPlayerEvents.Ready):this.isPlayingState&&this.schedulePlayback()}}).catch(e=>{this.totalFramesFailed+=t.length,this.logger.error("Failed to decode final remaining frames after markComplete",e)}));const e=this.frameExtractor.getRemainingBufferSize();e>0&&this.logger.warn("markComplete: Extractor buffer still has data after final extraction",{remainingBytes:e}),this.allAudioPlayed&&(this.logger.debug("markComplete: All audio was already played, emitting Finished."),this.isPlayingState=!1,this.emit(AudioPlayerEvents.Finished))}async processChunkQueue(){if(!this.isProcessingQueue){this.isProcessingQueue=!0;try{for(;this.chunkQueue.length>0;){const{base64String:t}=this.chunkQueue.shift();if(this.chunkAccumulator.push(t),this.chunkAccumulator.length>=this.MIN_CHUNKS_TO_PROCESS){const t=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(t)}}}finally{this.isProcessingQueue=!1}}}decodeBase64ToUint8Array(t){const e="undefined"!=typeof atob?atob(t):Buffer.from(t,"base64").toString("binary"),n=new Uint8Array(e.length);for(let t=0;t<e.length;t++)n[t]=e.charCodeAt(t);return n}combineArrays(t,e){const n=new Uint8Array(t.length+e.length);return n.set(t),n.set(e,t.length),n}async decodeAudioFrames(t){if(0===t.length)return null;if(!this.mp3Decoder)throw new Error("MP3 decoder not initialized. Call initialize() first.");const e=[];let n=0,r=0,i=0,o=0;for(let s=0;s<t.length;s++){const a=t[s];if(a.length<2||255!==a[0]||224&~a[1])this.logger.warn(`Frame ${s} doesn't start with valid sync word, skipping`,{firstBytes:Array.from(a.slice(0,4)),frameLength:a.length}),o++;else try{const t=this.mp3Decoder.decodeFrame(a);if(t.errors&&t.errors.length>0&&this.logger.warn(`Frame ${s} decoded with errors`,{errors:t.errors.map(t=>t.message||String(t)),frameLength:a.length}),0===t.samplesDecoded){this.logger.warn(`Frame ${s} decoded but produced 0 samples`,{frameLength:a.length,errors:t.errors?.map(t=>t.message||String(t))}),o++;continue}if(0===n?n=t.sampleRate:t.sampleRate!==n&&this.logger.warn(`Frame ${s} has different sample rate: ${t.sampleRate} vs ${n}`),0===e.length)for(let n=0;n<t.channelData.length;n++)e.push([]);for(let n=0;n<t.channelData.length;n++)n<e.length&&e[n].push(t.channelData[n]);r+=t.samplesDecoded,i++}catch(t){this.logger.error(`Failed to decode frame ${s}`,{error:t instanceof Error?t.message:String(t),frameLength:a.length,firstBytes:Array.from(a.slice(0,4))}),o++}}if(0===i)return this.logger.error("All frames failed to decode",{totalFrames:t.length}),null;o>0&&this.logger.warn("Some frames failed to decode",{successful:i,failed:o,total:t.length});const s=[];for(let t=0;t<e.length;t++){const n=new Float32Array(r);let i=0;for(const r of e[t])n.set(r,i),i+=r.length;s.push(n)}const a=this.audioContext.createBuffer(s.length,r,n);for(let t=0;t<s.length;t++)a.getChannelData(t).set(s[t]);return this.logger.debug("Decoded frames",{successful:i,failed:o,totalSamples:r,sampleRate:n,duration:a.duration.toFixed(3)}),a}async play(){this.isPlayingState||0===this.playbackQueue.length?this.logger.debug("Play called but already playing or queue is empty."):(this.isPlayingState=!0,this.stopped=!1,this.isPausedState=!1,this.isPausedState?this.scheduledPlayTime=this.audioContext.currentTime:(this.scheduledPlayTime=this.audioContext.currentTime,this.playbackStartTime=this.audioContext.currentTime),this.logger.debug(`Playback starting. Start time: ${this.playbackStartTime}`),this.schedulePlayback(),await this.emit(AudioPlayerEvents.Playing))}schedulePlayback(){if(this.isScheduling||0===this.playbackQueue.length||this.stopped)return;this.isScheduling=!0,this.currentSource&&(this.currentSource.onended=null);let t=null;for(;this.playbackQueue.length>0;){const e=this.playbackQueue.shift(),n=this.audioContext.createBufferSource();n.buffer=e,n.connect(this.audioContext.destination),this.scheduledPlayTime<this.audioContext.currentTime&&(this.logger.debug(`Adjusting scheduledPlayTime from ${this.scheduledPlayTime} to current time ${this.audioContext.currentTime}`),this.scheduledPlayTime=this.audioContext.currentTime),this.logger.debug(`Scheduling buffer of duration ${e.duration}s to start at ${this.scheduledPlayTime} (context time: ${this.audioContext.currentTime})`),n.start(this.scheduledPlayTime),this.scheduledPlayTime+=e.duration,t=n}t&&(this.currentSource=t,t.onended=()=>{this.logger.debug(`Buffer finished playing. Context time: ${this.audioContext.currentTime}, isPaused: ${this.isPausedState}, stopped: ${this.stopped}`),this.stopped||this.isPausedState||(this.playbackQueue.length>0?(this.logger.debug("More buffers in queue, scheduling next batch."),this.schedulePlayback()):this.isAudioComplete?(this.logger.debug("Last scheduled audio buffer finished and audio is complete."),this.isPlayingState=!1,this.emit(AudioPlayerEvents.Finished)):(this.logger.debug("All scheduled audio has been played, but not marked as complete yet."),this.allAudioPlayed=!0))}),this.isScheduling=!1}async pause(){this.currentSource&&this.isPlayingState&&(this.isPausedState=!0,this.isPlayingState=!1,this.audioContext.suspend(),await this.emit(AudioPlayerEvents.Paused))}async resume(){this.isPausedState&&(this.logger.debug("Resume called, resuming playback."),this.isPausedState=!1,this.isPlayingState=!0,this.audioContext.resume(),this.schedulePlayback(),await this.emit(AudioPlayerEvents.Playing))}async stop(){this.stopped=!0,this.resetState(),await this.emit(AudioPlayerEvents.Stopped)}getCurrentTime(){return this.isPlayingState?1e3*(this.audioContext.currentTime-this.playbackStartTime):0}getQueueLength(){return this.playbackQueue.length}getRemainingAudioSeconds(){const t=this.playbackQueue.reduce((t,e)=>t+e.duration,0);let e=0;return(this.isPlayingState||this.isPausedState)&&this.scheduledPlayTime>0&&(e=Math.max(0,this.scheduledPlayTime-this.audioContext.currentTime)),t+e}async decodeAndEnqueueChunks(t){if(0===t.length)return void this.logger.debug("decodeAndEnqueueChunks: no chunks to decode");let e=[];for(const n of t){const t=this.decodeBase64ToUint8Array(n),{frames:r,remainingData:i}=this.frameExtractor.feedAndExtractCompleteFrames(t);e=e.concat(r),this.totalFramesExtracted+=r.length,i.length>0&&this.logger.debug("Chunk ended with incomplete frame",{remainingBytes:i.length,framesExtracted:r.length})}if(this.logger.debug("decodeAndEnqueueChunks: total frames to decode",e.length),e.length>0){const t=e.map(t=>t.length).reduce((t,e)=>(t[e]=(t[e]||0)+1,t),{});this.logger.debug("Frame sizes distribution",t);try{const t=await this.decodeAudioFrames(e);if(t){this.totalFramesDecoded+=e.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(t),await this.emit(AudioPlayerEvents.Enqueued,{duration:t.duration}),this.logger.debug("decodeAndEnqueueChunks: enqueued audioBuffer, duration",t.duration,"frames decoded",e.length),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(AudioPlayerEvents.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(t){this.totalFramesFailed+=e.length,this.logger.error("Failed to decode audio frames",t),this.logger.error("Lost frames",{count:e.length,sizes:e.map(t=>t.length)})}}else this.logger.debug("decodeAndEnqueueChunks: no frames to decode")}async flush(){this.logger.debug("Flushing",{chunks:this.chunkAccumulator.length});const t=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(t);const e=this.frameExtractor.extractRemainingFrames();if(e.length>0){this.logger.debug("Flush: Found complete frames in extractor buffer",{count:e.length}),this.totalFramesExtracted+=e.length;try{const t=await this.decodeAudioFrames(e);if(t){this.totalFramesDecoded+=e.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(t),await this.emit(AudioPlayerEvents.Enqueued,{duration:t.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(AudioPlayerEvents.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(t){this.totalFramesFailed+=e.length,this.logger.error("Failed to decode remaining frames after flush",t)}}}resetAboutToComplete(){this.timing.reset()}getFrameStats(){return{totalFramesExtracted:this.totalFramesExtracted,totalFramesDecoded:this.totalFramesDecoded,totalFramesFailed:this.totalFramesFailed,extractorRemainingBufferSize:this.frameExtractor.getRemainingBufferSize()}}dispose(){if(this.logger.debug("Disposing AudioPlayer..."),this.stopped=!0,this.isPlayingState=!1,this.isPausedState=!1,this.currentSource){this.currentSource.onended=null;try{this.currentSource.stop()}catch(t){}this.currentSource=null}this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing&&this.timing.reset(),this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close().catch(t=>{this.logger.debug("Error closing AudioContext:",t)}),this.mp3Decoder=null,this.resetState(),this.removeAllListeners(),this.logger.debug("AudioPlayer disposed")}destroy(){this.dispose()}}const SubtitleManagerEvents={WordChange:"wordChange",Playing:"playing",Paused:"paused",SubtitleFinished:"subtitleFinished",SubtitleChange:"subtitleChange"};class SubtitleManager extends EventEmitter{getCurrentTime;subtitleQueue=[];rafId=null;isPlaying=!1;cumulativeOffset=0;tickDebugLast=0;state={currentLine:null,nextLine:null,globalWordIndex:-1};constructor(t){super(new DefaultLogger({category:"🎬 SubtitleManager",style:StylePink})),this.getCurrentTime=t,this._resetState()}enqueue(t){this.logger.debug("Enqueue subtitle",{subtitle:t,queueLength:this.subtitleQueue.length});const{wordBoundaries:e,wordStartTimesMs:n}=this._computeWordBoundariesAndStartTimes(t.characters,t.start_times_ms),r={...t,wordBoundaries:e,wordStartTimesMs:n};this.subtitleQueue.push(r),this.isPlaying||1!==this.subtitleQueue.length||(this.logger.debug("Reset globalWordIndex to -1 (initial enqueue)"),this.state.globalWordIndex=-1),this.isPlaying&&!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),this._emitSubtitleChange())}async play(){this.isPlaying?this.logger.debug("Play called but already playing"):(this.logger.debug("Play called, starting playback"),this.isPlaying=!0,await this.emit(SubtitleManagerEvents.Playing),this.subtitleQueue.length>0&&(this._prepareState(),await this._emitSubtitleChange()),this.rafId=requestAnimationFrame(this._tick))}async pause(){this.logger.debug("Pause called"),this.isPlaying=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),await this.emit(SubtitleManagerEvents.Paused)}clearQueue(){this.logger.debug("Clear queue"),this._resetState(),this.pause()}reset(){this._resetState()}_resetState(){this.subtitleQueue=[],this.cumulativeOffset=0,this.rafId=null,this.isPlaying=!1,this.tickDebugLast=0,this.state={currentLine:null,nextLine:null,globalWordIndex:-1}}_subtitleDuration(t){const{start_times_ms:e,durations_ms:n}=t;if(!e.length||!n.length)return 0;const r=e.length-1;return e[r]+n[r]}_applyOffset(t,e){return t.map(t=>t+e)}_prepareState(){if(!this.subtitleQueue.length)return;const t=this.subtitleQueue[0];t.adjustedWordStartTimesMs=this._applyOffset(t.wordStartTimesMs,this.cumulativeOffset);const e=this.subtitleQueue[1]||null;if(e){const n=this.cumulativeOffset+this._subtitleDuration(t);e.adjustedWordStartTimesMs=this._applyOffset(e.wordStartTimesMs,n)}this.state.currentLine=t,this.state.nextLine=e,this.logger.debug("Prepared state",{cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!t,hasNextLine:!!e,firstFewAdjusted:t.adjustedWordStartTimesMs?.slice(0,3)})}_computeWordBoundariesAndStartTimes(t,e){const n=[],r=[];let i=null;for(let o=0;o<t.length;o++){const s=t[o];if(" "!==s&&null===i&&(i=o),(" "===s||o===t.length-1)&&null!==i){const t=" "===s?o-1:o;n.push({start:i,end:t}),r.push(e[i]),i=null}}return{wordBoundaries:n,wordStartTimesMs:r}}_calculateGlobalWordIndex(t){let e=-1;const{currentLine:n,nextLine:r}=this.state;if(n?.adjustedWordStartTimesMs)for(let r=0;r<n.adjustedWordStartTimesMs.length&&t>=n.adjustedWordStartTimesMs[r];r++)e=r;if(r?.adjustedWordStartTimesMs){const i=n?.wordBoundaries.length||0;for(let n=0;n<r.adjustedWordStartTimesMs.length&&t>=r.adjustedWordStartTimesMs[n];n++)e=i+n}return e}_decodeGlobalIndex(t){if(t<0)return{lineIndex:0,wordIndex:-1};const e=this.state.currentLine?.wordBoundaries.length||0;return t<e?{lineIndex:0,wordIndex:t}:{lineIndex:1,wordIndex:t-e}}_isFinished(t,e,n){return e>n+this._subtitleDuration(t)}_buildWordChangeEvent(t){const{lineIndex:e,wordIndex:n}=this._decodeGlobalIndex(t),{currentLine:r,nextLine:i}=this.state,o=t=>t?{characters:t.characters,wordBoundaries:t.wordBoundaries}:null;let s;if(0===e&&r&&n>=0){const t=r.wordBoundaries[n];s=r.characters.slice(t.start,t.end+1).join("")}else if(1===e&&i&&n>=0){const t=i.wordBoundaries[n];s=i.characters.slice(t.start,t.end+1).join("")}return{globalWordIndex:t,currentLineIndex:e,wordIndexInLine:n,word:s,currentLineData:o(r),nextLineData:o(i)}}_buildSubtitleChangeEvent(){const t=t=>t?.adjustedWordStartTimesMs?{characters:t.characters,wordBoundaries:t.wordBoundaries,adjustedWordStartTimesMs:t.adjustedWordStartTimesMs}:null;return{currentLine:t(this.state.currentLine),nextLine:t(this.state.nextLine)}}async _emitWordChange(t){const e=this._buildWordChangeEvent(t);this.logger.debug("Word change",{globalWordIndex:t,lineIndex:e.currentLineIndex,wordIndex:e.wordIndexInLine,word:e.word}),await this.emit(SubtitleManagerEvents.WordChange,e)}async _emitSubtitleChange(){const t=this._buildSubtitleChangeEvent();this.logger.debug("Subtitle change",{hasCurrentLine:!!t.currentLine,hasNextLine:!!t.nextLine}),await this.emit(SubtitleManagerEvents.SubtitleChange,t)}_tick=async()=>{if(!this.isPlaying||0===this.subtitleQueue.length)return;!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),await this._emitSubtitleChange());const t=this.getCurrentTime();this.state.currentLine||this._prepareState(),t-this.tickDebugLast>=3e3&&(this.logger.debug("Tick debug",{currentTimeMs:t,cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!this.state.currentLine,hasNextLine:!!this.state.nextLine}),this.tickDebugLast=t);const e=this._calculateGlobalWordIndex(t);e!==this.state.globalWordIndex&&(this.state.globalWordIndex=e,await this._emitWordChange(e));const n=this.subtitleQueue[0],r=this.subtitleQueue[1]||null;let i=0;if(r){const e=this.cumulativeOffset+this._subtitleDuration(n);this._isFinished(r,t,e)&&(i=2)}else n&&this._isFinished(n,t,this.cumulativeOffset)&&(i=1);if(i>0){this.logger.debug(`Subtitle batch finished. Advancing ${i} lines.`,{currentTimeMs:t,cumulativeOffset:this.cumulativeOffset});const e=this.subtitleQueue.splice(0,i);for(const t of e)this.cumulativeOffset+=this._subtitleDuration(t),await this.emit(SubtitleManagerEvents.SubtitleFinished,t);if(!(this.subtitleQueue.length>0))return this.logger.debug("Queue empty, pausing"),this.state.globalWordIndex=-1,await this._emitWordChange(-1),void await this.pause();this._prepareState(),await this._emitSubtitleChange()}this.rafId=requestAnimationFrame(this._tick)}}class VisemeScheduler extends EventEmitter{scheduledEvents=[];masterClock;constructor(t){super(new DefaultLogger({category:"👄 VisemeScheduler",style:StyleRed})),this.masterClock=t}enqueue(t){this.scheduledEvents.push(...t),this.scheduleEvents()}async play(){await this.emit(VisemeSchedulerEvents.Playing)}async pause(){await this.emit(VisemeSchedulerEvents.Paused)}scheduleEvents(){this.masterClock.currentTime,this.scheduledEvents.forEach(t=>{setTimeout(async()=>{await this.emit(VisemeSchedulerEvents.Viseme,t)})})}}class AvatarManager extends EventEmitter{animationLayers=new Map;layerPriority=["mouth","facial","body","idle"];thinkToggle=!1;constructor(){super(new DefaultLogger({category:"🧒 AvatarManager",style:StyleOrange}))}playIdle(){this.playAnimation("body_idle",0,!0)}playListen(){this.playAnimation("body_idle_listen",0,!0)}playTalk(){this.playAnimation("body_talk_to_user_loop",0,!0)}playThink(){const t=this.thinkToggle?"body_idle_think2":"body_idle_think";this.thinkToggle=!this.thinkToggle,this.playAnimation(t,0,!0)}playLaugh(){this.playAnimation("body_laugh",0,!0)}playWaving(){this.playAnimation("body_waving",0,!1)}playViseme(t){this.playAnimation(t,1,!1)}async playAnimation(t,e=0,n=!0){this.animationLayers.set(e,t),await this.emit(AvatarManagerEvents.AnimationChanged,{name:t,layer:e,loop:n}),this.logger.debug(`Playing animation: ${t} on layer ${e} (loop: ${n})`)}async stopAnimation(t=0){this.animationLayers.delete(t),await this.emit(AvatarManagerEvents.AnimationStopped,{layer:t})}dispose(){try{this.logger.debug("Disposing AvatarManager..."),this.animationLayers.clear(),this.thinkToggle=!1,this.removeAllListeners(),this.logger.debug("AvatarManager disposed")}catch(t){this.logger.warn("Error while disposing AvatarManager",t)}}}const PlaybackManagerEvents={Playing:"playing",Paused:"paused",PlaybackError:"playbackError",SubtitleWordChange:"subtitleWordChange",SubtitleChange:"subtitleChange",ImageChange:"imageChange",AboutToComplete:"aboutToComplete",Finished:"finished",AvatarAnimationChanged:"avatarAnimationChanged"};class PlaybackManager extends EventEmitter{capabilities;audioPlayer;visemeScheduler;subtitleManager;isPaused=!0;hasStarted=!1;avatarManager;constructor(t){super(new DefaultLogger({category:"🎪 PlaybackManager",style:StyleOrange})),this.capabilities=t,this.audioPlayer=new AudioPlayer,this.visemeScheduler=new VisemeScheduler(new AudioContext),this.subtitleManager=new SubtitleManager(()=>this.audioPlayer.getCurrentTime()),this.avatarManager=new AvatarManager,this.avatarManager.on("animation-changed",async t=>{await this.emit(PlaybackManagerEvents.AvatarAnimationChanged,t)}),this.setupChildListeners(),this.resetState()}setupChildListeners(){this.audioPlayer.on(AudioPlayerEvents.Ready,()=>{this.isPaused&&!this.hasStarted?(this.logger.debug("Ready event received, starting playback"),this.play()):this.logger.debug("Ready event received but already playing or paused, ignoring")}),this.audioPlayer.on(AudioPlayerEvents.AboutToComplete,async()=>{this.logger.debug("Audio about to complete"),await this.emit(PlaybackManagerEvents.AboutToComplete)}),this.audioPlayer.on(AudioPlayerEvents.Error,async t=>{await this.emit(PlaybackManagerEvents.PlaybackError,{source:"audio",error:t})}),this.audioPlayer.on(AudioPlayerEvents.Finished,async()=>{await this.emit(PlaybackManagerEvents.Finished),this.reset()}),this.subtitleManager.on(SubtitleManagerEvents.WordChange,async t=>{await this.emit(PlaybackManagerEvents.SubtitleWordChange,t)}),this.subtitleManager.on(SubtitleManagerEvents.SubtitleChange,async t=>{await this.emit(PlaybackManagerEvents.SubtitleChange,t)})}resetState(){this.isPaused=!0,this.hasStarted=!1}async initialize(){this.logger.debug("Initialized",this.capabilities),this.isPaused=!0,this.hasStarted=!1,await this.audioPlayer.initialize()}handleMessage(t){"audio"===t.event||"subtitles"===t.event||"viseme"===t.event?this.enqueue(t):"audio_complete"===t.event?this.markAudioComplete():"image"===t.event&&this.emit(PlaybackManagerEvents.ImageChange,t)}enqueue(t){if(this.capabilities.audio&&"audio"===t.event){const e=t;this.audioPlayer.enqueue(e.audio)}}markAudioComplete(){this.logger.debug("Marking audio as complete"),this.capabilities.audio&&this.audioPlayer.markComplete()}async play(){this.isPaused=!1,this.hasStarted=!0,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.play():Promise.resolve()]),await this.emit(PlaybackManagerEvents.Playing)}async pause(){this.isPaused=!0,this.audioPlayer.pause(),this.visemeScheduler.pause(),this.subtitleManager.pause(),this.avatarManager.playIdle(),await this.emit(PlaybackManagerEvents.Paused)}async resume(){this.isPaused&&(this.isPaused=!1,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.resume():Promise.resolve()]),await this.emit(PlaybackManagerEvents.Playing))}async resumeAudioContext(){"function"==typeof this.audioPlayer.resumeAudioContext&&await this.audioPlayer.resumeAudioContext()}getRemainingAudioSeconds(){return this.audioPlayer?.getRemainingAudioSeconds()??0}reset(){this.resetState(),this.audioPlayer?.reset(),this.subtitleManager?.reset(),this.avatarManager.playIdle()}resetAboutToComplete(){this.audioPlayer?.resetAboutToComplete()}dispose(){this.logger.debug("Disposing PlaybackManager...");try{this.isPaused=!0,this.hasStarted=!1,this.audioPlayer?.pause(),this.visemeScheduler?.pause(),this.subtitleManager?.pause(),this.avatarManager?.playIdle()}catch(t){this.logger.warn("Error pausing components during dispose",t)}try{this.audioPlayer&&"function"==typeof this.audioPlayer.dispose&&this.audioPlayer.dispose()}catch(t){this.logger.warn("Error disposing audioPlayer",t)}try{this.avatarManager&&"function"==typeof this.avatarManager.dispose&&this.avatarManager.dispose()}catch(t){this.logger.warn("Error disposing avatarManager",t)}try{this.subtitleManager?.reset(),this.removeAllListeners()}catch(t){this.logger.warn("Error resetting subtitleManager or removing listeners",t)}this.logger.debug("PlaybackManager disposed")}wireVADToAvatar(t){t.on(ConversationManagerEvents.StateChange,t=>{"userSpeaking"===t.newState?this.avatarManager.playListen():"listening"===t.newState&&this.avatarManager.playIdle()})}wireConversationStateToAvatar(t){t.on(ConversationManagerEvents.StateChange,t=>{"waiting"===t.newState&&this.avatarManager.playThink()})}}var dist=__webpack_require__(937);const VadManagerEvents={VoiceActivity:"voiceActivity",Silence:"silence"};class VADManager extends EventEmitter{vadModel=null;silenceTimer=null;silenceTimeoutMs;positiveSpeechThreshold;negativeSpeechThreshold;minSpeechFrames;isDisposed=!1;constructor(t=300,e=.5,n=.35,r=3){super(new DefaultLogger({category:"🎤 VADManager",style:StylePurple})),this.silenceTimeoutMs=t,this.positiveSpeechThreshold=e,this.negativeSpeechThreshold=n,this.minSpeechFrames=r}async initialize(t){if(this.isDisposed)return;this.logger.debug("You may need to close the browser console for this to initialize");const e=await dist.Jl.new({stream:t,baseAssetPath:"/static/binaries/",onnxWASMBasePath:"/static/binaries/",positiveSpeechThreshold:this.positiveSpeechThreshold,negativeSpeechThreshold:this.negativeSpeechThreshold,minSpeechFrames:this.minSpeechFrames,onSpeechStart:async()=>{this.isDisposed||(this.logger.debug("Speech started"),this.clearSilenceTimer(),await this.emit(VadManagerEvents.VoiceActivity,{isSpeaking:!0,confidence:1}))},onSpeechEnd:async t=>{this.isDisposed||(this.logger.debug("Speech ended"),this.startSilenceTimer(),await this.emit(VadManagerEvents.VoiceActivity,{isSpeaking:!1,confidence:1}))},onVADMisfire:async()=>{this.isDisposed||(this.logger.debug("Misfire detected"),await this.emit(VadManagerEvents.VoiceActivity,{isSpeaking:!1,confidence:0,misfire:!0}))},onFrameProcessed:async t=>{}});if(this.isDisposed)return this.logger.debug("VADManager disposed during initialization, cleaning up model"),void("function"==typeof e.destroy?e.destroy():e.pause());this.vadModel=e,this.logger.debug(`VAD Manager initialized (MicVAD) with silenceTimeoutMs=${this.silenceTimeoutMs}, positiveSpeechThreshold=${this.positiveSpeechThreshold}, negativeSpeechThreshold=${this.negativeSpeechThreshold}, minSpeechFrames=${this.minSpeechFrames}`)}startAnalysis(){this.vadModel&&(this.vadModel.start(),this.logger.debug("VAD analysis started (MicVAD)"))}stopAnalysis(){this.clearSilenceTimer(),this.vadModel&&(this.vadModel.pause(),this.logger.debug("VAD analysis stopped (MicVAD)"))}startSilenceTimer(){this.silenceTimer||(this.silenceTimer=window.setTimeout(async()=>{await this.emit(VadManagerEvents.Silence),this.silenceTimer=null},this.silenceTimeoutMs))}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}dispose(){try{this.logger.debug("Disposing VADManager..."),this.isDisposed=!0,this.stopAnalysis(),this.vadModel&&("function"==typeof this.vadModel.destroy&&this.vadModel.destroy(),this.vadModel=null),this.clearSilenceTimer(),this.removeAllListeners(),this.logger.debug("VADManager disposed")}catch(t){this.logger.warn("Error while disposing VADManager",t)}}}const UserInputManagerEvents={UserInput:"user-input",UserSpeaking:"user-speaking",UserSilence:"user-silence"},AUDIO_RECORDER_EVENTS={RecordingStarted:"recording-started",RecordingStopped:"recording-stopped",AudioData:"audio-data",Error:"error"},types_VadManagerEvents={VoiceActivity:"voiceActivity",Silence:"silence"},randomUUID="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dist_native={randomUUID};let getRandomValues;const rnds8=new Uint8Array(16);function rng(){if(!getRandomValues){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");getRandomValues=crypto.getRandomValues.bind(crypto)}return getRandomValues(rnds8)}const byteToHex=[];for(let t=0;t<256;++t)byteToHex.push((t+256).toString(16).slice(1));function unsafeStringify(t,e=0){return(byteToHex[t[e+0]]+byteToHex[t[e+1]]+byteToHex[t[e+2]]+byteToHex[t[e+3]]+"-"+byteToHex[t[e+4]]+byteToHex[t[e+5]]+"-"+byteToHex[t[e+6]]+byteToHex[t[e+7]]+"-"+byteToHex[t[e+8]]+byteToHex[t[e+9]]+"-"+byteToHex[t[e+10]]+byteToHex[t[e+11]]+byteToHex[t[e+12]]+byteToHex[t[e+13]]+byteToHex[t[e+14]]+byteToHex[t[e+15]]).toLowerCase()}function stringify(t,e=0){const n=unsafeStringify(t,e);if(!validate(n))throw TypeError("Stringified UUID is invalid");return n}const dist_stringify=null;function _v4(t,e,n){const r=(t=t||{}).random??t.rng?.()??rng();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=15&r[6]|64,r[8]=63&r[8]|128,e){if((n=n||0)<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[n+t]=r[t];return e}return unsafeStringify(r)}function v4(t,e,n){return!dist_native.randomUUID||e||t?_v4(t,e,n):dist_native.randomUUID()}const dist_v4=v4;class WebSocketConnection{websocket=null;handlers;serverUrl;constructor(t,e){this.serverUrl=t,this.handlers=e}connect(){this.websocket=new WebSocket(this.serverUrl),this.setupHandlers()}disconnect(){this.websocket&&(this.websocket.onmessage=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket.close(1e3,"Client initiated disconnect"),this.websocket=null)}send(t){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("Cant send. WebSocket is not open");this.websocket.send(JSON.stringify(t))}isReady(){return this.websocket?.readyState===WebSocket.OPEN}setupHandlers(){this.websocket&&(this.websocket.onopen=()=>{this.handlers.onOpen&&this.handlers.onOpen()},this.websocket.onmessage=t=>{const e=JSON.parse(t.data);this.handlers.onMessage&&this.handlers.onMessage(e)},this.websocket.onerror=t=>{this.handlers.onError&&this.handlers.onError(t)},this.websocket.onclose=()=>{this.handlers.onClose&&this.handlers.onClose()})}}function bind(t,e){return function(){return t.apply(e,arguments)}}const{toString:utils_toString}=Object.prototype,{getPrototypeOf}=Object,{iterator,toStringTag}=Symbol,kindOf=(cache=Object.create(null),t=>{const e=utils_toString.call(t);return cache[e]||(cache[e]=e.slice(8,-1).toLowerCase())});var cache;const kindOfTest=t=>(t=t.toLowerCase(),e=>kindOf(e)===t),typeOfTest=t=>e=>typeof e===t,{isArray}=Array,isUndefined=typeOfTest("undefined");function isBuffer(t){return null!==t&&!isUndefined(t)&&null!==t.constructor&&!isUndefined(t.constructor)&&isFunction(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(t){let e;return e="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&isArrayBuffer(t.buffer),e}const isString=typeOfTest("string"),isFunction=typeOfTest("function"),isNumber=typeOfTest("number"),isObject=t=>null!==t&&"object"==typeof t,isBoolean=t=>!0===t||!1===t,isPlainObject=t=>{if("object"!==kindOf(t))return!1;const e=getPrototypeOf(t);return!(null!==e&&e!==Object.prototype&&null!==Object.getPrototypeOf(e)||toStringTag in t||iterator in t)},isEmptyObject=t=>{if(!isObject(t)||isBuffer(t))return!1;try{return 0===Object.keys(t).length&&Object.getPrototypeOf(t)===Object.prototype}catch(t){return!1}},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=t=>isObject(t)&&isFunction(t.pipe),isFormData=t=>{let e;return t&&("function"==typeof FormData&&t instanceof FormData||isFunction(t.append)&&("formdata"===(e=kindOf(t))||"object"===e&&isFunction(t.toString)&&"[object FormData]"===t.toString()))},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(t,e,{allOwnKeys:n=!1}={}){if(null==t)return;let r,i;if("object"!=typeof t&&(t=[t]),isArray(t))for(r=0,i=t.length;r<i;r++)e.call(null,t[r],r,t);else{if(isBuffer(t))return;const i=n?Object.getOwnPropertyNames(t):Object.keys(t),o=i.length;let s;for(r=0;r<o;r++)s=i[r],e.call(null,t[s],s,t)}}function findKey(t,e){if(isBuffer(t))return null;e=e.toLowerCase();const n=Object.keys(t);let r,i=n.length;for(;i-- >0;)if(r=n[i],e===r.toLowerCase())return r;return null}const _global="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,isContextDefined=t=>!isUndefined(t)&&t!==_global;function merge(){const{caseless:t,skipUndefined:e}=isContextDefined(this)&&this||{},n={},r=(r,i)=>{const o=t&&findKey(n,i)||i;isPlainObject(n[o])&&isPlainObject(r)?n[o]=merge(n[o],r):isPlainObject(r)?n[o]=merge({},r):isArray(r)?n[o]=r.slice():e&&isUndefined(r)||(n[o]=r)};for(let t=0,e=arguments.length;t<e;t++)arguments[t]&&forEach(arguments[t],r);return n}const extend=(t,e,n,{allOwnKeys:r}={})=>(forEach(e,(e,r)=>{n&&isFunction(e)?t[r]=bind(e,n):t[r]=e},{allOwnKeys:r}),t),stripBOM=t=>(65279===t.charCodeAt(0)&&(t=t.slice(1)),t),inherits=(t,e,n,r)=>{t.prototype=Object.create(e.prototype,r),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),n&&Object.assign(t.prototype,n)},toFlatObject=(t,e,n,r)=>{let i,o,s;const a={};if(e=e||{},null==t)return e;do{for(i=Object.getOwnPropertyNames(t),o=i.length;o-- >0;)s=i[o],r&&!r(s,t,e)||a[s]||(e[s]=t[s],a[s]=!0);t=!1!==n&&getPrototypeOf(t)}while(t&&(!n||n(t,e))&&t!==Object.prototype);return e},endsWith=(t,e,n)=>{t=String(t),(void 0===n||n>t.length)&&(n=t.length),n-=e.length;const r=t.indexOf(e,n);return-1!==r&&r===n},toArray=t=>{if(!t)return null;if(isArray(t))return t;let e=t.length;if(!isNumber(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=t[e];return n},isTypedArray=(TypedArray="undefined"!=typeof Uint8Array&&getPrototypeOf(Uint8Array),t=>TypedArray&&t instanceof TypedArray);var TypedArray;const forEachEntry=(t,e)=>{const n=(t&&t[iterator]).call(t);let r;for(;(r=n.next())&&!r.done;){const n=r.value;e.call(t,n[0],n[1])}},matchAll=(t,e)=>{let n;const r=[];for(;null!==(n=t.exec(e));)r.push(n);return r},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,e,n){return e.toUpperCase()+n}),utils_hasOwnProperty=(({hasOwnProperty:t})=>(e,n)=>t.call(e,n))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(t,e)=>{const n=Object.getOwnPropertyDescriptors(t),r={};forEach(n,(n,i)=>{let o;!1!==(o=e(n,i,t))&&(r[i]=o||n)}),Object.defineProperties(t,r)},freezeMethods=t=>{reduceDescriptors(t,(e,n)=>{if(isFunction(t)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const r=t[n];isFunction(r)&&(e.enumerable=!1,"writable"in e?e.writable=!1:e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet=(t,e)=>{const n={},r=t=>{t.forEach(t=>{n[t]=!0})};return isArray(t)?r(t):r(String(t).split(e)),n},noop=()=>{},toFiniteNumber=(t,e)=>null!=t&&Number.isFinite(t=+t)?t:e;function isSpecCompliantForm(t){return!!(t&&isFunction(t.append)&&"FormData"===t[toStringTag]&&t[iterator])}const toJSONObject=t=>{const e=new Array(10),n=(t,r)=>{if(isObject(t)){if(e.indexOf(t)>=0)return;if(isBuffer(t))return t;if(!("toJSON"in t)){e[r]=t;const i=isArray(t)?[]:{};return forEach(t,(t,e)=>{const o=n(t,r+1);!isUndefined(o)&&(i[e]=o)}),e[r]=void 0,i}}return t};return n(t,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=t=>t&&(isObject(t)||isFunction(t))&&isFunction(t.then)&&isFunction(t.catch),_setImmediate=(setImmediateSupported="function"==typeof setImmediate,postMessageSupported=isFunction(_global.postMessage),setImmediateSupported?setImmediate:postMessageSupported?(token=`axios@${Math.random()}`,callbacks=[],_global.addEventListener("message",({source:t,data:e})=>{t===_global&&e===token&&callbacks.length&&callbacks.shift()()},!1),t=>{callbacks.push(t),_global.postMessage(token,"*")}):t=>setTimeout(t));var setImmediateSupported,postMessageSupported,token,callbacks;const asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global):"undefined"!=typeof process&&process.nextTick||_setImmediate,isIterable=t=>null!=t&&isFunction(t[iterator]),utils={isArray,isArrayBuffer,isBuffer,isFormData,isArrayBufferView,isString,isNumber,isBoolean,isObject,isPlainObject,isEmptyObject,isReadableStream,isRequest,isResponse,isHeaders,isUndefined,isDate,isFile,isBlob,isRegExp,isFunction,isStream,isURLSearchParams,isTypedArray,isFileList,forEach,merge,extend,trim,stripBOM,inherits,toFlatObject,kindOf,kindOfTest,endsWith,toArray,forEachEntry,matchAll,isHTMLForm,hasOwnProperty:utils_hasOwnProperty,hasOwnProp:utils_hasOwnProperty,reduceDescriptors,freezeMethods,toObjectSet,toCamelCase,noop,toFiniteNumber,findKey,global:_global,isContextDefined,isSpecCompliantForm,toJSONObject,isAsyncFn,isThenable,setImmediate:_setImmediate,asap,isIterable};function AxiosError(t,e,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=t,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}utils.inherits(AxiosError,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:utils.toJSONObject(this.config),code:this.code,status:this.status}}});const AxiosError_prototype=AxiosError.prototype,descriptors={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{descriptors[t]={value:t}}),Object.defineProperties(AxiosError,descriptors),Object.defineProperty(AxiosError_prototype,"isAxiosError",{value:!0}),AxiosError.from=(t,e,n,r,i,o)=>{const s=Object.create(AxiosError_prototype);utils.toFlatObject(t,s,function(t){return t!==Error.prototype},t=>"isAxiosError"!==t);const a=t&&t.message?t.message:"Error",u=null==e&&t?t.code:e;return AxiosError.call(s,a,u,n,r,i),t&&null==s.cause&&Object.defineProperty(s,"cause",{value:t,configurable:!0}),s.name=t&&t.name||"Error",o&&Object.assign(s,o),s};const core_AxiosError=AxiosError,helpers_null=null;function isVisitable(t){return utils.isPlainObject(t)||utils.isArray(t)}function removeBrackets(t){return utils.endsWith(t,"[]")?t.slice(0,-2):t}function renderKey(t,e,n){return t?t.concat(e).map(function(t,e){return t=removeBrackets(t),!n&&e?"["+t+"]":t}).join(n?".":""):e}function isFlatArray(t){return utils.isArray(t)&&!t.some(isVisitable)}const predicates=utils.toFlatObject(utils,{},null,function(t){return/^is[A-Z]/.test(t)});function toFormData(t,e,n){if(!utils.isObject(t))throw new TypeError("target must be an object");e=e||new(helpers_null||FormData);const r=(n=utils.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(t,e){return!utils.isUndefined(e[t])})).metaTokens,i=n.visitor||l,o=n.dots,s=n.indexes,a=(n.Blob||"undefined"!=typeof Blob&&Blob)&&utils.isSpecCompliantForm(e);if(!utils.isFunction(i))throw new TypeError("visitor must be a function");function u(t){if(null===t)return"";if(utils.isDate(t))return t.toISOString();if(utils.isBoolean(t))return t.toString();if(!a&&utils.isBlob(t))throw new core_AxiosError("Blob is not supported. Use a Buffer instead.");return utils.isArrayBuffer(t)||utils.isTypedArray(t)?a&&"function"==typeof Blob?new Blob([t]):Buffer.from(t):t}function l(t,n,i){let a=t;if(t&&!i&&"object"==typeof t)if(utils.endsWith(n,"{}"))n=r?n:n.slice(0,-2),t=JSON.stringify(t);else if(utils.isArray(t)&&isFlatArray(t)||(utils.isFileList(t)||utils.endsWith(n,"[]"))&&(a=utils.toArray(t)))return n=removeBrackets(n),a.forEach(function(t,r){!utils.isUndefined(t)&&null!==t&&e.append(!0===s?renderKey([n],r,o):null===s?n:n+"[]",u(t))}),!1;return!!isVisitable(t)||(e.append(renderKey(i,n,o),u(t)),!1)}const c=[],d=Object.assign(predicates,{defaultVisitor:l,convertValue:u,isVisitable});if(!utils.isObject(t))throw new TypeError("data must be an object");return function t(n,r){if(!utils.isUndefined(n)){if(-1!==c.indexOf(n))throw Error("Circular reference detected in "+r.join("."));c.push(n),utils.forEach(n,function(n,o){!0===(!(utils.isUndefined(n)||null===n)&&i.call(e,n,utils.isString(o)?o.trim():o,r,d))&&t(n,r?r.concat(o):[o])}),c.pop()}}(t),e}const helpers_toFormData=toFormData;function encode(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(t){return e[t]})}function AxiosURLSearchParams(t,e){this._pairs=[],t&&helpers_toFormData(t,this,e)}const AxiosURLSearchParams_prototype=AxiosURLSearchParams.prototype;AxiosURLSearchParams_prototype.append=function(t,e){this._pairs.push([t,e])},AxiosURLSearchParams_prototype.toString=function(t){const e=t?function(e){return t.call(this,e,encode)}:encode;return this._pairs.map(function(t){return e(t[0])+"="+e(t[1])},"").join("&")};const helpers_AxiosURLSearchParams=AxiosURLSearchParams;function buildURL_encode(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function buildURL(t,e,n){if(!e)return t;const r=n&&n.encode||buildURL_encode;utils.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let o;if(o=i?i(e,n):utils.isURLSearchParams(e)?e.toString():new helpers_AxiosURLSearchParams(e,n).toString(r),o){const e=t.indexOf("#");-1!==e&&(t=t.slice(0,e)),t+=(-1===t.indexOf("?")?"?":"&")+o}return t}class InterceptorManager{constructor(){this.handlers=[]}use(t,e,n){return this.handlers.push({fulfilled:t,rejected:e,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){utils.forEach(this.handlers,function(e){null!==e&&t(e)})}}const core_InterceptorManager=InterceptorManager,defaults_transitional={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},classes_URLSearchParams="undefined"!=typeof URLSearchParams?URLSearchParams:helpers_AxiosURLSearchParams,classes_FormData="undefined"!=typeof FormData?FormData:null,classes_Blob="undefined"!=typeof Blob?Blob:null,browser={isBrowser:!0,classes:{URLSearchParams:classes_URLSearchParams,FormData:classes_FormData,Blob:classes_Blob},protocols:["http","https","file","blob","url","data"]},hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost",platform={...common_utils_namespaceObject,...browser};function toURLEncodedForm(t,e){return helpers_toFormData(t,new platform.classes.URLSearchParams,{visitor:function(t,e,n,r){return platform.isNode&&utils.isBuffer(t)?(this.append(e,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...e})}function parsePropPath(t){return utils.matchAll(/\w+|\[(\w*)]/g,t).map(t=>"[]"===t[0]?"":t[1]||t[0])}function arrayToObject(t){const e={},n=Object.keys(t);let r;const i=n.length;let o;for(r=0;r<i;r++)o=n[r],e[o]=t[o];return e}function formDataToJSON(t){function e(t,n,r,i){let o=t[i++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=i>=t.length;return o=!o&&utils.isArray(r)?r.length:o,a?(utils.hasOwnProp(r,o)?r[o]=[r[o],n]:r[o]=n,!s):(r[o]&&utils.isObject(r[o])||(r[o]=[]),e(t,n,r[o],i)&&utils.isArray(r[o])&&(r[o]=arrayToObject(r[o])),!s)}if(utils.isFormData(t)&&utils.isFunction(t.entries)){const n={};return utils.forEachEntry(t,(t,r)=>{e(parsePropPath(t),r,n,0)}),n}return null}const helpers_formDataToJSON=formDataToJSON;function stringifySafely(t,e,n){if(utils.isString(t))try{return(e||JSON.parse)(t),utils.trim(t)}catch(t){if("SyntaxError"!==t.name)throw t}return(n||JSON.stringify)(t)}const defaults={transitional:defaults_transitional,adapter:["xhr","http","fetch"],transformRequest:[function(t,e){const n=e.getContentType()||"",r=n.indexOf("application/json")>-1,i=utils.isObject(t);if(i&&utils.isHTMLForm(t)&&(t=new FormData(t)),utils.isFormData(t))return r?JSON.stringify(helpers_formDataToJSON(t)):t;if(utils.isArrayBuffer(t)||utils.isBuffer(t)||utils.isStream(t)||utils.isFile(t)||utils.isBlob(t)||utils.isReadableStream(t))return t;if(utils.isArrayBufferView(t))return t.buffer;if(utils.isURLSearchParams(t))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(i){if(n.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(t,this.formSerializer).toString();if((o=utils.isFileList(t))||n.indexOf("multipart/form-data")>-1){const e=this.env&&this.env.FormData;return helpers_toFormData(o?{"files[]":t}:t,e&&new e,this.formSerializer)}}return i||r?(e.setContentType("application/json",!1),stringifySafely(t)):t}],transformResponse:[function(t){const e=this.transitional||defaults.transitional,n=e&&e.forcedJSONParsing,r="json"===this.responseType;if(utils.isResponse(t)||utils.isReadableStream(t))return t;if(t&&utils.isString(t)&&(n&&!this.responseType||r)){const n=!(e&&e.silentJSONParsing)&&r;try{return JSON.parse(t,this.parseReviver)}catch(t){if(n){if("SyntaxError"===t.name)throw core_AxiosError.from(t,core_AxiosError.ERR_BAD_RESPONSE,this,null,this.response);throw t}}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils.forEach(["delete","get","head","post","put","patch"],t=>{defaults.headers[t]={}});const lib_defaults=defaults,ignoreDuplicateOf=utils.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),parseHeaders=t=>{const e={};let n,r,i;return t&&t.split("\n").forEach(function(t){i=t.indexOf(":"),n=t.substring(0,i).trim().toLowerCase(),r=t.substring(i+1).trim(),!n||e[n]&&ignoreDuplicateOf[n]||("set-cookie"===n?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},$internals=Symbol("internals");function normalizeHeader(t){return t&&String(t).trim().toLowerCase()}function normalizeValue(t){return!1===t||null==t?t:utils.isArray(t)?t.map(normalizeValue):String(t)}function parseTokens(t){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(t);)e[r[1]]=r[2];return e}const isValidHeaderName=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function matchHeaderValue(t,e,n,r,i){return utils.isFunction(r)?r.call(this,e,n):(i&&(e=n),utils.isString(e)?utils.isString(r)?-1!==e.indexOf(r):utils.isRegExp(r)?r.test(e):void 0:void 0)}function formatHeader(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,e,n)=>e.toUpperCase()+n)}function buildAccessors(t,e){const n=utils.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(t,r+n,{value:function(t,n,i){return this[r].call(this,e,t,n,i)},configurable:!0})})}class AxiosHeaders{constructor(t){t&&this.set(t)}set(t,e,n){const r=this;function i(t,e,n){const i=normalizeHeader(e);if(!i)throw new Error("header name must be a non-empty string");const o=utils.findKey(r,i);(!o||void 0===r[o]||!0===n||void 0===n&&!1!==r[o])&&(r[o||e]=normalizeValue(t))}const o=(t,e)=>utils.forEach(t,(t,n)=>i(t,n,e));if(utils.isPlainObject(t)||t instanceof this.constructor)o(t,e);else if(utils.isString(t)&&(t=t.trim())&&!isValidHeaderName(t))o(parseHeaders(t),e);else if(utils.isObject(t)&&utils.isIterable(t)){let n,r,i={};for(const e of t){if(!utils.isArray(e))throw TypeError("Object iterator must return a key-value pair");i[r=e[0]]=(n=i[r])?utils.isArray(n)?[...n,e[1]]:[n,e[1]]:e[1]}o(i,e)}else null!=t&&i(e,t,n);return this}get(t,e){if(t=normalizeHeader(t)){const n=utils.findKey(this,t);if(n){const t=this[n];if(!e)return t;if(!0===e)return parseTokens(t);if(utils.isFunction(e))return e.call(this,t,n);if(utils.isRegExp(e))return e.exec(t);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,e){if(t=normalizeHeader(t)){const n=utils.findKey(this,t);return!(!n||void 0===this[n]||e&&!matchHeaderValue(this,this[n],n,e))}return!1}delete(t,e){const n=this;let r=!1;function i(t){if(t=normalizeHeader(t)){const i=utils.findKey(n,t);!i||e&&!matchHeaderValue(n,n[i],i,e)||(delete n[i],r=!0)}}return utils.isArray(t)?t.forEach(i):i(t),r}clear(t){const e=Object.keys(this);let n=e.length,r=!1;for(;n--;){const i=e[n];t&&!matchHeaderValue(this,this[i],i,t,!0)||(delete this[i],r=!0)}return r}normalize(t){const e=this,n={};return utils.forEach(this,(r,i)=>{const o=utils.findKey(n,i);if(o)return e[o]=normalizeValue(r),void delete e[i];const s=t?formatHeader(i):String(i).trim();s!==i&&delete e[i],e[s]=normalizeValue(r),n[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const e=Object.create(null);return utils.forEach(this,(n,r)=>{null!=n&&!1!==n&&(e[r]=t&&utils.isArray(n)?n.join(", "):n)}),e}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,e])=>t+": "+e).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...e){const n=new this(t);return e.forEach(t=>n.set(t)),n}static accessor(t){const e=(this[$internals]=this[$internals]={accessors:{}}).accessors,n=this.prototype;function r(t){const r=normalizeHeader(t);e[r]||(buildAccessors(n,t),e[r]=!0)}return utils.isArray(t)?t.forEach(r):r(t),this}}AxiosHeaders.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils.reduceDescriptors(AxiosHeaders.prototype,({value:t},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(t){this[n]=t}}}),utils.freezeMethods(AxiosHeaders);const core_AxiosHeaders=AxiosHeaders;function transformData(t,e){const n=this||lib_defaults,r=e||n,i=core_AxiosHeaders.from(r.headers);let o=r.data;return utils.forEach(t,function(t){o=t.call(n,o,i.normalize(),e?e.status:void 0)}),i.normalize(),o}function isCancel(t){return!(!t||!t.__CANCEL__)}function CanceledError(t,e,n){core_AxiosError.call(this,null==t?"canceled":t,core_AxiosError.ERR_CANCELED,e,n),this.name="CanceledError"}utils.inherits(CanceledError,core_AxiosError,{__CANCEL__:!0});const cancel_CanceledError=CanceledError;function settle(t,e,n){const r=n.config.validateStatus;n.status&&r&&!r(n.status)?e(new core_AxiosError("Request failed with status code "+n.status,[core_AxiosError.ERR_BAD_REQUEST,core_AxiosError.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):t(n)}function parseProtocol(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function speedometer(t,e){t=t||10;const n=new Array(t),r=new Array(t);let i,o=0,s=0;return e=void 0!==e?e:1e3,function(a){const u=Date.now(),l=r[s];i||(i=u),n[o]=a,r[o]=u;let c=s,d=0;for(;c!==o;)d+=n[c++],c%=t;if(o=(o+1)%t,o===s&&(s=(s+1)%t),u-i<e)return;const h=l&&u-l;return h?Math.round(1e3*d/h):void 0}}const helpers_speedometer=speedometer;function throttle(t,e){let n,r,i=0,o=1e3/e;const s=(e,o=Date.now())=>{i=o,n=null,r&&(clearTimeout(r),r=null),t(...e)};return[(...t)=>{const e=Date.now(),a=e-i;a>=o?s(t,e):(n=t,r||(r=setTimeout(()=>{r=null,s(n)},o-a)))},()=>n&&s(n)]}const helpers_throttle=throttle,progressEventReducer=(t,e,n=3)=>{let r=0;const i=helpers_speedometer(50,250);return helpers_throttle(n=>{const o=n.loaded,s=n.lengthComputable?n.total:void 0,a=o-r,u=i(a);r=o,t({loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:u||void 0,estimated:u&&s&&o<=s?(s-o)/u:void 0,event:n,lengthComputable:null!=s,[e?"download":"upload"]:!0})},n)},progressEventDecorator=(t,e)=>{const n=null!=t;return[r=>e[0]({lengthComputable:n,total:t,loaded:r}),e[1]]},asyncDecorator=t=>(...e)=>utils.asap(()=>t(...e)),isURLSameOrigin=platform.hasStandardBrowserEnv?((t,e)=>n=>(n=new URL(n,platform.origin),t.protocol===n.protocol&&t.host===n.host&&(e||t.port===n.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(t,e,n,r,i,o){const s=[t+"="+encodeURIComponent(e)];utils.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),utils.isString(r)&&s.push("path="+r),utils.isString(i)&&s.push("domain="+i),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function isAbsoluteURL(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function combineURLs(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function buildFullPath(t,e,n){let r=!isAbsoluteURL(e);return t&&(r||0==n)?combineURLs(t,e):e}const headersToObject=t=>t instanceof core_AxiosHeaders?{...t}:t;function mergeConfig(t,e){e=e||{};const n={};function r(t,e,n,r){return utils.isPlainObject(t)&&utils.isPlainObject(e)?utils.merge.call({caseless:r},t,e):utils.isPlainObject(e)?utils.merge({},e):utils.isArray(e)?e.slice():e}function i(t,e,n,i){return utils.isUndefined(e)?utils.isUndefined(t)?void 0:r(void 0,t,0,i):r(t,e,0,i)}function o(t,e){if(!utils.isUndefined(e))return r(void 0,e)}function s(t,e){return utils.isUndefined(e)?utils.isUndefined(t)?void 0:r(void 0,t):r(void 0,e)}function a(n,i,o){return o in e?r(n,i):o in t?r(void 0,n):void 0}const u={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(t,e,n)=>i(headersToObject(t),headersToObject(e),0,!0)};return utils.forEach(Object.keys({...t,...e}),function(r){const o=u[r]||i,s=o(t[r],e[r],r);utils.isUndefined(s)&&o!==a||(n[r]=s)}),n}const resolveConfig=t=>{const e=mergeConfig({},t);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:o,headers:s,auth:a}=e;if(e.headers=s=core_AxiosHeaders.from(s),e.url=buildURL(buildFullPath(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),utils.isFormData(n))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(utils.isFunction(n.getHeaders)){const t=n.getHeaders(),e=["content-type","content-length"];Object.entries(t).forEach(([t,n])=>{e.includes(t.toLowerCase())&&s.set(t,n)})}if(platform.hasStandardBrowserEnv&&(r&&utils.isFunction(r)&&(r=r(e)),r||!1!==r&&isURLSameOrigin(e.url))){const t=i&&o&&cookies.read(o);t&&s.set(i,t)}return e},isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest,xhr=isXHRAdapterSupported&&function(t){return new Promise(function(e,n){const r=resolveConfig(t);let i=r.data;const o=core_AxiosHeaders.from(r.headers).normalize();let s,a,u,l,c,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=r;function f(){l&&l(),c&&c(),r.cancelToken&&r.cancelToken.unsubscribe(s),r.signal&&r.signal.removeEventListener("abort",s)}let g=new XMLHttpRequest;function m(){if(!g)return;const r=core_AxiosHeaders.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());settle(function(t){e(t),f()},function(t){n(t),f()},{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:r,config:t,request:g}),g=null}g.open(r.method.toUpperCase(),r.url,!0),g.timeout=r.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(n(new core_AxiosError("Request aborted",core_AxiosError.ECONNABORTED,t,g)),g=null)},g.onerror=function(e){const r=e&&e.message?e.message:"Network Error",i=new core_AxiosError(r,core_AxiosError.ERR_NETWORK,t,g);i.event=e||null,n(i),g=null},g.ontimeout=function(){let e=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||defaults_transitional;r.timeoutErrorMessage&&(e=r.timeoutErrorMessage),n(new core_AxiosError(e,i.clarifyTimeoutError?core_AxiosError.ETIMEDOUT:core_AxiosError.ECONNABORTED,t,g)),g=null},void 0===i&&o.setContentType(null),"setRequestHeader"in g&&utils.forEach(o.toJSON(),function(t,e){g.setRequestHeader(e,t)}),utils.isUndefined(r.withCredentials)||(g.withCredentials=!!r.withCredentials),d&&"json"!==d&&(g.responseType=r.responseType),p&&([u,c]=progressEventReducer(p,!0),g.addEventListener("progress",u)),h&&g.upload&&([a,l]=progressEventReducer(h),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",l)),(r.cancelToken||r.signal)&&(s=e=>{g&&(n(!e||e.type?new cancel_CanceledError(null,t,g):e),g.abort(),g=null)},r.cancelToken&&r.cancelToken.subscribe(s),r.signal&&(r.signal.aborted?s():r.signal.addEventListener("abort",s)));const b=parseProtocol(r.url);b&&-1===platform.protocols.indexOf(b)?n(new core_AxiosError("Unsupported protocol "+b+":",core_AxiosError.ERR_BAD_REQUEST,t)):g.send(i||null)})},composeSignals=(t,e)=>{const{length:n}=t=t?t.filter(Boolean):[];if(e||n){let n,r=new AbortController;const i=function(t){if(!n){n=!0,s();const e=t instanceof Error?t:this.reason;r.abort(e instanceof core_AxiosError?e:new cancel_CanceledError(e instanceof Error?e.message:e))}};let o=e&&setTimeout(()=>{o=null,i(new core_AxiosError(`timeout ${e} of ms exceeded`,core_AxiosError.ETIMEDOUT))},e);const s=()=>{t&&(o&&clearTimeout(o),o=null,t.forEach(t=>{t.unsubscribe?t.unsubscribe(i):t.removeEventListener("abort",i)}),t=null)};t.forEach(t=>t.addEventListener("abort",i));const{signal:a}=r;return a.unsubscribe=()=>utils.asap(s),a}},helpers_composeSignals=composeSignals,streamChunk=function*(t,e){let n=t.byteLength;if(!e||n<e)return void(yield t);let r,i=0;for(;i<n;)r=i+e,yield t.slice(i,r),i=r},readBytes=async function*(t,e){for await(const n of readStream(t))yield*streamChunk(n,e)},readStream=async function*(t){if(t[Symbol.asyncIterator])return void(yield*t);const e=t.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}},trackStream=(t,e,n,r)=>{const i=readBytes(t,e);let o,s=0,a=t=>{o||(o=!0,r&&r(t))};return new ReadableStream({async pull(t){try{const{done:e,value:r}=await i.next();if(e)return a(),void t.close();let o=r.byteLength;if(n){let t=s+=o;n(t)}t.enqueue(new Uint8Array(r))}catch(t){throw a(t),t}},cancel:t=>(a(t),i.return())},{highWaterMark:2})},DEFAULT_CHUNK_SIZE=65536,{isFunction:fetch_isFunction}=utils,globalFetchAPI=(({Request:t,Response:e})=>({Request:t,Response:e}))(utils.global),{ReadableStream:fetch_ReadableStream,TextEncoder}=utils.global,test=(t,...e)=>{try{return!!t(...e)}catch(t){return!1}},factory=t=>{t=utils.merge.call({skipUndefined:!0},globalFetchAPI,t);const{fetch:e,Request:n,Response:r}=t,i=e?fetch_isFunction(e):"function"==typeof fetch,o=fetch_isFunction(n),s=fetch_isFunction(r);if(!i)return!1;const a=i&&fetch_isFunction(fetch_ReadableStream),u=i&&("function"==typeof TextEncoder?(l=new TextEncoder,t=>l.encode(t)):async t=>new Uint8Array(await new n(t).arrayBuffer()));var l;const c=o&&a&&test(()=>{let t=!1;const e=new n(platform.origin,{body:new fetch_ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),d=s&&a&&test(()=>utils.isReadableStream(new r("").body)),h={stream:d&&(t=>t.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!h[t]&&(h[t]=(e,n)=>{let r=e&&e[t];if(r)return r.call(e);throw new core_AxiosError(`Response type '${t}' is not supported`,core_AxiosError.ERR_NOT_SUPPORT,n)})});return async t=>{let{url:i,method:s,data:a,signal:l,cancelToken:p,timeout:f,onDownloadProgress:g,onUploadProgress:m,responseType:b,headers:y,withCredentials:_="same-origin",fetchOptions:w}=resolveConfig(t),v=e||fetch;b=b?(b+"").toLowerCase():"text";let x=helpers_composeSignals([l,p&&p.toAbortSignal()],f),T=null;const S=x&&x.unsubscribe&&(()=>{x.unsubscribe()});let A;try{if(m&&c&&"get"!==s&&"head"!==s&&0!==(A=await(async(t,e)=>{const r=utils.toFiniteNumber(t.getContentLength());return null==r?(async t=>{if(null==t)return 0;if(utils.isBlob(t))return t.size;if(utils.isSpecCompliantForm(t)){const e=new n(platform.origin,{method:"POST",body:t});return(await e.arrayBuffer()).byteLength}return utils.isArrayBufferView(t)||utils.isArrayBuffer(t)?t.byteLength:(utils.isURLSearchParams(t)&&(t+=""),utils.isString(t)?(await u(t)).byteLength:void 0)})(e):r})(y,a))){let t,e=new n(i,{method:"POST",body:a,duplex:"half"});if(utils.isFormData(a)&&(t=e.headers.get("content-type"))&&y.setContentType(t),e.body){const[t,n]=progressEventDecorator(A,progressEventReducer(asyncDecorator(m)));a=trackStream(e.body,DEFAULT_CHUNK_SIZE,t,n)}}utils.isString(_)||(_=_?"include":"omit");const e=o&&"credentials"in n.prototype,l={...w,signal:x,method:s.toUpperCase(),headers:y.normalize().toJSON(),body:a,duplex:"half",credentials:e?_:void 0};T=o&&new n(i,l);let p=await(o?v(T,w):v(i,l));const f=d&&("stream"===b||"response"===b);if(d&&(g||f&&S)){const t={};["status","statusText","headers"].forEach(e=>{t[e]=p[e]});const e=utils.toFiniteNumber(p.headers.get("content-length")),[n,i]=g&&progressEventDecorator(e,progressEventReducer(asyncDecorator(g),!0))||[];p=new r(trackStream(p.body,DEFAULT_CHUNK_SIZE,n,()=>{i&&i(),S&&S()}),t)}b=b||"text";let E=await h[utils.findKey(h,b)||"text"](p,t);return!f&&S&&S(),await new Promise((e,n)=>{settle(e,n,{data:E,headers:core_AxiosHeaders.from(p.headers),status:p.status,statusText:p.statusText,config:t,request:T})})}catch(e){if(S&&S(),e&&"TypeError"===e.name&&/Load failed|fetch/i.test(e.message))throw Object.assign(new core_AxiosError("Network Error",core_AxiosError.ERR_NETWORK,t,T),{cause:e.cause||e});throw core_AxiosError.from(e,e&&e.code,t,T)}}},seedCache=new Map,getFetch=t=>{let e=t?t.env:{};const{fetch:n,Request:r,Response:i}=e,o=[r,i,n];let s,a,u=o.length,l=seedCache;for(;u--;)s=o[u],a=l.get(s),void 0===a&&l.set(s,a=u?new Map:factory(e)),l=a;return a},adapter=getFetch(),adapters_fetch=null,knownAdapters={http:helpers_null,xhr,fetch:{get:getFetch}};utils.forEach(knownAdapters,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(t){}Object.defineProperty(t,"adapterName",{value:e})}});const renderReason=t=>`- ${t}`,isResolvedHandle=t=>utils.isFunction(t)||null===t||!1===t,adapters={getAdapter:(t,e)=>{t=utils.isArray(t)?t:[t];const{length:n}=t;let r,i;const o={};for(let s=0;s<n;s++){let n;if(r=t[s],i=r,!isResolvedHandle(r)&&(i=knownAdapters[(n=String(r)).toLowerCase()],void 0===i))throw new core_AxiosError(`Unknown adapter '${n}'`);if(i&&(utils.isFunction(i)||(i=i.get(e))))break;o[n||"#"+s]=i}if(!i){const t=Object.entries(o).map(([t,e])=>`adapter ${t} `+(!1===e?"is not supported by the environment":"is not available in the build"));let e=n?t.length>1?"since :\n"+t.map(renderReason).join("\n"):" "+renderReason(t[0]):"as no adapter specified";throw new core_AxiosError("There is no suitable adapter to dispatch the request "+e,"ERR_NOT_SUPPORT")}return i},adapters:knownAdapters};function throwIfCancellationRequested(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new cancel_CanceledError(null,t)}function dispatchRequest(t){return throwIfCancellationRequested(t),t.headers=core_AxiosHeaders.from(t.headers),t.data=transformData.call(t,t.transformRequest),-1!==["post","put","patch"].indexOf(t.method)&&t.headers.setContentType("application/x-www-form-urlencoded",!1),adapters.getAdapter(t.adapter||lib_defaults.adapter,t)(t).then(function(e){return throwIfCancellationRequested(t),e.data=transformData.call(t,t.transformResponse,e),e.headers=core_AxiosHeaders.from(e.headers),e},function(e){return isCancel(e)||(throwIfCancellationRequested(t),e&&e.response&&(e.response.data=transformData.call(t,t.transformResponse,e.response),e.response.headers=core_AxiosHeaders.from(e.response.headers))),Promise.reject(e)})}const VERSION="1.12.2",validators={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{validators[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const deprecatedWarnings={};function assertOptions(t,e,n){if("object"!=typeof t)throw new core_AxiosError("options must be an object",core_AxiosError.ERR_BAD_OPTION_VALUE);const r=Object.keys(t);let i=r.length;for(;i-- >0;){const o=r[i],s=e[o];if(s){const e=t[o],n=void 0===e||s(e,o,t);if(!0!==n)throw new core_AxiosError("option "+o+" must be "+n,core_AxiosError.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new core_AxiosError("Unknown option "+o,core_AxiosError.ERR_BAD_OPTION)}}validators.transitional=function(t,e,n){function r(t,e){return"[Axios v"+VERSION+"] Transitional option '"+t+"'"+e+(n?". "+n:"")}return(n,i,o)=>{if(!1===t)throw new core_AxiosError(r(i," has been removed"+(e?" in "+e:"")),core_AxiosError.ERR_DEPRECATED);return e&&!deprecatedWarnings[i]&&(deprecatedWarnings[i]=!0,console.warn(r(i," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(n,i,o)}},validators.spelling=function(t){return(e,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};const validator={assertOptions,validators},Axios_validators=validator.validators;class Axios{constructor(t){this.defaults=t||{},this.interceptors={request:new core_InterceptorManager,response:new core_InterceptorManager}}async request(t,e){try{return await this._request(t,e)}catch(t){if(t instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const n=e.stack?e.stack.replace(/^.+\n/,""):"";try{t.stack?n&&!String(t.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(t.stack+="\n"+n):t.stack=n}catch(t){}}throw t}}_request(t,e){"string"==typeof t?(e=e||{}).url=t:e=t||{},e=mergeConfig(this.defaults,e);const{transitional:n,paramsSerializer:r,headers:i}=e;void 0!==n&&validator.assertOptions(n,{silentJSONParsing:Axios_validators.transitional(Axios_validators.boolean),forcedJSONParsing:Axios_validators.transitional(Axios_validators.boolean),clarifyTimeoutError:Axios_validators.transitional(Axios_validators.boolean)},!1),null!=r&&(utils.isFunction(r)?e.paramsSerializer={serialize:r}:validator.assertOptions(r,{encode:Axios_validators.function,serialize:Axios_validators.function},!0)),void 0!==e.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?e.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:e.allowAbsoluteUrls=!0),validator.assertOptions(e,{baseUrl:Axios_validators.spelling("baseURL"),withXsrfToken:Axios_validators.spelling("withXSRFToken")},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase();let o=i&&utils.merge(i.common,i[e.method]);i&&utils.forEach(["delete","get","head","post","put","patch","common"],t=>{delete i[t]}),e.headers=core_AxiosHeaders.concat(o,i);const s=[];let a=!0;this.interceptors.request.forEach(function(t){"function"==typeof t.runWhen&&!1===t.runWhen(e)||(a=a&&t.synchronous,s.unshift(t.fulfilled,t.rejected))});const u=[];let l;this.interceptors.response.forEach(function(t){u.push(t.fulfilled,t.rejected)});let c,d=0;if(!a){const t=[dispatchRequest.bind(this),void 0];for(t.unshift(...s),t.push(...u),c=t.length,l=Promise.resolve(e);d<c;)l=l.then(t[d++],t[d++]);return l}c=s.length;let h=e;for(;d<c;){const t=s[d++],e=s[d++];try{h=t(h)}catch(t){e.call(this,t);break}}try{l=dispatchRequest.call(this,h)}catch(t){return Promise.reject(t)}for(d=0,c=u.length;d<c;)l=l.then(u[d++],u[d++]);return l}getUri(t){return buildURL(buildFullPath((t=mergeConfig(this.defaults,t)).baseURL,t.url,t.allowAbsoluteUrls),t.params,t.paramsSerializer)}}utils.forEach(["delete","get","head","options"],function(t){Axios.prototype[t]=function(e,n){return this.request(mergeConfig(n||{},{method:t,url:e,data:(n||{}).data}))}}),utils.forEach(["post","put","patch"],function(t){function e(e){return function(n,r,i){return this.request(mergeConfig(i||{},{method:t,headers:e?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}Axios.prototype[t]=e(),Axios.prototype[t+"Form"]=e(!0)});const core_Axios=Axios;class CancelToken{constructor(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");let e;this.promise=new Promise(function(t){e=t});const n=this;this.promise.then(t=>{if(!n._listeners)return;let e=n._listeners.length;for(;e-- >0;)n._listeners[e](t);n._listeners=null}),this.promise.then=t=>{let e;const r=new Promise(t=>{n.subscribe(t),e=t}).then(t);return r.cancel=function(){n.unsubscribe(e)},r},t(function(t,r,i){n.reason||(n.reason=new cancel_CanceledError(t,r,i),e(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){this.reason?t(this.reason):this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1)}toAbortSignal(){const t=new AbortController,e=e=>{t.abort(e)};return this.subscribe(e),t.signal.unsubscribe=()=>this.unsubscribe(e),t.signal}static source(){let t;return{token:new CancelToken(function(e){t=e}),cancel:t}}}const cancel_CancelToken=CancelToken;function spread(t){return function(e){return t.apply(null,e)}}function isAxiosError(t){return utils.isObject(t)&&!0===t.isAxiosError}const HttpStatusCode={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode).forEach(([t,e])=>{HttpStatusCode[e]=t});const helpers_HttpStatusCode=HttpStatusCode;function createInstance(t){const e=new core_Axios(t),n=bind(core_Axios.prototype.request,e);return utils.extend(n,core_Axios.prototype,e,{allOwnKeys:!0}),utils.extend(n,e,null,{allOwnKeys:!0}),n.create=function(e){return createInstance(mergeConfig(t,e))},n}const axios=createInstance(lib_defaults);axios.Axios=core_Axios,axios.CanceledError=cancel_CanceledError,axios.CancelToken=cancel_CancelToken,axios.isCancel=isCancel,axios.VERSION=VERSION,axios.toFormData=helpers_toFormData,axios.AxiosError=core_AxiosError,axios.Cancel=axios.CanceledError,axios.all=function(t){return Promise.all(t)},axios.spread=spread,axios.isAxiosError=isAxiosError,axios.mergeConfig=mergeConfig,axios.AxiosHeaders=core_AxiosHeaders,axios.formToJSON=t=>helpers_formDataToJSON(utils.isHTMLForm(t)?new FormData(t):t),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=helpers_HttpStatusCode,axios.default=axios;const lib_axios=axios;class LocalStorage{static setItem(t,e){localStorage.setItem(t,e)}static setWithExpiry(t,e,n=33e5){const r={value:e,expiry:Date.now()+n};try{localStorage.setItem(t,JSON.stringify(r))}catch{}}static getWithExpiry(t){const e=localStorage.getItem(t);if(!e)return null;let n=null;try{n=JSON.parse(e)}catch(e){throw localStorage.removeItem(t),e}const r="number"==typeof n.expiry?n.expiry:0;return Date.now()>r?(localStorage.removeItem(t),null):n.value}static removeItem(t){localStorage.removeItem(t)}}const core_localStorage=LocalStorage,REQUEST_ID_HEADER="x-request-id";class Api{_authToken;_requestId=null;apiUrl;_apiKey;_federatedId=null;apiClient;constructor({apiUrl:t,apiKey:e,federatedId:n}){this.apiUrl=t,this._apiKey=e,this._federatedId=n,this._authToken=core_localStorage.getWithExpiry("authToken")||void 0,this.apiClient=lib_axios.create({baseURL:this.apiUrl,headers:{Authorization:`Bearer ${this.authToken}`}}),this.setInterceptors()}async login(){if(!Boolean(core_localStorage.getWithExpiry("authToken")||this.authToken))try{await this.loginWithApiKey()}catch(t){throw console.error("Failed to authenticate with client credentials.",t),core_localStorage.removeItem("authToken"),this._authToken=void 0,t}}setInterceptors(){this.apiClient.interceptors.request.use(async t=>(t.url?.includes("/auth/login")||this.login(),t),t=>Promise.reject(t)),this.apiClient.interceptors.response.use(t=>(this.updatedRequestFromResponse(t),t),t=>(t.response&&this.updatedRequestFromResponse(t.response),Promise.reject(t))),this.apiClient.interceptors.response.use(t=>t,this.handleError.bind(this)),this.apiClient.interceptors.response.use(t=>t,t=>{if(t.response)try{return JSON.stringify(t.response.data),lib_axios.isAxiosError(t)&&401===t.response?.status&&(core_localStorage.removeItem("authToken"),this._authToken=void 0),Promise.reject(t)}catch(t){return console.error(t),Promise.reject(t)}return Promise.reject(t)})}async verifyAuthentication(){await this.getMe()}updatedRequestFromResponse(t){return this.updateRequestId(t.headers[REQUEST_ID_HEADER]??""),t}handleError(t){return Promise.reject(t)}get authToken(){return this._authToken}set authToken(t){t?core_localStorage.setWithExpiry("authToken",t):core_localStorage.removeItem("authToken"),this._authToken=t,this.apiClient&&(this.apiClient.defaults.headers.Authorization=`Bearer ${t}`)}get requestId(){return this._requestId}updateRequestId(t){t&&(this._requestId=t)}async loginWithApiKey(){const t=await this.apiClient.post("/auth/login",{api_key:this._apiKey,federated_id:this._federatedId});return this.authToken=t.data.access_token,this.apiClient.defaults.headers.common.Authorization=`Bearer ${this.authToken}`,this.authToken||""}async getMe(){return(await this.apiClient.get("/users/me")).data}async generateImage(t){const{provider:e,...n}=t,r=`/images/generate/${e}`;return(await this.apiClient.post(r,n)).data}async generateImageWithBria(t){return(await this.apiClient.post("/images/generate/bria",t)).data}async generateImageWithReplicate(t){return(await this.apiClient.post("/images/generate/replicate",t)).data}async getAvailableModels(){return(await this.apiClient.get("/images/models")).data}}const api=Api,audioConfig={sampling_rate:48e3,mime_type:"audio/mpeg"};class ConversationNetwork extends EventEmitter{config;wsConnection=null;_api=null;pendingRequests=new Map;constructor(t){super(new DefaultLogger({category:"🗣️ConversationNetwork",style:StyleGrey})),this.config=t,this._api=new api({apiUrl:t.apiUrl,apiKey:t.apiKey,federatedId:t.federatedId})}async initialize(){try{await this._api.login()}catch(t){const e=t.response?.data?.error||t.message||"Authentication failed",n=t.response?.data?.traceback;n?this.logger.error("Authentication failed:",e,"\nTraceback:",n):this.logger.error("Authentication failed:",e);const r=new Error(e);throw n&&(r.traceback=n),r}}async connect(){let t=this.config.apiUrl.replace(/\/api\/?$/,"")+"/interact";this.wsConnection=new WebSocketConnection(t,this.getWebSocketHandlers()),this.wsConnection.connect(),await this.waitForWebSocketReady(1e4),this.logger.debug("Network connections established - Authenticating next...")}async waitForWebSocketReady(t){return new Promise((e,n)=>{if(!this.wsConnection)return void n(new Error("WebSocket connection not initialized"));if(this.wsConnection.isReady())return void e();const r=setTimeout(()=>{n(new Error(`WebSocket connection timeout after ${t}ms`))},t),i=()=>{this.wsConnection?.isReady()?(clearTimeout(r),e()):setTimeout(i,50)};i()})}getWebSocketHandlers(){return{onOpen:async()=>{try{await this.authenticate(),await this.setConfiguration(),this.emit(ConversationNetworkEvents.Connected),await this.interact({text:".",uid:"",kind:"interact",type:"stream"})}catch(t){const e=t?.error||String(t);this.emit(ConversationNetworkEvents.Error,new Error(e))}},onMessage:async t=>{if(t.uid&&this.pendingRequests.has(t.uid)){const e=this.pendingRequests.get(t.uid);if(e)if(e.isStream)"close"===t.kind?(clearTimeout(e.timeout),e.resolve(t),this.pendingRequests.delete(t.uid)):"error"===t.kind?(this.logger.error(t.error),this.emit(ConversationNetworkEvents.Error,new Error(t.error))):this.emit(ConversationNetworkEvents.Message,t);else{if(clearTimeout(e.timeout),"error"===t.kind){const n=t;this.logger.error(n?.error),e.reject(n.error)}else e.resolve(t);this.pendingRequests.delete(t.uid),this.emit(ConversationNetworkEvents.Message,t)}}else"interact"===t.kind?this.emit(ConversationNetworkEvents.Message,t):"error"===t.kind?(this.logger.error(t.error),await this.emit(ConversationNetworkEvents.Error,t.error)):this.logger.warn("Received message without a matching request UID",t)},onError:async t=>{await this.emit(ConversationNetworkEvents.Error,t)},onClose:async()=>{await this.emit(ConversationNetworkEvents.Disconnected)}}}async makeRequest(t,e=5e4){return this.makeRequestInternal(t,e,!1)}async makeStreamRequest(t,e=5e4){return this.makeRequestInternal(t,e,!0)}async makeRequestInternal(t,e,n){if(!this.wsConnection?.isReady())throw new Error("WebSocket not ready");t.uid=dist_v4(),t.client_start_time=(new Date).toISOString();const r=new Promise((r,i)=>{const o=setTimeout(()=>{this.pendingRequests.delete(t.uid),i(new Error(`Request ${t.uid} timed out after ${e}ms`))},e);this.pendingRequests.set(t.uid,{resolve:r,reject:i,timeout:o,isStream:n})});return this.wsConnection.send(t),r}async authenticate(){const t={type:"request",kind:"authenticate",access_token:this._api.authToken,uid:""};await this.makeRequest(t)}updateConfig(t){this.config=t}async updateRemoteConfiguration(t){this.updateConfig(t),await this.setConfiguration()}async setConfiguration(){const t={type:"request",kind:"set_configuration",config:{prompt:this.config.prompt,voice_profile:this.config.voiceProfile,utilities:this.config.utilities,safety_policy:this.config.safetyPolicy},uid:""};await this.makeRequest(t)}async addAudio(t){const e={type:"request",kind:"add_audio",audio:t,uid:"",config:audioConfig};await this.makeRequest(e)}async clearAudio(){await this.makeRequest({type:"request",kind:"clear_audio",uid:""})}async checkTurn(){await this.makeRequest({type:"request",kind:"check_turn",uid:""})}async generateImage(t){return{kind:"generate_image",uid:"",image:(await this._api.generateImage(t)).image}}async generateImageWithBria(t){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithBria(t)).image}}async generateImageWithReplicate(t){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithReplicate(t)).image}}async getAvailableModels(){return{kind:"get_available_models",uid:"",models:(await this._api.getAvailableModels()).models}}async interact(t){t.context={...this.config.context,...t.context},t.audio_output=this.config.capabilities?.audio??!0,t.kind=t.kind??"interact",t.type=t.type??"stream",await this.makeStreamRequest(t)}async interactAudio(t){t.context={...this.config.context,...t.context},t.audio_output=this.config.capabilities?.audio??!0,t.kind=t.kind??"interact",t.type=t.type??"stream",await this.makeStreamRequest(t)}async disconnect(){this.wsConnection?.disconnect()}isReady(){return this.wsConnection?.isReady()||!1}async send(t){"audio"!==t.type?this.logger.warn("ConversationNetwork.send is deprecated. Use specific methods instead."):await this.addAudio(t.audio)}}class MediaRecorderFallback{mediaRecorder=null;mimeType;onAudioData;timeslice;logger=new DefaultLogger({category:"🎤 MediaRecorderFallback",style:StyleBrown});constructor(t,e,n=100){this.mimeType=t,this.onAudioData=e,this.timeslice=n}initialize(t){this.logger.debug("Initializing MediaRecorder for audio processing"),this.mediaRecorder=new MediaRecorder(t,{mimeType:this.mimeType}),this.logger.debug("MediaRecorder created, state:",this.mediaRecorder.state),this.mediaRecorder.ondataavailable=t=>{this.logger.debug("ondataavailable called, size:",t.data.size),t.data.size>0&&t.data.arrayBuffer().then(t=>{this.onAudioData(t)})}}start(){this.mediaRecorder&&"inactive"===this.mediaRecorder.state&&(this.mediaRecorder.start(this.timeslice),this.logger.debug(`MediaRecorder started with ${this.timeslice}ms timeslice`))}stop(){this.mediaRecorder&&"inactive"!==this.mediaRecorder.state&&(this.mediaRecorder.stop(),this.logger.debug("MediaRecorder stopped"))}}const AudioRecorderEvents={RecordingStarted:"recording-started",RecordingStopped:"recording-stopped",AudioData:"audio-data",Error:"error"};class AudioRecorder extends EventEmitter{mediaStream=null;audioContext=null;workletNode=null;mediaRecorder=null;recording=!1;config;useMediaRecorder=!1;mediaRecorderFallback=null;audioBuffer=[];bufferingMode=!1;MIME_TYPE="audio/webm;codecs=opus";constructor(t={}){super(new DefaultLogger({category:"🎤 AudioRecorder",style:StyleBrown})),this.config={sampleRate:41e3,channels:1,bitDepth:16,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,timeslice:100,...t}}async initialize(t){try{this.logger.debug("Initializing..."),await this.setupAudioContext(),await this.loadAudioWorklet(),this.mediaStream=t,this.useMediaRecorder&&(this.mediaRecorderFallback=new MediaRecorderFallback(this.MIME_TYPE,t=>this.handleAudioData(t),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream)),this.logger.debug("Initialized successfully")}catch(t){throw this.logger.error("Failed to initialize",t),t}}async start(){if(this.recording)this.logger.warn("Recording already in progress");else{if(this.audioContext&&"suspended"===this.audioContext.state)try{await this.audioContext.resume(),this.logger.debug("AudioContext resumed successfully at start of recording.")}catch(t){this.logger.error("Failed to resume AudioContext:",t);const e=new Error("The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developer.chrome.com/blog/autoplay/#web_audio");throw await this.emit(AudioRecorderEvents.Error,e),e}this.audioContext||(await this.setupAudioContext(),await this.loadAudioWorklet());try{if(this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext before starting recording..."),await this.audioContext.resume()),!this.mediaStream)throw new Error("AudioRecorder: mediaStream must be set via initialize(stream) before starting recording.");this.logger.debug("setupMediaStream complete"),await this.setupAudioProcessing(),this.logger.debug("setupAudioProcessing complete"),this.recording=!0,await this.emit(AudioRecorderEvents.RecordingStarted),this.logger.debug("Audio recording started")}catch(t){throw this.logger.error("Failed to start recording",t),await this.emit(AudioRecorderEvents.Error,t),t}}}async stop(){if(this.logger.debug("Stopping recording..."),this.recording)try{await this.cleanup(),this.recording=!1,await this.emit(AudioRecorderEvents.RecordingStopped),this.logger.debug("Audio recording stopped")}catch(t){throw this.logger.error("Failed to stop recording",t),await this.emit(AudioRecorderEvents.Error,t),t}else this.logger.warn("No recording in progress")}isRecording(){return this.recording}enableBufferingMode(){this.logger.debug("Buffering mode enabled"),this.bufferingMode=!0,this.audioBuffer=[]}disableBufferingMode(){this.logger.debug("Buffering mode disabled"),this.bufferingMode=!1}getBufferedAudio(){return[...this.audioBuffer]}clearBuffer(){const t=this.audioBuffer.length;this.logger.debug(`Audio buffer cleared (Was ${t})`),this.audioBuffer=[]}async resumeAudioContext(){this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, state:",this.audioContext.state))}async setupMediaRecorder(){this.logger.debug("Setting up MediaRecorder fallback..."),this.useMediaRecorder=!0}async setupAudioContext(){this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=new AudioContext({sampleRate:this.config.sampleRate,latencyHint:"interactive"}),this.logger.debug("AudioContext created, state:",this.audioContext.state)),"suspended"===this.audioContext.state&&(this.logger.debug("Resuming suspended AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, new state:",this.audioContext.state))}async loadAudioWorklet(){if(!this.audioContext)throw new Error("AudioContext not initialized");return this.setupMediaRecorder()}async setupAudioProcessing(){if(this.logger.debug("setupAudioProcessing called, useMediaRecorder:",this.useMediaRecorder),!this.audioContext||!this.mediaStream)throw new Error("AudioContext or MediaStream not initialized");if(this.useMediaRecorder)this.logger.debug("Using MediaRecorder fallback branch"),this.mediaRecorderFallback&&(this.logger.debug("Stopping existing MediaRecorderFallback before creating new one"),this.mediaRecorderFallback.stop()),this.mediaRecorderFallback=new MediaRecorderFallback(this.MIME_TYPE,t=>this.handleAudioData(t),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream),this.mediaRecorderFallback.start();else{this.logger.debug("Using AudioWorklet for audio processing");const t=this.audioContext.createMediaStreamSource(this.mediaStream);this.workletNode=new AudioWorkletNode(this.audioContext,"audio-recording-processor",{processorOptions:{sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth}}),t.connect(this.workletNode),this.workletNode.port.onmessage=t=>{const{type:e,data:n}=t.data;e===AudioRecorderEvents.AudioData&&this.handleAudioData(n)}}}async handleAudioData(t){let e=new Uint8Array(t),n=e.findIndex(t=>0!==t);if(-1===n)return void this.logger.warn("Skipping all-zero audio packet");n>0&&(this.logger.debug(`Trimming ${n} leading zero bytes from audio packet`),e=e.slice(n),t=e.buffer);const r=Array.from(e.slice(0,8));this.logger.debug(`Audio chunk: size=${t.byteLength}, first bytes=${r.join(",")}`),this.bufferingMode?(this.logger.debug(`Buffered audio chunk, buffer size: ${this.audioBuffer.length+1}`),this.audioBuffer.push(t)):await this.emit(AudioRecorderEvents.AudioData,t)}async cleanup(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder=null),this.mediaRecorderFallback&&(this.mediaRecorderFallback.stop(),this.mediaRecorderFallback=null),this.audioBuffer=[],this.bufferingMode=!1,this.logger.debug("Audio buffer cleared during cleanup")}async preInitialize(){try{await this.setupAudioContext(),await this.loadAudioWorklet(),this.logger.debug("Pre-initialization complete")}catch(t){this.logger.error("Pre-initialization failed",t)}}isInitialized(){return null!==this.mediaStream}dispose(){try{this.logger.debug("Disposing AudioRecorder..."),this.recording&&this.stop(),this.cleanup(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close().catch(t=>{this.logger.debug("Error closing AudioContext:",t)}),this.audioContext=null),this.mediaStream=null,this.removeAllListeners(),this.logger.debug("AudioRecorder disposed")}catch(t){this.logger.warn("Error while disposing AudioRecorder",t)}}}class UserInputManager extends EventEmitter{capabilities;vadManager;network;recordingConfig;audioRecorder=null;isStopped=!0;mediaStream=null;isInputCompleteSent=!1;debugMode=!1;capturedAudioChunks=[];constructor(t,e,n,r){super(new DefaultLogger({category:"🎩 UserInputManager",style:StyleBlue})),this.capabilities=t,this.vadManager=e,this.network=n,this.recordingConfig=r,this.setupListeners(),this.capabilities.audio&&(this.audioRecorder=new AudioRecorder(r),this.setupRecorderListeners())}async initialize(t){await this.reinitializeAudio(t)}async reinitializeAudio(t){if(this.capabilities.audio){if(t&&(this.mediaStream=t),!this.mediaStream){const t={echoCancellation:this.recordingConfig?.echoCancellation,noiseSuppression:this.recordingConfig?.noiseSuppression,autoGainControl:this.recordingConfig?.autoGainControl,sampleRate:this.recordingConfig?.sampleRate,channelCount:this.recordingConfig?.channels};Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:t})}await this.vadManager.initialize(this.mediaStream),await(this.audioRecorder?.initialize(this.mediaStream))}}async start(t=!1){if(this.isStopped){this.isStopped=!1;try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(t){this.logger.error("Failed to clear server audio buffer",t)}this.debugMode&&(this.capturedAudioChunks=[],this.logger.debug("Cleared captured audio chunks for new interaction")),this.capabilities.audio&&(t?this.logger.debug("Skipping VAD startup to reduce CPU contention during playback"):this.vadManager.startAnalysis(),await this.startRecording())}}startVAD(){this.capabilities.audio&&!this.isStopped&&(this.logger.debug("Starting VAD analysis"),this.vadManager.startAnalysis())}async stop(){return!this.isStopped&&(this.logger.debug("Stopping User Input..."),this.isStopped=!0,this.capabilities.audio&&(this.vadManager.stopAnalysis(),await this.stopRecording()),!0)}async updateCapabilities(t){this.capabilities=t,this.logger.debug("Input capabilities updated",this.capabilities),this.capabilities.audio&&!this.audioRecorder?(this.audioRecorder=new AudioRecorder(this.recordingConfig),this.setupRecorderListeners(),await this.reinitializeAudio()):!this.capabilities.audio&&this.audioRecorder&&(this.vadManager.stopAnalysis(),await this.audioRecorder.stop(),this.audioRecorder=null,this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null))}async stopRecording(){this.capabilities.audio&&this.audioRecorder?.isRecording()&&await this.audioRecorder.stop()}async startRecording(){this.capabilities.audio&&this.audioRecorder?(this.audioRecorder.isInitialized()||(this.logger.warn("AudioRecorder not initialized, reinitializing..."),await this.reinitializeAudio()),await this.audioRecorder.start()):this.logger.info("Will not start recording, audio capabilities are not enabled or audio recorder is not initialized")}isRecording(){return this.capabilities.audio&&(this.audioRecorder?.isRecording()||!1)}enableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.enableBufferingMode()}disableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.disableBufferingMode()}getBufferedAudio(){return this.audioRecorder?.getBufferedAudio()||[]}clearAudioBuffer(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.clearBuffer()}async flushBufferedAudio(){this.disableAudioBuffering();const t=this.getBufferedAudio();if(this.clearAudioBuffer(),t.length>0){this.logger.debug(`Flushing ${t.length} buffered audio chunks`);for(const e of t)await this.sendAudio(e)}}async sendAudio(t){if(this.isStopped)return;this.logger.debug("sendAudio called, size:",t.byteLength),this.debugMode&&(this.capturedAudioChunks.push(t),this.logger.debug(`Captured audio chunk for debug (${this.capturedAudioChunks.length} total chunks)`));const e=this.arrayBufferToBase64(t);await this.network.addAudio(e)}arrayBufferToBase64(t){let e="";const n=new Uint8Array(t),r=n.byteLength;for(let t=0;t<r;t++)e+=String.fromCharCode(n[t]);return btoa(e)}async interact(t){await this.network.interact(t)}async sendInputComplete(){this.isStopped||this.isInputCompleteSent||(this.isInputCompleteSent=!0,await this.emit(UserInputManagerEvents.UserInput,{type:"input_complete"}))}reset(){this.isInputCompleteSent=!1,this.debugMode&&this.capturedAudioChunks.length>0&&(this.logger.debug(`Clearing ${this.capturedAudioChunks.length} captured audio chunks on reset`),this.capturedAudioChunks=[])}dispose(){try{this.logger.debug("Disposing UserInputManager..."),this.isStopped=!0,this.vadManager&&(this.vadManager.stopAnalysis(),"function"==typeof this.vadManager.dispose&&this.vadManager.dispose()),this.capabilities.audio&&this.audioRecorder?.isRecording()&&this.audioRecorder.stop(),this.audioRecorder&&"function"==typeof this.audioRecorder.dispose&&this.audioRecorder.dispose(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>{t.stop(),this.logger.debug(`Stopped media track: ${t.kind}`)}),this.mediaStream=null),this.removeAllListeners(),this.logger.debug("UserInputManager disposed")}catch(t){this.logger.warn("Error while disposing UserInputManager",t)}}setupListeners(){this.capabilities.audio&&(this.vadManager.on(types_VadManagerEvents.VoiceActivity,async t=>{t&&!this.isStopped&&(t.isSpeaking?await this.emit(UserInputManagerEvents.UserSpeaking):await this.emit(UserInputManagerEvents.UserSilence))}),this.vadManager.on(types_VadManagerEvents.Silence,async()=>{await this.sendInputComplete(),await this.network.checkTurn()}))}setupRecorderListeners(){this.audioRecorder&&this.audioRecorder.on(AudioRecorderEvents.AudioData,t=>{this.sendAudio(t).catch(t=>{this.logger.error("Failed to send audio chunk",t)})})}async resumeAudioContext(){this.capabilities.audio&&this.audioRecorder&&await this.audioRecorder.resumeAudioContext()}enableDebugMode(){this.debugMode=!0,this.capturedAudioChunks=[],this.logger.info("Debug mode enabled - audio chunks will be captured")}disableDebugMode(){this.debugMode=!1,this.logger.info("Debug mode disabled")}clearCapturedAudio(){this.capturedAudioChunks=[],this.logger.info("Captured audio chunks cleared")}downloadCapturedAudio(t="captured-audio.webm"){if(0===this.capturedAudioChunks.length)return void this.logger.warn("No audio chunks captured to download");this.logger.info(`Downloading ${this.capturedAudioChunks.length} captured audio chunks as ${t}`);const e=new Blob(this.capturedAudioChunks,{type:"audio/webm;codecs=opus"}),n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),this.logger.info("Download completed")}getCapturedAudioInfo(){const t=this.capturedAudioChunks.reduce((t,e)=>t+e.byteLength,0);return{chunkCount:this.capturedAudioChunks.length,totalSize:t}}}class ConversationCommands{static DEFAULT_START_COMMAND="[start conversation]";static DEFAULT_PAUSE_RESUME_COMMAND="[resume after short pause]";static DEFAULT_LONG_PAUSE_RESUME_COMMAND="[resume after long break]";static DEFAULT_ERROR_RESUME_COMMAND="[resume after error]";startCommand=ConversationCommands.DEFAULT_START_COMMAND;pauseResumeCommand=ConversationCommands.DEFAULT_PAUSE_RESUME_COMMAND;longPauseResumeCommand=ConversationCommands.DEFAULT_LONG_PAUSE_RESUME_COMMAND;errorResumeCommand=ConversationCommands.DEFAULT_ERROR_RESUME_COMMAND;set(t,e,n,r){this.startCommand=t??ConversationCommands.DEFAULT_START_COMMAND,this.pauseResumeCommand=e??ConversationCommands.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=n??ConversationCommands.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=r??ConversationCommands.DEFAULT_ERROR_RESUME_COMMAND}setDefault(){this.startCommand=ConversationCommands.DEFAULT_START_COMMAND,this.pauseResumeCommand=ConversationCommands.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=ConversationCommands.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=ConversationCommands.DEFAULT_ERROR_RESUME_COMMAND}}class ErrorRetryHandler{deps;static DEFAULT_MAX_RETRY_COUNT=3;currentRetryCount=0;isRetrying=!1;maxRetryCount;constructor(t){this.deps=t,this.maxRetryCount=t.maxRetryCount??ErrorRetryHandler.DEFAULT_MAX_RETRY_COUNT}async attemptRecovery(t){if(this.deps.logger.info("Attempting silent recovery for error type: "+t),!["network_timeout","network_error","server_error"].includes(t))return!1;if(!this.deps.isConnected())return this.deps.logger.info("Network is not connected, skipping retry"),!1;if(this.currentRetryCount>=this.maxRetryCount)return!1;if(this.isRetrying)return!1;this.currentRetryCount++,this.isRetrying=!0,this.deps.logger.info(`Attempting silent retry ${this.currentRetryCount}/${this.maxRetryCount} with error resume command`);try{return await this.deps.sendText(this.deps.conversationCommands.errorResumeCommand),this.isRetrying=!1,!0}catch(e){return this.deps.logger.error(`Retry attempt ${this.currentRetryCount} failed`,e),this.isRetrying=!1,this.currentRetryCount<this.maxRetryCount&&await this.attemptRecovery(t)}}resetRetryCount(){this.currentRetryCount=0,this.isRetrying=!1}getCurrentRetryCount(){return this.currentRetryCount}}const ConversationManagerEvents={StateChange:"stateChange"};class ConversationManager extends EventEmitter{state="idle";network;vadManager;userInputManager;playbackManager;config;interactionCompletePending=!1;mediaStream=null;isTextOnly=!1;isDisposed=!1;isTransitioning=!1;pausedFromState=null;errorRetryHandler;isSimulateErrorsDebugMode=!1;conversationCommands=new ConversationCommands;constructor(t){const e=new DefaultLogger({category:"🧞 ConversationManager",style:StylePurple});super(e),this.setConfiguration(t);const n={...t,...t.apiKey&&{apiKey:t.apiKey.slice(0,4)+"..."},...t.federatedId&&{federatedId:t.federatedId.slice(0,4)+"..."}};e.info("Initializing with config",n),this.network=new ConversationNetwork(this.config),this.vadManager=new VADManager,this.userInputManager=new UserInputManager(this.config.inputCapabilities,this.vadManager,this.network,t.recordingConfig),this.playbackManager=new PlaybackManager(this.config.capabilities),this.playbackManager.wireVADToAvatar(this),this.playbackManager.wireConversationStateToAvatar(this),this.setupEventListeners(),this.errorRetryHandler=new ErrorRetryHandler({logger:this.logger,conversationCommands:this.conversationCommands,sendText:t=>this.sendText(t),isConnected:()=>this.isConnected(),maxRetryCount:3}),this.setState("uninitialized")}async setConfiguration(t){if(console.log("[SDK] setConfiguration called with languageCode:",t.languageCode),this.config={...t,capabilities:t.capabilities||{audio:!0,viseme:!0,subtitles:!0,avatar:!0},inputCapabilities:t.inputCapabilities||{audio:!0,text:!0},hooks:{...this.config?.hooks||{},...t.hooks},onInputUtilities:t.onInputUtilities??this.config?.onInputUtilities,onInputNonBlockingUtilities:t.onInputNonBlockingUtilities??this.config?.onInputNonBlockingUtilities,onOutputUtilities:t.onOutputUtilities??this.config?.onOutputUtilities},this.network&&(this.network.updateConfig(this.config),this.network.isReady())){this.logger.debug("Updating remote configuration");try{await this.network.updateRemoteConfiguration(this.config),this.logger.debug("Remote configuration updated successfully")}catch(t){this.logger.error("Failed to update remote configuration",t)}}}async initialize(){try{if(this.logger.debug("Initializing..."),this.setState("initializing"),await this.network.initialize(),await this.playbackManager.initialize(),this.config.inputCapabilities?.audio&&!this.mediaStream){const t=this.config.recordingConfig,e={echoCancellation:t?.echoCancellation,noiseSuppression:t?.noiseSuppression,autoGainControl:t?.autoGainControl,sampleRate:t?.sampleRate,channelCount:t?.channels};Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:e})}await this.userInputManager.initialize(this.mediaStream??void 0),await this.network.connect(),this.logger.debug("Initialized successfully"),this.setState("waiting")}catch(t){this.handleError("server_error",t)}}async startListening(){if("idle"!==this.state)throw new Error(`Cannot start listening from state: ${this.state}`);try{await this.userInputManager.start(),this.setState("listening")}catch(t){this.handleError("mic_denied",t)}}async stopListening(){this.logger.debug("stopListening called from state:",this.state),await this.userInputManager.stop()||this.setState("waiting")}async sendText(t){return console.log("[SDK] sendText called with languageCode:",this.config.languageCode),this.interact({text:t,kind:"interact",type:"stream",uid:"",language_code:this.config.languageCode})}async generateImage(t){return this.network.generateImage(t)}async generateImageWithBria(t){return this.network.generateImageWithBria(t)}async generateImageWithReplicate(t){return this.network.generateImageWithReplicate(t)}async getAvailableModels(){return this.network.getAvailableModels()}async interact(t){if(!this.network.isReady()){const t="Network is not ready, cannot send text. probably disconnected";return this.logger.error(t),void await this.handleError("network_timeout",new Error(t))}if("idle"===this.state||"listening"===this.state||"processing_complete"===this.state||"error"===this.state)try{if(this.playbackManager.reset(),this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.setState("waiting"),await this.userInputManager.interact(t)}catch(t){this.logger.error("Error sending text message",t),await this.handleError("network_timeout",t)}}async interrupt(){this.playbackManager.pause(),await this.setState("interrupted")}async pause(){if(this.isTransitioning)this.logger.debug("Pause ignored: transition already in progress");else if("playing"===this.state||"processing_complete"===this.state||"listening"===this.state||"userSpeaking"===this.state){this.isTransitioning=!0;try{if(this.pausedFromState=this.state,"listening"===this.state||"userSpeaking"===this.state){this.logger.debug("Pausing from listening/speaking state, stopping input and clearing audio"),await this.userInputManager.stop(),this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio()}catch(t){this.logger.warn("Failed to clear server audio buffer on pause",t)}}else this.playbackManager.pause();await this.setState("paused")}finally{this.isTransitioning=!1}}else this.logger.warn(`Cannot pause from state: ${this.state}`)}async resume(){if(this.isTransitioning)this.logger.debug("Resume ignored: transition already in progress");else if("paused"===this.state||"processing_complete"===this.state){this.isTransitioning=!0;try{const t=this.playbackManager.getRemainingAudioSeconds()>0,e="listening"===this.pausedFromState||"userSpeaking"===this.pausedFromState;if(t){this.logger.debug("Resuming playback with buffered audio");try{await this.playbackManager.resume(),await this.setState("playing")}catch(t){this.logger.error("Failed to resume playback, falling back to listening",t),await this.userInputManager.start(),await this.setState("listening")}}else if(e){this.logger.debug("Resuming from listening pause, restarting recording");try{await this.userInputManager.start(),await this.setState("listening")}catch(t){this.logger.error("Failed to restart recording after pause",t),await this.handleError("mic_denied",t)}}else this.logger.debug("No buffered audio to resume, going to listening state"),this.interactionCompletePending?(this.interactionCompletePending=!1,await this.handleInteractionComplete()):await this.setState("listening")}finally{this.pausedFromState=null,this.isTransitioning=!1}}else this.logger.warn(`Cannot resume from state: ${this.state}`)}async forceInputComplete(){"userSpeaking"===this.state||"listening"===this.state?await this.userInputManager.sendInputComplete():this.logger.warn(`Cannot force input complete from state: ${this.state}`)}async stop(){await this.userInputManager.stop(),this.playbackManager.pause(),await this.network.disconnect(),await this.setState("idle")}async dispose(){if(this.isDisposed)this.logger.warn("ConversationManager already disposed");else{this.logger.debug("Disposing ConversationManager..."),this.isDisposed=!0,this.userInputManager?.removeAllListeners(),this.playbackManager?.removeAllListeners(),this.network?.removeAllListeners(),this.state="idle";try{this.userInputManager&&"function"==typeof this.userInputManager.dispose?this.userInputManager.dispose():(await this.userInputManager.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>{t.stop(),this.logger.debug(`Stopped media track: ${t.kind}`)}),this.mediaStream=null)),this.playbackManager&&"function"==typeof this.playbackManager.dispose&&this.playbackManager.dispose(),await this.network.disconnect(),this.removeAllListeners(),this.logger.debug("ConversationManager disposed successfully")}catch(t){this.logger.warn("Error while disposing ConversationManager",t)}}}async setState(t){if(this.isDisposed)return;if(this.state===t)return;const e=this.state;this.state=t,this.config.hooks.onStateChange?.(t),await this.emit(ConversationManagerEvents.StateChange,{oldState:e,newState:t}),this.logger.debug(`State transition: ${e} -> ${t}`)}setupEventListeners(){this.userInputManager.on(UserInputManagerEvents.UserInput,async t=>{await this.network.send(t),"input_complete"===t.type&&await this.setState("waiting")}),this.playbackManager.on(PlaybackManagerEvents.SubtitleWordChange,t=>{this.config.hooks.onSubtitleHighlight?.(t)}),this.playbackManager.on(PlaybackManagerEvents.SubtitleChange,t=>{this.config.hooks.onSubtitleChange?.(t)}),this.playbackManager.on(PlaybackManagerEvents.ImageChange,t=>{this.config.hooks.onImageChange?.(t)}),this.playbackManager.on(PlaybackManagerEvents.AvatarAnimationChanged,t=>{this.config.hooks.onAvatarAnimationChanged?.(t)}),this.userInputManager.on(UserInputManagerEvents.UserSpeaking,async()=>{await this.setState("userSpeaking")}),this.userInputManager.on(UserInputManagerEvents.UserSilence,async()=>{await this.setState("listening")}),this.network.on(ConversationNetworkEvents.Connected,async()=>{this.config.hooks.onNetworkStatusChange?.(!0)}),this.network.on(ConversationNetworkEvents.Disconnected,async()=>{this.config.hooks.onNetworkStatusChange?.(!1)}),this.network.on(ConversationNetworkEvents.Message,async t=>{if("interact"===t.kind&&"text"===t.event&&this.config.hooks.onTextMessage?.(t),"data"===t.event&&this.config.hooks.onDataMessage?.(t),"interact"===t.kind&&"safety_policy"===t.event&&this.config.hooks.onSafetyEvent?.(t),"check_turn"===t.kind&&!1===t.is_user_still_speaking){if(this.logger.debug(`check_turn handler: state is ${this.state}`),"playing"===this.state||"paused"===this.state)return void this.logger.debug("check_turn received while playing / paused, ignoring.");await this.stopListening();try{if(this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.network.interactAudio({uid:"",kind:"interact",type:"stream",on_input_non_blocking:this.config.onInputNonBlockingUtilities,on_input:this.config.onInputUtilities,on_output:this.config.onOutputUtilities,language_code:this.config.languageCode})}catch(t){this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(t){this.logger.error("Failed to clear server audio buffer",t)}this.logger.error("Error in interactAudio",t),await this.handleError("network_timeout",t)}}"interact"===t.kind&&"interaction_complete"===t.event&&(this.errorRetryHandler.resetRetryCount(),"playing"===this.state||"paused"===this.state?(this.logger.debug("Interaction complete received while playing / paused, deferring."),this.interactionCompletePending=!0,await this.setState("processing_complete")):await this.handleInteractionComplete()),"interaction_error"===t.type&&this.handleError("server_error",new Error(t.error||"Unknown server interaction error")),"string"===t.type&&this.config.hooks.onStringMessage?.(t),this.playbackManager.handleMessage(t)}),this.network.on(ConversationNetworkEvents.Error,async t=>{this.handleError("network_error",t)}),this.playbackManager.on(PlaybackManagerEvents.PlaybackError,async t=>{this.handleError("decode_error",t)}),this.playbackManager.on(PlaybackManagerEvents.Playing,async()=>{await this.setState("playing")}),this.playbackManager.on(PlaybackManagerEvents.Finished,async()=>{if(this.interactionCompletePending)this.logger.debug("Playback finished, processing deferred interaction complete."),this.interactionCompletePending=!1,await this.handleInteractionComplete();else if("playing"===this.state){this.logger.debug("Playback finished, starting recording now (no overlap)"),this.userInputManager.reset();try{await this.userInputManager.start(),await this.setState("listening"),this.logger.debug("Recording started successfully after playback")}catch(t){this.logger.error("Failed to start recording after playback",t),await this.setState("idle")}}})}async handleError(t,e){await this.setState("error"),this.logger.error("handleError called with type: "+t+" and error: "+e.message);let n=!1;try{n=await this.errorRetryHandler.attemptRecovery(t)}catch(t){this.logger.error("Error during recovery attempt",t),n=!1}if(n)return void this.logger.debug("Error recovery succeeded, not raising error");const r={type:t,message:e.message,originalError:e};this.config.hooks.onError?.(r),this.logger.error(`Conversation error: ${t}`,e)}async handleInteractionComplete(){this.logger.debug("Interaction complete received"),this.playbackManager.resetAboutToComplete();try{if(this.userInputManager.reset(),this.userInputManager.isRecording())await this.setState("listening");else{this.logger.debug("Starting recording after interaction complete");try{await this.userInputManager.start(),await this.setState("listening")}catch(t){this.logger.error("Failed to start recording",t),await this.setState("idle")}}}catch(t){this.logger.error("Failed to handle interaction complete",t),await this.handleError("network_timeout",t)}}async toggleTextOnlyInput(t){this.isTextOnly=t,await this.updateInputCapabilities()}isConnected(){return this.network.isReady()}enableAudioDebugMode(){this.userInputManager.enableDebugMode(),this.logger.info("Audio debug mode enabled")}disableAudioDebugMode(){this.userInputManager.disableDebugMode(),this.logger.info("Audio debug mode disabled")}downloadCapturedAudio(t){this.userInputManager.downloadCapturedAudio(t)}clearCapturedAudio(){this.userInputManager.clearCapturedAudio()}getCapturedAudioInfo(){return this.userInputManager.getCapturedAudioInfo()}async updateInputCapabilities(){this.logger.debug(`Updating input capabilities, textOnly: ${this.isTextOnly}`),this.config.inputCapabilities={...this.config.inputCapabilities,audio:!this.isTextOnly,text:this.isTextOnly},await this.userInputManager.updateCapabilities(this.config.inputCapabilities),this.isTextOnly?await this.userInputManager.stopRecording():"idle"===this.state&&await this.startListening()}}export{AudioPlayer,ConversationCommands,ConversationManager};
|
|
184
|
+
½ÇaztÅò¬¼Åâ`});var S={a:x};this.setModule=t=>{e.setModule(v,t)},this.getModule=()=>e.getModule(v),this.instantiate=()=>(this.getModule().then(e=>WebAssembly.instantiate(e,S)).then(e=>{const r=e.exports;var s;!function(e){m=e.m,g=e.n,y=e.p,w=e.q,b=e.r,_=e.s,$=e.t}(r),s=(i=r.k).buffer,new Int8Array(s),new Int16Array(s),t=new Uint8Array(s),new Uint16Array(s),new Int32Array(s),n=new Uint32Array(s),new Float32Array(s),new Float64Array(s),new BigInt64Array(s),new BigUint64Array(s),function(e){e.l()}(r),a()}),this.ready=new Promise(e=>{a=e}).then(()=>{this.HEAP=i.buffer,this.malloc=m,this.free=g,this.mpeg_decoder_feed=w,this.mpeg_decoder_read=b,this.mpeg_frame_decoder_create=y,this.mpeg_frame_decoder_destroy=_}),this)}function x(e={}){return this._init=()=>(new this._WASMAudioDecoderCommon).instantiate(this._EmscriptenWASM,this._module).then(t=>{this._common=t,this._sampleRate=0,this._inputBytes=0,this._outputSamples=0,this._frameNumber=0,this._input=this._common.allocateTypedArray(this._inputSize,Uint8Array),this._output=this._common.allocateTypedArray(this._outputSize,Float32Array);const n=this._common.allocateTypedArray(1,Uint32Array);this._samplesDecodedPtr=this._common.allocateTypedArray(1,Uint32Array),this._sampleRatePtr=this._common.allocateTypedArray(1,Uint32Array),this._errorStringPtr=this._common.allocateTypedArray(1,Uint32Array);const i=this._common.wasm.mpeg_frame_decoder_create(n.ptr,!1===e.enableGapless?0:1);if(i)throw Error(this._getErrorMessage(i));this._decoder=n.buf[0]}),Object.defineProperty(this,"ready",{enumerable:!0,get:()=>this._ready}),this._getErrorMessage=e=>e+" "+this._common.codeToString(this._errorStringPtr.buf[0]),this.reset=()=>(this.free(),this._init()),this.free=()=>{this._common.wasm.mpeg_frame_decoder_destroy(this._decoder),this._common.wasm.free(this._decoder),this._common.free()},this.decode=e=>{let t=[],n=[],i=0;if(!(e instanceof Uint8Array))throw Error("Data to decode must be Uint8Array. Instead got "+typeof e);e:for(let r=0,s=0;r<e.length;r+=s){const a=e.subarray(r,this._input.len+r);s=a.length,this._inputBytes+=s,this._input.buf.set(a);let o=this._common.wasm.mpeg_decoder_feed(this._decoder,this._input.ptr,s);if(-10!==o)for(;;){this._samplesDecodedPtr.buf[0]=0,o=this._common.wasm.mpeg_decoder_read(this._decoder,this._output.ptr,this._output.len,this._samplesDecodedPtr.ptr,this._sampleRatePtr.ptr,this._errorStringPtr.ptr);const e=this._samplesDecodedPtr.buf[0];if(this._outputSamples+=e,e&&(i+=e,t.push([this._output.buf.slice(0,e),this._output.buf.slice(e,2*e)])),-11!=o){if(-10===o)continue e;if(o){const e=this._getErrorMessage(o);console.error("mpg123-decoder: "+e),this._common.addError(n,e,0,this._frameNumber,this._inputBytes,this._outputSamples)}}}}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,t,2,i,this._sampleRatePtr.buf[0])},this.decodeFrame=e=>{const t=this.decode(e);return this._frameNumber++,t},this.decodeFrames=e=>{let t=[],n=[],i=0,r=0;for(;r<e.length;){const s=this.decodeFrame(e[r++]);t.push(s.channelData),n=n.concat(s.errors),i+=s.samplesDecoded}return this._WASMAudioDecoderCommon.getDecodedAudioMultiChannel(n,t,2,i,this._sampleRatePtr.buf[0])},this._isWebWorker=x.isWebWorker,this._WASMAudioDecoderCommon=x.WASMAudioDecoderCommon||$,this._EmscriptenWASM=x.EmscriptenWASM||v,this._module=x.module,this._inputSize=65536,this._outputSize=92448,this._ready=this._init(),this}class S extends u{MIN_CHUNKS_TO_PROCESS=2;FLUSH_DELAY_MS=450;audioContext;currentSource=null;playbackQueue=[];mp3Decoder=null;scheduledPlayTime=0;playbackStartTime=0;chunkQueue=[];isProcessingQueue=!1;frameExtractor=new g;totalFramesDecoded=0;totalFramesFailed=0;totalFramesExtracted=0;isPlayingState=!1;isPausedState=!1;stopped=!1;frameBuffer=[];chunkAccumulator=[];flushTimeout=null;isAudioComplete=!1;timing;isScheduling=!1;allAudioPlayed=!1;constructor(){super(new o({category:"🎵 AudioPlayer",style:"color: #4caf50; font-weight: bold; font-size: larger"})),this.audioContext=new AudioContext,this.timing=new w(()=>this.getCurrentTime(),()=>this.getQueueLength(),()=>this.getRemainingAudioSeconds(),1e3),this.setupTimingListeners()}setupTimingListeners(){this.timing.on("about-to-complete",async()=>{await this.emit(p.AboutToComplete)})}async initialize(){this.audioContext||(this.audioContext=new AudioContext,this.logger.debug("AudioContext created by user gesture")),"suspended"===this.audioContext.state&&(this.audioContext.resume(),this.logger.debug("AudioContext resumed by user gesture")),this.mp3Decoder||(this.logger.debug("Initializing MP3 decoder..."),this.mp3Decoder=new x,await this.mp3Decoder.ready,this.logger.debug("MP3 decoder ready")),this.resetState()}resetState(){this.currentSource&&(this.currentSource.onended=null,this.currentSource.stop(),this.currentSource=null),this.playbackQueue=[],this.scheduledPlayTime=0,this.playbackStartTime=0,this.chunkQueue=[],this.isProcessingQueue=!1,this.frameExtractor=new g,this.isPlayingState=!1,this.isPausedState=!1,this.stopped=!1,this.frameBuffer=[],this.chunkAccumulator=[],this.isAudioComplete=!1,this.totalFramesDecoded=0,this.totalFramesFailed=0,this.totalFramesExtracted=0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.reset(),this.allAudioPlayed=!1}reset(){this.resetState()}enqueue(e){this.logger.debug("Enqueue: received chunk"),this.allAudioPlayed=!1,this.chunkQueue.push({base64String:e}),this.processChunkQueue(),this.isAudioComplete||(this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=setTimeout(()=>{this.logger.debug("auto-flush timer fired"),this.flush()},this.FLUSH_DELAY_MS))}markComplete(){this.logger.debug("markComplete: no more audio will be added"),this.isAudioComplete=!0,this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing.onAudioComplete(),this.flush();const e=this.frameExtractor.extractRemainingFrames();e.length>0&&(this.logger.debug("markComplete: Found additional frames after flush",{count:e.length}),this.totalFramesExtracted+=e.length,this.decodeAudioFrames(e).then(t=>{if(t){this.totalFramesDecoded+=e.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(t),this.emit(p.Enqueued,{duration:t.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}).catch(t=>{this.totalFramesFailed+=e.length,this.logger.error("Failed to decode final remaining frames after markComplete",t)}));const t=this.frameExtractor.getRemainingBufferSize();t>0&&this.logger.warn("markComplete: Extractor buffer still has data after final extraction",{remainingBytes:t}),this.allAudioPlayed&&(this.logger.debug("markComplete: All audio was already played, emitting Finished."),this.isPlayingState=!1,this.emit(p.Finished))}async processChunkQueue(){if(!this.isProcessingQueue){this.isProcessingQueue=!0;try{for(;this.chunkQueue.length>0;){const{base64String:e}=this.chunkQueue.shift();if(this.chunkAccumulator.push(e),this.chunkAccumulator.length>=this.MIN_CHUNKS_TO_PROCESS){const e=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(e)}}}finally{this.isProcessingQueue=!1}}}decodeBase64ToUint8Array(e){const t="undefined"!=typeof atob?atob(e):Buffer.from(e,"base64").toString("binary"),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}combineArrays(e,t){const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async decodeAudioFrames(e){if(0===e.length)return null;if(!this.mp3Decoder)throw new Error("MP3 decoder not initialized. Call initialize() first.");const t=[];let n=0,i=0,r=0,s=0;for(let a=0;a<e.length;a++){const o=e[a];if(o.length<2||255!==o[0]||224&~o[1])this.logger.warn(`Frame ${a} doesn't start with valid sync word, skipping`,{firstBytes:Array.from(o.slice(0,4)),frameLength:o.length}),s++;else try{const e=this.mp3Decoder.decodeFrame(o);if(e.errors&&e.errors.length>0&&this.logger.warn(`Frame ${a} decoded with errors`,{errors:e.errors.map(e=>e.message||String(e)),frameLength:o.length}),0===e.samplesDecoded){this.logger.warn(`Frame ${a} decoded but produced 0 samples`,{frameLength:o.length,errors:e.errors?.map(e=>e.message||String(e))}),s++;continue}if(0===n?n=e.sampleRate:e.sampleRate!==n&&this.logger.warn(`Frame ${a} has different sample rate: ${e.sampleRate} vs ${n}`),0===t.length)for(let n=0;n<e.channelData.length;n++)t.push([]);for(let n=0;n<e.channelData.length;n++)n<t.length&&t[n].push(e.channelData[n]);i+=e.samplesDecoded,r++}catch(e){this.logger.error(`Failed to decode frame ${a}`,{error:e instanceof Error?e.message:String(e),frameLength:o.length,firstBytes:Array.from(o.slice(0,4))}),s++}}if(0===r)return this.logger.error("All frames failed to decode",{totalFrames:e.length}),null;s>0&&this.logger.warn("Some frames failed to decode",{successful:r,failed:s,total:e.length});const a=[];for(let e=0;e<t.length;e++){const n=new Float32Array(i);let r=0;for(const i of t[e])n.set(i,r),r+=i.length;a.push(n)}const o=this.audioContext.createBuffer(a.length,i,n);for(let e=0;e<a.length;e++)o.getChannelData(e).set(a[e]);return this.logger.debug("Decoded frames",{successful:r,failed:s,totalSamples:i,sampleRate:n,duration:o.duration.toFixed(3)}),o}async play(){this.isPlayingState||0===this.playbackQueue.length?this.logger.debug("Play called but already playing or queue is empty."):(this.isPlayingState=!0,this.stopped=!1,this.isPausedState=!1,this.isPausedState?this.scheduledPlayTime=this.audioContext.currentTime:(this.scheduledPlayTime=this.audioContext.currentTime,this.playbackStartTime=this.audioContext.currentTime),this.logger.debug(`Playback starting. Start time: ${this.playbackStartTime}`),this.schedulePlayback(),await this.emit(p.Playing))}schedulePlayback(){if(this.isScheduling||0===this.playbackQueue.length||this.stopped)return;this.isScheduling=!0,this.currentSource&&(this.currentSource.onended=null);let e=null;for(;this.playbackQueue.length>0;){const t=this.playbackQueue.shift(),n=this.audioContext.createBufferSource();n.buffer=t,n.connect(this.audioContext.destination),this.scheduledPlayTime<this.audioContext.currentTime&&(this.logger.debug(`Adjusting scheduledPlayTime from ${this.scheduledPlayTime} to current time ${this.audioContext.currentTime}`),this.scheduledPlayTime=this.audioContext.currentTime),this.logger.debug(`Scheduling buffer of duration ${t.duration}s to start at ${this.scheduledPlayTime} (context time: ${this.audioContext.currentTime})`),n.start(this.scheduledPlayTime),this.scheduledPlayTime+=t.duration,e=n}e&&(this.currentSource=e,e.onended=()=>{this.logger.debug(`Buffer finished playing. Context time: ${this.audioContext.currentTime}, isPaused: ${this.isPausedState}, stopped: ${this.stopped}`),this.stopped||this.isPausedState||(this.playbackQueue.length>0?(this.logger.debug("More buffers in queue, scheduling next batch."),this.schedulePlayback()):this.isAudioComplete?(this.logger.debug("Last scheduled audio buffer finished and audio is complete."),this.isPlayingState=!1,this.emit(p.Finished)):(this.logger.debug("All scheduled audio has been played, but not marked as complete yet."),this.allAudioPlayed=!0))}),this.isScheduling=!1}async pause(){this.currentSource&&this.isPlayingState&&(this.isPausedState=!0,this.isPlayingState=!1,this.audioContext.suspend(),await this.emit(p.Paused))}async resume(){this.isPausedState&&(this.logger.debug("Resume called, resuming playback."),this.isPausedState=!1,this.isPlayingState=!0,this.audioContext.resume(),this.schedulePlayback(),await this.emit(p.Playing))}async stop(){this.stopped=!0,this.resetState(),await this.emit(p.Stopped)}getCurrentTime(){return this.isPlayingState?1e3*(this.audioContext.currentTime-this.playbackStartTime):0}getQueueLength(){return this.playbackQueue.length}getRemainingAudioSeconds(){const e=this.playbackQueue.reduce((e,t)=>e+t.duration,0);let t=0;return(this.isPlayingState||this.isPausedState)&&this.scheduledPlayTime>0&&(t=Math.max(0,this.scheduledPlayTime-this.audioContext.currentTime)),e+t}async decodeAndEnqueueChunks(e){if(0===e.length)return void this.logger.debug("decodeAndEnqueueChunks: no chunks to decode");let t=[];for(const n of e){const e=this.decodeBase64ToUint8Array(n),{frames:i,remainingData:r}=this.frameExtractor.feedAndExtractCompleteFrames(e);t=t.concat(i),this.totalFramesExtracted+=i.length,r.length>0&&this.logger.debug("Chunk ended with incomplete frame",{remainingBytes:r.length,framesExtracted:i.length})}if(this.logger.debug("decodeAndEnqueueChunks: total frames to decode",t.length),t.length>0){const e=t.map(e=>e.length).reduce((e,t)=>(e[t]=(e[t]||0)+1,e),{});this.logger.debug("Frame sizes distribution",e);try{const e=await this.decodeAudioFrames(t);if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),await this.emit(p.Enqueued,{duration:e.duration}),this.logger.debug("decodeAndEnqueueChunks: enqueued audioBuffer, duration",e.duration,"frames decoded",t.length),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(e){this.totalFramesFailed+=t.length,this.logger.error("Failed to decode audio frames",e),this.logger.error("Lost frames",{count:t.length,sizes:t.map(e=>e.length)})}}else this.logger.debug("decodeAndEnqueueChunks: no frames to decode")}async flush(){this.logger.debug("Flushing",{chunks:this.chunkAccumulator.length});const e=this.chunkAccumulator;this.chunkAccumulator=[],await this.decodeAndEnqueueChunks(e);const t=this.frameExtractor.extractRemainingFrames();if(t.length>0){this.logger.debug("Flush: Found complete frames in extractor buffer",{count:t.length}),this.totalFramesExtracted+=t.length;try{const e=await this.decodeAudioFrames(t);if(e){this.totalFramesDecoded+=t.length;const n=0===this.playbackQueue.length;this.playbackQueue.push(e),await this.emit(p.Enqueued,{duration:e.duration}),this.timing.onAudioEnqueued(),n&&!this.isPlayingState?await this.emit(p.Ready):this.isPlayingState&&this.schedulePlayback()}}catch(e){this.totalFramesFailed+=t.length,this.logger.error("Failed to decode remaining frames after flush",e)}}}resetAboutToComplete(){this.timing.reset()}getFrameStats(){return{totalFramesExtracted:this.totalFramesExtracted,totalFramesDecoded:this.totalFramesDecoded,totalFramesFailed:this.totalFramesFailed,extractorRemainingBufferSize:this.frameExtractor.getRemainingBufferSize()}}dispose(){if(this.logger.debug("Disposing AudioPlayer..."),this.stopped=!0,this.isPlayingState=!1,this.isPausedState=!1,this.currentSource){this.currentSource.onended=null;try{this.currentSource.stop()}catch(e){}this.currentSource=null}this.flushTimeout&&(clearTimeout(this.flushTimeout),this.flushTimeout=null),this.timing&&this.timing.reset(),this.audioContext&&"closed"!==this.audioContext.state&&this.audioContext.close().catch(e=>{this.logger.debug("Error closing AudioContext:",e)}),this.mp3Decoder=null,this.resetState(),this.removeAllListeners(),this.logger.debug("AudioPlayer disposed")}destroy(){this.dispose()}}const T="wordChange",k="subtitleChange";class E extends u{getCurrentTime;subtitleQueue=[];rafId=null;isPlaying=!1;cumulativeOffset=0;tickDebugLast=0;state={currentLine:null,nextLine:null,globalWordIndex:-1};constructor(e){super(new o({category:"🎬 SubtitleManager",style:"color: #e91e63; font-weight: bold; font-size: larger"})),this.getCurrentTime=e,this._resetState()}enqueue(e){this.logger.debug("Enqueue subtitle",{subtitle:e,queueLength:this.subtitleQueue.length});const{wordBoundaries:t,wordStartTimesMs:n}=this._computeWordBoundariesAndStartTimes(e.characters,e.start_times_ms),i={...e,wordBoundaries:t,wordStartTimesMs:n};this.subtitleQueue.push(i),this.isPlaying||1!==this.subtitleQueue.length||(this.logger.debug("Reset globalWordIndex to -1 (initial enqueue)"),this.state.globalWordIndex=-1),this.isPlaying&&!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),this._emitSubtitleChange())}async play(){this.isPlaying?this.logger.debug("Play called but already playing"):(this.logger.debug("Play called, starting playback"),this.isPlaying=!0,await this.emit("playing"),this.subtitleQueue.length>0&&(this._prepareState(),await this._emitSubtitleChange()),this.rafId=requestAnimationFrame(this._tick))}async pause(){this.logger.debug("Pause called"),this.isPlaying=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),await this.emit("paused")}clearQueue(){this.logger.debug("Clear queue"),this._resetState(),this.pause()}reset(){this._resetState()}_resetState(){this.subtitleQueue=[],this.cumulativeOffset=0,this.rafId=null,this.isPlaying=!1,this.tickDebugLast=0,this.state={currentLine:null,nextLine:null,globalWordIndex:-1}}_subtitleDuration(e){const{start_times_ms:t,durations_ms:n}=e;if(!t.length||!n.length)return 0;const i=t.length-1;return t[i]+n[i]}_applyOffset(e,t){return e.map(e=>e+t)}_prepareState(){if(!this.subtitleQueue.length)return;const e=this.subtitleQueue[0];e.adjustedWordStartTimesMs=this._applyOffset(e.wordStartTimesMs,this.cumulativeOffset);const t=this.subtitleQueue[1]||null;if(t){const n=this.cumulativeOffset+this._subtitleDuration(e);t.adjustedWordStartTimesMs=this._applyOffset(t.wordStartTimesMs,n)}this.state.currentLine=e,this.state.nextLine=t,this.logger.debug("Prepared state",{cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!e,hasNextLine:!!t,firstFewAdjusted:e.adjustedWordStartTimesMs?.slice(0,3)})}_computeWordBoundariesAndStartTimes(e,t){const n=[],i=[];let r=null;for(let s=0;s<e.length;s++){const a=e[s];if(" "!==a&&null===r&&(r=s),(" "===a||s===e.length-1)&&null!==r){const e=" "===a?s-1:s;n.push({start:r,end:e}),i.push(t[r]),r=null}}return{wordBoundaries:n,wordStartTimesMs:i}}_calculateGlobalWordIndex(e){let t=-1;const{currentLine:n,nextLine:i}=this.state;if(n?.adjustedWordStartTimesMs)for(let i=0;i<n.adjustedWordStartTimesMs.length&&e>=n.adjustedWordStartTimesMs[i];i++)t=i;if(i?.adjustedWordStartTimesMs){const r=n?.wordBoundaries.length||0;for(let n=0;n<i.adjustedWordStartTimesMs.length&&e>=i.adjustedWordStartTimesMs[n];n++)t=r+n}return t}_decodeGlobalIndex(e){if(e<0)return{lineIndex:0,wordIndex:-1};const t=this.state.currentLine?.wordBoundaries.length||0;return e<t?{lineIndex:0,wordIndex:e}:{lineIndex:1,wordIndex:e-t}}_isFinished(e,t,n){return t>n+this._subtitleDuration(e)}_buildWordChangeEvent(e){const{lineIndex:t,wordIndex:n}=this._decodeGlobalIndex(e),{currentLine:i,nextLine:r}=this.state,s=e=>e?{characters:e.characters,wordBoundaries:e.wordBoundaries}:null;let a;if(0===t&&i&&n>=0){const e=i.wordBoundaries[n];a=i.characters.slice(e.start,e.end+1).join("")}else if(1===t&&r&&n>=0){const e=r.wordBoundaries[n];a=r.characters.slice(e.start,e.end+1).join("")}return{globalWordIndex:e,currentLineIndex:t,wordIndexInLine:n,word:a,currentLineData:s(i),nextLineData:s(r)}}_buildSubtitleChangeEvent(){const e=e=>e?.adjustedWordStartTimesMs?{characters:e.characters,wordBoundaries:e.wordBoundaries,adjustedWordStartTimesMs:e.adjustedWordStartTimesMs}:null;return{currentLine:e(this.state.currentLine),nextLine:e(this.state.nextLine)}}async _emitWordChange(e){const t=this._buildWordChangeEvent(e);this.logger.debug("Word change",{globalWordIndex:e,lineIndex:t.currentLineIndex,wordIndex:t.wordIndexInLine,word:t.word}),await this.emit(T,t)}async _emitSubtitleChange(){const e=this._buildSubtitleChangeEvent();this.logger.debug("Subtitle change",{hasCurrentLine:!!e.currentLine,hasNextLine:!!e.nextLine}),await this.emit(k,e)}_tick=async()=>{if(!this.isPlaying||0===this.subtitleQueue.length)return;!this.state.nextLine&&this.subtitleQueue.length>1&&(this._prepareState(),await this._emitSubtitleChange());const e=this.getCurrentTime();this.state.currentLine||this._prepareState(),e-this.tickDebugLast>=3e3&&(this.logger.debug("Tick debug",{currentTimeMs:e,cumulativeOffset:this.cumulativeOffset,hasCurrentLine:!!this.state.currentLine,hasNextLine:!!this.state.nextLine}),this.tickDebugLast=e);const t=this._calculateGlobalWordIndex(e);t!==this.state.globalWordIndex&&(this.state.globalWordIndex=t,await this._emitWordChange(t));const n=this.subtitleQueue[0],i=this.subtitleQueue[1]||null;let r=0;if(i){const t=this.cumulativeOffset+this._subtitleDuration(n);this._isFinished(i,e,t)&&(r=2)}else n&&this._isFinished(n,e,this.cumulativeOffset)&&(r=1);if(r>0){this.logger.debug(`Subtitle batch finished. Advancing ${r} lines.`,{currentTimeMs:e,cumulativeOffset:this.cumulativeOffset});const t=this.subtitleQueue.splice(0,r);for(const e of t)this.cumulativeOffset+=this._subtitleDuration(e),await this.emit("subtitleFinished",e);if(!(this.subtitleQueue.length>0))return this.logger.debug("Queue empty, pausing"),this.state.globalWordIndex=-1,await this._emitWordChange(-1),void await this.pause();this._prepareState(),await this._emitSubtitleChange()}this.rafId=requestAnimationFrame(this._tick)}}class C extends u{scheduledEvents=[];masterClock;constructor(e){super(new o({category:"👄 VisemeScheduler",style:"color: #f44336; font-weight: bold; font-size: larger"})),this.masterClock=e}enqueue(e){this.scheduledEvents.push(...e),this.scheduleEvents()}async play(){await this.emit(f.Playing)}async pause(){await this.emit(f.Paused)}scheduleEvents(){this.masterClock.currentTime,this.scheduledEvents.forEach(e=>{setTimeout(async()=>{await this.emit(f.Viseme,e)})})}}class I extends u{animationLayers=new Map;layerPriority=["mouth","facial","body","idle"];thinkToggle=!1;constructor(){super(new o({category:"🧒 AvatarManager",style:r}))}playIdle(){this.playAnimation("body_idle",0,!0)}playListen(){this.playAnimation("body_idle_listen",0,!0)}playTalk(){this.playAnimation("body_talk_to_user_loop",0,!0)}playThink(){const e=this.thinkToggle?"body_idle_think2":"body_idle_think";this.thinkToggle=!this.thinkToggle,this.playAnimation(e,0,!0)}playLaugh(){this.playAnimation("body_laugh",0,!0)}playWaving(){this.playAnimation("body_waving",0,!1)}playViseme(e){this.playAnimation(e,1,!1)}async playAnimation(e,t=0,n=!0){this.animationLayers.set(t,e),await this.emit(m.AnimationChanged,{name:e,layer:t,loop:n}),this.logger.debug(`Playing animation: ${e} on layer ${t} (loop: ${n})`)}async stopAnimation(e=0){this.animationLayers.delete(e),await this.emit(m.AnimationStopped,{layer:e})}dispose(){try{this.logger.debug("Disposing AvatarManager..."),this.animationLayers.clear(),this.thinkToggle=!1,this.removeAllListeners(),this.logger.debug("AvatarManager disposed")}catch(e){this.logger.warn("Error while disposing AvatarManager",e)}}}const A="playing",R="playbackError",M="subtitleWordChange",z="subtitleChange",O="imageChange",P="finished",B="avatarAnimationChanged";class D extends u{capabilities;audioPlayer;visemeScheduler;subtitleManager;isPaused=!0;hasStarted=!1;avatarManager;constructor(e){super(new o({category:"🎪 PlaybackManager",style:r})),this.capabilities=e,this.audioPlayer=new S,this.visemeScheduler=new C(new AudioContext),this.subtitleManager=new E(()=>this.audioPlayer.getCurrentTime()),this.avatarManager=new I,this.avatarManager.on("animation-changed",async e=>{await this.emit(B,e)}),this.setupChildListeners(),this.resetState()}setupChildListeners(){this.audioPlayer.on(p.Ready,()=>{this.isPaused&&!this.hasStarted?(this.logger.debug("Ready event received, starting playback"),this.play()):this.logger.debug("Ready event received but already playing or paused, ignoring")}),this.audioPlayer.on(p.AboutToComplete,async()=>{this.logger.debug("Audio about to complete"),await this.emit("aboutToComplete")}),this.audioPlayer.on(p.Error,async e=>{await this.emit(R,{source:"audio",error:e})}),this.audioPlayer.on(p.Finished,async()=>{await this.emit(P),this.reset()}),this.subtitleManager.on(T,async e=>{await this.emit(M,e)}),this.subtitleManager.on(k,async e=>{await this.emit(z,e)})}resetState(){this.isPaused=!0,this.hasStarted=!1}async initialize(){this.logger.debug("Initialized",this.capabilities),this.isPaused=!0,this.hasStarted=!1,await this.audioPlayer.initialize()}handleMessage(e){"audio"===e.event||"subtitles"===e.event||"viseme"===e.event?this.enqueue(e):"audio_complete"===e.event?this.markAudioComplete():"image"===e.event&&this.emit(O,e)}enqueue(e){if(this.capabilities.audio&&"audio"===e.event){const t=e;this.audioPlayer.enqueue(t.audio)}}markAudioComplete(){this.logger.debug("Marking audio as complete"),this.capabilities.audio&&this.audioPlayer.markComplete()}async play(){this.isPaused=!1,this.hasStarted=!0,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.play():Promise.resolve()]),await this.emit(A)}async pause(){this.isPaused=!0,this.audioPlayer.pause(),this.visemeScheduler.pause(),this.subtitleManager.pause(),this.avatarManager.playIdle(),await this.emit("paused")}async resume(){this.isPaused&&(this.isPaused=!1,this.avatarManager.playTalk(),await Promise.all([this.capabilities.viseme?this.visemeScheduler.play():Promise.resolve(),this.capabilities.subtitles?this.subtitleManager.play():Promise.resolve(),this.capabilities.audio?this.audioPlayer.resume():Promise.resolve()]),await this.emit(A))}async resumeAudioContext(){"function"==typeof this.audioPlayer.resumeAudioContext&&await this.audioPlayer.resumeAudioContext()}getRemainingAudioSeconds(){return this.audioPlayer?.getRemainingAudioSeconds()??0}reset(){this.resetState(),this.audioPlayer?.reset(),this.subtitleManager?.reset(),this.avatarManager.playIdle()}resetAboutToComplete(){this.audioPlayer?.resetAboutToComplete()}dispose(){this.logger.debug("Disposing PlaybackManager...");try{this.isPaused=!0,this.hasStarted=!1,this.audioPlayer?.pause(),this.visemeScheduler?.pause(),this.subtitleManager?.pause(),this.avatarManager?.playIdle()}catch(e){this.logger.warn("Error pausing components during dispose",e)}try{this.audioPlayer&&"function"==typeof this.audioPlayer.dispose&&this.audioPlayer.dispose()}catch(e){this.logger.warn("Error disposing audioPlayer",e)}try{this.avatarManager&&"function"==typeof this.avatarManager.dispose&&this.avatarManager.dispose()}catch(e){this.logger.warn("Error disposing avatarManager",e)}try{this.subtitleManager?.reset(),this.removeAllListeners()}catch(e){this.logger.warn("Error resetting subtitleManager or removing listeners",e)}this.logger.debug("PlaybackManager disposed")}wireVADToAvatar(e){e.on(Sn.StateChange,e=>{"userSpeaking"===e.newState?this.avatarManager.playListen():"listening"===e.newState&&this.avatarManager.playIdle()})}wireConversationStateToAvatar(e){e.on(Sn.StateChange,e=>{"waiting"===e.newState&&this.avatarManager.playThink()})}}var U=n(937);const L="voiceActivity";class N extends u{vadModel=null;silenceTimer=null;silenceTimeoutMs;positiveSpeechThreshold;negativeSpeechThreshold;minSpeechMs;isDisposed=!1;currentStream=null;constructor(e=300,t=.5,n=.35,i=100){super(new o({category:"🎤 VADManager",style:s})),this.silenceTimeoutMs=e,this.positiveSpeechThreshold=t,this.negativeSpeechThreshold=n,this.minSpeechMs=i}async initialize(e){if(this.isDisposed)return;this.currentStream=e,this.logger.debug("You may need to close the browser console for this to initialize");const t=await U.Jl.new({getStream:async()=>this.currentStream,pauseStream:async()=>{},resumeStream:async e=>e,startOnLoad:!1,baseAssetPath:"/static/binaries/",onnxWASMBasePath:"/static/binaries/",positiveSpeechThreshold:this.positiveSpeechThreshold,negativeSpeechThreshold:this.negativeSpeechThreshold,minSpeechMs:this.minSpeechMs,onSpeechStart:async()=>{this.isDisposed||(this.logger.debug("Speech started"),this.clearSilenceTimer(),await this.emit(L,{isSpeaking:!0,confidence:1}))},onSpeechEnd:async e=>{this.isDisposed||(this.logger.debug("Speech ended"),this.startSilenceTimer(),await this.emit(L,{isSpeaking:!1,confidence:1}))},onVADMisfire:async()=>{this.isDisposed||(this.logger.debug("Misfire detected"),await this.emit(L,{isSpeaking:!1,confidence:0,misfire:!0}))},onFrameProcessed:async e=>{}});if(this.isDisposed)return this.logger.debug("VADManager disposed during initialization, cleaning up model"),void("function"==typeof t.destroy?t.destroy():t.pause());this.vadModel=t,this.logger.debug(`VAD Manager initialized (MicVAD) with silenceTimeoutMs=${this.silenceTimeoutMs}, positiveSpeechThreshold=${this.positiveSpeechThreshold}, negativeSpeechThreshold=${this.negativeSpeechThreshold}, minSpeechMs=${this.minSpeechMs}`)}startAnalysis(){this.vadModel&&(this.vadModel.start(),this.logger.debug("VAD analysis started (MicVAD)"))}stopAnalysis(){this.clearSilenceTimer(),this.vadModel&&(this.vadModel.pause(),this.logger.debug("VAD analysis stopped (MicVAD)"))}startSilenceTimer(){this.silenceTimer||(this.silenceTimer=window.setTimeout(async()=>{await this.emit("silence"),this.silenceTimer=null},this.silenceTimeoutMs))}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}dispose(){try{this.logger.debug("Disposing VADManager..."),this.isDisposed=!0,this.stopAnalysis(),this.vadModel&&("function"==typeof this.vadModel.destroy&&this.vadModel.destroy(),this.vadModel=null),this.currentStream=null,this.clearSilenceTimer(),this.removeAllListeners(),this.logger.debug("VADManager disposed")}catch(e){this.logger.warn("Error while disposing VADManager",e)}}}const H="user-input",F="user-speaking",q="user-silence",V={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let W;const j=new Uint8Array(16),G=[];for(let e=0;e<256;++e)G.push((e+256).toString(16).slice(1));function K(e,t,n){const i=(e=e||{}).random??e.rng?.()??function(){if(!W){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");W=crypto.getRandomValues.bind(crypto)}return W(j)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=i[e];return t}return function(e,t=0){return(G[e[t+0]]+G[e[t+1]]+G[e[t+2]]+G[e[t+3]]+"-"+G[e[t+4]]+G[e[t+5]]+"-"+G[e[t+6]]+G[e[t+7]]+"-"+G[e[t+8]]+G[e[t+9]]+"-"+G[e[t+10]]+G[e[t+11]]+G[e[t+12]]+G[e[t+13]]+G[e[t+14]]+G[e[t+15]]).toLowerCase()}(i)}class Q{websocket=null;handlers;serverUrl;constructor(e,t){this.serverUrl=e,this.handlers=t}connect(){this.websocket=new WebSocket(this.serverUrl),this.setupHandlers()}disconnect(){this.websocket&&(this.websocket.onmessage=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket.close(1e3,"Client initiated disconnect"),this.websocket=null)}send(e){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("Cant send. WebSocket is not open");this.websocket.send(JSON.stringify(e))}isReady(){return this.websocket?.readyState===WebSocket.OPEN}setupHandlers(){this.websocket&&(this.websocket.onopen=()=>{this.handlers.onOpen&&this.handlers.onOpen()},this.websocket.onmessage=e=>{const t=JSON.parse(e.data);this.handlers.onMessage&&this.handlers.onMessage(t)},this.websocket.onerror=e=>{this.handlers.onError&&this.handlers.onError(e)},this.websocket.onclose=()=>{this.handlers.onClose&&this.handlers.onClose()})}}function J(e,t){return function(){return e.apply(t,arguments)}}const{toString:X}=Object.prototype,{getPrototypeOf:Z}=Object,{iterator:Y,toStringTag:ee}=Symbol,te=(ne=Object.create(null),e=>{const t=X.call(e);return ne[t]||(ne[t]=t.slice(8,-1).toLowerCase())});var ne;const ie=e=>(e=e.toLowerCase(),t=>te(t)===e),re=e=>t=>typeof t===e,{isArray:se}=Array,ae=re("undefined");function oe(e){return null!==e&&!ae(e)&&null!==e.constructor&&!ae(e.constructor)&&de(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ue=ie("ArrayBuffer"),le=re("string"),de=re("function"),he=re("number"),ce=e=>null!==e&&"object"==typeof e,pe=e=>{if("object"!==te(e))return!1;const t=Z(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||ee in e||Y in e)},fe=ie("Date"),me=ie("File"),ge=ie("Blob"),ye=ie("FileList"),we=ie("URLSearchParams"),[be,_e,$e,ve]=["ReadableStream","Request","Response","Headers"].map(ie);function xe(e,t,{allOwnKeys:n=!1}={}){if(null==e)return;let i,r;if("object"!=typeof e&&(e=[e]),se(e))for(i=0,r=e.length;i<r;i++)t.call(null,e[i],i,e);else{if(oe(e))return;const r=n?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(i=0;i<s;i++)a=r[i],t.call(null,e[a],a,e)}}function Se(e,t){if(oe(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const Te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,ke=e=>!ae(e)&&e!==Te,Ee=(Ce="undefined"!=typeof Uint8Array&&Z(Uint8Array),e=>Ce&&e instanceof Ce);var Ce;const Ie=ie("HTMLFormElement"),Ae=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),Re=ie("RegExp"),Me=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};xe(n,(n,r)=>{let s;!1!==(s=t(n,r,e))&&(i[r]=s||n)}),Object.defineProperties(e,i)},ze=ie("AsyncFunction"),Oe=(Pe="function"==typeof setImmediate,Be=de(Te.postMessage),Pe?setImmediate:Be?(De=`axios@${Math.random()}`,Ue=[],Te.addEventListener("message",({source:e,data:t})=>{e===Te&&t===De&&Ue.length&&Ue.shift()()},!1),e=>{Ue.push(e),Te.postMessage(De,"*")}):e=>setTimeout(e));var Pe,Be,De,Ue;const Le="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Te):"undefined"!=typeof process&&process.nextTick||Oe,Ne={isArray:se,isArrayBuffer:ue,isBuffer:oe,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||de(e.append)&&("formdata"===(t=te(e))||"object"===t&&de(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&ue(e.buffer),t},isString:le,isNumber:he,isBoolean:e=>!0===e||!1===e,isObject:ce,isPlainObject:pe,isEmptyObject:e=>{if(!ce(e)||oe(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:be,isRequest:_e,isResponse:$e,isHeaders:ve,isUndefined:ae,isDate:fe,isFile:me,isBlob:ge,isRegExp:Re,isFunction:de,isStream:e=>ce(e)&&de(e.pipe),isURLSearchParams:we,isTypedArray:Ee,isFileList:ye,forEach:xe,merge:function e(){const{caseless:t,skipUndefined:n}=ke(this)&&this||{},i={},r=(r,s)=>{const a=t&&Se(i,s)||s;pe(i[a])&&pe(r)?i[a]=e(i[a],r):pe(r)?i[a]=e({},r):se(r)?i[a]=r.slice():n&&ae(r)||(i[a]=r)};for(let e=0,t=arguments.length;e<t;e++)arguments[e]&&xe(arguments[e],r);return i},extend:(e,t,n,{allOwnKeys:i}={})=>(xe(t,(t,i)=>{n&&de(t)?e[i]=J(t,n):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,s,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],i&&!i(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==n&&Z(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:te,kindOfTest:ie,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(se(e))return e;let t=e.length;if(!he(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Y]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:Ie,hasOwnProperty:Ae,hasOwnProp:Ae,reduceDescriptors:Me,freezeMethods:e=>{Me(e,(t,n)=>{if(de(e)&&-1!==["arguments","caller","callee"].indexOf(n))return!1;const i=e[n];de(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},i=e=>{e.forEach(e=>{n[e]=!0})};return se(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,n){return t.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:Se,global:Te,isContextDefined:ke,isSpecCompliantForm:function(e){return!!(e&&de(e.append)&&"FormData"===e[ee]&&e[Y])},toJSONObject:e=>{const t=new Array(10),n=(e,i)=>{if(ce(e)){if(t.indexOf(e)>=0)return;if(oe(e))return e;if(!("toJSON"in e)){t[i]=e;const r=se(e)?[]:{};return xe(e,(e,t)=>{const s=n(e,i+1);!ae(s)&&(r[t]=s)}),t[i]=void 0,r}}return e};return n(e,0)},isAsyncFn:ze,isThenable:e=>e&&(ce(e)||de(e))&&de(e.then)&&de(e.catch),setImmediate:Oe,asap:Le,isIterable:e=>null!=e&&de(e[Y])};function He(e,t,n,i,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status?r.status:null)}Ne.inherits(He,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Ne.toJSONObject(this.config),code:this.code,status:this.status}}});const Fe=He.prototype,qe={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{qe[e]={value:e}}),Object.defineProperties(He,qe),Object.defineProperty(Fe,"isAxiosError",{value:!0}),He.from=(e,t,n,i,r,s)=>{const a=Object.create(Fe);Ne.toFlatObject(e,a,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e);const o=e&&e.message?e.message:"Error",u=null==t&&e?e.code:t;return He.call(a,o,u,n,i,r),e&&null==a.cause&&Object.defineProperty(a,"cause",{value:e,configurable:!0}),a.name=e&&e.name||"Error",s&&Object.assign(a,s),a};const Ve=He;function We(e){return Ne.isPlainObject(e)||Ne.isArray(e)}function je(e){return Ne.endsWith(e,"[]")?e.slice(0,-2):e}function Ge(e,t,n){return e?e.concat(t).map(function(e,t){return e=je(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}const Ke=Ne.toFlatObject(Ne,{},null,function(e){return/^is[A-Z]/.test(e)}),Qe=function(e,t,n){if(!Ne.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=Ne.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Ne.isUndefined(t[e])})).metaTokens,r=n.visitor||l,s=n.dots,a=n.indexes,o=(n.Blob||"undefined"!=typeof Blob&&Blob)&&Ne.isSpecCompliantForm(t);if(!Ne.isFunction(r))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(Ne.isDate(e))return e.toISOString();if(Ne.isBoolean(e))return e.toString();if(!o&&Ne.isBlob(e))throw new Ve("Blob is not supported. Use a Buffer instead.");return Ne.isArrayBuffer(e)||Ne.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function l(e,n,r){let o=e;if(e&&!r&&"object"==typeof e)if(Ne.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=JSON.stringify(e);else if(Ne.isArray(e)&&function(e){return Ne.isArray(e)&&!e.some(We)}(e)||(Ne.isFileList(e)||Ne.endsWith(n,"[]"))&&(o=Ne.toArray(e)))return n=je(n),o.forEach(function(e,i){!Ne.isUndefined(e)&&null!==e&&t.append(!0===a?Ge([n],i,s):null===a?n:n+"[]",u(e))}),!1;return!!We(e)||(t.append(Ge(r,n,s),u(e)),!1)}const d=[],h=Object.assign(Ke,{defaultVisitor:l,convertValue:u,isVisitable:We});if(!Ne.isObject(e))throw new TypeError("data must be an object");return function e(n,i){if(!Ne.isUndefined(n)){if(-1!==d.indexOf(n))throw Error("Circular reference detected in "+i.join("."));d.push(n),Ne.forEach(n,function(n,s){!0===(!(Ne.isUndefined(n)||null===n)&&r.call(t,n,Ne.isString(s)?s.trim():s,i,h))&&e(n,i?i.concat(s):[s])}),d.pop()}}(e),t};function Je(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Xe(e,t){this._pairs=[],e&&Qe(e,this,t)}const Ze=Xe.prototype;Ze.append=function(e,t){this._pairs.push([e,t])},Ze.toString=function(e){const t=e?function(t){return e.call(this,t,Je)}:Je;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};const Ye=Xe;function et(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function tt(e,t,n){if(!t)return e;const i=n&&n.encode||et;Ne.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let s;if(s=r?r(t,n):Ne.isURLSearchParams(t)?t.toString():new Ye(t,n).toString(i),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}const nt=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Ne.forEach(this.handlers,function(t){null!==t&&e(t)})}},it={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ye,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},st="undefined"!=typeof window&&"undefined"!=typeof document,at="object"==typeof navigator&&navigator||void 0,ot=st&&(!at||["ReactNative","NativeScript","NS"].indexOf(at.product)<0),ut="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,lt=st&&window.location.href||"http://localhost",dt={...i,...rt},ht=function(e){function t(e,n,i,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;return s=!s&&Ne.isArray(i)?i.length:s,o?(Ne.hasOwnProp(i,s)?i[s]=[i[s],n]:i[s]=n,!a):(i[s]&&Ne.isObject(i[s])||(i[s]=[]),t(e,n,i[s],r)&&Ne.isArray(i[s])&&(i[s]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let s;for(i=0;i<r;i++)s=n[i],t[s]=e[s];return t}(i[s])),!a)}if(Ne.isFormData(e)&&Ne.isFunction(e.entries)){const n={};return Ne.forEachEntry(e,(e,i)=>{t(function(e){return Ne.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,n,0)}),n}return null},ct={transitional:it,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=Ne.isObject(e);if(r&&Ne.isHTMLForm(e)&&(e=new FormData(e)),Ne.isFormData(e))return i?JSON.stringify(ht(e)):e;if(Ne.isArrayBuffer(e)||Ne.isBuffer(e)||Ne.isStream(e)||Ne.isFile(e)||Ne.isBlob(e)||Ne.isReadableStream(e))return e;if(Ne.isArrayBufferView(e))return e.buffer;if(Ne.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Qe(e,new dt.classes.URLSearchParams,{visitor:function(e,t,n,i){return dt.isNode&&Ne.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((s=Ne.isFileList(e))||n.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Qe(s?{"files[]":e}:e,t&&new t,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(e){if(Ne.isString(e))try{return(0,JSON.parse)(e),Ne.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||ct.transitional,n=t&&t.forcedJSONParsing,i="json"===this.responseType;if(Ne.isResponse(e)||Ne.isReadableStream(e))return e;if(e&&Ne.isString(e)&&(n&&!this.responseType||i)){const n=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(e){if(n){if("SyntaxError"===e.name)throw Ve.from(e,Ve.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:dt.classes.FormData,Blob:dt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ne.forEach(["delete","get","head","post","put","patch"],e=>{ct.headers[e]={}});const pt=ct,ft=Ne.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mt=Symbol("internals");function gt(e){return e&&String(e).trim().toLowerCase()}function yt(e){return!1===e||null==e?e:Ne.isArray(e)?e.map(yt):String(e)}function wt(e,t,n,i,r){return Ne.isFunction(i)?i.call(this,t,n):(r&&(t=n),Ne.isString(t)?Ne.isString(i)?-1!==t.indexOf(i):Ne.isRegExp(i)?i.test(t):void 0:void 0)}class bt{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=gt(t);if(!r)throw new Error("header name must be a non-empty string");const s=Ne.findKey(i,r);(!s||void 0===i[s]||!0===n||void 0===n&&!1!==i[s])&&(i[s||t]=yt(e))}const s=(e,t)=>Ne.forEach(e,(e,n)=>r(e,n,t));if(Ne.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(Ne.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach(function(e){r=e.indexOf(":"),n=e.substring(0,r).trim().toLowerCase(),i=e.substring(r+1).trim(),!n||t[n]&&ft[n]||("set-cookie"===n?t[n]?t[n].push(i):t[n]=[i]:t[n]=t[n]?t[n]+", "+i:i)}),t})(e),t);else if(Ne.isObject(e)&&Ne.isIterable(e)){let n,i,r={};for(const t of e){if(!Ne.isArray(t))throw TypeError("Object iterator must return a key-value pair");r[i=t[0]]=(n=r[i])?Ne.isArray(n)?[...n,t[1]]:[n,t[1]]:t[1]}s(r,t)}else null!=e&&r(t,e,n);return this}get(e,t){if(e=gt(e)){const n=Ne.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(Ne.isFunction(t))return t.call(this,e,n);if(Ne.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=gt(e)){const n=Ne.findKey(this,e);return!(!n||void 0===this[n]||t&&!wt(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=gt(e)){const r=Ne.findKey(n,e);!r||t&&!wt(0,n[r],r,t)||(delete n[r],i=!0)}}return Ne.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!wt(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return Ne.forEach(this,(i,r)=>{const s=Ne.findKey(n,r);if(s)return t[s]=yt(i),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}(r):String(r).trim();a!==r&&delete t[r],t[a]=yt(i),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Ne.forEach(this,(n,i)=>{null!=n&&!1!==n&&(t[i]=e&&Ne.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(e=>n.set(e)),n}static accessor(e){const t=(this[mt]=this[mt]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=gt(e);t[i]||(function(e,t){const n=Ne.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+n,{value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})})}(n,e),t[i]=!0)}return Ne.isArray(e)?e.forEach(i):i(e),this}}bt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ne.reduceDescriptors(bt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[n]=e}}}),Ne.freezeMethods(bt);const _t=bt;function $t(e,t){const n=this||pt,i=t||n,r=_t.from(i.headers);let s=i.data;return Ne.forEach(e,function(e){s=e.call(n,s,r.normalize(),t?t.status:void 0)}),r.normalize(),s}function vt(e){return!(!e||!e.__CANCEL__)}function xt(e,t,n){Ve.call(this,null==e?"canceled":e,Ve.ERR_CANCELED,t,n),this.name="CanceledError"}Ne.inherits(xt,Ve,{__CANCEL__:!0});const St=xt;function Tt(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Ve("Request failed with status code "+n.status,[Ve.ERR_BAD_REQUEST,Ve.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}const kt=(e,t,n=3)=>{let i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,s=0,a=0;return t=void 0!==t?t:1e3,function(o){const u=Date.now(),l=i[a];r||(r=u),n[s]=o,i[s]=u;let d=a,h=0;for(;d!==s;)h+=n[d++],d%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),u-r<t)return;const c=l&&u-l;return c?Math.round(1e3*h/c):void 0}}(50,250);return function(e,t){let n,i,r=0,s=1e3/t;const a=(t,s=Date.now())=>{r=s,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(n=e,i||(i=setTimeout(()=>{i=null,a(n)},s-o)))},()=>n&&a(n)]}(n=>{const s=n.loaded,a=n.lengthComputable?n.total:void 0,o=s-i,u=r(o);i=s,e({loaded:s,total:a,progress:a?s/a:void 0,bytes:o,rate:u||void 0,estimated:u&&a&&s<=a?(a-s)/u:void 0,event:n,lengthComputable:null!=a,[t?"download":"upload"]:!0})},n)},Et=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Ct=e=>(...t)=>Ne.asap(()=>e(...t)),It=dt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,dt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(dt.origin),dt.navigator&&/(msie|trident)/i.test(dt.navigator.userAgent)):()=>!0,At=dt.hasStandardBrowserEnv?{write(e,t,n,i,r,s){const a=[e+"="+encodeURIComponent(t)];Ne.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),Ne.isString(i)&&a.push("path="+i),Ne.isString(r)&&a.push("domain="+r),!0===s&&a.push("secure"),document.cookie=a.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Rt(e,t,n){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==n)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Mt=e=>e instanceof _t?{...e}:e;function zt(e,t){t=t||{};const n={};function i(e,t,n,i){return Ne.isPlainObject(e)&&Ne.isPlainObject(t)?Ne.merge.call({caseless:i},e,t):Ne.isPlainObject(t)?Ne.merge({},t):Ne.isArray(t)?t.slice():t}function r(e,t,n,r){return Ne.isUndefined(t)?Ne.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function s(e,t){if(!Ne.isUndefined(t))return i(void 0,t)}function a(e,t){return Ne.isUndefined(t)?Ne.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function o(n,r,s){return s in t?i(n,r):s in e?i(void 0,n):void 0}const u={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:o,headers:(e,t,n)=>r(Mt(e),Mt(t),0,!0)};return Ne.forEach(Object.keys({...e,...t}),function(i){const s=u[i]||r,a=s(e[i],t[i],i);Ne.isUndefined(a)&&s!==o||(n[i]=a)}),n}const Ot=e=>{const t=zt({},e);let{data:n,withXSRFToken:i,xsrfHeaderName:r,xsrfCookieName:s,headers:a,auth:o}=t;if(t.headers=a=_t.from(a),t.url=tt(Rt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),o&&a.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):""))),Ne.isFormData(n))if(dt.hasStandardBrowserEnv||dt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(Ne.isFunction(n.getHeaders)){const e=n.getHeaders(),t=["content-type","content-length"];Object.entries(e).forEach(([e,n])=>{t.includes(e.toLowerCase())&&a.set(e,n)})}if(dt.hasStandardBrowserEnv&&(i&&Ne.isFunction(i)&&(i=i(t)),i||!1!==i&&It(t.url))){const e=r&&s&&At.read(s);e&&a.set(r,e)}return t},Pt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,n){const i=Ot(e);let r=i.data;const s=_t.from(i.headers).normalize();let a,o,u,l,d,{responseType:h,onUploadProgress:c,onDownloadProgress:p}=i;function f(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(a),i.signal&&i.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;const i=_t.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Tt(function(e){t(e),f()},function(e){n(e),f()},{data:h&&"text"!==h&&"json"!==h?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(n(new Ve("Request aborted",Ve.ECONNABORTED,e,m)),m=null)},m.onerror=function(t){const i=t&&t.message?t.message:"Network Error",r=new Ve(i,Ve.ERR_NETWORK,e,m);r.event=t||null,n(r),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const r=i.transitional||it;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),n(new Ve(t,r.clarifyTimeoutError?Ve.ETIMEDOUT:Ve.ECONNABORTED,e,m)),m=null},void 0===r&&s.setContentType(null),"setRequestHeader"in m&&Ne.forEach(s.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Ne.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),h&&"json"!==h&&(m.responseType=i.responseType),p&&([u,d]=kt(p,!0),m.addEventListener("progress",u)),c&&m.upload&&([o,l]=kt(c),m.upload.addEventListener("progress",o),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(a=t=>{m&&(n(!t||t.type?new St(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(a),i.signal&&(i.signal.aborted?a():i.signal.addEventListener("abort",a)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===dt.protocols.indexOf(y)?n(new Ve("Unsupported protocol "+y+":",Ve.ERR_BAD_REQUEST,e)):m.send(r||null)})},Bt=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let n,i=new AbortController;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Ve?t:new St(t instanceof Error?t.message:t))}};let s=t&&setTimeout(()=>{s=null,r(new Ve(`timeout ${t} of ms exceeded`,Ve.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)}),e=null)};e.forEach(e=>e.addEventListener("abort",r));const{signal:o}=i;return o.unsubscribe=()=>Ne.asap(a),o}},Dt=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},Ut=(e,t,n,i)=>{const r=async function*(e,t){for await(const n of async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)break;yield n}}finally{await t.cancel()}}(e))yield*Dt(n,t)}(e,t);let s,a=0,o=e=>{s||(s=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await r.next();if(t)return o(),void e.close();let s=i.byteLength;if(n){let e=a+=s;n(e)}e.enqueue(new Uint8Array(i))}catch(e){throw o(e),e}},cancel:e=>(o(e),r.return())},{highWaterMark:2})},{isFunction:Lt}=Ne,Nt=(({Request:e,Response:t})=>({Request:e,Response:t}))(Ne.global),{ReadableStream:Ht,TextEncoder:Ft}=Ne.global,qt=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Vt=e=>{e=Ne.merge.call({skipUndefined:!0},Nt,e);const{fetch:t,Request:n,Response:i}=e,r=t?Lt(t):"function"==typeof fetch,s=Lt(n),a=Lt(i);if(!r)return!1;const o=r&&Lt(Ht),u=r&&("function"==typeof Ft?(l=new Ft,e=>l.encode(e)):async e=>new Uint8Array(await new n(e).arrayBuffer()));var l;const d=s&&o&&qt(()=>{let e=!1;const t=new n(dt.origin,{body:new Ht,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),h=a&&o&&qt(()=>Ne.isReadableStream(new i("").body)),c={stream:h&&(e=>e.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!c[e]&&(c[e]=(t,n)=>{let i=t&&t[e];if(i)return i.call(t);throw new Ve(`Response type '${e}' is not supported`,Ve.ERR_NOT_SUPPORT,n)})});return async e=>{let{url:r,method:a,data:o,signal:l,cancelToken:p,timeout:f,onDownloadProgress:m,onUploadProgress:g,responseType:y,headers:w,withCredentials:b="same-origin",fetchOptions:_}=Ot(e),$=t||fetch;y=y?(y+"").toLowerCase():"text";let v=Bt([l,p&&p.toAbortSignal()],f),x=null;const S=v&&v.unsubscribe&&(()=>{v.unsubscribe()});let T;try{if(g&&d&&"get"!==a&&"head"!==a&&0!==(T=await(async(e,t)=>{const i=Ne.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(Ne.isBlob(e))return e.size;if(Ne.isSpecCompliantForm(e)){const t=new n(dt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Ne.isArrayBufferView(e)||Ne.isArrayBuffer(e)?e.byteLength:(Ne.isURLSearchParams(e)&&(e+=""),Ne.isString(e)?(await u(e)).byteLength:void 0)})(t):i})(w,o))){let e,t=new n(r,{method:"POST",body:o,duplex:"half"});if(Ne.isFormData(o)&&(e=t.headers.get("content-type"))&&w.setContentType(e),t.body){const[e,n]=Et(T,kt(Ct(g)));o=Ut(t.body,65536,e,n)}}Ne.isString(b)||(b=b?"include":"omit");const t=s&&"credentials"in n.prototype,l={..._,signal:v,method:a.toUpperCase(),headers:w.normalize().toJSON(),body:o,duplex:"half",credentials:t?b:void 0};x=s&&new n(r,l);let p=await(s?$(x,_):$(r,l));const f=h&&("stream"===y||"response"===y);if(h&&(m||f&&S)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=p[t]});const t=Ne.toFiniteNumber(p.headers.get("content-length")),[n,r]=m&&Et(t,kt(Ct(m),!0))||[];p=new i(Ut(p.body,65536,n,()=>{r&&r(),S&&S()}),e)}y=y||"text";let k=await c[Ne.findKey(c,y)||"text"](p,e);return!f&&S&&S(),await new Promise((t,n)=>{Tt(t,n,{data:k,headers:_t.from(p.headers),status:p.status,statusText:p.statusText,config:e,request:x})})}catch(t){if(S&&S(),t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new Ve("Network Error",Ve.ERR_NETWORK,e,x),{cause:t.cause||t});throw Ve.from(t,t&&t.code,e,x)}}},Wt=new Map,jt=e=>{let t=e?e.env:{};const{fetch:n,Request:i,Response:r}=t,s=[i,r,n];let a,o,u=s.length,l=Wt;for(;u--;)a=s[u],o=l.get(a),void 0===o&&l.set(a,o=u?new Map:Vt(t)),l=o;return o},Gt=(jt(),{http:null,xhr:Pt,fetch:{get:jt}});Ne.forEach(Gt,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}});const Kt=e=>`- ${e}`,Qt=e=>Ne.isFunction(e)||null===e||!1===e,Jt=(e,t)=>{e=Ne.isArray(e)?e:[e];const{length:n}=e;let i,r;const s={};for(let a=0;a<n;a++){let n;if(i=e[a],r=i,!Qt(i)&&(r=Gt[(n=String(i)).toLowerCase()],void 0===r))throw new Ve(`Unknown adapter '${n}'`);if(r&&(Ne.isFunction(r)||(r=r.get(t))))break;s[n||"#"+a]=r}if(!r){const e=Object.entries(s).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));let t=n?e.length>1?"since :\n"+e.map(Kt).join("\n"):" "+Kt(e[0]):"as no adapter specified";throw new Ve("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r};function Xt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new St(null,e)}function Zt(e){return Xt(e),e.headers=_t.from(e.headers),e.data=$t.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Jt(e.adapter||pt.adapter,e)(e).then(function(t){return Xt(e),t.data=$t.call(e,e.transformResponse,t),t.headers=_t.from(t.headers),t},function(t){return vt(t)||(Xt(e),t&&t.response&&(t.response.data=$t.call(e,e.transformResponse,t.response),t.response.headers=_t.from(t.response.headers))),Promise.reject(t)})}const Yt="1.12.2",en={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{en[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const tn={};en.transitional=function(e,t,n){function i(e,t){return"[Axios v"+Yt+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,s)=>{if(!1===e)throw new Ve(i(r," has been removed"+(t?" in "+t:"")),Ve.ERR_DEPRECATED);return t&&!tn[r]&&(tn[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,s)}},en.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};const nn={assertOptions:function(e,t,n){if("object"!=typeof e)throw new Ve("options must be an object",Ve.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const s=i[r],a=t[s];if(a){const t=e[s],n=void 0===t||a(t,s,e);if(!0!==n)throw new Ve("option "+s+" must be "+n,Ve.ERR_BAD_OPTION_VALUE);continue}if(!0!==n)throw new Ve("Unknown option "+s,Ve.ERR_BAD_OPTION)}},validators:en},rn=nn.validators;class sn{constructor(e){this.defaults=e||{},this.interceptors={request:new nt,response:new nt}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const n=t.stack?t.stack.replace(/^.+\n/,""):"";try{e.stack?n&&!String(e.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(e.stack+="\n"+n):e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=zt(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;void 0!==n&&nn.assertOptions(n,{silentJSONParsing:rn.transitional(rn.boolean),forcedJSONParsing:rn.transitional(rn.boolean),clarifyTimeoutError:rn.transitional(rn.boolean)},!1),null!=i&&(Ne.isFunction(i)?t.paramsSerializer={serialize:i}:nn.assertOptions(i,{encode:rn.function,serialize:rn.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),nn.assertOptions(t,{baseUrl:rn.spelling("baseURL"),withXsrfToken:rn.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&Ne.merge(r.common,r[t.method]);r&&Ne.forEach(["delete","get","head","post","put","patch","common"],e=>{delete r[e]}),t.headers=_t.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,a.unshift(e.fulfilled,e.rejected))});const u=[];let l;this.interceptors.response.forEach(function(e){u.push(e.fulfilled,e.rejected)});let d,h=0;if(!o){const e=[Zt.bind(this),void 0];for(e.unshift(...a),e.push(...u),d=e.length,l=Promise.resolve(t);h<d;)l=l.then(e[h++],e[h++]);return l}d=a.length;let c=t;for(;h<d;){const e=a[h++],t=a[h++];try{c=e(c)}catch(e){t.call(this,e);break}}try{l=Zt.call(this,c)}catch(e){return Promise.reject(e)}for(h=0,d=u.length;h<d;)l=l.then(u[h++],u[h++]);return l}getUri(e){return tt(Rt((e=zt(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Ne.forEach(["delete","get","head","options"],function(e){sn.prototype[e]=function(t,n){return this.request(zt(n||{},{method:e,url:t,data:(n||{}).data}))}}),Ne.forEach(["post","put","patch"],function(e){function t(t){return function(n,i,r){return this.request(zt(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}sn.prototype[e]=t(),sn.prototype[e+"Form"]=t(!0)});const an=sn;class on{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const n=this;this.promise.then(e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{n.subscribe(e),t=e}).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e(function(e,i,r){n.reason||(n.reason=new St(e,i,r),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new on(function(t){e=t}),cancel:e}}}const un=on,ln={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ln).forEach(([e,t])=>{ln[t]=e});const dn=ln,hn=function e(t){const n=new an(t),i=J(an.prototype.request,n);return Ne.extend(i,an.prototype,n,{allOwnKeys:!0}),Ne.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(zt(t,n))},i}(pt);hn.Axios=an,hn.CanceledError=St,hn.CancelToken=un,hn.isCancel=vt,hn.VERSION=Yt,hn.toFormData=Qe,hn.AxiosError=Ve,hn.Cancel=hn.CanceledError,hn.all=function(e){return Promise.all(e)},hn.spread=function(e){return function(t){return e.apply(null,t)}},hn.isAxiosError=function(e){return Ne.isObject(e)&&!0===e.isAxiosError},hn.mergeConfig=zt,hn.AxiosHeaders=_t,hn.formToJSON=e=>ht(Ne.isHTMLForm(e)?new FormData(e):e),hn.getAdapter=Jt,hn.HttpStatusCode=dn,hn.default=hn;const cn=hn,pn=class{static setItem(e,t){localStorage.setItem(e,t)}static setWithExpiry(e,t,n=33e5){const i={value:t,expiry:Date.now()+n};try{localStorage.setItem(e,JSON.stringify(i))}catch{}}static getWithExpiry(e){const t=localStorage.getItem(e);if(!t)return null;let n=null;try{n=JSON.parse(t)}catch(t){throw localStorage.removeItem(e),t}const i="number"==typeof n.expiry?n.expiry:0;return Date.now()>i?(localStorage.removeItem(e),null):n.value}static removeItem(e){localStorage.removeItem(e)}},fn=class{_authToken;_requestId=null;apiUrl;_apiKey;_federatedId=null;apiClient;constructor({apiUrl:e,apiKey:t,federatedId:n}){this.apiUrl=e,this._apiKey=t,this._federatedId=n,this._authToken=pn.getWithExpiry("authToken")||void 0,this.apiClient=cn.create({baseURL:this.apiUrl,headers:{Authorization:`Bearer ${this.authToken}`}}),this.setInterceptors()}async login(){if(!Boolean(pn.getWithExpiry("authToken")||this.authToken))try{await this.loginWithApiKey()}catch(e){throw console.error("Failed to authenticate with client credentials.",e),pn.removeItem("authToken"),this._authToken=void 0,e}}setInterceptors(){this.apiClient.interceptors.request.use(async e=>(e.url?.includes("/auth/login")||this.login(),e),e=>Promise.reject(e)),this.apiClient.interceptors.response.use(e=>(this.updatedRequestFromResponse(e),e),e=>(e.response&&this.updatedRequestFromResponse(e.response),Promise.reject(e))),this.apiClient.interceptors.response.use(e=>e,this.handleError.bind(this)),this.apiClient.interceptors.response.use(e=>e,e=>{if(e.response)try{return JSON.stringify(e.response.data),cn.isAxiosError(e)&&401===e.response?.status&&(pn.removeItem("authToken"),this._authToken=void 0),Promise.reject(e)}catch(e){return console.error(e),Promise.reject(e)}return Promise.reject(e)})}async verifyAuthentication(){await this.getMe()}updatedRequestFromResponse(e){return this.updateRequestId(e.headers["x-request-id"]??""),e}handleError(e){return Promise.reject(e)}get authToken(){return this._authToken}set authToken(e){e?pn.setWithExpiry("authToken",e):pn.removeItem("authToken"),this._authToken=e,this.apiClient&&(this.apiClient.defaults.headers.Authorization=`Bearer ${e}`)}get requestId(){return this._requestId}updateRequestId(e){e&&(this._requestId=e)}async loginWithApiKey(){const e=await this.apiClient.post("/auth/login",{api_key:this._apiKey,federated_id:this._federatedId});return this.authToken=e.data.access_token,this.apiClient.defaults.headers.common.Authorization=`Bearer ${this.authToken}`,this.authToken||""}async getMe(){return(await this.apiClient.get("/users/me")).data}async generateImage(e){const{provider:t,...n}=e,i=`/images/generate/${t}`;return(await this.apiClient.post(i,n)).data}async generateImageWithBria(e){return(await this.apiClient.post("/images/generate/bria",e)).data}async generateImageWithReplicate(e){return(await this.apiClient.post("/images/generate/replicate",e)).data}async getAvailableModels(){return(await this.apiClient.get("/images/models")).data}},mn={sampling_rate:48e3,mime_type:"audio/mpeg"};class gn extends u{config;wsConnection=null;_api=null;pendingRequests=new Map;constructor(e){super(new o({category:"🗣️ConversationNetwork",style:"color: #607d8b; font-weight: bold; font-size: larger"})),this.config=e,this._api=new fn({apiUrl:e.apiUrl,apiKey:e.apiKey,federatedId:e.federatedId})}async initialize(){try{await this._api.login()}catch(e){const t=e.response?.data?.error||e.message||"Authentication failed",n=e.response?.data?.traceback;n?this.logger.error("Authentication failed:",t,"\nTraceback:",n):this.logger.error("Authentication failed:",t);const i=new Error(t);throw n&&(i.traceback=n),i}}async connect(){let e=this.config.apiUrl.replace(/\/api\/?$/,"")+"/interact";this.wsConnection=new Q(e,this.getWebSocketHandlers()),this.wsConnection.connect(),await this.waitForWebSocketReady(1e4),this.logger.debug("Network connections established - Authenticating next...")}async waitForWebSocketReady(e){return new Promise((t,n)=>{if(!this.wsConnection)return void n(new Error("WebSocket connection not initialized"));if(this.wsConnection.isReady())return void t();const i=setTimeout(()=>{n(new Error(`WebSocket connection timeout after ${e}ms`))},e),r=()=>{this.wsConnection?.isReady()?(clearTimeout(i),t()):setTimeout(r,50)};r()})}getWebSocketHandlers(){return{onOpen:async()=>{try{await this.authenticate(),await this.setConfiguration(),this.emit(c),await this.interact({text:".",uid:"",kind:"interact",type:"stream"})}catch(e){const t=e?.error||String(e);this.emit(d,new Error(t))}},onMessage:async e=>{if(e.uid&&this.pendingRequests.has(e.uid)){const t=this.pendingRequests.get(e.uid);if(t)if(t.isStream)"close"===e.kind?(clearTimeout(t.timeout),t.resolve(e),this.pendingRequests.delete(e.uid)):"error"===e.kind?(this.logger.error(e.error),this.emit(d,new Error(e.error))):this.emit(l,e);else{if(clearTimeout(t.timeout),"error"===e.kind){const n=e;this.logger.error(n?.error),t.reject(n.error)}else t.resolve(e);this.pendingRequests.delete(e.uid),this.emit(l,e)}}else"interact"===e.kind?this.emit(l,e):"error"===e.kind?(this.logger.error(e.error),await this.emit(d,e.error)):this.logger.warn("Received message without a matching request UID",e)},onError:async e=>{await this.emit(d,e)},onClose:async()=>{await this.emit(h)}}}async makeRequest(e,t=5e4){return this.makeRequestInternal(e,t,!1)}async makeStreamRequest(e,t=5e4){return this.makeRequestInternal(e,t,!0)}async makeRequestInternal(e,t,n){if(!this.wsConnection?.isReady())throw new Error("WebSocket not ready");var i,r,s;e.uid=!V.randomUUID||r||i?K(i,r,s):V.randomUUID(),e.client_start_time=(new Date).toISOString();const a=new Promise((i,r)=>{const s=setTimeout(()=>{this.pendingRequests.delete(e.uid),r(new Error(`Request ${e.uid} timed out after ${t}ms`))},t);this.pendingRequests.set(e.uid,{resolve:i,reject:r,timeout:s,isStream:n})});return this.wsConnection.send(e),a}async authenticate(){const e={type:"request",kind:"authenticate",access_token:this._api.authToken,uid:""};await this.makeRequest(e)}updateConfig(e){this.config=e}async updateRemoteConfiguration(e){this.updateConfig(e),await this.setConfiguration()}async setConfiguration(){const e={type:"request",kind:"set_configuration",config:{prompt:this.config.prompt,voice_profile:this.config.voiceProfile,utilities:this.config.utilities,safety_policy:this.config.safetyPolicy},uid:""};await this.makeRequest(e)}async addAudio(e){const t={type:"request",kind:"add_audio",audio:e,uid:"",config:mn};await this.makeRequest(t)}async clearAudio(){await this.makeRequest({type:"request",kind:"clear_audio",uid:""})}async checkTurn(){await this.makeRequest({type:"request",kind:"check_turn",uid:""})}async generateImage(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImage(e)).image}}async generateImageWithBria(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithBria(e)).image}}async generateImageWithReplicate(e){return{kind:"generate_image",uid:"",image:(await this._api.generateImageWithReplicate(e)).image}}async getAvailableModels(){return{kind:"get_available_models",uid:"",models:(await this._api.getAvailableModels()).models}}async interact(e){e.context={...this.config.context,...e.context},e.audio_output=this.config.capabilities?.audio??!0,e.kind=e.kind??"interact",e.type=e.type??"stream",await this.makeStreamRequest(e)}async interactAudio(e){e.context={...this.config.context,...e.context},e.audio_output=this.config.capabilities?.audio??!0,e.kind=e.kind??"interact",e.type=e.type??"stream",await this.makeStreamRequest(e)}async disconnect(){this.wsConnection?.disconnect()}isReady(){return this.wsConnection?.isReady()||!1}async send(e){"audio"!==e.type?this.logger.warn("ConversationNetwork.send is deprecated. Use specific methods instead."):await this.addAudio(e.audio)}}class yn{mediaRecorder=null;mimeType;onAudioData;timeslice;logger=new o({category:"🎤 MediaRecorderFallback",style:a});constructor(e,t,n=100){this.mimeType=e,this.onAudioData=t,this.timeslice=n}initialize(e){this.logger.debug("Initializing MediaRecorder for audio processing"),this.mediaRecorder=new MediaRecorder(e,{mimeType:this.mimeType}),this.logger.debug("MediaRecorder created, state:",this.mediaRecorder.state),this.mediaRecorder.ondataavailable=e=>{this.logger.debug("ondataavailable called, size:",e.data.size),e.data.size>0&&e.data.arrayBuffer().then(e=>{this.onAudioData(e)})}}start(){this.mediaRecorder&&"inactive"===this.mediaRecorder.state&&(this.mediaRecorder.start(this.timeslice),this.logger.debug(`MediaRecorder started with ${this.timeslice}ms timeslice`))}stop(){this.mediaRecorder&&"inactive"!==this.mediaRecorder.state&&(this.mediaRecorder.stop(),this.logger.debug("MediaRecorder stopped"))}}const wn="audio-data",bn="error";class _n extends u{mediaStream=null;audioContext=null;workletNode=null;mediaRecorder=null;recording=!1;config;useMediaRecorder=!1;mediaRecorderFallback=null;audioBuffer=[];bufferingMode=!1;MIME_TYPE="audio/webm;codecs=opus";constructor(e={}){super(new o({category:"🎤 AudioRecorder",style:a})),this.config={sampleRate:41e3,channels:1,bitDepth:16,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,timeslice:100,...e}}async initialize(e){try{this.logger.debug("Initializing..."),await this.setupAudioContext(),await this.loadAudioWorklet(),this.mediaStream=e,this.useMediaRecorder&&(this.mediaRecorderFallback=new yn(this.MIME_TYPE,e=>this.handleAudioData(e),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream)),this.logger.debug("Initialized successfully")}catch(e){throw this.logger.error("Failed to initialize",e),e}}async start(){if(this.recording)this.logger.warn("Recording already in progress");else{if(this.audioContext&&"suspended"===this.audioContext.state)try{await this.audioContext.resume(),this.logger.debug("AudioContext resumed successfully at start of recording.")}catch(e){this.logger.error("Failed to resume AudioContext:",e);const t=new Error("The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developer.chrome.com/blog/autoplay/#web_audio");throw await this.emit(bn,t),t}this.audioContext||(await this.setupAudioContext(),await this.loadAudioWorklet());try{if(this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext before starting recording..."),await this.audioContext.resume()),!this.mediaStream)throw new Error("AudioRecorder: mediaStream must be set via initialize(stream) before starting recording.");this.logger.debug("setupMediaStream complete"),await this.setupAudioProcessing(),this.logger.debug("setupAudioProcessing complete"),this.recording=!0,await this.emit("recording-started"),this.logger.debug("Audio recording started")}catch(e){throw this.logger.error("Failed to start recording",e),await this.emit(bn,e),e}}}async stop(){if(this.logger.debug("Stopping recording..."),this.recording)try{await this.cleanup(),this.recording=!1,await this.emit("recording-stopped"),this.logger.debug("Audio recording stopped")}catch(e){throw this.logger.error("Failed to stop recording",e),await this.emit(bn,e),e}else this.logger.warn("No recording in progress")}isRecording(){return this.recording}enableBufferingMode(){this.logger.debug("Buffering mode enabled"),this.bufferingMode=!0,this.audioBuffer=[]}disableBufferingMode(){this.logger.debug("Buffering mode disabled"),this.bufferingMode=!1}getBufferedAudio(){return[...this.audioBuffer]}clearBuffer(){const e=this.audioBuffer.length;this.logger.debug(`Audio buffer cleared (Was ${e})`),this.audioBuffer=[]}async resumeAudioContext(){this.audioContext&&"suspended"===this.audioContext.state&&(this.logger.debug("Resuming AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, state:",this.audioContext.state))}async setupMediaRecorder(){this.logger.debug("Setting up MediaRecorder fallback..."),this.useMediaRecorder=!0}async setupAudioContext(){this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=new AudioContext({sampleRate:this.config.sampleRate,latencyHint:"interactive"}),this.logger.debug("AudioContext created, state:",this.audioContext.state)),"suspended"===this.audioContext.state&&(this.logger.debug("Resuming suspended AudioContext..."),await this.audioContext.resume(),this.logger.debug("AudioContext resumed, new state:",this.audioContext.state))}async loadAudioWorklet(){if(!this.audioContext)throw new Error("AudioContext not initialized");return this.setupMediaRecorder()}async setupAudioProcessing(){if(this.logger.debug("setupAudioProcessing called, useMediaRecorder:",this.useMediaRecorder),!this.audioContext||!this.mediaStream)throw new Error("AudioContext or MediaStream not initialized");if(this.useMediaRecorder)this.logger.debug("Using MediaRecorder fallback branch"),this.mediaRecorderFallback&&(this.logger.debug("Stopping existing MediaRecorderFallback before creating new one"),this.mediaRecorderFallback.stop()),this.mediaRecorderFallback=new yn(this.MIME_TYPE,e=>this.handleAudioData(e),this.config.timeslice),this.mediaRecorderFallback.initialize(this.mediaStream),this.mediaRecorderFallback.start();else{this.logger.debug("Using AudioWorklet for audio processing");const e=this.audioContext.createMediaStreamSource(this.mediaStream);this.workletNode=new AudioWorkletNode(this.audioContext,"audio-recording-processor",{processorOptions:{sampleRate:this.config.sampleRate,channels:this.config.channels,bitDepth:this.config.bitDepth}}),e.connect(this.workletNode),this.workletNode.port.onmessage=e=>{const{type:t,data:n}=e.data;t===wn&&this.handleAudioData(n)}}}async handleAudioData(e){let t=new Uint8Array(e),n=t.findIndex(e=>0!==e);if(-1===n)return void this.logger.warn("Skipping all-zero audio packet");n>0&&(this.logger.debug(`Trimming ${n} leading zero bytes from audio packet`),t=t.slice(n),e=t.buffer);const i=Array.from(t.slice(0,8));this.logger.debug(`Audio chunk: size=${e.byteLength}, first bytes=${i.join(",")}`),this.bufferingMode?(this.logger.debug(`Buffered audio chunk, buffer size: ${this.audioBuffer.length+1}`),this.audioBuffer.push(e)):await this.emit(wn,e)}async cleanup(){this.workletNode&&(this.workletNode.disconnect(),this.workletNode=null),this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder=null),this.mediaRecorderFallback&&(this.mediaRecorderFallback.stop(),this.mediaRecorderFallback=null),this.audioBuffer=[],this.bufferingMode=!1,this.logger.debug("Audio buffer cleared during cleanup")}async preInitialize(){try{await this.setupAudioContext(),await this.loadAudioWorklet(),this.logger.debug("Pre-initialization complete")}catch(e){this.logger.error("Pre-initialization failed",e)}}isInitialized(){return null!==this.mediaStream}dispose(){try{this.logger.debug("Disposing AudioRecorder..."),this.recording&&this.stop(),this.cleanup(),this.audioContext&&"closed"!==this.audioContext.state&&(this.audioContext.close().catch(e=>{this.logger.debug("Error closing AudioContext:",e)}),this.audioContext=null),this.mediaStream=null,this.removeAllListeners(),this.logger.debug("AudioRecorder disposed")}catch(e){this.logger.warn("Error while disposing AudioRecorder",e)}}}class $n extends u{capabilities;vadManager;network;recordingConfig;audioRecorder=null;isStopped=!0;mediaStream=null;isInputCompleteSent=!1;debugMode=!1;capturedAudioChunks=[];constructor(e,t,n,i){super(new o({category:"🎩 UserInputManager",style:"color: #2196f3; font-weight: bold; font-size: larger"})),this.capabilities=e,this.vadManager=t,this.network=n,this.recordingConfig=i,this.setupListeners(),this.capabilities.audio&&(this.audioRecorder=new _n(i),this.setupRecorderListeners())}async initialize(e){await this.reinitializeAudio(e)}async reinitializeAudio(e){if(this.capabilities.audio){if(e&&(this.mediaStream=e),!this.mediaStream){const e={echoCancellation:this.recordingConfig?.echoCancellation,noiseSuppression:this.recordingConfig?.noiseSuppression,autoGainControl:this.recordingConfig?.autoGainControl,sampleRate:this.recordingConfig?.sampleRate,channelCount:this.recordingConfig?.channels};Object.keys(e).forEach(t=>void 0===e[t]&&delete e[t]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:e})}await this.vadManager.initialize(this.mediaStream),await(this.audioRecorder?.initialize(this.mediaStream))}}async start(e=!1){if(this.isStopped){this.isStopped=!1;try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(e){this.logger.error("Failed to clear server audio buffer",e)}this.debugMode&&(this.capturedAudioChunks=[],this.logger.debug("Cleared captured audio chunks for new interaction")),this.capabilities.audio&&(e?this.logger.debug("Skipping VAD startup to reduce CPU contention during playback"):this.vadManager.startAnalysis(),await this.startRecording())}}startVAD(){this.capabilities.audio&&!this.isStopped&&(this.logger.debug("Starting VAD analysis"),this.vadManager.startAnalysis())}async stop(){return!this.isStopped&&(this.logger.debug("Stopping User Input..."),this.isStopped=!0,this.capabilities.audio&&(this.vadManager.stopAnalysis(),await this.stopRecording()),!0)}async updateCapabilities(e){this.capabilities=e,this.logger.debug("Input capabilities updated",this.capabilities),this.capabilities.audio&&!this.audioRecorder?(this.audioRecorder=new _n(this.recordingConfig),this.setupRecorderListeners(),await this.reinitializeAudio()):!this.capabilities.audio&&this.audioRecorder&&(this.vadManager.stopAnalysis(),await this.audioRecorder.stop(),this.audioRecorder=null,this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null))}async stopRecording(){this.capabilities.audio&&this.audioRecorder?.isRecording()&&await this.audioRecorder.stop()}async startRecording(){this.capabilities.audio&&this.audioRecorder?(this.audioRecorder.isInitialized()||(this.logger.warn("AudioRecorder not initialized, reinitializing..."),await this.reinitializeAudio()),await this.audioRecorder.start()):this.logger.info("Will not start recording, audio capabilities are not enabled or audio recorder is not initialized")}isRecording(){return this.capabilities.audio&&(this.audioRecorder?.isRecording()||!1)}enableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.enableBufferingMode()}disableAudioBuffering(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.disableBufferingMode()}getBufferedAudio(){return this.audioRecorder?.getBufferedAudio()||[]}clearAudioBuffer(){this.capabilities.audio&&this.audioRecorder&&this.audioRecorder.clearBuffer()}async flushBufferedAudio(){this.disableAudioBuffering();const e=this.getBufferedAudio();if(this.clearAudioBuffer(),e.length>0){this.logger.debug(`Flushing ${e.length} buffered audio chunks`);for(const t of e)await this.sendAudio(t)}}async sendAudio(e){if(this.isStopped)return;this.logger.debug("sendAudio called, size:",e.byteLength),this.debugMode&&(this.capturedAudioChunks.push(e),this.logger.debug(`Captured audio chunk for debug (${this.capturedAudioChunks.length} total chunks)`));const t=this.arrayBufferToBase64(e);await this.network.addAudio(t)}arrayBufferToBase64(e){let t="";const n=new Uint8Array(e),i=n.byteLength;for(let e=0;e<i;e++)t+=String.fromCharCode(n[e]);return btoa(t)}async interact(e){await this.network.interact(e)}async sendInputComplete(){this.isStopped||this.isInputCompleteSent||(this.isInputCompleteSent=!0,await this.emit(H,{type:"input_complete"}))}reset(){this.isInputCompleteSent=!1,this.debugMode&&this.capturedAudioChunks.length>0&&(this.logger.debug(`Clearing ${this.capturedAudioChunks.length} captured audio chunks on reset`),this.capturedAudioChunks=[])}dispose(){try{this.logger.debug("Disposing UserInputManager..."),this.isStopped=!0,this.vadManager&&(this.vadManager.stopAnalysis(),"function"==typeof this.vadManager.dispose&&this.vadManager.dispose()),this.capabilities.audio&&this.audioRecorder?.isRecording()&&this.audioRecorder.stop(),this.audioRecorder&&"function"==typeof this.audioRecorder.dispose&&this.audioRecorder.dispose(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop(),this.logger.debug(`Stopped media track: ${e.kind}`)}),this.mediaStream=null),this.removeAllListeners(),this.logger.debug("UserInputManager disposed")}catch(e){this.logger.warn("Error while disposing UserInputManager",e)}}setupListeners(){this.capabilities.audio&&(this.vadManager.on("voiceActivity",async e=>{e&&!this.isStopped&&(e.isSpeaking?await this.emit(F):await this.emit(q))}),this.vadManager.on("silence",async()=>{await this.sendInputComplete(),await this.network.checkTurn()}))}setupRecorderListeners(){this.audioRecorder&&this.audioRecorder.on(wn,e=>{this.sendAudio(e).catch(e=>{this.logger.error("Failed to send audio chunk",e)})})}async resumeAudioContext(){this.capabilities.audio&&this.audioRecorder&&await this.audioRecorder.resumeAudioContext()}enableDebugMode(){this.debugMode=!0,this.capturedAudioChunks=[],this.logger.info("Debug mode enabled - audio chunks will be captured")}disableDebugMode(){this.debugMode=!1,this.logger.info("Debug mode disabled")}clearCapturedAudio(){this.capturedAudioChunks=[],this.logger.info("Captured audio chunks cleared")}downloadCapturedAudio(e="captured-audio.webm"){if(0===this.capturedAudioChunks.length)return void this.logger.warn("No audio chunks captured to download");this.logger.info(`Downloading ${this.capturedAudioChunks.length} captured audio chunks as ${e}`);const t=new Blob(this.capturedAudioChunks,{type:"audio/webm;codecs=opus"}),n=URL.createObjectURL(t),i=document.createElement("a");i.href=n,i.download=e,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(n),this.logger.info("Download completed")}getCapturedAudioInfo(){const e=this.capturedAudioChunks.reduce((e,t)=>e+t.byteLength,0);return{chunkCount:this.capturedAudioChunks.length,totalSize:e}}}class vn{static DEFAULT_START_COMMAND="[start conversation]";static DEFAULT_PAUSE_RESUME_COMMAND="[resume after short pause]";static DEFAULT_LONG_PAUSE_RESUME_COMMAND="[resume after long break]";static DEFAULT_ERROR_RESUME_COMMAND="[resume after error]";startCommand=vn.DEFAULT_START_COMMAND;pauseResumeCommand=vn.DEFAULT_PAUSE_RESUME_COMMAND;longPauseResumeCommand=vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND;errorResumeCommand=vn.DEFAULT_ERROR_RESUME_COMMAND;set(e,t,n,i){this.startCommand=e??vn.DEFAULT_START_COMMAND,this.pauseResumeCommand=t??vn.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=n??vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=i??vn.DEFAULT_ERROR_RESUME_COMMAND}setDefault(){this.startCommand=vn.DEFAULT_START_COMMAND,this.pauseResumeCommand=vn.DEFAULT_PAUSE_RESUME_COMMAND,this.longPauseResumeCommand=vn.DEFAULT_LONG_PAUSE_RESUME_COMMAND,this.errorResumeCommand=vn.DEFAULT_ERROR_RESUME_COMMAND}}class xn{deps;static DEFAULT_MAX_RETRY_COUNT=3;currentRetryCount=0;isRetrying=!1;maxRetryCount;constructor(e){this.deps=e,this.maxRetryCount=e.maxRetryCount??xn.DEFAULT_MAX_RETRY_COUNT}async attemptRecovery(e){if(this.deps.logger.info("Attempting silent recovery for error type: "+e),!["network_timeout","network_error","server_error"].includes(e))return!1;if(!this.deps.isConnected())return this.deps.logger.info("Network is not connected, skipping retry"),!1;if(this.currentRetryCount>=this.maxRetryCount)return!1;if(this.isRetrying)return!1;this.currentRetryCount++,this.isRetrying=!0,this.deps.logger.info(`Attempting silent retry ${this.currentRetryCount}/${this.maxRetryCount} with error resume command`);try{return await this.deps.sendText(this.deps.conversationCommands.errorResumeCommand),this.isRetrying=!1,!0}catch(t){return this.deps.logger.error(`Retry attempt ${this.currentRetryCount} failed`,t),this.isRetrying=!1,this.currentRetryCount<this.maxRetryCount&&await this.attemptRecovery(e)}}resetRetryCount(){this.currentRetryCount=0,this.isRetrying=!1}getCurrentRetryCount(){return this.currentRetryCount}}const Sn={StateChange:"stateChange"};class Tn extends u{state="idle";network;vadManager;userInputManager;playbackManager;config;interactionCompletePending=!1;mediaStream=null;isTextOnly=!1;isDisposed=!1;isTransitioning=!1;pausedFromState=null;errorRetryHandler;isSimulateErrorsDebugMode=!1;conversationCommands=new vn;constructor(e){const t=new o({category:"🧞 ConversationManager",style:s});super(t),this.setConfiguration(e);const n={...e,...e.apiKey&&{apiKey:e.apiKey.slice(0,4)+"..."},...e.federatedId&&{federatedId:e.federatedId.slice(0,4)+"..."}};t.info("Initializing with config",n),this.network=new gn(this.config),this.vadManager=new N,this.userInputManager=new $n(this.config.inputCapabilities,this.vadManager,this.network,e.recordingConfig),this.playbackManager=new D(this.config.capabilities),this.playbackManager.wireVADToAvatar(this),this.playbackManager.wireConversationStateToAvatar(this),this.setupEventListeners(),this.errorRetryHandler=new xn({logger:this.logger,conversationCommands:this.conversationCommands,sendText:e=>this.sendText(e),isConnected:()=>this.isConnected(),maxRetryCount:3}),this.setState("uninitialized")}async setConfiguration(e){if(console.log("[SDK] setConfiguration called with languageCode:",e.languageCode),this.config={...e,capabilities:e.capabilities||{audio:!0,viseme:!0,subtitles:!0,avatar:!0},inputCapabilities:e.inputCapabilities||{audio:!0,text:!0},hooks:{...this.config?.hooks||{},...e.hooks},onInputUtilities:e.onInputUtilities??this.config?.onInputUtilities,onInputNonBlockingUtilities:e.onInputNonBlockingUtilities??this.config?.onInputNonBlockingUtilities,onOutputUtilities:e.onOutputUtilities??this.config?.onOutputUtilities},this.network&&(this.network.updateConfig(this.config),this.network.isReady())){this.logger.debug("Updating remote configuration");try{await this.network.updateRemoteConfiguration(this.config),this.logger.debug("Remote configuration updated successfully")}catch(e){this.logger.error("Failed to update remote configuration",e)}}}async initialize(){try{if(this.logger.debug("Initializing..."),this.setState("initializing"),await this.network.initialize(),await this.playbackManager.initialize(),this.config.inputCapabilities?.audio&&!this.mediaStream){const e=this.config.recordingConfig,t={echoCancellation:e?.echoCancellation,noiseSuppression:e?.noiseSuppression,autoGainControl:e?.autoGainControl,sampleRate:e?.sampleRate,channelCount:e?.channels};Object.keys(t).forEach(e=>void 0===t[e]&&delete t[e]),this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:t})}await this.userInputManager.initialize(this.mediaStream??void 0),await this.network.connect(),this.logger.debug("Initialized successfully"),this.setState("waiting")}catch(e){this.handleError("server_error",e)}}async startListening(){if("idle"!==this.state)throw new Error(`Cannot start listening from state: ${this.state}`);try{await this.userInputManager.start(),this.setState("listening")}catch(e){this.handleError("mic_denied",e)}}async stopListening(){this.logger.debug("stopListening called from state:",this.state),await this.userInputManager.stop()||this.setState("waiting")}async sendText(e){return console.log("[SDK] sendText called with languageCode:",this.config.languageCode),this.interact({text:e,kind:"interact",type:"stream",uid:"",language_code:this.config.languageCode})}async generateImage(e){return this.network.generateImage(e)}async generateImageWithBria(e){return this.network.generateImageWithBria(e)}async generateImageWithReplicate(e){return this.network.generateImageWithReplicate(e)}async getAvailableModels(){return this.network.getAvailableModels()}async interact(e){if(!this.network.isReady()){const e="Network is not ready, cannot send text. probably disconnected";return this.logger.error(e),void await this.handleError("network_timeout",new Error(e))}if("idle"===this.state||"listening"===this.state||"processing_complete"===this.state||"error"===this.state)try{if(this.playbackManager.reset(),this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.setState("waiting"),await this.userInputManager.interact(e)}catch(e){this.logger.error("Error sending text message",e),await this.handleError("network_timeout",e)}}async interrupt(){this.playbackManager.pause(),await this.setState("interrupted")}async pause(){if(this.isTransitioning)this.logger.debug("Pause ignored: transition already in progress");else if("playing"===this.state||"processing_complete"===this.state||"listening"===this.state||"userSpeaking"===this.state){this.isTransitioning=!0;try{if(this.pausedFromState=this.state,"listening"===this.state||"userSpeaking"===this.state){this.logger.debug("Pausing from listening/speaking state, stopping input and clearing audio"),await this.userInputManager.stop(),this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio()}catch(e){this.logger.warn("Failed to clear server audio buffer on pause",e)}}else this.playbackManager.pause();await this.setState("paused")}finally{this.isTransitioning=!1}}else this.logger.warn(`Cannot pause from state: ${this.state}`)}async resume(){if(this.isTransitioning)this.logger.debug("Resume ignored: transition already in progress");else if("paused"===this.state||"processing_complete"===this.state){this.isTransitioning=!0;try{const e=this.playbackManager.getRemainingAudioSeconds()>0,t="listening"===this.pausedFromState||"userSpeaking"===this.pausedFromState;if(e){this.logger.debug("Resuming playback with buffered audio");try{await this.playbackManager.resume(),await this.setState("playing")}catch(e){this.logger.error("Failed to resume playback, falling back to listening",e),await this.userInputManager.start(),await this.setState("listening")}}else if(t){this.logger.debug("Resuming from listening pause, restarting recording");try{await this.userInputManager.start(),await this.setState("listening")}catch(e){this.logger.error("Failed to restart recording after pause",e),await this.handleError("mic_denied",e)}}else this.logger.debug("No buffered audio to resume, going to listening state"),this.interactionCompletePending?(this.interactionCompletePending=!1,await this.handleInteractionComplete()):await this.setState("listening")}finally{this.pausedFromState=null,this.isTransitioning=!1}}else this.logger.warn(`Cannot resume from state: ${this.state}`)}async forceInputComplete(){"userSpeaking"===this.state||"listening"===this.state?await this.userInputManager.sendInputComplete():this.logger.warn(`Cannot force input complete from state: ${this.state}`)}async stop(){await this.userInputManager.stop(),this.playbackManager.pause(),await this.network.disconnect(),await this.setState("idle")}async dispose(){if(this.isDisposed)this.logger.warn("ConversationManager already disposed");else{this.logger.debug("Disposing ConversationManager..."),this.isDisposed=!0,this.userInputManager?.removeAllListeners(),this.playbackManager?.removeAllListeners(),this.network?.removeAllListeners(),this.state="idle";try{this.userInputManager&&"function"==typeof this.userInputManager.dispose?this.userInputManager.dispose():(await this.userInputManager.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>{e.stop(),this.logger.debug(`Stopped media track: ${e.kind}`)}),this.mediaStream=null)),this.playbackManager&&"function"==typeof this.playbackManager.dispose&&this.playbackManager.dispose(),await this.network.disconnect(),this.removeAllListeners(),this.logger.debug("ConversationManager disposed successfully")}catch(e){this.logger.warn("Error while disposing ConversationManager",e)}}}async setState(e){if(this.isDisposed)return;if(this.state===e)return;const t=this.state;this.state=e,this.config.hooks.onStateChange?.(e),await this.emit(Sn.StateChange,{oldState:t,newState:e}),this.logger.debug(`State transition: ${t} -> ${e}`)}setupEventListeners(){this.userInputManager.on(H,async e=>{await this.network.send(e),"input_complete"===e.type&&await this.setState("waiting")}),this.playbackManager.on(M,e=>{this.config.hooks.onSubtitleHighlight?.(e)}),this.playbackManager.on(z,e=>{this.config.hooks.onSubtitleChange?.(e)}),this.playbackManager.on(O,e=>{this.config.hooks.onImageChange?.(e)}),this.playbackManager.on(B,e=>{this.config.hooks.onAvatarAnimationChanged?.(e)}),this.userInputManager.on(F,async()=>{await this.setState("userSpeaking")}),this.userInputManager.on(q,async()=>{await this.setState("listening")}),this.network.on(c,async()=>{this.config.hooks.onNetworkStatusChange?.(!0)}),this.network.on(h,async()=>{this.config.hooks.onNetworkStatusChange?.(!1)}),this.network.on(l,async e=>{if("interact"===e.kind&&"text"===e.event&&this.config.hooks.onTextMessage?.(e),"data"===e.event&&this.config.hooks.onDataMessage?.(e),"interact"===e.kind&&"safety_policy"===e.event&&this.config.hooks.onSafetyEvent?.(e),"check_turn"===e.kind&&!1===e.is_user_still_speaking){if(this.logger.debug(`check_turn handler: state is ${this.state}`),"playing"===this.state||"paused"===this.state)return void this.logger.debug("check_turn received while playing / paused, ignoring.");await this.stopListening();try{if(this.isSimulateErrorsDebugMode&&Math.random()<.5)throw this.logger.error("DebugMode:Simulating server error"),new Error("server_error");await this.network.interactAudio({uid:"",kind:"interact",type:"stream",on_input_non_blocking:this.config.onInputNonBlockingUtilities,on_input:this.config.onInputUtilities,on_output:this.config.onOutputUtilities,language_code:this.config.languageCode})}catch(e){this.userInputManager.clearAudioBuffer();try{await this.network.clearAudio(),this.logger.debug("Server audio buffer cleared for new session")}catch(e){this.logger.error("Failed to clear server audio buffer",e)}this.logger.error("Error in interactAudio",e),await this.handleError("network_timeout",e)}}"interact"===e.kind&&"interaction_complete"===e.event&&(this.errorRetryHandler.resetRetryCount(),"playing"===this.state||"paused"===this.state?(this.logger.debug("Interaction complete received while playing / paused, deferring."),this.interactionCompletePending=!0,await this.setState("processing_complete")):await this.handleInteractionComplete()),"interaction_error"===e.type&&this.handleError("server_error",new Error(e.error||"Unknown server interaction error")),"string"===e.type&&this.config.hooks.onStringMessage?.(e),this.playbackManager.handleMessage(e)}),this.network.on(d,async e=>{this.handleError("network_error",e)}),this.playbackManager.on(R,async e=>{this.handleError("decode_error",e)}),this.playbackManager.on(A,async()=>{await this.setState("playing")}),this.playbackManager.on(P,async()=>{if(this.interactionCompletePending)this.logger.debug("Playback finished, processing deferred interaction complete."),this.interactionCompletePending=!1,await this.handleInteractionComplete();else if("playing"===this.state){this.logger.debug("Playback finished, starting recording now (no overlap)"),this.userInputManager.reset();try{await this.userInputManager.start(),await this.setState("listening"),this.logger.debug("Recording started successfully after playback")}catch(e){this.logger.error("Failed to start recording after playback",e),await this.setState("idle")}}})}async handleError(e,t){await this.setState("error"),this.logger.error("handleError called with type: "+e+" and error: "+t.message);let n=!1;try{n=await this.errorRetryHandler.attemptRecovery(e)}catch(e){this.logger.error("Error during recovery attempt",e),n=!1}if(n)return void this.logger.debug("Error recovery succeeded, not raising error");const i={type:e,message:t.message,originalError:t};this.config.hooks.onError?.(i),this.logger.error(`Conversation error: ${e}`,t)}async handleInteractionComplete(){this.logger.debug("Interaction complete received"),this.playbackManager.resetAboutToComplete();try{if(this.userInputManager.reset(),this.userInputManager.isRecording())await this.setState("listening");else{this.logger.debug("Starting recording after interaction complete");try{await this.userInputManager.start(),await this.setState("listening")}catch(e){this.logger.error("Failed to start recording",e),await this.setState("idle")}}}catch(e){this.logger.error("Failed to handle interaction complete",e),await this.handleError("network_timeout",e)}}async toggleTextOnlyInput(e){this.isTextOnly=e,await this.updateInputCapabilities()}isConnected(){return this.network.isReady()}enableAudioDebugMode(){this.userInputManager.enableDebugMode(),this.logger.info("Audio debug mode enabled")}disableAudioDebugMode(){this.userInputManager.disableDebugMode(),this.logger.info("Audio debug mode disabled")}downloadCapturedAudio(e){this.userInputManager.downloadCapturedAudio(e)}clearCapturedAudio(){this.userInputManager.clearCapturedAudio()}getCapturedAudioInfo(){return this.userInputManager.getCapturedAudioInfo()}async updateInputCapabilities(){this.logger.debug(`Updating input capabilities, textOnly: ${this.isTextOnly}`),this.config.inputCapabilities={...this.config.inputCapabilities,audio:!this.isTextOnly,text:this.isTextOnly},await this.userInputManager.updateCapabilities(this.config.inputCapabilities),this.isTextOnly?await this.userInputManager.stopRecording():"idle"===this.state&&await this.startListening()}}export{S as AudioPlayer,vn as ConversationCommands,Tn as ConversationManager};
|