diff --git "a/assets/index-DrJn1j_q.js" "b/assets/index-DrJn1j_q.js" new file mode 100644--- /dev/null +++ "b/assets/index-DrJn1j_q.js" @@ -0,0 +1,6837 @@ +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function t(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(s){if(s.ep)return;s.ep=!0;const o=t(s);fetch(s.href,o)}})();function C1(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var x0={exports:{}},Mm={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Lb;function UP(){if(Lb)return Mm;Lb=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function t(i,s,o){var l=null;if(o!==void 0&&(l=""+o),s.key!==void 0&&(l=""+s.key),"key"in s){o={};for(var u in s)u!=="key"&&(o[u]=s[u])}else o=s;return s=o.ref,{$$typeof:n,type:i,key:l,ref:s!==void 0?s:null,props:o}}return Mm.Fragment=e,Mm.jsx=t,Mm.jsxs=t,Mm}var Fb;function BP(){return Fb||(Fb=1,x0.exports=UP()),x0.exports}var Un=BP(),w0={exports:{}},Dn={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var kb;function $P(){if(kb)return Dn;kb=1;var n=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),t=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),o=Symbol.for("react.consumer"),l=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.iterator;function _(W){return W===null||typeof W!="object"?null:(W=h&&W[h]||W["@@iterator"],typeof W=="function"?W:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function T(W,q,G){this.props=W,this.context=q,this.refs=b,this.updater=G||g}T.prototype.isReactComponent={},T.prototype.setState=function(W,q){if(typeof W!="object"&&typeof W!="function"&&W!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,W,q,"setState")},T.prototype.forceUpdate=function(W){this.updater.enqueueForceUpdate(this,W,"forceUpdate")};function v(){}v.prototype=T.prototype;function x(W,q,G){this.props=W,this.context=q,this.refs=b,this.updater=G||g}var P=x.prototype=new v;P.constructor=x,y(P,T.prototype),P.isPureReactComponent=!0;var w=Array.isArray,C={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function A(W,q,G,te,B,le){return G=le.ref,{$$typeof:n,type:W,key:q,ref:G!==void 0?G:null,props:le}}function L(W,q){return A(W.type,q,void 0,void 0,void 0,W.props)}function I(W){return typeof W=="object"&&W!==null&&W.$$typeof===n}function O(W){var q={"=":"=0",":":"=2"};return"$"+W.replace(/[=:]/g,function(G){return q[G]})}var H=/\/+/g;function Z(W,q){return typeof W=="object"&&W!==null&&W.key!=null?O(""+W.key):q.toString(36)}function $(){}function J(W){switch(W.status){case"fulfilled":return W.value;case"rejected":throw W.reason;default:switch(typeof W.status=="string"?W.then($,$):(W.status="pending",W.then(function(q){W.status==="pending"&&(W.status="fulfilled",W.value=q)},function(q){W.status==="pending"&&(W.status="rejected",W.reason=q)})),W.status){case"fulfilled":return W.value;case"rejected":throw W.reason}}throw W}function ee(W,q,G,te,B){var le=typeof W;(le==="undefined"||le==="boolean")&&(W=null);var ye=!1;if(W===null)ye=!0;else switch(le){case"bigint":case"string":case"number":ye=!0;break;case"object":switch(W.$$typeof){case n:case e:ye=!0;break;case m:return ye=W._init,ee(ye(W._payload),q,G,te,B)}}if(ye)return B=B(W),ye=te===""?"."+Z(W,0):te,w(B)?(G="",ye!=null&&(G=ye.replace(H,"$&/")+"/"),ee(B,q,G,"",function(ze){return ze})):B!=null&&(I(B)&&(B=L(B,G+(B.key==null||W&&W.key===B.key?"":(""+B.key).replace(H,"$&/")+"/")+ye)),q.push(B)),1;ye=0;var me=te===""?".":te+":";if(w(W))for(var xe=0;xe>>1,W=X[oe];if(0>>1;oes(te,Q))Bs(le,te)?(X[oe]=le,X[B]=Q,oe=B):(X[oe]=te,X[G]=Q,oe=G);else if(Bs(le,Q))X[oe]=le,X[B]=Q,oe=B;else break e}}return ne}function s(X,ne){var Q=X.sortIndex-ne.sortIndex;return Q!==0?Q:X.id-ne.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var o=performance;n.unstable_now=function(){return o.now()}}else{var l=Date,u=l.now();n.unstable_now=function(){return l.now()-u}}var d=[],f=[],m=1,h=null,_=3,g=!1,y=!1,b=!1,T=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;function P(X){for(var ne=t(f);ne!==null;){if(ne.callback===null)i(f);else if(ne.startTime<=X)i(f),ne.sortIndex=ne.expirationTime,e(d,ne);else break;ne=t(f)}}function w(X){if(b=!1,P(X),!y)if(t(d)!==null)y=!0,J();else{var ne=t(f);ne!==null&&ee(w,ne.startTime-X)}}var C=!1,E=-1,A=5,L=-1;function I(){return!(n.unstable_now()-LX&&I());){var oe=h.callback;if(typeof oe=="function"){h.callback=null,_=h.priorityLevel;var W=oe(h.expirationTime<=X);if(X=n.unstable_now(),typeof W=="function"){h.callback=W,P(X),ne=!0;break t}h===t(d)&&i(d),P(X)}else i(d);h=t(d)}if(h!==null)ne=!0;else{var q=t(f);q!==null&&ee(w,q.startTime-X),ne=!1}}break e}finally{h=null,_=Q,g=!1}ne=void 0}}finally{ne?H():C=!1}}}var H;if(typeof x=="function")H=function(){x(O)};else if(typeof MessageChannel<"u"){var Z=new MessageChannel,$=Z.port2;Z.port1.onmessage=O,H=function(){$.postMessage(null)}}else H=function(){T(O,0)};function J(){C||(C=!0,H())}function ee(X,ne){E=T(function(){X(n.unstable_now())},ne)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(X){X.callback=null},n.unstable_continueExecution=function(){y||g||(y=!0,J())},n.unstable_forceFrameRate=function(X){0>X||125oe?(X.sortIndex=Q,e(f,X),t(d)===null&&X===t(f)&&(b?(v(E),E=-1):b=!0,ee(w,Q-oe))):(X.sortIndex=W,e(d,X),y||g||(y=!0,J())),X},n.unstable_shouldYield=I,n.unstable_wrapCallback=function(X){var ne=_;return function(){var Q=_;_=ne;try{return X.apply(this,arguments)}finally{_=Q}}}}(S0)),S0}var Ub;function GP(){return Ub||(Ub=1,E0.exports=VP()),E0.exports}var A0={exports:{}},Hr={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Bb;function jP(){if(Bb)return Hr;Bb=1;var n=yM();function e(d){var f="https://react.dev/errors/"+d;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),A0.exports=jP(),A0.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Vb;function WP(){if(Vb)return bm;Vb=1;var n=GP(),e=yM(),t=P1();function i(r){var a="https://react.dev/errors/"+r;if(1)":-1M||be[p]!==Le[M]){var dt=` +`+be[p].replace(" at new "," at ");return r.displayName&&dt.includes("")&&(dt=dt.replace("",r.displayName)),dt}while(1<=p&&0<=M);break}}}finally{J=!1,Error.prepareStackTrace=c}return(c=r?r.displayName||r.name:"")?$(c):""}function X(r){switch(r.tag){case 26:case 27:case 5:return $(r.type);case 16:return $("Lazy");case 13:return $("Suspense");case 19:return $("SuspenseList");case 0:case 15:return r=ee(r.type,!1),r;case 11:return r=ee(r.type.render,!1),r;case 1:return r=ee(r.type,!0),r;default:return""}}function ne(r){try{var a="";do a+=X(r),r=r.return;while(r);return a}catch(c){return` +Error generating stack: `+c.message+` +`+c.stack}}function Q(r){var a=r,c=r;if(r.alternate)for(;a.return;)a=a.return;else{r=a;do a=r,a.flags&4098&&(c=a.return),r=a.return;while(r)}return a.tag===3?c:null}function oe(r){if(r.tag===13){var a=r.memoizedState;if(a===null&&(r=r.alternate,r!==null&&(a=r.memoizedState)),a!==null)return a.dehydrated}return null}function W(r){if(Q(r)!==r)throw Error(i(188))}function q(r){var a=r.alternate;if(!a){if(a=Q(r),a===null)throw Error(i(188));return a!==r?null:r}for(var c=r,p=a;;){var M=c.return;if(M===null)break;var R=M.alternate;if(R===null){if(p=M.return,p!==null){c=p;continue}break}if(M.child===R.child){for(R=M.child;R;){if(R===c)return W(M),r;if(R===p)return W(M),a;R=R.sibling}throw Error(i(188))}if(c.return!==p.return)c=M,p=R;else{for(var K=!1,de=M.child;de;){if(de===c){K=!0,c=M,p=R;break}if(de===p){K=!0,p=M,c=R;break}de=de.sibling}if(!K){for(de=R.child;de;){if(de===c){K=!0,c=R,p=M;break}if(de===p){K=!0,p=R,c=M;break}de=de.sibling}if(!K)throw Error(i(189))}}if(c.alternate!==p)throw Error(i(190))}if(c.tag!==3)throw Error(i(188));return c.stateNode.current===c?r:a}function G(r){var a=r.tag;if(a===5||a===26||a===27||a===6)return r;for(r=r.child;r!==null;){if(a=G(r),a!==null)return a;r=r.sibling}return null}var te=Array.isArray,B=t.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,le={pending:!1,data:null,method:null,action:null},ye=[],me=-1;function xe(r){return{current:r}}function ze(r){0>me||(r.current=ye[me],ye[me]=null,me--)}function Me(r,a){me++,ye[me]=r.current,r.current=a}var ce=xe(null),ae=xe(null),we=xe(null),re=xe(null);function He(r,a){switch(Me(we,a),Me(ae,r),Me(ce,null),r=a.nodeType,r){case 9:case 11:a=(a=a.documentElement)&&(a=a.namespaceURI)?Eo(a):0;break;default:if(r=r===8?a.parentNode:a,a=r.tagName,r=r.namespaceURI)r=Eo(r),a=ps(r,a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}ze(ce),Me(ce,a)}function Ne(){ze(ce),ze(ae),ze(we)}function We(r){r.memoizedState!==null&&Me(re,r);var a=ce.current,c=ps(a,r.type);a!==c&&(Me(ae,r),Me(ce,c))}function ke(r){ae.current===r&&(ze(ce),ze(ae)),re.current===r&&(ze(re),mm._currentValue=le)}var st=Object.prototype.hasOwnProperty,Ke=n.unstable_scheduleCallback,F=n.unstable_cancelCallback,U=n.unstable_shouldYield,j=n.unstable_requestPaint,se=n.unstable_now,_e=n.unstable_getCurrentPriorityLevel,ge=n.unstable_ImmediatePriority,Ce=n.unstable_UserBlockingPriority,Ie=n.unstable_NormalPriority,Ee=n.unstable_LowPriority,je=n.unstable_IdlePriority,Qe=n.log,ot=n.unstable_setDisableYieldValue,bt=null,_t=null;function nt(r){if(_t&&typeof _t.onCommitFiberRoot=="function")try{_t.onCommitFiberRoot(bt,r,void 0,(r.current.flags&128)===128)}catch{}}function ft(r){if(typeof Qe=="function"&&ot(r),_t&&typeof _t.setStrictMode=="function")try{_t.setStrictMode(bt,r)}catch{}}var vt=Math.clz32?Math.clz32:St,mn=Math.log,Se=Math.LN2;function St(r){return r>>>=0,r===0?32:31-(mn(r)/Se|0)|0}var Ze=128,it=4194304;function yt(r){var a=r&42;if(a!==0)return a;switch(r&-r){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return r&4194176;case 4194304:case 8388608:case 16777216:case 33554432:return r&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return r}}function tt(r,a){var c=r.pendingLanes;if(c===0)return 0;var p=0,M=r.suspendedLanes,R=r.pingedLanes,K=r.warmLanes;r=r.finishedLanes!==0;var de=c&134217727;return de!==0?(c=de&~M,c!==0?p=yt(c):(R&=de,R!==0?p=yt(R):r||(K=de&~K,K!==0&&(p=yt(K))))):(de=c&~M,de!==0?p=yt(de):R!==0?p=yt(R):r||(K=c&~K,K!==0&&(p=yt(K)))),p===0?0:a!==0&&a!==p&&!(a&M)&&(M=p&-p,K=a&-a,M>=K||M===32&&(K&4194176)!==0)?a:p}function gt(r,a){return(r.pendingLanes&~(r.suspendedLanes&~r.pingedLanes)&a)===0}function Pt(r,a){switch(r){case 1:case 2:case 4:case 8:return a+250;case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function tn(){var r=Ze;return Ze<<=1,!(Ze&4194176)&&(Ze=128),r}function rn(){var r=it;return it<<=1,!(it&62914560)&&(it=4194304),r}function Pn(r){for(var a=[],c=0;31>c;c++)a.push(r);return a}function ln(r,a){r.pendingLanes|=a,a!==268435456&&(r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0)}function vi(r,a,c,p,M,R){var K=r.pendingLanes;r.pendingLanes=c,r.suspendedLanes=0,r.pingedLanes=0,r.warmLanes=0,r.expiredLanes&=c,r.entangledLanes&=c,r.errorRecoveryDisabledLanes&=c,r.shellSuspendCounter=0;var de=r.entanglements,be=r.expirationTimes,Le=r.hiddenUpdates;for(c=K&~c;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),qt=RegExp("^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"),sn={},Jt={};function yn(r){return st.call(Jt,r)?!0:st.call(sn,r)?!1:qt.test(r)?Jt[r]=!0:(sn[r]=!0,!1)}function Sn(r,a,c){if(yn(a))if(c===null)r.removeAttribute(a);else{switch(typeof c){case"undefined":case"function":case"symbol":r.removeAttribute(a);return;case"boolean":var p=a.toLowerCase().slice(0,5);if(p!=="data-"&&p!=="aria-"){r.removeAttribute(a);return}}r.setAttribute(a,""+c)}}function Jn(r,a,c){if(c===null)r.removeAttribute(a);else{switch(typeof c){case"undefined":case"function":case"symbol":case"boolean":r.removeAttribute(a);return}r.setAttribute(a,""+c)}}function Ln(r,a,c,p){if(p===null)r.removeAttribute(c);else{switch(typeof p){case"undefined":case"function":case"symbol":case"boolean":r.removeAttribute(c);return}r.setAttributeNS(a,c,""+p)}}function dn(r){switch(typeof r){case"bigint":case"boolean":case"number":case"string":case"undefined":return r;case"object":return r;default:return""}}function nn(r){var a=r.type;return(r=r.nodeName)&&r.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function li(r){var a=nn(r)?"checked":"value",c=Object.getOwnPropertyDescriptor(r.constructor.prototype,a),p=""+r[a];if(!r.hasOwnProperty(a)&&typeof c<"u"&&typeof c.get=="function"&&typeof c.set=="function"){var M=c.get,R=c.set;return Object.defineProperty(r,a,{configurable:!0,get:function(){return M.call(this)},set:function(K){p=""+K,R.call(this,K)}}),Object.defineProperty(r,a,{enumerable:c.enumerable}),{getValue:function(){return p},setValue:function(K){p=""+K},stopTracking:function(){r._valueTracker=null,delete r[a]}}}}function An(r){r._valueTracker||(r._valueTracker=li(r))}function sr(r){if(!r)return!1;var a=r._valueTracker;if(!a)return!0;var c=a.getValue(),p="";return r&&(p=nn(r)?r.checked?"true":"false":r.value),r=p,r!==c?(a.setValue(r),!0):!1}function yr(r){if(r=r||(typeof document<"u"?document:void 0),typeof r>"u")return null;try{return r.activeElement||r.body}catch{return r.body}}var Xi=/[\n"\\]/g;function yi(r){return r.replace(Xi,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Kn(r,a,c,p,M,R,K,de){r.name="",K!=null&&typeof K!="function"&&typeof K!="symbol"&&typeof K!="boolean"?r.type=K:r.removeAttribute("type"),a!=null?K==="number"?(a===0&&r.value===""||r.value!=a)&&(r.value=""+dn(a)):r.value!==""+dn(a)&&(r.value=""+dn(a)):K!=="submit"&&K!=="reset"||r.removeAttribute("value"),a!=null?V(r,K,dn(a)):c!=null?V(r,K,dn(c)):p!=null&&r.removeAttribute("value"),M==null&&R!=null&&(r.defaultChecked=!!R),M!=null&&(r.checked=M&&typeof M!="function"&&typeof M!="symbol"),de!=null&&typeof de!="function"&&typeof de!="symbol"&&typeof de!="boolean"?r.name=""+dn(de):r.removeAttribute("name")}function Pe(r,a,c,p,M,R,K,de){if(R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"&&(r.type=R),a!=null||c!=null){if(!(R!=="submit"&&R!=="reset"||a!=null))return;c=c!=null?""+dn(c):"",a=a!=null?""+dn(a):c,de||a===r.value||(r.value=a),r.defaultValue=a}p=p??M,p=typeof p!="function"&&typeof p!="symbol"&&!!p,r.checked=de?r.checked:!!p,r.defaultChecked=!!p,K!=null&&typeof K!="function"&&typeof K!="symbol"&&typeof K!="boolean"&&(r.name=K)}function V(r,a,c){a==="number"&&yr(r.ownerDocument)===r||r.defaultValue===""+c||(r.defaultValue=""+c)}function fe(r,a,c,p){if(r=r.options,a){a={};for(var M=0;M=Zr),Yc=" ",Sd=!1;function Za(r,a){switch(r){case"keyup":return wd.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Us(r){return r=r.detail,typeof r=="object"&&"data"in r?r.data:null}var Bs=!1;function Ad(r,a){switch(r){case"compositionend":return Us(a);case"keypress":return a.which!==32?null:(Sd=!0,Yc);case"textInput":return r=a.data,r===Yc&&Sd?null:r;default:return null}}function Cd(r,a){if(Bs)return r==="compositionend"||!Io&&Za(r,a)?(r=Qr(),Or=Ki=Mi=null,Bs=!1,r):null;switch(r){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:c,offset:a-r};r=p}e:{for(;c;){if(c.nextSibling){c=c.nextSibling;break e}c=c.parentNode}c=void 0}c=ko(c)}}function No(r,a){return r&&a?r===a?!0:r&&r.nodeType===3?!1:a&&a.nodeType===3?No(r,a.parentNode):"contains"in r?r.contains(a):r.compareDocumentPosition?!!(r.compareDocumentPosition(a)&16):!1:!1}function zo(r){r=r!=null&&r.ownerDocument!=null&&r.ownerDocument.defaultView!=null?r.ownerDocument.defaultView:window;for(var a=yr(r.document);a instanceof r.HTMLIFrameElement;){try{var c=typeof a.contentWindow.location.href=="string"}catch{c=!1}if(c)r=a.contentWindow;else break;a=yr(r.document)}return a}function Uo(r){var a=r&&r.nodeName&&r.nodeName.toLowerCase();return a&&(a==="input"&&(r.type==="text"||r.type==="search"||r.type==="tel"||r.type==="url"||r.type==="password")||a==="textarea"||r.contentEditable==="true")}function tu(r,a){var c=zo(a);a=r.focusedElem;var p=r.selectionRange;if(c!==a&&a&&a.ownerDocument&&No(a.ownerDocument.documentElement,a)){if(p!==null&&Uo(a)){if(r=p.start,c=p.end,c===void 0&&(c=r),"selectionStart"in a)a.selectionStart=r,a.selectionEnd=Math.min(c,a.value.length);else if(c=(r=a.ownerDocument||document)&&r.defaultView||window,c.getSelection){c=c.getSelection();var M=a.textContent.length,R=Math.min(p.start,M);p=p.end===void 0?R:Math.min(p.end,M),!c.extend&&R>p&&(M=p,p=R,R=M),M=$l(a,R);var K=$l(a,p);M&&K&&(c.rangeCount!==1||c.anchorNode!==M.node||c.anchorOffset!==M.offset||c.focusNode!==K.node||c.focusOffset!==K.offset)&&(r=r.createRange(),r.setStart(M.node,M.offset),c.removeAllRanges(),R>p?(c.addRange(r),c.extend(K.node,K.offset)):(r.setEnd(K.node,K.offset),c.addRange(r)))}}for(r=[],c=a;c=c.parentNode;)c.nodeType===1&&r.push({element:c,left:c.scrollLeft,top:c.scrollTop});for(typeof a.focus=="function"&&a.focus(),a=0;a=document.documentMode,Ms=null,ro=null,$s=null,Bo=!1;function Vl(r,a,c){var p=c.window===c?c.document:c.nodeType===9?c:c.ownerDocument;Bo||Ms==null||Ms!==yr(p)||(p=Ms,"selectionStart"in p&&Uo(p)?p={start:p.selectionStart,end:p.selectionEnd}:(p=(p.ownerDocument&&p.ownerDocument.defaultView||window).getSelection(),p={anchorNode:p.anchorNode,anchorOffset:p.anchorOffset,focusNode:p.focusNode,focusOffset:p.focusOffset}),$s&&va($s,p)||($s=p,p=Ra(ro,"onSelect"),0>=K,M-=K,js=1<<32-vt(a)+M|c<gn?(Pr=un,un=null):Pr=un.sibling;var ai=Je($e,un,Xe[gn],pt);if(ai===null){un===null&&(un=Pr);break}r&&un&&ai.alternate===null&&a($e,un),De=R(ai,De,gn),Vn===null?Zt=ai:Vn.sibling=ai,Vn=ai,un=Pr}if(gn===Xe.length)return c($e,un),Yn&&Ma($e,gn),Zt;if(un===null){for(;gngn?(Pr=un,un=null):Pr=un.sibling;var wc=Je($e,un,ai.value,pt);if(wc===null){un===null&&(un=Pr);break}r&&un&&wc.alternate===null&&a($e,un),De=R(wc,De,gn),Vn===null?Zt=wc:Vn.sibling=wc,Vn=wc,un=Pr}if(ai.done)return c($e,un),Yn&&Ma($e,gn),Zt;if(un===null){for(;!ai.done;gn++,ai=Xe.next())ai=Tt($e,ai.value,pt),ai!==null&&(De=R(ai,De,gn),Vn===null?Zt=ai:Vn.sibling=ai,Vn=ai);return Yn&&Ma($e,gn),Zt}for(un=p(un);!ai.done;gn++,ai=Xe.next())ai=ct(un,$e,gn,ai.value,pt),ai!==null&&(r&&ai.alternate!==null&&un.delete(ai.key===null?gn:ai.key),De=R(ai,De,gn),Vn===null?Zt=ai:Vn.sibling=ai,Vn=ai);return r&&un.forEach(function(zP){return a($e,zP)}),Yn&&Ma($e,gn),Zt}function or($e,De,Xe,pt){if(typeof Xe=="object"&&Xe!==null&&Xe.type===d&&Xe.key===null&&(Xe=Xe.props.children),typeof Xe=="object"&&Xe!==null){switch(Xe.$$typeof){case l:e:{for(var Zt=Xe.key;De!==null;){if(De.key===Zt){if(Zt=Xe.type,Zt===d){if(De.tag===7){c($e,De.sibling),pt=M(De,Xe.props.children),pt.return=$e,$e=pt;break e}}else if(De.elementType===Zt||typeof Zt=="object"&&Zt!==null&&Zt.$$typeof===x&&Dh(Zt)===De.type){c($e,De.sibling),pt=M(De,Xe.props),Zl(pt,Xe),pt.return=$e,$e=pt;break e}c($e,De);break}else a($e,De);De=De.sibling}Xe.type===d?(pt=xo(Xe.props.children,$e.mode,pt,Xe.key),pt.return=$e,$e=pt):(pt=Iu(Xe.type,Xe.key,Xe.props,null,$e.mode,pt),Zl(pt,Xe),pt.return=$e,$e=pt)}return K($e);case u:e:{for(Zt=Xe.key;De!==null;){if(De.key===Zt)if(De.tag===4&&De.stateNode.containerInfo===Xe.containerInfo&&De.stateNode.implementation===Xe.implementation){c($e,De.sibling),pt=M(De,Xe.children||[]),pt.return=$e,$e=pt;break e}else{c($e,De);break}else a($e,De);De=De.sibling}pt=Lu(Xe,$e.mode,pt),pt.return=$e,$e=pt}return K($e);case x:return Zt=Xe._init,Xe=Zt(Xe._payload),or($e,De,Xe,pt)}if(te(Xe))return an($e,De,Xe,pt);if(E(Xe)){if(Zt=E(Xe),typeof Zt!="function")throw Error(i(150));return Xe=Zt.call(Xe),En($e,De,Xe,pt)}if(typeof Xe.then=="function")return or($e,De,su(Xe),pt);if(Xe.$$typeof===g)return or($e,De,uc($e,Xe),pt);Jl($e,Xe)}return typeof Xe=="string"&&Xe!==""||typeof Xe=="number"||typeof Xe=="bigint"?(Xe=""+Xe,De!==null&&De.tag===6?(c($e,De.sibling),pt=M(De,Xe),pt.return=$e,$e=pt):(c($e,De),pt=Ou(Xe,$e.mode,pt),pt.return=$e,$e=pt),K($e)):c($e,De)}return function($e,De,Xe,pt){try{Ql=0;var Zt=or($e,De,Xe,pt);return Go=null,Zt}catch(un){if(un===Xl)throw un;var Vn=hs(29,un,null,$e.mode);return Vn.lanes=pt,Vn.return=$e,Vn}finally{}}}var lo=Ih(!0),Oh=Ih(!1),co=xe(null),au=xe(0);function Lh(r,a){r=Aa,Me(au,r),Me(co,a),Aa=r|a.baseLanes}function Nd(){Me(au,Aa),Me(co,co.current)}function zd(){Aa=au.current,ze(co),ze(au)}var Vr=xe(null),bs=null;function ba(r){var a=r.alternate;Me(ar,ar.current&1),Me(Vr,r),bs===null&&(a===null||co.current!==null||a.memoizedState!==null)&&(bs=r)}function Fh(r){if(r.tag===22){if(Me(ar,ar.current),Me(Vr,r),bs===null){var a=r.alternate;a!==null&&a.memoizedState!==null&&(bs=r)}}else xa()}function xa(){Me(ar,ar.current),Me(Vr,Vr.current)}function xs(r){ze(Vr),bs===r&&(bs=null),ze(ar)}var ar=xe(0);function ou(r){for(var a=r;a!==null;){if(a.tag===13){var c=a.memoizedState;if(c!==null&&(c=c.dehydrated,c===null||c.data==="$?"||c.data==="$!"))return a}else if(a.tag===19&&a.memoizedProps.revealOrder!==void 0){if(a.flags&128)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===r)break;for(;a.sibling===null;){if(a.return===null||a.return===r)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var kh=typeof AbortController<"u"?AbortController:function(){var r=[],a=this.signal={aborted:!1,addEventListener:function(c,p){r.push(p)}};this.abort=function(){a.aborted=!0,r.forEach(function(c){return c()})}},a_=n.unstable_scheduleCallback,o_=n.unstable_NormalPriority,Qi={$$typeof:g,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Ud(){return{controller:new kh,data:new Map,refCount:0}}function ec(r){r.refCount--,r.refCount===0&&a_(o_,function(){r.controller.abort()})}var jo=null,Bd=0,Wo=0,uo=null;function l_(r,a){if(jo===null){var c=jo=[];Bd=0,Wo=Bi(),uo={status:"pending",value:void 0,then:function(p){c.push(p)}}}return Bd++,a.then(Nh,Nh),a}function Nh(){if(--Bd===0&&jo!==null){uo!==null&&(uo.status="fulfilled");var r=jo;jo=null,Wo=0,uo=null;for(var a=0;aR?R:8;var K=I.T,de={};I.T=de,sf(r,!1,a,c);try{var be=M(),Le=I.S;if(Le!==null&&Le(de,be),be!==null&&typeof be=="object"&&typeof be.then=="function"){var dt=$d(be,p);Ko(r,a,dt,as(r))}else Ko(r,a,p,as(r))}catch(Tt){Ko(r,a,{then:function(){},status:"rejected",reason:Tt},as())}finally{B.p=R,I.T=K}}function f_(){}function tf(r,a,c,p){if(r.tag!==5)throw Error(i(476));var M=cp(r).queue;lp(r,M,a,le,c===null?f_:function(){return nf(r),c(p)})}function cp(r){var a=r.memoizedState;if(a!==null)return a;a={memoizedState:le,baseState:le,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qs,lastRenderedState:le},next:null};var c={};return a.next={memoizedState:c,baseState:c,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:qs,lastRenderedState:c},next:null},r.memoizedState=a,r=r.alternate,r!==null&&(r.memoizedState=a),a}function nf(r){var a=cp(r).next.queue;Ko(r,a,{},as())}function rf(){return Mr(mm)}function up(){return Zi().memoizedState}function dp(){return Zi().memoizedState}function h_(r){for(var a=r.return;a!==null;){switch(a.tag){case 24:case 3:var c=as();r=Zs(c);var p=Ta(a,r,c);p!==null&&(Fr(p,a,c),dc(p,a,c)),a={cache:Ud()},r.payload=a;return}a=a.return}}function p_(r,a,c){var p=as();c={lane:p,revertLane:0,action:c,hasEagerState:!1,eagerState:null,next:null},yu(r)?af(a,c):(c=Pd(r,a,c,p),c!==null&&(Fr(c,r,p),hp(c,a,p)))}function fp(r,a,c){var p=as();Ko(r,a,c,p)}function Ko(r,a,c,p){var M={lane:p,revertLane:0,action:c,hasEagerState:!1,eagerState:null,next:null};if(yu(r))af(a,M);else{var R=r.alternate;if(r.lanes===0&&(R===null||R.lanes===0)&&(R=a.lastRenderedReducer,R!==null))try{var K=a.lastRenderedState,de=R(K,c);if(M.hasEagerState=!0,M.eagerState=de,mr(de,K))return nu(r,a,M,0),bi===null&&jl(),!1}catch{}finally{}if(c=Pd(r,a,M,p),c!==null)return Fr(c,r,p),hp(c,a,p),!0}return!1}function sf(r,a,c,p){if(p={lane:2,revertLane:Bi(),action:p,hasEagerState:!1,eagerState:null,next:null},yu(r)){if(a)throw Error(i(479))}else a=Pd(r,c,p,2),a!==null&&Fr(a,r,2)}function yu(r){var a=r.alternate;return r===Rn||a!==null&&a===Rn}function af(r,a){Ho=nc=!0;var c=r.pending;c===null?a.next=a:(a.next=c.next,c.next=a),r.pending=a}function hp(r,a,c){if(c&4194176){var p=a.lanes;p&=r.pendingLanes,c|=p,a.lanes=c,ut(r,c)}}var ws={readContext:Mr,use:fu,useCallback:ji,useContext:ji,useEffect:ji,useImperativeHandle:ji,useLayoutEffect:ji,useInsertionEffect:ji,useMemo:ji,useReducer:ji,useRef:ji,useState:ji,useDebugValue:ji,useDeferredValue:ji,useTransition:ji,useSyncExternalStore:ji,useId:ji};ws.useCacheRefresh=ji,ws.useMemoCache=ji,ws.useHostTransitionStatus=ji,ws.useFormState=ji,ws.useActionState=ji,ws.useOptimistic=ji;var Gr={readContext:Mr,use:fu,useCallback:function(r,a){return Lr().memoizedState=[r,a===void 0?null:a],r},useContext:Mr,useEffect:ip,useImperativeHandle:function(r,a,c){c=c!=null?c.concat([r]):null,_u(4194308,4,Yd.bind(null,a,r),c)},useLayoutEffect:function(r,a){return _u(4194308,4,r,a)},useInsertionEffect:function(r,a){_u(4,2,r,a)},useMemo:function(r,a){var c=Lr();a=a===void 0?null:a;var p=r();if(ho){ft(!0);try{r()}finally{ft(!1)}}return c.memoizedState=[p,a],p},useReducer:function(r,a,c){var p=Lr();if(c!==void 0){var M=c(a);if(ho){ft(!0);try{c(a)}finally{ft(!1)}}}else M=a;return p.memoizedState=p.baseState=M,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:r,lastRenderedState:M},p.queue=r,r=r.dispatch=p_.bind(null,Rn,r),[p.memoizedState,r]},useRef:function(r){var a=Lr();return r={current:r},a.memoizedState=r},useState:function(r){r=qd(r);var a=r.queue,c=fp.bind(null,Rn,a);return a.dispatch=c,[r.memoizedState,c]},useDebugValue:Qd,useDeferredValue:function(r,a){var c=Lr();return Jd(c,r,a)},useTransition:function(){var r=qd(!1);return r=lp.bind(null,Rn,r.queue,!0,!1),Lr().memoizedState=r,[!1,r]},useSyncExternalStore:function(r,a,c){var p=Rn,M=Lr();if(Yn){if(c===void 0)throw Error(i(407));c=c()}else{if(c=a(),bi===null)throw Error(i(349));jn&60||jh(p,a,c)}M.memoizedState=c;var R={value:c,getSnapshot:a};return M.queue=R,ip(Wh.bind(null,p,R,r),[r]),p.flags|=2048,po(9,Hd.bind(null,p,R,c,a),{destroy:void 0},null),c},useId:function(){var r=Lr(),a=bi.identifierPrefix;if(Yn){var c=Ws,p=js;c=(p&~(1<<32-vt(p)-1)).toString(32)+c,a=":"+a+"R"+c,c=cu++,0 title"))),dr(R,p,c),R[ri]=r,Ue(R),p=R;break e;case"link":var K=Mb("link","href",M).get(p+(c.href||""));if(K){for(var de=0;de<\/script>",r=r.removeChild(r.firstChild);break;case"select":r=typeof p.is=="string"?M.createElement("select",{is:p.is}):M.createElement("select"),p.multiple?r.multiple=!0:p.size&&(r.size=p.size);break;default:r=typeof p.is=="string"?M.createElement(c,{is:p.is}):M.createElement(c)}}r[ri]=a,r[Ti]=p;e:for(M=a.child;M!==null;){if(M.tag===5||M.tag===6)r.appendChild(M.stateNode);else if(M.tag!==4&&M.tag!==27&&M.child!==null){M.child.return=M,M=M.child;continue}if(M===a)break e;for(;M.sibling===null;){if(M.return===null||M.return===a)break e;M=M.return}M.sibling.return=M.return,M=M.sibling}a.stateNode=r;e:switch(dr(r,c,p),c){case"button":case"input":case"select":case"textarea":r=!!p.autoFocus;break e;case"img":r=!0;break e;default:r=!1}r&&Sa(a)}}return ki(a),a.flags&=-16777217,null;case 6:if(r&&a.stateNode!=null)r.memoizedProps!==p&&Sa(a);else{if(typeof p!="string"&&a.stateNode===null)throw Error(i(166));if(r=we.current,Hl(a)){if(r=a.stateNode,c=a.memoizedProps,p=null,M=Ar,M!==null)switch(M.tag){case 27:case 5:p=M.memoizedProps}r[ri]=a,r=!!(r.nodeValue===c||p!==null&&p.suppressHydrationWarning===!0||If(r.nodeValue,c)),r||oo(a)}else r=Ff(r).createTextNode(p),r[ri]=a,a.stateNode=r}return ki(a),null;case 13:if(p=a.memoizedState,r===null||r.memoizedState!==null&&r.memoizedState.dehydrated!==null){if(M=Hl(a),p!==null&&p.dehydrated!==null){if(r===null){if(!M)throw Error(i(318));if(M=a.memoizedState,M=M!==null?M.dehydrated:null,!M)throw Error(i(317));M[ri]=a}else Vo(),!(a.flags&128)&&(a.memoizedState=null),a.flags|=4;ki(a),M=!1}else us!==null&&(im(us),us=null),M=!0;if(!M)return a.flags&256?(xs(a),a):(xs(a),null)}if(xs(a),a.flags&128)return a.lanes=c,a;if(c=p!==null,r=r!==null&&r.memoizedState!==null,c){p=a.child,M=null,p.alternate!==null&&p.alternate.memoizedState!==null&&p.alternate.memoizedState.cachePool!==null&&(M=p.alternate.memoizedState.cachePool.pool);var R=null;p.memoizedState!==null&&p.memoizedState.cachePool!==null&&(R=p.memoizedState.cachePool.pool),R!==M&&(p.flags|=2048)}return c!==r&&c&&(a.child.flags|=8192),Fu(a,a.updateQueue),ki(a),null;case 4:return Ne(),r===null&&gi(a.stateNode.containerInfo),ki(a),null;case 10:return Qs(a.type),ki(a),null;case 19:if(ze(ar),M=a.memoizedState,M===null)return ki(a),null;if(p=(a.flags&128)!==0,R=M.rendering,R===null)if(p)nl(M,!1);else{if(Ui!==0||r!==null&&r.flags&128)for(r=a.child;r!==null;){if(R=ou(r),R!==null){for(a.flags|=128,nl(M,!1),r=R.updateQueue,a.updateQueue=r,Fu(a,r),a.subtreeFlags=0,r=c,c=a.child;c!==null;)Xp(c,r),c=c.sibling;return Me(ar,ar.current&1|2),a.child}r=r.sibling}M.tail!==null&&se()>Sf&&(a.flags|=128,p=!0,nl(M,!1),a.lanes=4194304)}else{if(!p)if(r=ou(R),r!==null){if(a.flags|=128,p=!0,r=r.updateQueue,a.updateQueue=r,Fu(a,r),nl(M,!0),M.tail===null&&M.tailMode==="hidden"&&!R.alternate&&!Yn)return ki(a),null}else 2*se()-M.renderingStartTime>Sf&&c!==536870912&&(a.flags|=128,p=!0,nl(M,!1),a.lanes=4194304);M.isBackwards?(R.sibling=a.child,a.child=R):(r=M.last,r!==null?r.sibling=R:a.child=R,M.last=R)}return M.tail!==null?(a=M.tail,M.rendering=a,M.tail=a.sibling,M.renderingStartTime=se(),a.sibling=null,r=ar.current,Me(ar,p?r&1|2:r&1),a):(ki(a),null);case 22:case 23:return xs(a),zd(),p=a.memoizedState!==null,r!==null?r.memoizedState!==null!==p&&(a.flags|=8192):p&&(a.flags|=8192),p?c&536870912&&!(a.flags&128)&&(ki(a),a.subtreeFlags&6&&(a.flags|=8192)):ki(a),c=a.updateQueue,c!==null&&Fu(a,c.retryQueue),c=null,r!==null&&r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(c=r.memoizedState.cachePool.pool),p=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(p=a.memoizedState.cachePool.pool),p!==c&&(a.flags|=2048),r!==null&&ze(fo),null;case 24:return c=null,r!==null&&(c=r.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),Qs(Qi),ki(a),null;case 25:return null}throw Error(i(156,a.tag))}function r0(r,a){switch(Dd(a),a.tag){case 1:return r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 3:return Qs(Qi),Ne(),r=a.flags,r&65536&&!(r&128)?(a.flags=r&-65537|128,a):null;case 26:case 27:case 5:return ke(a),null;case 13:if(xs(a),r=a.memoizedState,r!==null&&r.dehydrated!==null){if(a.alternate===null)throw Error(i(340));Vo()}return r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 19:return ze(ar),null;case 4:return Ne(),null;case 10:return Qs(a.type),null;case 22:case 23:return xs(a),zd(),r!==null&&ze(fo),r=a.flags,r&65536?(a.flags=r&-65537|128,a):null;case 24:return Qs(Qi),null;case 25:return null;default:return null}}function Qp(r,a){switch(Dd(a),a.tag){case 3:Qs(Qi),Ne();break;case 26:case 27:case 5:ke(a);break;case 4:Ne();break;case 13:xs(a);break;case 19:ze(ar);break;case 10:Qs(a.type);break;case 22:case 23:xs(a),zd(),r!==null&&ze(fo);break;case 24:Qs(Qi)}}var T_={getCacheForType:function(r){var a=Mr(Qi),c=a.data.get(r);return c===void 0&&(c=r(),a.data.set(r,c)),c}},E_=typeof WeakMap=="function"?WeakMap:Map,_i=0,bi=null,kn=null,jn=0,xi=0,Wr=null,ia=!1,il=!1,Tf=!1,Aa=0,Ui=0,Ca=0,wo=0,Ef=0,ss=0,rl=0,ku=null,Ss=null,Zp=!1,Jp=0,Sf=1/0,Af=null,To=null,Cf=!1,sl=null,Nu=0,em=0,tm=null,zu=0,nm=null;function as(){if(_i&2&&jn!==0)return jn&-jn;if(I.T!==null){var r=Wo;return r!==0?r:Bi()}return Bt()}function S_(){ss===0&&(ss=!(jn&536870912)||Yn?tn():536870912);var r=Vr.current;return r!==null&&(r.flags|=32),ss}function Fr(r,a,c){(r===bi&&xi===2||r.cancelPendingCommit!==null)&&(gc(r,0),Pa(r,jn,ss,!1)),ln(r,c),(!(_i&2)||r!==bi)&&(r===bi&&(!(_i&2)&&(wo|=c),Ui===4&&Pa(r,jn,ss,!1)),Vt(r))}function A_(r,a,c){if(_i&6)throw Error(i(327));var p=!c&&(a&60)===0&&(a&r.expiredLanes)===0||gt(r,a),M=p?o0(r,a):am(r,a,!0),R=p;do{if(M===0){il&&!p&&Pa(r,a,0,!1);break}else if(M===6)Pa(r,a,0,!ia);else{if(c=r.current.alternate,R&&!s0(c)){M=am(r,a,!1),R=!1;continue}if(M===2){if(R=a,r.errorRecoveryDisabledLanes&R)var K=0;else K=r.pendingLanes&-536870913,K=K!==0?K:K&536870912?536870912:0;if(K!==0){a=K;e:{var de=r;M=ku;var be=de.current.memoizedState.isDehydrated;if(be&&(gc(de,K).flags|=256),K=am(de,K,!1),K!==2){if(Tf&&!be){de.errorRecoveryDisabledLanes|=R,wo|=R,M=4;break e}R=Ss,Ss=M,R!==null&&im(R)}M=K}if(R=!1,M!==2)continue}}if(M===1){gc(r,0),Pa(r,a,0,!0);break}e:{switch(p=r,M){case 0:case 1:throw Error(i(345));case 4:if((a&4194176)===a){Pa(p,a,ss,!ia);break e}break;case 2:Ss=null;break;case 3:case 5:break;default:throw Error(i(329))}if(p.finishedWork=c,p.finishedLanes=a,(a&62914560)===a&&(R=Jp+300-se(),10c?32:c,I.T=null,sl===null)var R=!1;else{c=tm,tm=null;var K=sl,de=Nu;if(sl=null,Nu=0,_i&6)throw Error(i(331));var be=_i;if(_i|=4,Hp(K.current),jp(K,K.current,de,c),_i=be,$n(0,!1),_t&&typeof _t.onPostCommitFiberRoot=="function")try{_t.onPostCommitFiberRoot(bt,K)}catch{}R=!0}return R}finally{B.p=M,I.T=p,O_(r,a)}}return!1}function om(r,a,c){a=es(c,a),a=Yo(r.stateNode,a,2),r=Ta(r,a,2),r!==null&&(ln(r,2),Vt(r))}function k(r,a,c){if(r.tag===3)om(r,r,c);else for(;a!==null;){if(a.tag===3){om(a,r,c);break}else if(a.tag===1){var p=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof p.componentDidCatch=="function"&&(To===null||!To.has(p))){r=es(c,r),c=vp(2),p=Ta(a,c,2),p!==null&&(yp(c,p,a,r),ln(p,2),Vt(p));break}}a=a.return}}function N(r,a,c){var p=r.pingCache;if(p===null){p=r.pingCache=new E_;var M=new Set;p.set(a,M)}else M=p.get(a),M===void 0&&(M=new Set,p.set(a,M));M.has(c)||(Tf=!0,M.add(c),r=he.bind(null,r,a,c),a.then(r,r))}function he(r,a,c){var p=r.pingCache;p!==null&&p.delete(a),r.pingedLanes|=r.suspendedLanes&c,r.warmLanes&=~c,bi===r&&(jn&c)===c&&(Ui===4||Ui===3&&(jn&62914560)===jn&&300>se()-Jp?!(_i&2)&&gc(r,0):Ef|=c,rl===jn&&(rl=0)),Vt(r)}function Re(r,a){a===0&&(a=rn()),r=Gs(r,a),r!==null&&(ln(r,a),Vt(r))}function Ve(r){var a=r.memoizedState,c=0;a!==null&&(c=a.retryLane),Re(r,c)}function Ye(r,a){var c=0;switch(r.tag){case 13:var p=r.stateNode,M=r.memoizedState;M!==null&&(c=M.retryLane);break;case 19:p=r.stateNode;break;case 22:p=r.stateNode._retryCache;break;default:throw Error(i(314))}p!==null&&p.delete(a),Re(r,c)}function ht(r,a){return Ke(r,a)}var xt=null,Et=null,$t=!1,pn=!1,vn=!1,Kt=0;function Vt(r){r!==Et&&r.next===null&&(Et===null?xt=Et=r:Et=Et.next=r),pn=!0,$t||($t=!0,Ni(on))}function $n(r,a){if(!vn&&pn){vn=!0;do for(var c=!1,p=xt;p!==null;){if(r!==0){var M=p.pendingLanes;if(M===0)var R=0;else{var K=p.suspendedLanes,de=p.pingedLanes;R=(1<<31-vt(42|r)+1)-1,R&=M&~(K&~de),R=R&201326677?R&201326677|1:R?R|2:0}R!==0&&(c=!0,fi(p,R))}else R=jn,R=tt(p,p===bi?R:0),!(R&3)||gt(p,R)||(c=!0,fi(p,R));p=p.next}while(c);vn=!1}}function on(){pn=$t=!1;var r=0;Kt!==0&&(uP()&&(r=Kt),Kt=0);for(var a=se(),c=null,p=xt;p!==null;){var M=p.next,R=Qt(p,a);R===0?(p.next=null,c===null?xt=M:c.next=M,M===null&&(Et=c)):(c=p,(r!==0||R&3)&&(pn=!0)),p=M}$n(r)}function Qt(r,a){for(var c=r.suspendedLanes,p=r.pingedLanes,M=r.expirationTimes,R=r.pendingLanes&-62914561;0"u"?null:document;function _b(r,a,c){var p=kf;if(p&&typeof a=="string"&&a){var M=yi(a);M='link[rel="'+r+'"][href="'+M+'"]',typeof c=="string"&&(M+='[crossorigin="'+c+'"]'),mb.has(M)||(mb.add(M),r={rel:r,crossOrigin:c,href:a},p.querySelector(M)===null&&(a=p.createElement("link"),dr(a,"link",r),Ue(a),p.head.appendChild(a)))}}function vP(r){hl.D(r),_b("dns-prefetch",r,null)}function yP(r,a){hl.C(r,a),_b("preconnect",r,a)}function MP(r,a,c){hl.L(r,a,c);var p=kf;if(p&&r&&a){var M='link[rel="preload"][as="'+yi(a)+'"]';a==="image"&&c&&c.imageSrcSet?(M+='[imagesrcset="'+yi(c.imageSrcSet)+'"]',typeof c.imageSizes=="string"&&(M+='[imagesizes="'+yi(c.imageSizes)+'"]')):M+='[href="'+yi(r)+'"]';var R=M;switch(a){case"style":R=Nf(r);break;case"script":R=zf(r)}sa.has(R)||(r=O({rel:"preload",href:a==="image"&&c&&c.imageSrcSet?void 0:r,as:a},c),sa.set(R,r),p.querySelector(M)!==null||a==="style"&&p.querySelector(fm(R))||a==="script"&&p.querySelector(hm(R))||(a=p.createElement("link"),dr(a,"link",r),Ue(a),p.head.appendChild(a)))}}function bP(r,a){hl.m(r,a);var c=kf;if(c&&r){var p=a&&typeof a.as=="string"?a.as:"script",M='link[rel="modulepreload"][as="'+yi(p)+'"][href="'+yi(r)+'"]',R=M;switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":R=zf(r)}if(!sa.has(R)&&(r=O({rel:"modulepreload",href:r},a),sa.set(R,r),c.querySelector(M)===null)){switch(p){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(c.querySelector(hm(R)))return}p=c.createElement("link"),dr(p,"link",r),Ue(p),c.head.appendChild(p)}}}function xP(r,a,c){hl.S(r,a,c);var p=kf;if(p&&r){var M=qe(p).hoistableStyles,R=Nf(r);a=a||"default";var K=M.get(R);if(!K){var de={loading:0,preload:null};if(K=p.querySelector(fm(R)))de.loading=5;else{r=O({rel:"stylesheet",href:r,"data-precedence":a},c),(c=sa.get(R))&&h0(r,c);var be=K=p.createElement("link");Ue(be),dr(be,"link",r),be._p=new Promise(function(Le,dt){be.onload=Le,be.onerror=dt}),be.addEventListener("load",function(){de.loading|=1}),be.addEventListener("error",function(){de.loading|=2}),de.loading|=4,k_(K,a,p)}K={type:"stylesheet",instance:K,count:1,state:de},M.set(R,K)}}}function wP(r,a){hl.X(r,a);var c=kf;if(c&&r){var p=qe(c).hoistableScripts,M=zf(r),R=p.get(M);R||(R=c.querySelector(hm(M)),R||(r=O({src:r,async:!0},a),(a=sa.get(M))&&p0(r,a),R=c.createElement("script"),Ue(R),dr(R,"link",r),c.head.appendChild(R)),R={type:"script",instance:R,count:1,state:null},p.set(M,R))}}function TP(r,a){hl.M(r,a);var c=kf;if(c&&r){var p=qe(c).hoistableScripts,M=zf(r),R=p.get(M);R||(R=c.querySelector(hm(M)),R||(r=O({src:r,async:!0,type:"module"},a),(a=sa.get(M))&&p0(r,a),R=c.createElement("script"),Ue(R),dr(R,"link",r),c.head.appendChild(R)),R={type:"script",instance:R,count:1,state:null},p.set(M,R))}}function gb(r,a,c,p){var M=(M=we.current)?F_(M):null;if(!M)throw Error(i(446));switch(r){case"meta":case"title":return null;case"style":return typeof c.precedence=="string"&&typeof c.href=="string"?(a=Nf(c.href),c=qe(M).hoistableStyles,p=c.get(a),p||(p={type:"style",instance:null,count:0,state:null},c.set(a,p)),p):{type:"void",instance:null,count:0,state:null};case"link":if(c.rel==="stylesheet"&&typeof c.href=="string"&&typeof c.precedence=="string"){r=Nf(c.href);var R=qe(M).hoistableStyles,K=R.get(r);if(K||(M=M.ownerDocument||M,K={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},R.set(r,K),(R=M.querySelector(fm(r)))&&!R._p&&(K.instance=R,K.state.loading=5),sa.has(r)||(c={rel:"preload",as:"style",href:c.href,crossOrigin:c.crossOrigin,integrity:c.integrity,media:c.media,hrefLang:c.hrefLang,referrerPolicy:c.referrerPolicy},sa.set(r,c),R||EP(M,r,c,K.state))),a&&p===null)throw Error(i(528,""));return K}if(a&&p!==null)throw Error(i(529,""));return null;case"script":return a=c.async,c=c.src,typeof c=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=zf(c),c=qe(M).hoistableScripts,p=c.get(a),p||(p={type:"script",instance:null,count:0,state:null},c.set(a,p)),p):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,r))}}function Nf(r){return'href="'+yi(r)+'"'}function fm(r){return'link[rel="stylesheet"]['+r+"]"}function vb(r){return O({},r,{"data-precedence":r.precedence,precedence:null})}function EP(r,a,c,p){r.querySelector('link[rel="preload"][as="style"]['+a+"]")?p.loading=1:(a=r.createElement("link"),p.preload=a,a.addEventListener("load",function(){return p.loading|=1}),a.addEventListener("error",function(){return p.loading|=2}),dr(a,"link",c),Ue(a),r.head.appendChild(a))}function zf(r){return'[src="'+yi(r)+'"]'}function hm(r){return"script[async]"+r}function yb(r,a,c){if(a.count++,a.instance===null)switch(a.type){case"style":var p=r.querySelector('style[data-href~="'+yi(c.href)+'"]');if(p)return a.instance=p,Ue(p),p;var M=O({},c,{"data-href":c.href,"data-precedence":c.precedence,href:null,precedence:null});return p=(r.ownerDocument||r).createElement("style"),Ue(p),dr(p,"style",M),k_(p,c.precedence,r),a.instance=p;case"stylesheet":M=Nf(c.href);var R=r.querySelector(fm(M));if(R)return a.state.loading|=4,a.instance=R,Ue(R),R;p=vb(c),(M=sa.get(M))&&h0(p,M),R=(r.ownerDocument||r).createElement("link"),Ue(R);var K=R;return K._p=new Promise(function(de,be){K.onload=de,K.onerror=be}),dr(R,"link",p),a.state.loading|=4,k_(R,c.precedence,r),a.instance=R;case"script":return R=zf(c.src),(M=r.querySelector(hm(R)))?(a.instance=M,Ue(M),M):(p=c,(M=sa.get(R))&&(p=O({},c),p0(p,M)),r=r.ownerDocument||r,M=r.createElement("script"),Ue(M),dr(M,"link",p),r.head.appendChild(M),a.instance=M);case"void":return null;default:throw Error(i(443,a.type))}else a.type==="stylesheet"&&!(a.state.loading&4)&&(p=a.instance,a.state.loading|=4,k_(p,c.precedence,r));return a.instance}function k_(r,a,c){for(var p=c.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),M=p.length?p[p.length-1]:null,R=M,K=0;K title"):null)}function SP(r,a,c){if(c===1||a.itemProp!=null)return!1;switch(r){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return r=a.disabled,typeof a.precedence=="string"&&r==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function xb(r){return!(r.type==="stylesheet"&&!(r.state.loading&3))}var pm=null;function AP(){}function CP(r,a,c){if(pm===null)throw Error(i(475));var p=pm;if(a.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&!(a.state.loading&4)){if(a.instance===null){var M=Nf(c.href),R=r.querySelector(fm(M));if(R){r=R._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(p.count++,p=z_.bind(p),r.then(p,p)),a.state.loading|=4,a.instance=R,Ue(R);return}R=r.ownerDocument||r,c=vb(c),(M=sa.get(M))&&h0(c,M),R=R.createElement("link"),Ue(R);var K=R;K._p=new Promise(function(de,be){K.onload=de,K.onerror=be}),dr(R,"link",c),a.instance=R}p.stylesheets===null&&(p.stylesheets=new Map),p.stylesheets.set(a,r),(r=a.state.preload)&&!(a.state.loading&3)&&(p.count++,a=z_.bind(p),r.addEventListener("load",a),r.addEventListener("error",a))}}function PP(){if(pm===null)throw Error(i(475));var r=pm;return r.stylesheets&&r.count===0&&m0(r,r.stylesheets),0"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),T0.exports=WP(),T0.exports}var qP=HP();function R1(n){var e,t,i="";if(typeof n=="string"||typeof n=="number")i+=n;else if(typeof n=="object")if(Array.isArray(n)){var s=n.length;for(e=0;e{const e=QP(n),{conflictingClassGroups:t,conflictingClassGroupModifiers:i}=n;return{getClassGroupId:l=>{const u=l.split(MM);return u[0]===""&&u.length!==1&&u.shift(),D1(u,e)||YP(l)},getConflictingClassGroupIds:(l,u)=>{const d=t[l]||[];return u&&i[l]?[...d,...i[l]]:d}}},D1=(n,e)=>{if(n.length===0)return e.classGroupId;const t=n[0],i=e.nextPart.get(t),s=i?D1(n.slice(1),i):void 0;if(s)return s;if(e.validators.length===0)return;const o=n.join(MM);return e.validators.find(({validator:l})=>l(o))?.classGroupId},jb=/^\[(.+)\]$/,YP=n=>{if(jb.test(n)){const e=jb.exec(n)[1],t=e?.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},QP=n=>{const{theme:e,classGroups:t}=n,i={nextPart:new Map,validators:[]};for(const s in t)uy(t[s],i,s,e);return i},uy=(n,e,t,i)=>{n.forEach(s=>{if(typeof s=="string"){const o=s===""?e:Wb(e,s);o.classGroupId=t;return}if(typeof s=="function"){if(ZP(s)){uy(s(i),e,t,i);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([o,l])=>{uy(l,Wb(e,o),t,i)})})},Wb=(n,e)=>{let t=n;return e.split(MM).forEach(i=>{t.nextPart.has(i)||t.nextPart.set(i,{nextPart:new Map,validators:[]}),t=t.nextPart.get(i)}),t},ZP=n=>n.isThemeGetter,JP=n=>{if(n<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,i=new Map;const s=(o,l)=>{t.set(o,l),e++,e>n&&(e=0,i=t,t=new Map)};return{get(o){let l=t.get(o);if(l!==void 0)return l;if((l=i.get(o))!==void 0)return s(o,l),l},set(o,l){t.has(o)?t.set(o,l):s(o,l)}}},dy="!",fy=":",eR=fy.length,tR=n=>{const{prefix:e,experimentalParseClassName:t}=n;let i=s=>{const o=[];let l=0,u=0,d=0,f;for(let y=0;yd?f-d:void 0;return{modifiers:o,hasImportantModifier:_,baseClassName:h,maybePostfixModifierPosition:g}};if(e){const s=e+fy,o=i;i=l=>l.startsWith(s)?o(l.substring(s.length)):{isExternal:!0,modifiers:[],hasImportantModifier:!1,baseClassName:l,maybePostfixModifierPosition:void 0}}if(t){const s=i;i=o=>t({className:o,parseClassName:s})}return i},nR=n=>n.endsWith(dy)?n.substring(0,n.length-1):n.startsWith(dy)?n.substring(1):n,iR=n=>{const e=Object.fromEntries(n.orderSensitiveModifiers.map(i=>[i,!0]));return i=>{if(i.length<=1)return i;const s=[];let o=[];return i.forEach(l=>{l[0]==="["||e[l]?(s.push(...o.sort(),l),o=[]):o.push(l)}),s.push(...o.sort()),s}},rR=n=>({cache:JP(n.cacheSize),parseClassName:tR(n),sortModifiers:iR(n),...KP(n)}),sR=/\s+/,aR=(n,e)=>{const{parseClassName:t,getClassGroupId:i,getConflictingClassGroupIds:s,sortModifiers:o}=e,l=[],u=n.trim().split(sR);let d="";for(let f=u.length-1;f>=0;f-=1){const m=u[f],{isExternal:h,modifiers:_,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:b}=t(m);if(h){d=m+(d.length>0?" "+d:d);continue}let T=!!b,v=i(T?y.substring(0,b):y);if(!v){if(!T){d=m+(d.length>0?" "+d:d);continue}if(v=i(y),!v){d=m+(d.length>0?" "+d:d);continue}T=!1}const x=o(_).join(":"),P=g?x+dy:x,w=P+v;if(l.includes(w))continue;l.push(w);const C=s(v,T);for(let E=0;E0?" "+d:d)}return d};function oR(){let n=0,e,t,i="";for(;n{if(typeof n=="string")return n;let e,t="";for(let i=0;ih(m),n());return t=rR(f),i=t.cache.get,s=t.cache.set,o=u,u(d)}function u(d){const f=i(d);if(f)return f;const m=aR(d,t);return s(d,m),m}return function(){return o(oR.apply(null,arguments))}}const Rr=n=>{const e=t=>t[n]||[];return e.isThemeGetter=!0,e},O1=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,L1=/^\((?:(\w[\w-]*):)?(.+)\)$/i,cR=/^\d+\/\d+$/,uR=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,dR=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,fR=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,hR=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,pR=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Uf=n=>cR.test(n),Xn=n=>!!n&&!Number.isNaN(Number(n)),Uu=n=>!!n&&Number.isInteger(Number(n)),Hb=n=>n.endsWith("%")&&Xn(n.slice(0,-1)),Tc=n=>uR.test(n),mR=()=>!0,_R=n=>dR.test(n)&&!fR.test(n),bM=()=>!1,gR=n=>hR.test(n),vR=n=>pR.test(n),yR=n=>!jt(n)&&!Wt(n),MR=n=>yh(n,N1,bM),jt=n=>O1.test(n),Bu=n=>yh(n,z1,_R),C0=n=>yh(n,DR,Xn),bR=n=>yh(n,F1,bM),xR=n=>yh(n,k1,vR),wR=n=>yh(n,bM,gR),Wt=n=>L1.test(n),q_=n=>Mh(n,z1),TR=n=>Mh(n,IR),ER=n=>Mh(n,F1),SR=n=>Mh(n,N1),AR=n=>Mh(n,k1),CR=n=>Mh(n,OR,!0),yh=(n,e,t)=>{const i=O1.exec(n);return i?i[1]?e(i[1]):t(i[2]):!1},Mh=(n,e,t=!1)=>{const i=L1.exec(n);return i?i[1]?e(i[1]):t:!1},F1=n=>n==="position",PR=new Set(["image","url"]),k1=n=>PR.has(n),RR=new Set(["length","size","percentage"]),N1=n=>RR.has(n),z1=n=>n==="length",DR=n=>n==="number",IR=n=>n==="family-name",OR=n=>n==="shadow",LR=()=>{const n=Rr("color"),e=Rr("font"),t=Rr("text"),i=Rr("font-weight"),s=Rr("tracking"),o=Rr("leading"),l=Rr("breakpoint"),u=Rr("container"),d=Rr("spacing"),f=Rr("radius"),m=Rr("shadow"),h=Rr("inset-shadow"),_=Rr("drop-shadow"),g=Rr("blur"),y=Rr("perspective"),b=Rr("aspect"),T=Rr("ease"),v=Rr("animate"),x=()=>["auto","avoid","all","avoid-page","page","left","right","column"],P=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],w=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],E=()=>[Uf,"px","full","auto",Wt,jt,d],A=()=>[Uu,"none","subgrid",Wt,jt],L=()=>["auto",{span:["full",Uu,Wt,jt]},Wt,jt],I=()=>[Uu,"auto",Wt,jt],O=()=>["auto","min","max","fr",Wt,jt],H=()=>[Wt,jt,d],Z=()=>["start","end","center","between","around","evenly","stretch","baseline"],$=()=>["start","end","center","stretch"],J=()=>[Wt,jt,d],ee=()=>["px",...J()],X=()=>["px","auto",...J()],ne=()=>[Uf,"auto","px","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",Wt,jt,d],Q=()=>[n,Wt,jt],oe=()=>[Hb,Bu],W=()=>["","none","full",f,Wt,jt],q=()=>["",Xn,q_,Bu],G=()=>["solid","dashed","dotted","double"],te=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],B=()=>["","none",g,Wt,jt],le=()=>["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Wt,jt],ye=()=>["none",Xn,Wt,jt],me=()=>["none",Xn,Wt,jt],xe=()=>[Xn,Wt,jt],ze=()=>[Uf,"full","px",Wt,jt,d];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Tc],breakpoint:[Tc],color:[mR],container:[Tc],"drop-shadow":[Tc],ease:["in","out","in-out"],font:[yR],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Tc],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Tc],shadow:[Tc],spacing:[Xn],text:[Tc],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Uf,jt,Wt,b]}],container:["container"],columns:[{columns:[Xn,jt,Wt,u]}],"break-after":[{"break-after":x()}],"break-before":[{"break-before":x()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...P(),jt,Wt]}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:E()}],"inset-x":[{"inset-x":E()}],"inset-y":[{"inset-y":E()}],start:[{start:E()}],end:[{end:E()}],top:[{top:E()}],right:[{right:E()}],bottom:[{bottom:E()}],left:[{left:E()}],visibility:["visible","invisible","collapse"],z:[{z:[Uu,"auto",Wt,jt]}],basis:[{basis:[Uf,"full","auto",Wt,jt,u,d]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Xn,Uf,"auto","initial","none",jt]}],grow:[{grow:["",Xn,Wt,jt]}],shrink:[{shrink:["",Xn,Wt,jt]}],order:[{order:[Uu,"first","last","none",Wt,jt]}],"grid-cols":[{"grid-cols":A()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":I()}],"col-end":[{"col-end":I()}],"grid-rows":[{"grid-rows":A()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":I()}],"row-end":[{"row-end":I()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":O()}],"auto-rows":[{"auto-rows":O()}],gap:[{gap:H()}],"gap-x":[{"gap-x":H()}],"gap-y":[{"gap-y":H()}],"justify-content":[{justify:[...Z(),"normal"]}],"justify-items":[{"justify-items":[...$(),"normal"]}],"justify-self":[{"justify-self":["auto",...$()]}],"align-content":[{content:["normal",...Z()]}],"align-items":[{items:[...$(),"baseline"]}],"align-self":[{self:["auto",...$(),"baseline"]}],"place-content":[{"place-content":Z()}],"place-items":[{"place-items":[...$(),"baseline"]}],"place-self":[{"place-self":["auto",...$()]}],p:[{p:ee()}],px:[{px:ee()}],py:[{py:ee()}],ps:[{ps:ee()}],pe:[{pe:ee()}],pt:[{pt:ee()}],pr:[{pr:ee()}],pb:[{pb:ee()}],pl:[{pl:ee()}],m:[{m:X()}],mx:[{mx:X()}],my:[{my:X()}],ms:[{ms:X()}],me:[{me:X()}],mt:[{mt:X()}],mr:[{mr:X()}],mb:[{mb:X()}],ml:[{ml:X()}],"space-x":[{"space-x":J()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":J()}],"space-y-reverse":["space-y-reverse"],size:[{size:ne()}],w:[{w:[u,"screen",...ne()]}],"min-w":[{"min-w":[u,"screen","none",...ne()]}],"max-w":[{"max-w":[u,"screen","none","prose",{screen:[l]},...ne()]}],h:[{h:["screen",...ne()]}],"min-h":[{"min-h":["screen","none",...ne()]}],"max-h":[{"max-h":["screen",...ne()]}],"font-size":[{text:["base",t,q_,Bu]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[i,Wt,C0]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Hb,jt]}],"font-family":[{font:[TR,jt,e]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,Wt,jt]}],"line-clamp":[{"line-clamp":[Xn,"none",Wt,C0]}],leading:[{leading:[Wt,jt,o,d]}],"list-image":[{"list-image":["none",Wt,jt]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Wt,jt]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:Q()}],"text-color":[{text:Q()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...G(),"wavy"]}],"text-decoration-thickness":[{decoration:[Xn,"from-font","auto",Wt,Bu]}],"text-decoration-color":[{decoration:Q()}],"underline-offset":[{"underline-offset":[Xn,"auto",Wt,jt]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:["px",...J()]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Wt,jt]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Wt,jt]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...P(),ER,bR]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:["auto","cover","contain",SR,MR]}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Uu,Wt,jt],radial:["",Wt,jt],conic:[Uu,Wt,jt]},AR,xR]}],"bg-color":[{bg:Q()}],"gradient-from-pos":[{from:oe()}],"gradient-via-pos":[{via:oe()}],"gradient-to-pos":[{to:oe()}],"gradient-from":[{from:Q()}],"gradient-via":[{via:Q()}],"gradient-to":[{to:Q()}],rounded:[{rounded:W()}],"rounded-s":[{"rounded-s":W()}],"rounded-e":[{"rounded-e":W()}],"rounded-t":[{"rounded-t":W()}],"rounded-r":[{"rounded-r":W()}],"rounded-b":[{"rounded-b":W()}],"rounded-l":[{"rounded-l":W()}],"rounded-ss":[{"rounded-ss":W()}],"rounded-se":[{"rounded-se":W()}],"rounded-ee":[{"rounded-ee":W()}],"rounded-es":[{"rounded-es":W()}],"rounded-tl":[{"rounded-tl":W()}],"rounded-tr":[{"rounded-tr":W()}],"rounded-br":[{"rounded-br":W()}],"rounded-bl":[{"rounded-bl":W()}],"border-w":[{border:q()}],"border-w-x":[{"border-x":q()}],"border-w-y":[{"border-y":q()}],"border-w-s":[{"border-s":q()}],"border-w-e":[{"border-e":q()}],"border-w-t":[{"border-t":q()}],"border-w-r":[{"border-r":q()}],"border-w-b":[{"border-b":q()}],"border-w-l":[{"border-l":q()}],"divide-x":[{"divide-x":q()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":q()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...G(),"hidden","none"]}],"divide-style":[{divide:[...G(),"hidden","none"]}],"border-color":[{border:Q()}],"border-color-x":[{"border-x":Q()}],"border-color-y":[{"border-y":Q()}],"border-color-s":[{"border-s":Q()}],"border-color-e":[{"border-e":Q()}],"border-color-t":[{"border-t":Q()}],"border-color-r":[{"border-r":Q()}],"border-color-b":[{"border-b":Q()}],"border-color-l":[{"border-l":Q()}],"divide-color":[{divide:Q()}],"outline-style":[{outline:[...G(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Xn,Wt,jt]}],"outline-w":[{outline:["",Xn,q_,Bu]}],"outline-color":[{outline:[n]}],shadow:[{shadow:["","none",m,CR,wR]}],"shadow-color":[{shadow:Q()}],"inset-shadow":[{"inset-shadow":["none",Wt,jt,h]}],"inset-shadow-color":[{"inset-shadow":Q()}],"ring-w":[{ring:q()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:Q()}],"ring-offset-w":[{"ring-offset":[Xn,Bu]}],"ring-offset-color":[{"ring-offset":Q()}],"inset-ring-w":[{"inset-ring":q()}],"inset-ring-color":[{"inset-ring":Q()}],opacity:[{opacity:[Xn,Wt,jt]}],"mix-blend":[{"mix-blend":[...te(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":te()}],filter:[{filter:["","none",Wt,jt]}],blur:[{blur:B()}],brightness:[{brightness:[Xn,Wt,jt]}],contrast:[{contrast:[Xn,Wt,jt]}],"drop-shadow":[{"drop-shadow":["","none",_,Wt,jt]}],grayscale:[{grayscale:["",Xn,Wt,jt]}],"hue-rotate":[{"hue-rotate":[Xn,Wt,jt]}],invert:[{invert:["",Xn,Wt,jt]}],saturate:[{saturate:[Xn,Wt,jt]}],sepia:[{sepia:["",Xn,Wt,jt]}],"backdrop-filter":[{"backdrop-filter":["","none",Wt,jt]}],"backdrop-blur":[{"backdrop-blur":B()}],"backdrop-brightness":[{"backdrop-brightness":[Xn,Wt,jt]}],"backdrop-contrast":[{"backdrop-contrast":[Xn,Wt,jt]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Xn,Wt,jt]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Xn,Wt,jt]}],"backdrop-invert":[{"backdrop-invert":["",Xn,Wt,jt]}],"backdrop-opacity":[{"backdrop-opacity":[Xn,Wt,jt]}],"backdrop-saturate":[{"backdrop-saturate":[Xn,Wt,jt]}],"backdrop-sepia":[{"backdrop-sepia":["",Xn,Wt,jt]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":J()}],"border-spacing-x":[{"border-spacing-x":J()}],"border-spacing-y":[{"border-spacing-y":J()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Wt,jt]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Xn,"initial",Wt,jt]}],ease:[{ease:["linear","initial",T,Wt,jt]}],delay:[{delay:[Xn,Wt,jt]}],animate:[{animate:["none",v,Wt,jt]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,Wt,jt]}],"perspective-origin":[{"perspective-origin":le()}],rotate:[{rotate:ye()}],"rotate-x":[{"rotate-x":ye()}],"rotate-y":[{"rotate-y":ye()}],"rotate-z":[{"rotate-z":ye()}],scale:[{scale:me()}],"scale-x":[{"scale-x":me()}],"scale-y":[{"scale-y":me()}],"scale-z":[{"scale-z":me()}],"scale-3d":["scale-3d"],skew:[{skew:xe()}],"skew-x":[{"skew-x":xe()}],"skew-y":[{"skew-y":xe()}],transform:[{transform:[Wt,jt,"","none","gpu","cpu"]}],"transform-origin":[{origin:le()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ze()}],"translate-x":[{"translate-x":ze()}],"translate-y":[{"translate-y":ze()}],"translate-z":[{"translate-z":ze()}],"translate-none":["translate-none"],accent:[{accent:Q()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:Q()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Wt,jt]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":J()}],"scroll-mx":[{"scroll-mx":J()}],"scroll-my":[{"scroll-my":J()}],"scroll-ms":[{"scroll-ms":J()}],"scroll-me":[{"scroll-me":J()}],"scroll-mt":[{"scroll-mt":J()}],"scroll-mr":[{"scroll-mr":J()}],"scroll-mb":[{"scroll-mb":J()}],"scroll-ml":[{"scroll-ml":J()}],"scroll-p":[{"scroll-p":J()}],"scroll-px":[{"scroll-px":J()}],"scroll-py":[{"scroll-py":J()}],"scroll-ps":[{"scroll-ps":J()}],"scroll-pe":[{"scroll-pe":J()}],"scroll-pt":[{"scroll-pt":J()}],"scroll-pr":[{"scroll-pr":J()}],"scroll-pb":[{"scroll-pb":J()}],"scroll-pl":[{"scroll-pl":J()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Wt,jt]}],fill:[{fill:["none",...Q()]}],"stroke-w":[{stroke:[Xn,q_,Bu,C0]}],stroke:[{stroke:["none",...Q()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["before","after","placeholder","file","marker","selection","first-line","first-letter","backdrop","*","**"]}},FR=lR(LR);function kR(...n){return FR(XP(n))}const U1=mt.forwardRef(({className:n,...e},t)=>Un.jsx("textarea",{className:kR("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 text-lg",n),ref:t,...e}));U1.displayName="Textarea";/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const NR=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),B1=(...n)=>n.filter((e,t,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===t).join(" ").trim();/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var zR={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const UR=mt.forwardRef(({color:n="currentColor",size:e=24,strokeWidth:t=2,absoluteStrokeWidth:i,className:s="",children:o,iconNode:l,...u},d)=>mt.createElement("svg",{ref:d,...zR,width:e,height:e,stroke:n,strokeWidth:i?Number(t)*24/Number(e):t,className:B1("lucide",s),...u},[...l.map(([f,m])=>mt.createElement(f,m)),...Array.isArray(o)?o:[o]]));/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const e_=(n,e)=>{const t=mt.forwardRef(({className:i,...s},o)=>mt.createElement(UR,{ref:o,iconNode:e,className:B1(`lucide-${NR(n)}`,i),...s}));return t.displayName=`${n}`,t};/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const BR=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]],$R=e_("BrainCircuit",BR);/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const VR=[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]],GR=e_("MicOff",VR);/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const jR=[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]],WR=e_("Mic",jR);/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const HR=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],qR=e_("Send",HR);/** + * @license lucide-react v0.475.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const XR=[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]],KR=e_("Trash2",XR),Og=new Map,Qu=[],YR=(n,e,t)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){const i=Og.get(n);if(i===void 0)Og.set(n,{backend:e,priority:t});else{if(i.priority>t)return;if(i.priority===t&&i.backend!==e)throw new Error(`cannot register backend "${n}" using priority ${t}`)}if(t>=0){const s=Qu.indexOf(n);s!==-1&&Qu.splice(s,1);for(let o=0;o{const e=Og.get(n);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{const t=!!e.initPromise;try{return t||(e.initPromise=e.backend.init(n)),await e.initPromise,e.initialized=!0,e.backend}catch(i){return t||(e.error=`${i}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},ZR=async n=>{const e=n.executionProviders||[],t=e.map(d=>typeof d=="string"?d:d.name),i=t.length===0?Qu:t;let s;const o=[],l=new Set;for(const d of i){const f=await QR(d);typeof f=="string"?o.push({name:d,err:f}):(s||(s=f),s===f&&l.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${o.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(const{name:d,err:f}of o)t.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${f}`);const u=e.filter(d=>l.has(typeof d=="string"?d:d.name));return[s,new Proxy(n,{get:(d,f)=>f==="executionProviders"?u:Reflect.get(d,f)})]},JR="1.21.0";let qb="warning";const Ha={wasm:{},webgl:{},webgpu:{},versions:{common:JR},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);qb=n}},get logLevel(){return qb}};Object.defineProperty(Ha,"logLevel",{enumerable:!0});const eD=Ha,tD=(n,e)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=n.dims[3],t.height=n.dims[2];const i=t.getContext("2d");if(i!=null){let s,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=n.dims[2],o=n.dims[3]):(s=n.dims[3],o=n.dims[2]);const l=e?.format!==void 0?e.format:"RGB",u=e?.norm;let d,f;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?f=[0,0,0,0]:typeof u.bias=="number"?f=[u.bias,u.bias,u.bias,u.bias]:(f=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(f[3]=u.bias[3]));const m=o*s;let h=0,_=m,g=m*2,y=-1;l==="RGBA"?(h=0,_=m,g=m*2,y=m*3):l==="RGB"?(h=0,_=m,g=m*2):l==="RBG"&&(h=0,g=m,_=m*2);for(let b=0;b{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let i;if(t!=null){let s,o,l;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=n.dims[2],o=n.dims[1],l=n.dims[3]):(s=n.dims[3],o=n.dims[2],l=n.dims[1]);const u=e!==void 0&&e.format!==void 0?e.format:"RGB",d=e?.norm;let f,m;d===void 0||d.mean===void 0?f=[255,255,255,255]:typeof d.mean=="number"?f=[d.mean,d.mean,d.mean,d.mean]:(f=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(f[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias=="number"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));const h=o*s;if(e!==void 0&&(e.format!==void 0&&l===4&&e.format!=="RGBA"||l===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const _=4;let g=0,y=1,b=2,T=3,v=0,x=h,P=h*2,w=-1;u==="RGBA"?(v=0,x=h,P=h*2,w=h*3):u==="RGB"?(v=0,x=h,P=h*2):u==="RBG"&&(v=0,P=h,x=h*2),i=t.createImageData(s,o);for(let C=0;C{if(n===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:i}=e,s=e.norm??{mean:255,bias:0};let o,l;typeof s.mean=="number"?o=[s.mean,s.mean,s.mean,s.mean]:o=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?l=[s.bias,s.bias,s.bias,s.bias]:l=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];const u=e.format!==void 0?e.format:"RGBA",d=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",f=t*i,m=d==="RGBA"?new Float32Array(f*4):new Float32Array(f*3);let h=4,_=0,g=1,y=2,b=3,T=0,v=f,x=f*2,P=-1;u==="RGB"&&(h=3,_=0,g=1,y=2,b=-1),d==="RGBA"?P=f*3:d==="RBG"?(T=0,x=f,v=f*2):d==="BGR"&&(x=0,v=f,T=f*2);for(let C=0;C{const t=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,i=typeof ImageData<"u"&&n instanceof ImageData,s=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,o=typeof n=="string";let l,u=e??{};const d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},f=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(t){const m=d();m.width=n.width,m.height=n.height;const h=f(m);if(h!=null){let _=n.height,g=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,g=e.resizedWidth),e!==void 0){if(u=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=_,u.width=g}else u.tensorFormat="RGBA",u.height=_,u.width=g;h.drawImage(n,0,0),l=h.getImageData(0,0,g,_).data}else throw new Error("Can not access image data")}else if(i){let m,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(m=e.resizedHeight,h=e.resizedWidth):(m=n.height,h=n.width),e!==void 0&&(u=e),u.format="RGBA",u.height=m,u.width=h,e!==void 0){const _=d();_.width=h,_.height=m;const g=f(_);if(g!=null)g.putImageData(n,0,0),l=g.getImageData(0,0,h,m).data;else throw new Error("Can not access image data")}else l=n.data}else if(s){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");const m=d();m.width=n.width,m.height=n.height;const h=f(m);if(h!=null){const _=n.height,g=n.width;return h.drawImage(n,0,0,g,_),l=h.getImageData(0,0,g,_).data,u.height=_,u.width=g,P0(l,u)}else throw new Error("Can not access image data")}else{if(o)return new Promise((m,h)=>{const _=d(),g=f(_);if(!n||!g)return h();const y=new Image;y.crossOrigin="Anonymous",y.src=n,y.onload=()=>{_.width=y.width,_.height=y.height,g.drawImage(y,0,0,_.width,_.height);const b=g.getImageData(0,0,_.width,_.height);u.height=_.height,u.width=_.width,m(P0(b.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(l!==void 0)return P0(l,u);throw new Error("Input data provided is not supported - aborted tensor creation")},rD=(n,e)=>{const{width:t,height:i,download:s,dispose:o}=e,l=[1,i,t,4];return new da({location:"texture",type:"float32",texture:n,dims:l,download:s,dispose:o})},sD=(n,e)=>{const{dataType:t,dims:i,download:s,dispose:o}=e;return new da({location:"gpu-buffer",type:t??"float32",gpuBuffer:n,dims:i,download:s,dispose:o})},aD=(n,e)=>{const{dataType:t,dims:i,download:s,dispose:o}=e;return new da({location:"ml-tensor",type:t??"float32",mlTensor:n,dims:i,download:s,dispose:o})},oD=(n,e,t)=>new da({location:"cpu-pinned",type:n,data:e,dims:t??[e.length]}),ih=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Lg=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Xb=!1;const lD=()=>{if(!Xb){Xb=!0;const n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,i=typeof t<"u"&&t.from;n&&(ih.set("int64",BigInt64Array),Lg.set(BigInt64Array,"int64")),e&&(ih.set("uint64",BigUint64Array),Lg.set(BigUint64Array,"uint64")),i?(ih.set("float16",t),Lg.set(t,"float16")):ih.set("float16",Uint16Array)}},cD=n=>{let e=1;for(let t=0;t{switch(n.location){case"cpu":return new da(n.type,n.data,e);case"cpu-pinned":return new da({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new da({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new da({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});case"ml-tensor":return new da({location:"ml-tensor",mlTensor:n.mlTensor,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}};let da=class{constructor(e,t,i){lD();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{const u=ih.get(s);if(!u)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof u))throw new TypeError(`buffer should be of type ${u.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let u,d;if(typeof e=="string")if(s=e,d=i,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{const f=ih.get(e);if(f===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&f===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${f.name} as data.`);e==="uint64"||e==="int64"?u=f.from(t,BigInt):u=f.from(t)}else if(t instanceof f)u=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")u=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&f!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${s} tensor's data must be type of ${f}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const f=typeof e[0];if(f==="string")s="string",u=e;else if(f==="boolean")s="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${f}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",u=Uint8Array.from(e);else{const f=Lg.get(e.constructor);if(f===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=f,u=e}if(d===void 0)d=[u.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");o=d,this.cpuData=u,this.dataLocation="cpu"}const l=cD(o);if(this.cpuData&&l!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=l}static async fromImage(e,t){return iD(e,t)}static fromTexture(e,t){return rD(e,t)}static fromGpuBuffer(e,t){return sD(e,t)}static fromMLTensor(e,t){return aD(e,t)}static fromPinnedBuffer(e,t,i){return oD(e,t,i)}toDataURL(e){return tD(this,e)}toImageData(e){return nD(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;const 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(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return uD(this,e)}};const th=da,$1=(n,e)=>{(typeof Ha.trace>"u"?!Ha.wasm.trace:!Ha.trace)||console.timeStamp(`${n}::ORT::${e}`)},V1=(n,e)=>{const t=new Error().stack?.split(/\r\n|\r|\n/g)||[];let i=!1;for(let s=0;s{(typeof Ha.trace>"u"?!Ha.wasm.trace:!Ha.trace)||V1("BEGIN",n)},py=n=>{(typeof Ha.trace>"u"?!Ha.wasm.trace:!Ha.trace)||V1("END",n)};let dD=class G1{constructor(e){this.handler=e}async run(e,t,i){hy();const s={};let o={};if(typeof e!="object"||e===null||e instanceof th||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof th)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const f of t){if(typeof f!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(f)===-1)throw new RangeError(`'fetches' contains invalid output name: ${f}.`);s[f]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let f=!1;const m=Object.getOwnPropertyNames(t);for(const h of this.outputNames)if(m.indexOf(h)!==-1){const _=t[h];(_===null||_ instanceof th)&&(f=!0,l=!1,s[h]=_)}if(f){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const f of this.inputNames)if(typeof e[f]>"u")throw new Error(`input '${f}' is missing in 'feeds'.`);if(l)for(const f of this.outputNames)s[f]=null;const u=await this.handler.run(e,s,o),d={};for(const f in u)if(Object.hasOwnProperty.call(u,f)){const m=u[f];m instanceof th?d[f]=m:d[f]=new th(m.type,m.data,m.dims)}return py(),d}async release(){return this.handler.dispose()}static async create(e,t,i,s){hy();let o,l={};if(typeof e=="string"){if(o=e,typeof t=="object"&&t!==null)l=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof t=="object"&&t!==null)l=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){const m=e;let h=0,_=e.byteLength;if(typeof t=="object"&&t!==null)l=t;else if(typeof t=="number"){if(h=t,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(_=e.byteLength-h,typeof i=="number"){if(_=i,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||h+_>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-h}].`);if(typeof s=="object"&&s!==null)l=s;else if(typeof s<"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 t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(m,h,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[u,d]=await ZR(l),f=await u.createInferenceSessionHandler(o,d);return py(),new G1(f)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const fD=dD,hD=Object.freeze(Object.defineProperty({__proto__:null,InferenceSession:fD,TRACE:$1,TRACE_FUNC_BEGIN:hy,TRACE_FUNC_END:py,Tensor:th,env:eD,registerBackend:YR},Symbol.toStringTag,{value:"Module"}));/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var xM=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,mD=Object.getOwnPropertyNames,_D=Object.prototype.hasOwnProperty,gD=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),At=(n,e)=>()=>(n&&(e=n(n=0)),e),bh=(n,e)=>{for(var t in e)xM(n,t,{get:e[t],enumerable:!0})},vD=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of mD(e))!_D.call(n,s)&&s!==t&&xM(n,s,{get:()=>e[s],enumerable:!(i=pD(e,s))||i.enumerable});return n},qm=n=>vD(xM({},"__esModule",{value:!0}),n),xm,Ec,rd,Kb,j1,W1=At(()=>{xm=new Map,Ec=[],rd=(n,e,t)=>{if(e&&typeof e.init=="function"&&typeof e.createInferenceSessionHandler=="function"){let i=xm.get(n);if(i===void 0)xm.set(n,{backend:e,priority:t});else{if(i.priority>t)return;if(i.priority===t&&i.backend!==e)throw new Error(`cannot register backend "${n}" using priority ${t}`)}if(t>=0){let s=Ec.indexOf(n);s!==-1&&Ec.splice(s,1);for(let o=0;o{let e=xm.get(n);if(!e)return"backend not found.";if(e.initialized)return e.backend;if(e.aborted)return e.error;{let t=!!e.initPromise;try{return t||(e.initPromise=e.backend.init(n)),await e.initPromise,e.initialized=!0,e.backend}catch(i){return t||(e.error=`${i}`,e.aborted=!0),e.error}finally{delete e.initPromise}}},j1=async n=>{let e=n.executionProviders||[],t=e.map(d=>typeof d=="string"?d:d.name),i=t.length===0?Ec:t,s,o=[],l=new Set;for(let d of i){let f=await Kb(d);typeof f=="string"?o.push({name:d,err:f}):(s||(s=f),s===f&&l.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${o.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:f}of o)t.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${f}`);let u=e.filter(d=>l.has(typeof d=="string"?d:d.name));return[s,new Proxy(n,{get:(d,f)=>f==="executionProviders"?u:Reflect.get(d,f)})]}}),yD=At(()=>{W1()}),H1,MD=At(()=>{H1="1.22.0-dev.20250409-89f8206ba4"}),R0,la,q1=At(()=>{MD(),R0="warning",la={wasm:{},webgl:{},webgpu:{},versions:{common:H1},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);R0=n}},get logLevel(){return R0}},Object.defineProperty(la,"logLevel",{enumerable:!0})}),Di,bD=At(()=>{q1(),Di=la}),X1,K1,xD=At(()=>{X1=(n,e)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=n.dims[3],t.height=n.dims[2];let i=t.getContext("2d");if(i!=null){let s,o;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=n.dims[2],o=n.dims[3]):(s=n.dims[3],o=n.dims[2]);let l=e?.format!==void 0?e.format:"RGB",u=e?.norm,d,f;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?f=[0,0,0,0]:typeof u.bias=="number"?f=[u.bias,u.bias,u.bias,u.bias]:(f=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(f[3]=u.bias[3]));let m=o*s,h=0,_=m,g=m*2,y=-1;l==="RGBA"?(h=0,_=m,g=m*2,y=m*3):l==="RGB"?(h=0,_=m,g=m*2):l==="RBG"&&(h=0,g=m,_=m*2);for(let b=0;b{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(t!=null){let s,o,l;e?.tensorLayout!==void 0&&e.tensorLayout==="NHWC"?(s=n.dims[2],o=n.dims[1],l=n.dims[3]):(s=n.dims[3],o=n.dims[2],l=n.dims[1]);let u=e!==void 0&&e.format!==void 0?e.format:"RGB",d=e?.norm,f,m;d===void 0||d.mean===void 0?f=[255,255,255,255]:typeof d.mean=="number"?f=[d.mean,d.mean,d.mean,d.mean]:(f=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(f[3]=d.mean[3])),d===void 0||d.bias===void 0?m=[0,0,0,0]:typeof d.bias=="number"?m=[d.bias,d.bias,d.bias,d.bias]:(m=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(m[3]=d.bias[3]));let h=o*s;if(e!==void 0&&(e.format!==void 0&&l===4&&e.format!=="RGBA"||l===3&&e.format!=="RGB"&&e.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let _=4,g=0,y=1,b=2,T=3,v=0,x=h,P=h*2,w=-1;u==="RGBA"?(v=0,x=h,P=h*2,w=h*3):u==="RGB"?(v=0,x=h,P=h*2):u==="RBG"&&(v=0,P=h,x=h*2),i=t.createImageData(s,o);for(let C=0;C{wM(),X_=(n,e)=>{if(n===void 0)throw new Error("Image buffer must be defined");if(e.height===void 0||e.width===void 0)throw new Error("Image height and width must be defined");if(e.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:i}=e,s=e.norm??{mean:255,bias:0},o,l;typeof s.mean=="number"?o=[s.mean,s.mean,s.mean,s.mean]:o=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?l=[s.bias,s.bias,s.bias,s.bias]:l=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=e.format!==void 0?e.format:"RGBA",d=e.tensorFormat!==void 0&&e.tensorFormat!==void 0?e.tensorFormat:"RGB",f=t*i,m=d==="RGBA"?new Float32Array(f*4):new Float32Array(f*3),h=4,_=0,g=1,y=2,b=3,T=0,v=f,x=f*2,P=-1;u==="RGB"&&(h=3,_=0,g=1,y=2,b=-1),d==="RGBA"?P=f*3:d==="RBG"?(T=0,x=f,v=f*2):d==="BGR"&&(x=0,v=f,T=f*2);for(let w=0;w{let t=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,i=typeof ImageData<"u"&&n instanceof ImageData,s=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,o=typeof n=="string",l,u=e??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},f=m=>typeof HTMLCanvasElement<"u"&&m instanceof HTMLCanvasElement||m instanceof OffscreenCanvas?m.getContext("2d"):null;if(t){let m=d();m.width=n.width,m.height=n.height;let h=f(m);if(h!=null){let _=n.height,g=n.width;if(e!==void 0&&e.resizedHeight!==void 0&&e.resizedWidth!==void 0&&(_=e.resizedHeight,g=e.resizedWidth),e!==void 0){if(u=e,e.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=_,u.width=g}else u.tensorFormat="RGBA",u.height=_,u.width=g;h.drawImage(n,0,0),l=h.getImageData(0,0,g,_).data}else throw new Error("Can not access image data")}else if(i){let m,h;if(e!==void 0&&e.resizedWidth!==void 0&&e.resizedHeight!==void 0?(m=e.resizedHeight,h=e.resizedWidth):(m=n.height,h=n.width),e!==void 0&&(u=e),u.format="RGBA",u.height=m,u.width=h,e!==void 0){let _=d();_.width=h,_.height=m;let g=f(_);if(g!=null)g.putImageData(n,0,0),l=g.getImageData(0,0,h,m).data;else throw new Error("Can not access image data")}else l=n.data}else if(s){if(e===void 0)throw new Error("Please provide image config with format for Imagebitmap");let m=d();m.width=n.width,m.height=n.height;let h=f(m);if(h!=null){let _=n.height,g=n.width;return h.drawImage(n,0,0,g,_),l=h.getImageData(0,0,g,_).data,u.height=_,u.width=g,X_(l,u)}else throw new Error("Can not access image data")}else{if(o)return new Promise((m,h)=>{let _=d(),g=f(_);if(!n||!g)return h();let y=new Image;y.crossOrigin="Anonymous",y.src=n,y.onload=()=>{_.width=y.width,_.height=y.height,g.drawImage(y,0,0,_.width,_.height);let b=g.getImageData(0,0,_.width,_.height);u.height=_.height,u.width=_.width,m(X_(b.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(l!==void 0)return X_(l,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Q1=(n,e)=>{let{width:t,height:i,download:s,dispose:o}=e,l=[1,i,t,4];return new Is({location:"texture",type:"float32",texture:n,dims:l,download:s,dispose:o})},Z1=(n,e)=>{let{dataType:t,dims:i,download:s,dispose:o}=e;return new Is({location:"gpu-buffer",type:t??"float32",gpuBuffer:n,dims:i,download:s,dispose:o})},J1=(n,e)=>{let{dataType:t,dims:i,download:s,dispose:o}=e;return new Is({location:"ml-tensor",type:t??"float32",mlTensor:n,dims:i,download:s,dispose:o})},eS=(n,e,t)=>new Is({location:"cpu-pinned",type:n,data:e,dims:t??[e.length]})}),ed,zm,D0,tS,TD=At(()=>{ed=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),zm=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),D0=!1,tS=()=>{if(!D0){D0=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,e=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,i=typeof t<"u"&&t.from;n&&(ed.set("int64",BigInt64Array),zm.set(BigInt64Array,"int64")),e&&(ed.set("uint64",BigUint64Array),zm.set(BigUint64Array,"uint64")),i?(ed.set("float16",t),zm.set(t,"float16")):ed.set("float16",Uint16Array)}}}),nS,iS,ED=At(()=>{wM(),nS=n=>{let e=1;for(let t=0;t{switch(n.location){case"cpu":return new Is(n.type,n.data,e);case"cpu-pinned":return new Is({location:"cpu-pinned",data:n.data,type:n.type,dims:e});case"texture":return new Is({location:"texture",texture:n.texture,type:n.type,dims:e});case"gpu-buffer":return new Is({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:e});case"ml-tensor":return new Is({location:"ml-tensor",mlTensor:n.mlTensor,type:n.type,dims:e});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}}),Is,wM=At(()=>{xD(),wD(),TD(),ED(),Is=class{constructor(n,e,t){tS();let i,s;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,i=n.type,s=n.dims,n.location){case"cpu-pinned":{let l=ed.get(i);if(!l)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(n.data instanceof l))throw new TypeError(`buffer should be of type ${l.name}`);this.cpuData=n.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=n.mlTensor,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let l,u;if(typeof n=="string")if(i=n,u=t,n==="string"){if(!Array.isArray(e))throw new TypeError("A string tensor's data must be a string array.");l=e}else{let d=ed.get(n);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(e)){if(n==="float16"&&d===Uint16Array||n==="uint4"||n==="int4")throw new TypeError(`Creating a ${n} tensor from number array is not supported. Please use ${d.name} as data.`);n==="uint64"||n==="int64"?l=d.from(e,BigInt):l=d.from(e)}else if(e instanceof d)l=e;else if(e instanceof Uint8ClampedArray)if(n==="uint8")l=Uint8Array.from(e);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(n==="float16"&&e instanceof Uint16Array&&d!==Uint16Array)l=new globalThis.Float16Array(e.buffer,e.byteOffset,e.length);else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(u=e,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof n[0];if(d==="string")i="string",l=n;else if(d==="boolean")i="bool",l=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(n instanceof Uint8ClampedArray)i="uint8",l=Uint8Array.from(n);else{let d=zm.get(n.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);i=d,l=n}if(u===void 0)u=[l.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=l,this.dataLocation="cpu"}let o=nS(s);if(this.cpuData&&o!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=s,this.size=o}static async fromImage(n,e){return Y1(n,e)}static fromTexture(n,e){return Q1(n,e)}static fromGpuBuffer(n,e){return Z1(n,e)}static fromMLTensor(n,e){return J1(n,e)}static fromPinnedBuffer(n,e,t){return eS(n,e,t)}toDataURL(n){return X1(this,n)}toImageData(n){return K1(this,n)}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(n){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 e=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=e,n&&this.disposer&&(this.disposer(),this.disposer=void 0),e}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return iS(this,n)}}}),Ga,rS=At(()=>{wM(),Ga=Is}),Xm,I0,Xa,fa,sS=At(()=>{q1(),Xm=(n,e)=>{(typeof la.trace>"u"?!la.wasm.trace:!la.trace)||console.timeStamp(`${n}::ORT::${e}`)},I0=(n,e)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let s=0;s{(typeof la.trace>"u"?!la.wasm.trace:!la.trace)||I0("BEGIN",n)},fa=n=>{(typeof la.trace>"u"?!la.wasm.trace:!la.trace)||I0("END",n)}}),aS,SD=At(()=>{W1(),rS(),sS(),aS=class oS{constructor(e){this.handler=e}async run(e,t,i){Xa();let s={},o={};if(typeof e!="object"||e===null||e instanceof Ga||Array.isArray(e))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Ga)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let f of t){if(typeof f!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(f)===-1)throw new RangeError(`'fetches' contains invalid output name: ${f}.`);s[f]=null}if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let f=!1,m=Object.getOwnPropertyNames(t);for(let h of this.outputNames)if(m.indexOf(h)!==-1){let _=t[h];(_===null||_ instanceof Ga)&&(f=!0,l=!1,s[h]=_)}if(f){if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let f of this.inputNames)if(typeof e[f]>"u")throw new Error(`input '${f}' is missing in 'feeds'.`);if(l)for(let f of this.outputNames)s[f]=null;let u=await this.handler.run(e,s,o),d={};for(let f in u)if(Object.hasOwnProperty.call(u,f)){let m=u[f];m instanceof Ga?d[f]=m:d[f]=new Ga(m.type,m.data,m.dims)}return fa(),d}async release(){return this.handler.dispose()}static async create(e,t,i,s){Xa();let o,l={};if(typeof e=="string"){if(o=e,typeof t=="object"&&t!==null)l=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof Uint8Array){if(o=e,typeof t=="object"&&t!==null)l=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer){let m=e,h=0,_=e.byteLength;if(typeof t=="object"&&t!==null)l=t;else if(typeof t=="number"){if(h=t,!Number.isSafeInteger(h))throw new RangeError("'byteOffset' must be an integer.");if(h<0||h>=m.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${m.byteLength}).`);if(_=e.byteLength-h,typeof i=="number"){if(_=i,!Number.isSafeInteger(_))throw new RangeError("'byteLength' must be an integer.");if(_<=0||h+_>m.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${m.byteLength-h}].`);if(typeof s=="object"&&s!==null)l=s;else if(typeof s<"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 t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(m,h,_)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await j1(l),f=await u.createInferenceSessionHandler(o,d);return fa(),new oS(f)}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}}}),TM,AD=At(()=>{SD(),TM=aS}),CD=At(()=>{}),PD=At(()=>{}),RD=At(()=>{}),DD=At(()=>{}),lS={};bh(lS,{InferenceSession:()=>TM,TRACE:()=>Xm,TRACE_FUNC_BEGIN:()=>Xa,TRACE_FUNC_END:()=>fa,Tensor:()=>Ga,env:()=>Di,registerBackend:()=>rd});var Ka=At(()=>{yD(),bD(),AD(),rS(),CD(),PD(),sS(),RD(),DD()}),EM=At(()=>{}),cS={};bh(cS,{default:()=>uS});var O0,L0,uS,ID=At(()=>{mC(),fd(),SM(),O0="ort-wasm-proxy-worker",L0=globalThis.self?.name===O0,L0&&(self.onmessage=n=>{let{type:e,in:t}=n.data;try{switch(e){case"init-wasm":AM(t.wasm).then(()=>{WM(t).then(()=>{postMessage({type:e})},i=>{postMessage({type:e,err:i})})},i=>{postMessage({type:e,err:i})});break;case"init-ep":{let{epName:i,env:s}=t;HM(s,i).then(()=>{postMessage({type:e})},o=>{postMessage({type:e,err:o})});break}case"copy-from":{let{buffer:i}=t,s=Yg(i);postMessage({type:e,out:s});break}case"create":{let{model:i,options:s}=t;qM(i,s).then(o=>{postMessage({type:e,out:o})},o=>{postMessage({type:e,err:o})});break}case"release":XM(t),postMessage({type:e});break;case"run":{let{sessionId:i,inputIndices:s,inputs:o,outputIndices:l,options:u}=t;KM(i,s,o,l,new Array(l.length).fill(null),u).then(d=>{d.some(f=>f[3]!=="cpu")?postMessage({type:e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:e,out:d},QM([...o,...d]))},d=>{postMessage({type:e,err:d})});break}case"end-profiling":YM(t),postMessage({type:e});break;default:}}catch(i){postMessage({type:e,err:i})}}),uS=L0?null:n=>new Worker(n??Ds,{type:"module",name:O0})}),dS={};bh(dS,{default:()=>fS});var F0,k0,fS,Yb,OD=At(()=>{k0=(F0=import.meta.url,async function(n={}){var e,t,i=n,s=new Promise((S,z)=>{e=S,t=z}),o=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&self.name?.startsWith("em-pthread");i.mountExternalData=(S,z)=>{S.startsWith("./")&&(S=S.substring(2)),(i.Eb||(i.Eb=new Map)).set(S,z)},i.unmountExternalData=()=>{delete i.Eb};var d=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let f=S=>async(...z)=>{try{if(i.Fb)throw Error("Session already started");let Y=i.Fb={dc:z[0],errors:[]},ie=await S(...z);if(i.Fb!==Y)throw Error("Session mismatch");i.Jb?.flush();let pe=Y.errors;if(0rt),0{if(S==="webgpu"){[i.Jb,i.Ub,i.Yb,i.Kb,i.Xb,i.jb,i.Zb,i.ac,i.Vb,i.Wb,i.$b]=z;let Y=i.Jb;i.jsepRegisterBuffer=(ie,pe,Ae,rt)=>Y.registerBuffer(ie,pe,Ae,rt),i.jsepGetBuffer=ie=>Y.getBuffer(ie),i.jsepCreateDownloader=(ie,pe,Ae)=>Y.createDownloader(ie,pe,Ae),i.jsepOnCreateSession=ie=>{Y.onCreateSession(ie)},i.jsepOnReleaseSession=ie=>{Y.onReleaseSession(ie)},i.jsepOnRunStart=ie=>Y.onRunStart(ie),i.bc=(ie,pe)=>{Y.upload(ie,pe)}}else if(S==="webnn"){let Y=z[0];[i.nc,i.Nb,i.webnnEnsureTensor,i.Ob,i.webnnDownloadTensor]=z.slice(1),i.webnnReleaseTensorId=i.Nb,i.webnnUploadTensor=i.Ob,i.webnnOnRunStart=ie=>Y.onRunStart(ie),i.webnnOnRunEnd=Y.onRunEnd.bind(Y),i.webnnRegisterMLContext=(ie,pe)=>{Y.registerMLContext(ie,pe)},i.webnnOnReleaseSession=ie=>{Y.onReleaseSession(ie)},i.webnnCreateMLTensorDownloader=(ie,pe)=>Y.createMLTensorDownloader(ie,pe),i.webnnRegisterMLTensor=(ie,pe,Ae,rt)=>Y.registerMLTensor(ie,pe,Ae,rt),i.webnnCreateMLContext=ie=>Y.createMLContext(ie),i.webnnRegisterMLConstant=(ie,pe,Ae,rt,Mt,kt)=>Y.registerMLConstant(ie,pe,Ae,rt,Mt,i.Eb,kt),i.webnnRegisterGraphInput=Y.registerGraphInput.bind(Y),i.webnnIsGraphInput=Y.isGraphInput.bind(Y),i.webnnCreateTemporaryTensor=Y.createTemporaryTensor.bind(Y),i.webnnIsInt64Supported=Y.isInt64Supported.bind(Y)}};let m=()=>{let S=(z,Y,ie)=>(...pe)=>{let Ae=Oi,rt=Y?.();pe=z(...pe);let Mt=Y?.();return rt!==Mt&&(z=Mt,ie(rt),Y=ie=null),Oi!=Ae?new Promise((kt,Gt)=>{Ki={resolve:kt,reject:Gt}}):pe};(()=>{for(let z of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])i[z]=S(i[z],()=>i[z],Y=>i[z]=Y)})(),f!==void 0&&(i._OrtRun=f(i._OrtRun),i._OrtRunWithBinding=f(i._OrtRunWithBinding)),m=void 0};i.asyncInit=()=>{m?.()};var h,_,g=Object.assign({},i),y=(S,z)=>{throw z},b="";(o||l)&&(l?b=self.location.href:typeof document<"u"&&document.currentScript&&(b=document.currentScript.src),F0&&(b=F0),b=b.startsWith("blob:")?"":b.slice(0,b.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(_=S=>{var z=new XMLHttpRequest;return z.open("GET",S,!1),z.responseType="arraybuffer",z.send(null),new Uint8Array(z.response)}),h=async S=>{if(oe(S))return new Promise((Y,ie)=>{var pe=new XMLHttpRequest;pe.open("GET",S,!0),pe.responseType="arraybuffer",pe.onload=()=>{pe.status==200||pe.status==0&&pe.response?Y(pe.response):ie(pe.status)},pe.onerror=ie,pe.send(null)});var z=await fetch(S,{credentials:"same-origin"});if(z.ok)return z.arrayBuffer();throw Error(z.status+" : "+z.url)});var T=console.log.bind(console),v=console.error.bind(console),x=T,P=v;Object.assign(i,g),g=null;var w,C,E,A,L,I,O,H,Z,$,J,ee,X,ne=i.wasmBinary,Q=!1,oe=S=>S.startsWith("file://");function W(){return w.buffer!=A.buffer&&Me(),A}function q(){return w.buffer!=A.buffer&&Me(),L}function G(){return w.buffer!=A.buffer&&Me(),I}function te(){return w.buffer!=A.buffer&&Me(),O}function B(){return w.buffer!=A.buffer&&Me(),H}function le(){return w.buffer!=A.buffer&&Me(),Z}function ye(){return w.buffer!=A.buffer&&Me(),$}function me(){return w.buffer!=A.buffer&&Me(),X}if(u){let S=function(z){try{var Y=z.data,ie=Y.Bb;if(ie==="load"){let pe=[];self.onmessage=Ae=>pe.push(Ae),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let Ae of pe)S(Ae);self.onmessage=S};for(let Ae of Y.Rb)i[Ae]&&!i[Ae].proxy||(i[Ae]=(...rt)=>{postMessage({Bb:"callHandler",Qb:Ae,args:rt})},Ae=="print"&&(x=i[Ae]),Ae=="printErr"&&(P=i[Ae]));w=Y.kc,Me(),xe(Y.lc)}else if(ie==="run"){mn(Y.Ab),mr(Y.Ab,0,0,1,0,0),nt(),Te(Y.Ab),ze||(Bl(),ze=!0);try{Se(Y.fc,Y.Hb)}catch(pe){if(pe!="unwind")throw pe}}else Y.target!=="setimmediate"&&(ie==="checkMailbox"?ze&&Be():ie&&(P(`worker: received unknown command ${ie}`),P(Y)))}catch(pe){throw va(),pe}};var xe,ze=!1;P=function(...z){z=z.join(" "),console.error(z)},self.alert=function(...z){postMessage({Bb:"alert",text:z.join(" "),ic:Fo()})},self.onunhandledrejection=z=>{throw z.reason||z},self.onmessage=S}function Me(){var S=w.buffer;i.HEAP8=A=new Int8Array(S),i.HEAP16=I=new Int16Array(S),i.HEAPU8=L=new Uint8Array(S),i.HEAPU16=O=new Uint16Array(S),i.HEAP32=H=new Int32Array(S),i.HEAPU32=Z=new Uint32Array(S),i.HEAPF32=$=new Float32Array(S),i.HEAPF64=X=new Float64Array(S),i.HEAP64=J=new BigInt64Array(S),i.HEAPU64=ee=new BigUint64Array(S)}function ce(){u?startWorker(i):Xt.Ca()}u||(w=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Me());var ae,we=0,re=null;function He(){if(--we==0&&re){var S=re;re=null,S()}}function Ne(S){throw P(S="Aborted("+S+")"),Q=!0,S=new WebAssembly.RuntimeError(S+". Build with -sASSERTIONS for more info."),t(S),S}function We(){return{a:{L:Ke,Aa:st,b:Ze,$:yt,A:tn,pa:rn,X:vi,Z:On,qa:ut,na:It,ga:Bt,ma:Vi,J:rr,Y:ri,V:Ti,oa:Er,W:zr,va:Ur,E:qe,Q:Fe,O:yn,D:Jn,u:Ln,r:dn,P:nn,z:Pe,R:V,ja:fe,T:lt,aa:Lt,M:Ft,F:Dt,ia:Te,sa:Cn,t:Gi,Ba:ci,w:Ci,o:Yi,l:Pi,c:Nt,n:Ya,j:Do,v:pa,p:pd,f:md,s:_d,m:Dl,e:gd,k:$c,i:vd,g:yd,d:Vc,da:Gc,ea:Th,fa:Ll,ba:Fl,ca:Wc,N:qc,xa:Md,ua:xd,h:Nl,C:Kc,G:wd,ta:bd,x:Io,ra:Zr,U:Td,q:Hc,y:Ed,K:Yc,S:Sd,za:Ad,ya:Cd,ka:ma,la:_a,_:Ee,B:Qc,I:ga,ha:Ul,H:eo,a:w,wa:Ce}}}var ke={829644:(S,z,Y,ie,pe)=>{if(i===void 0||!i.Eb)return 1;if((S=Pt(Number(S>>>0))).startsWith("./")&&(S=S.substring(2)),!(S=i.Eb.get(S)))return 2;if(z=Number(z>>>0),Y=Number(Y>>>0),ie=Number(ie>>>0),z+Y>S.byteLength)return 3;try{let Ae=S.subarray(z,z+Y);switch(pe){case 0:q().set(Ae,ie>>>0);break;case 1:i.mc?i.mc(ie,Ae):i.bc(ie,Ae);break;default:return 4}return 0}catch{return 4}},830468:(S,z,Y)=>{i.Ob(S,q().subarray(z>>>0,z+Y>>>0))},830532:()=>i.nc(),830574:S=>{i.Nb(S)},830611:()=>{i.Vb()},830642:()=>{i.Wb()},830671:()=>{i.$b()},830696:S=>i.Ub(S),830729:S=>i.Yb(S),830761:(S,z,Y)=>{i.Kb(Number(S),Number(z),Number(Y),!0)},830824:(S,z,Y)=>{i.Kb(Number(S),Number(z),Number(Y))},830881:()=>typeof wasmOffsetConverter<"u",830938:S=>{i.jb("Abs",S,void 0)},830989:S=>{i.jb("Neg",S,void 0)},831040:S=>{i.jb("Floor",S,void 0)},831093:S=>{i.jb("Ceil",S,void 0)},831145:S=>{i.jb("Reciprocal",S,void 0)},831203:S=>{i.jb("Sqrt",S,void 0)},831255:S=>{i.jb("Exp",S,void 0)},831306:S=>{i.jb("Erf",S,void 0)},831357:S=>{i.jb("Sigmoid",S,void 0)},831412:(S,z,Y)=>{i.jb("HardSigmoid",S,{alpha:z,beta:Y})},831491:S=>{i.jb("Log",S,void 0)},831542:S=>{i.jb("Sin",S,void 0)},831593:S=>{i.jb("Cos",S,void 0)},831644:S=>{i.jb("Tan",S,void 0)},831695:S=>{i.jb("Asin",S,void 0)},831747:S=>{i.jb("Acos",S,void 0)},831799:S=>{i.jb("Atan",S,void 0)},831851:S=>{i.jb("Sinh",S,void 0)},831903:S=>{i.jb("Cosh",S,void 0)},831955:S=>{i.jb("Asinh",S,void 0)},832008:S=>{i.jb("Acosh",S,void 0)},832061:S=>{i.jb("Atanh",S,void 0)},832114:S=>{i.jb("Tanh",S,void 0)},832166:S=>{i.jb("Not",S,void 0)},832217:(S,z,Y)=>{i.jb("Clip",S,{min:z,max:Y})},832286:S=>{i.jb("Clip",S,void 0)},832338:(S,z)=>{i.jb("Elu",S,{alpha:z})},832396:S=>{i.jb("Gelu",S,void 0)},832448:S=>{i.jb("Relu",S,void 0)},832500:(S,z)=>{i.jb("LeakyRelu",S,{alpha:z})},832564:(S,z)=>{i.jb("ThresholdedRelu",S,{alpha:z})},832634:(S,z)=>{i.jb("Cast",S,{to:z})},832692:S=>{i.jb("Add",S,void 0)},832743:S=>{i.jb("Sub",S,void 0)},832794:S=>{i.jb("Mul",S,void 0)},832845:S=>{i.jb("Div",S,void 0)},832896:S=>{i.jb("Pow",S,void 0)},832947:S=>{i.jb("Equal",S,void 0)},833e3:S=>{i.jb("Greater",S,void 0)},833055:S=>{i.jb("GreaterOrEqual",S,void 0)},833117:S=>{i.jb("Less",S,void 0)},833169:S=>{i.jb("LessOrEqual",S,void 0)},833228:(S,z,Y,ie,pe)=>{i.jb("ReduceMean",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},833403:(S,z,Y,ie,pe)=>{i.jb("ReduceMax",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},833577:(S,z,Y,ie,pe)=>{i.jb("ReduceMin",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},833751:(S,z,Y,ie,pe)=>{i.jb("ReduceProd",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},833926:(S,z,Y,ie,pe)=>{i.jb("ReduceSum",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},834100:(S,z,Y,ie,pe)=>{i.jb("ReduceL1",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},834273:(S,z,Y,ie,pe)=>{i.jb("ReduceL2",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},834446:(S,z,Y,ie,pe)=>{i.jb("ReduceLogSum",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},834623:(S,z,Y,ie,pe)=>{i.jb("ReduceSumSquare",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},834803:(S,z,Y,ie,pe)=>{i.jb("ReduceLogSumExp",S,{keepDims:!!z,noopWithEmptyAxes:!!Y,axes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},834983:S=>{i.jb("Where",S,void 0)},835036:(S,z,Y)=>{i.jb("Transpose",S,{perm:z?Array.from(B().subarray(Number(z)>>>0,Number(Y)>>>0)):[]})},835160:(S,z,Y,ie)=>{i.jb("DepthToSpace",S,{blocksize:z,mode:Pt(Y),format:ie?"NHWC":"NCHW"})},835293:(S,z,Y,ie)=>{i.jb("DepthToSpace",S,{blocksize:z,mode:Pt(Y),format:ie?"NHWC":"NCHW"})},835426:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn,$r)=>{i.jb("ConvTranspose",S,{format:kt?"NHWC":"NCHW",autoPad:z,dilations:[Y],group:ie,kernelShape:[pe],pads:[Ae,rt],strides:[Mt],wIsConst:()=>!!W()[Gt>>>0],outputPadding:hn?Array.from(B().subarray(Number(hn)>>>0,Number(Fn)>>>0)):[],outputShape:wn?Array.from(B().subarray(Number(wn)>>>0,Number(Qn)>>>0)):[],activation:Pt($r)})},835859:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn)=>{i.jb("ConvTranspose",S,{format:Mt?"NHWC":"NCHW",autoPad:z,dilations:Array.from(B().subarray(Number(Y)>>>0,2+(Number(Y)>>>0)>>>0)),group:ie,kernelShape:Array.from(B().subarray(Number(pe)>>>0,2+(Number(pe)>>>0)>>>0)),pads:Array.from(B().subarray(Number(Ae)>>>0,4+(Number(Ae)>>>0)>>>0)),strides:Array.from(B().subarray(Number(rt)>>>0,2+(Number(rt)>>>0)>>>0)),wIsConst:()=>!!W()[kt>>>0],outputPadding:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],outputShape:Fn?Array.from(B().subarray(Number(Fn)>>>0,Number(wn)>>>0)):[],activation:Pt(Qn)})},836520:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn,$r)=>{i.jb("ConvTranspose",S,{format:kt?"NHWC":"NCHW",autoPad:z,dilations:[Y],group:ie,kernelShape:[pe],pads:[Ae,rt],strides:[Mt],wIsConst:()=>!!W()[Gt>>>0],outputPadding:hn?Array.from(B().subarray(Number(hn)>>>0,Number(Fn)>>>0)):[],outputShape:wn?Array.from(B().subarray(Number(wn)>>>0,Number(Qn)>>>0)):[],activation:Pt($r)})},836953:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn)=>{i.jb("ConvTranspose",S,{format:Mt?"NHWC":"NCHW",autoPad:z,dilations:Array.from(B().subarray(Number(Y)>>>0,2+(Number(Y)>>>0)>>>0)),group:ie,kernelShape:Array.from(B().subarray(Number(pe)>>>0,2+(Number(pe)>>>0)>>>0)),pads:Array.from(B().subarray(Number(Ae)>>>0,4+(Number(Ae)>>>0)>>>0)),strides:Array.from(B().subarray(Number(rt)>>>0,2+(Number(rt)>>>0)>>>0)),wIsConst:()=>!!W()[kt>>>0],outputPadding:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],outputShape:Fn?Array.from(B().subarray(Number(Fn)>>>0,Number(wn)>>>0)):[],activation:Pt(Qn)})},837614:(S,z)=>{i.jb("GlobalAveragePool",S,{format:z?"NHWC":"NCHW"})},837705:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn)=>{i.jb("AveragePool",S,{format:Qn?"NHWC":"NCHW",auto_pad:z,ceil_mode:Y,count_include_pad:ie,storage_order:pe,dilations:Ae?Array.from(B().subarray(Number(Ae)>>>0,Number(rt)>>>0)):[],kernel_shape:Mt?Array.from(B().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],pads:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],strides:Fn?Array.from(B().subarray(Number(Fn)>>>0,Number(wn)>>>0)):[]})},838184:(S,z)=>{i.jb("GlobalAveragePool",S,{format:z?"NHWC":"NCHW"})},838275:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn)=>{i.jb("AveragePool",S,{format:Qn?"NHWC":"NCHW",auto_pad:z,ceil_mode:Y,count_include_pad:ie,storage_order:pe,dilations:Ae?Array.from(B().subarray(Number(Ae)>>>0,Number(rt)>>>0)):[],kernel_shape:Mt?Array.from(B().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],pads:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],strides:Fn?Array.from(B().subarray(Number(Fn)>>>0,Number(wn)>>>0)):[]})},838754:(S,z)=>{i.jb("GlobalMaxPool",S,{format:z?"NHWC":"NCHW"})},838841:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn)=>{i.jb("MaxPool",S,{format:Qn?"NHWC":"NCHW",auto_pad:z,ceil_mode:Y,count_include_pad:ie,storage_order:pe,dilations:Ae?Array.from(B().subarray(Number(Ae)>>>0,Number(rt)>>>0)):[],kernel_shape:Mt?Array.from(B().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],pads:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],strides:Fn?Array.from(B().subarray(Number(Fn)>>>0,Number(wn)>>>0)):[]})},839316:(S,z)=>{i.jb("GlobalMaxPool",S,{format:z?"NHWC":"NCHW"})},839403:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn)=>{i.jb("MaxPool",S,{format:Qn?"NHWC":"NCHW",auto_pad:z,ceil_mode:Y,count_include_pad:ie,storage_order:pe,dilations:Ae?Array.from(B().subarray(Number(Ae)>>>0,Number(rt)>>>0)):[],kernel_shape:Mt?Array.from(B().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],pads:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],strides:Fn?Array.from(B().subarray(Number(Fn)>>>0,Number(wn)>>>0)):[]})},839878:(S,z,Y,ie,pe)=>{i.jb("Gemm",S,{alpha:z,beta:Y,transA:ie,transB:pe})},839982:S=>{i.jb("MatMul",S,void 0)},840036:(S,z,Y,ie)=>{i.jb("ArgMax",S,{keepDims:!!z,selectLastIndex:!!Y,axis:ie})},840144:(S,z,Y,ie)=>{i.jb("ArgMin",S,{keepDims:!!z,selectLastIndex:!!Y,axis:ie})},840252:(S,z)=>{i.jb("Softmax",S,{axis:z})},840315:(S,z)=>{i.jb("Concat",S,{axis:z})},840375:(S,z,Y,ie,pe)=>{i.jb("Split",S,{axis:z,numOutputs:Y,splitSizes:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},840531:S=>{i.jb("Expand",S,void 0)},840585:(S,z)=>{i.jb("Gather",S,{axis:Number(z)})},840656:(S,z)=>{i.jb("GatherElements",S,{axis:Number(z)})},840735:(S,z)=>{i.jb("GatherND",S,{batch_dims:Number(z)})},840814:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn)=>{i.jb("Resize",S,{antialias:z,axes:Y?Array.from(B().subarray(Number(Y)>>>0,Number(ie)>>>0)):[],coordinateTransformMode:Pt(pe),cubicCoeffA:Ae,excludeOutside:rt,extrapolationValue:Mt,keepAspectRatioPolicy:Pt(kt),mode:Pt(Gt),nearestMode:Pt(hn)})},841176:(S,z,Y,ie,pe,Ae,rt)=>{i.jb("Slice",S,{starts:z?Array.from(B().subarray(Number(z)>>>0,Number(Y)>>>0)):[],ends:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[],axes:Ae?Array.from(B().subarray(Number(Ae)>>>0,Number(rt)>>>0)):[]})},841440:S=>{i.jb("Tile",S,void 0)},841492:(S,z,Y)=>{i.jb("InstanceNormalization",S,{epsilon:z,format:Y?"NHWC":"NCHW"})},841606:(S,z,Y)=>{i.jb("InstanceNormalization",S,{epsilon:z,format:Y?"NHWC":"NCHW"})},841720:S=>{i.jb("Range",S,void 0)},841773:(S,z)=>{i.jb("Einsum",S,{equation:Pt(z)})},841854:(S,z,Y,ie,pe)=>{i.jb("Pad",S,{mode:z,value:Y,pads:ie?Array.from(B().subarray(Number(ie)>>>0,Number(pe)>>>0)):[]})},841997:(S,z,Y,ie,pe,Ae)=>{i.jb("BatchNormalization",S,{epsilon:z,momentum:Y,spatial:!!pe,trainingMode:!!ie,format:Ae?"NHWC":"NCHW"})},842166:(S,z,Y,ie,pe,Ae)=>{i.jb("BatchNormalization",S,{epsilon:z,momentum:Y,spatial:!!pe,trainingMode:!!ie,format:Ae?"NHWC":"NCHW"})},842335:(S,z,Y)=>{i.jb("CumSum",S,{exclusive:Number(z),reverse:Number(Y)})},842432:(S,z,Y)=>{i.jb("DequantizeLinear",S,{axis:z,blockSize:Y})},842522:(S,z,Y,ie,pe)=>{i.jb("GridSample",S,{align_corners:z,mode:Pt(Y),padding_mode:Pt(ie),format:pe?"NHWC":"NCHW"})},842692:(S,z,Y,ie,pe)=>{i.jb("GridSample",S,{align_corners:z,mode:Pt(Y),padding_mode:Pt(ie),format:pe?"NHWC":"NCHW"})},842862:(S,z)=>{i.jb("ScatterND",S,{reduction:Pt(z)})},842947:(S,z,Y,ie,pe,Ae,rt,Mt,kt)=>{i.jb("Attention",S,{numHeads:z,isUnidirectional:Y,maskFilterValue:ie,scale:pe,doRotary:Ae,qkvHiddenSizes:rt?Array.from(B().subarray(Number(Mt)>>>0,Number(Mt)+rt>>>0)):[],pastPresentShareBuffer:!!kt})},843219:S=>{i.jb("BiasAdd",S,void 0)},843274:S=>{i.jb("BiasSplitGelu",S,void 0)},843335:S=>{i.jb("FastGelu",S,void 0)},843391:(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt,hn,Fn,wn,Qn,$r,Gl)=>{i.jb("Conv",S,{format:Fn?"NHWC":"NCHW",auto_pad:z,dilations:Y?Array.from(B().subarray(Number(Y)>>>0,Number(ie)>>>0)):[],group:pe,kernel_shape:Ae?Array.from(B().subarray(Number(Ae)>>>0,Number(rt)>>>0)):[],pads:Mt?Array.from(B().subarray(Number(Mt)>>>0,Number(kt)>>>0)):[],strides:Gt?Array.from(B().subarray(Number(Gt)>>>0,Number(hn)>>>0)):[],w_is_const:()=>!!W()[Number(wn)>>>0],activation:Pt(Qn),activation_params:$r?Array.from(ye().subarray(Number($r)>>>0,Number(Gl)>>>0)):[]})},843975:S=>{i.jb("Gelu",S,void 0)},844027:(S,z,Y,ie,pe,Ae,rt,Mt,kt)=>{i.jb("GroupQueryAttention",S,{numHeads:z,kvNumHeads:Y,scale:ie,softcap:pe,doRotary:Ae,rotaryInterleaved:rt,smoothSoftmax:Mt,localWindowSize:kt})},844244:(S,z,Y,ie)=>{i.jb("LayerNormalization",S,{axis:z,epsilon:Y,simplified:!!ie})},844355:(S,z,Y,ie)=>{i.jb("LayerNormalization",S,{axis:z,epsilon:Y,simplified:!!ie})},844466:(S,z,Y,ie,pe,Ae)=>{i.jb("MatMulNBits",S,{k:z,n:Y,accuracyLevel:ie,bits:pe,blockSize:Ae})},844593:(S,z,Y,ie,pe,Ae)=>{i.jb("MultiHeadAttention",S,{numHeads:z,isUnidirectional:Y,maskFilterValue:ie,scale:pe,doRotary:Ae})},844752:(S,z)=>{i.jb("QuickGelu",S,{alpha:z})},844816:(S,z,Y,ie,pe)=>{i.jb("RotaryEmbedding",S,{interleaved:!!z,numHeads:Y,rotaryEmbeddingDim:ie,scale:pe})},844955:(S,z,Y)=>{i.jb("SkipLayerNormalization",S,{epsilon:z,simplified:!!Y})},845057:(S,z,Y)=>{i.jb("SkipLayerNormalization",S,{epsilon:z,simplified:!!Y})},845159:(S,z,Y,ie)=>{i.jb("GatherBlockQuantized",S,{gatherAxis:z,quantizeAxis:Y,blockSize:ie})},845280:S=>{i.Zb(S)},845314:(S,z)=>i.ac(Number(S),Number(z),i.Fb.dc,i.Fb.errors)};function st(S,z,Y){return Qr(async()=>{await i.Xb(Number(S),Number(z),Number(Y))})}function Ke(){return typeof wasmOffsetConverter<"u"}class F{name="ExitStatus";constructor(z){this.message=`Program terminated with exit(${z})`,this.status=z}}var U=S=>{S.terminate(),S.onmessage=()=>{}},j=[],se=S=>{je.length==0&&(vt(),ft(je[0]));var z=je.pop();if(!z)return 6;Qe.push(z),bt[S.Ab]=z,z.Ab=S.Ab;var Y={Bb:"run",fc:S.ec,Hb:S.Hb,Ab:S.Ab};return z.postMessage(Y,S.Mb),0},_e=0,ge=(S,z,...Y)=>{for(var ie=2*Y.length,pe=ro(),Ae=Ms(8*ie),rt=Ae>>>3,Mt=0;Mt>>0]=kt)}return S=ko(S,0,ie,Ae,z),io(pe),S};function Ce(S){if(u)return ge(0,1,S);if(E=S,!(0<_e)){for(var z of Qe)U(z);for(z of je)U(z);je=[],Qe=[],bt={},Q=!0}y(0,new F(S))}function Ie(S){if(u)return ge(1,0,S);Ee(S)}var Ee=S=>{if(E=S,u)throw Ie(S),"unwind";Ce(S)},je=[],Qe=[],ot=[],bt={},_t=S=>{var z=S.Ab;delete bt[z],je.push(S),Qe.splice(Qe.indexOf(S),1),S.Ab=0,$l(z)};function nt(){ot.forEach(S=>S())}var ft=S=>new Promise(z=>{S.onmessage=pe=>{var Ae=(pe=pe.data).Bb;if(pe.Gb&&pe.Gb!=Fo()){var rt=bt[pe.Gb];rt?rt.postMessage(pe,pe.Mb):P(`Internal error! Worker sent a message "${Ae}" to target pthread ${pe.Gb}, but that thread no longer exists!`)}else Ae==="checkMailbox"?Be():Ae==="spawnThread"?se(pe):Ae==="cleanupThread"?_t(bt[pe.hc]):Ae==="loaded"?(S.loaded=!0,z(S)):Ae==="alert"?alert(`Thread ${pe.ic}: ${pe.text}`):pe.target==="setimmediate"?S.postMessage(pe):Ae==="callHandler"?i[pe.Qb](...pe.args):Ae&&P(`worker sent an unknown command ${Ae}`)},S.onerror=pe=>{throw P(`worker sent an error! ${pe.filename}:${pe.lineno}: ${pe.message}`),pe};var Y,ie=[];for(Y of[])i.propertyIsEnumerable(Y)&&ie.push(Y);S.postMessage({Bb:"load",Rb:ie,kc:w,lc:C})});function vt(){var S=new Worker((()=>{let z=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new z("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});je.push(S)}var mn=S=>{Me();var z=le()[S+52>>>2>>>0];S=le()[S+56>>>2>>>0],tu(z,z-S),io(z)},Se=(S,z)=>{_e=0,S=$s(S,z),0<_e?E=S:No(S)};class St{constructor(z){this.Ib=z-24}}function Ze(S,z,Y){var ie=new St(S>>>=0);throw z>>>=0,Y>>>=0,le()[ie.Ib+16>>>2>>>0]=0,le()[ie.Ib+4>>>2>>>0]=z,le()[ie.Ib+8>>>2>>>0]=Y,S}function it(S,z,Y,ie){return u?ge(2,1,S,z,Y,ie):yt(S,z,Y,ie)}function yt(S,z,Y,ie){if(S>>>=0,Y>>>=0,ie>>>=0,d===void 0)return 6;var pe=[];return u&&pe.length===0?it(S,z>>>=0,Y,ie):(S={ec:Y,Ab:S,Hb:ie,Mb:pe},u?(S.Bb="spawnThread",postMessage(S,pe),0):se(S))}var tt=typeof TextDecoder<"u"?new TextDecoder:void 0,gt=(S,z=0,Y=NaN)=>{var ie=(z>>>=0)+Y;for(Y=z;S[Y]&&!(Y>=ie);)++Y;if(16(pe=(240&pe)==224?(15&pe)<<12|Ae<<6|rt:(7&pe)<<18|Ae<<12|rt<<6|63&S[z++])?ie+=String.fromCharCode(pe):(pe-=65536,ie+=String.fromCharCode(55296|pe>>10,56320|1023&pe))}}else ie+=String.fromCharCode(pe)}return ie},Pt=(S,z)=>(S>>>=0)?gt(q(),S,z):"";function tn(S,z,Y){return u?ge(3,1,S,z,Y):0}function rn(S,z){if(u)return ge(4,1,S,z)}var Pn=S=>{for(var z=0,Y=0;Y=ie?z++:2047>=ie?z+=2:55296<=ie&&57343>=ie?(z+=4,++Y):z+=3}return z},ln=(S,z,Y)=>{var ie=q();if(z>>>=0,0=rt&&(rt=65536+((1023&rt)<<10)|1023&S.charCodeAt(++Ae)),127>=rt){if(z>=Y)break;ie[z++>>>0]=rt}else{if(2047>=rt){if(z+1>=Y)break;ie[z++>>>0]=192|rt>>6}else{if(65535>=rt){if(z+2>=Y)break;ie[z++>>>0]=224|rt>>12}else{if(z+3>=Y)break;ie[z++>>>0]=240|rt>>18,ie[z++>>>0]=128|rt>>12&63}ie[z++>>>0]=128|rt>>6&63}ie[z++>>>0]=128|63&rt}}ie[z>>>0]=0,S=z-pe}else S=0;return S};function vi(S,z){if(u)return ge(5,1,S,z)}function On(S,z,Y){if(u)return ge(6,1,S,z,Y)}function ut(S,z,Y){return u?ge(7,1,S,z,Y):0}function It(S,z){if(u)return ge(8,1,S,z)}function Bt(S,z,Y){if(u)return ge(9,1,S,z,Y)}function Vi(S,z,Y,ie){if(u)return ge(10,1,S,z,Y,ie)}function rr(S,z,Y,ie){if(u)return ge(11,1,S,z,Y,ie)}function ri(S,z,Y,ie){if(u)return ge(12,1,S,z,Y,ie)}function Ti(S){if(u)return ge(13,1,S)}function Er(S,z){if(u)return ge(14,1,S,z)}function zr(S,z,Y){if(u)return ge(15,1,S,z,Y)}var Ns,Sr,Ur=()=>Ne(""),Ii=S=>{for(var z="";q()[S>>>0];)z+=Ns[q()[S++>>>0]];return z},Yr={},vr={};function ue(S,z,Y={}){return function(ie,pe,Ae={}){var rt=pe.name;if(!ie)throw new Sr(`type "${rt}" must have a positive integer typeid pointer`);if(vr.hasOwnProperty(ie)){if(Ae.Sb)return;throw new Sr(`Cannot register type '${rt}' twice`)}vr[ie]=pe,Yr.hasOwnProperty(ie)&&(pe=Yr[ie],delete Yr[ie],pe.forEach(Mt=>Mt()))}(S,z,Y)}var Oe=(S,z,Y)=>{switch(z){case 1:return Y?ie=>W()[ie>>>0]:ie=>q()[ie>>>0];case 2:return Y?ie=>G()[ie>>>1>>>0]:ie=>te()[ie>>>1>>>0];case 4:return Y?ie=>B()[ie>>>2>>>0]:ie=>le()[ie>>>2>>>0];case 8:return Y?ie=>J[ie>>>3]:ie=>ee[ie>>>3];default:throw new TypeError(`invalid integer width (${z}): ${S}`)}};function qe(S,z,Y){Y>>>=0,ue(S>>>=0,{name:z=Ii(z>>>0),fromWireType:ie=>ie,toWireType:function(ie,pe){if(typeof pe!="bigint"&&typeof pe!="number")throw pe=pe===null?"null":(ie=typeof pe)=="object"||ie==="array"||ie==="function"?pe.toString():""+pe,new TypeError(`Cannot convert "${pe}" to ${this.name}`);return typeof pe=="number"&&(pe=BigInt(pe)),pe},Cb:Ue,readValueFromPointer:Oe(z,Y,z.indexOf("u")==-1),Db:null})}var Ue=8;function Fe(S,z,Y,ie){ue(S>>>=0,{name:z=Ii(z>>>0),fromWireType:function(pe){return!!pe},toWireType:function(pe,Ae){return Ae?Y:ie},Cb:Ue,readValueFromPointer:function(pe){return this.fromWireType(q()[pe>>>0])},Db:null})}var wt=[],Ct=[];function Nt(S){9<(S>>>=0)&&--Ct[S+1]==0&&(Ct[S]=void 0,wt.push(S))}var Rt=S=>{if(!S)throw new Sr("Cannot use deleted val. handle = "+S);return Ct[S]},qt=S=>{switch(S){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let z=wt.pop()||Ct.length;return Ct[z]=S,Ct[z+1]=1,z}};function sn(S){return this.fromWireType(le()[S>>>2>>>0])}var Jt={name:"emscripten::val",fromWireType:S=>{var z=Rt(S);return Nt(S),z},toWireType:(S,z)=>qt(z),Cb:Ue,readValueFromPointer:sn,Db:null};function yn(S){return ue(S>>>0,Jt)}var Sn=(S,z)=>{switch(z){case 4:return function(Y){return this.fromWireType(ye()[Y>>>2>>>0])};case 8:return function(Y){return this.fromWireType(me()[Y>>>3>>>0])};default:throw new TypeError(`invalid float width (${z}): ${S}`)}};function Jn(S,z,Y){Y>>>=0,ue(S>>>=0,{name:z=Ii(z>>>0),fromWireType:ie=>ie,toWireType:(ie,pe)=>pe,Cb:Ue,readValueFromPointer:Sn(z,Y),Db:null})}function Ln(S,z,Y,ie,pe){if(S>>>=0,Y>>>=0,z=Ii(z>>>0),pe===-1&&(pe=4294967295),pe=Mt=>Mt,ie===0){var Ae=32-8*Y;pe=Mt=>Mt<>>Ae}var rt=z.includes("unsigned")?function(Mt,kt){return kt>>>0}:function(Mt,kt){return kt};ue(S,{name:z,fromWireType:pe,toWireType:rt,Cb:Ue,readValueFromPointer:Oe(z,Y,ie!==0),Db:null})}function dn(S,z,Y){function ie(Ae){var rt=le()[Ae>>>2>>>0];return Ae=le()[Ae+4>>>2>>>0],new pe(W().buffer,Ae,rt)}var pe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][z];ue(S>>>=0,{name:Y=Ii(Y>>>0),fromWireType:ie,Cb:Ue,readValueFromPointer:ie},{Sb:!0})}function nn(S,z){ue(S>>>=0,{name:z=Ii(z>>>0),fromWireType:function(Y){for(var ie,pe=le()[Y>>>2>>>0],Ae=Y+4,rt=Ae,Mt=0;Mt<=pe;++Mt){var kt=Ae+Mt;Mt!=pe&&q()[kt>>>0]!=0||(rt=Pt(rt,kt-rt),ie===void 0?ie=rt:(ie+="\0",ie+=rt),rt=kt+1)}return Jr(Y),ie},toWireType:function(Y,ie){ie instanceof ArrayBuffer&&(ie=new Uint8Array(ie));var pe=typeof ie=="string";if(!(pe||ie instanceof Uint8Array||ie instanceof Uint8ClampedArray||ie instanceof Int8Array))throw new Sr("Cannot pass non-string to std::string");var Ae=pe?Pn(ie):ie.length,rt=no(4+Ae+1),Mt=rt+4;if(le()[rt>>>2>>>0]=Ae,pe)ln(ie,Mt,Ae+1);else if(pe)for(pe=0;pe>>0]=kt}else for(pe=0;pe>>0]=ie[pe];return Y!==null&&Y.push(Jr,rt),rt},Cb:Ue,readValueFromPointer:sn,Db(Y){Jr(Y)}})}var li=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,An=(S,z)=>{for(var Y=S>>1,ie=Y+z/2;!(Y>=ie)&&te()[Y>>>0];)++Y;if(32<(Y<<=1)-S&&li)return li.decode(q().slice(S,Y));for(Y="",ie=0;!(ie>=z/2);++ie){var pe=G()[S+2*ie>>>1>>>0];if(pe==0)break;Y+=String.fromCharCode(pe)}return Y},sr=(S,z,Y)=>{if(Y??=2147483647,2>Y)return 0;var ie=z;Y=(Y-=2)<2*S.length?Y/2:S.length;for(var pe=0;pe>>1>>>0]=Ae,z+=2}return G()[z>>>1>>>0]=0,z-ie},yr=S=>2*S.length,Xi=(S,z)=>{for(var Y=0,ie="";!(Y>=z/4);){var pe=B()[S+4*Y>>>2>>>0];if(pe==0)break;++Y,65536<=pe?(pe-=65536,ie+=String.fromCharCode(55296|pe>>10,56320|1023&pe)):ie+=String.fromCharCode(pe)}return ie},yi=(S,z,Y)=>{if(z>>>=0,Y??=2147483647,4>Y)return 0;var ie=z;Y=ie+Y-4;for(var pe=0;pe=Ae&&(Ae=65536+((1023&Ae)<<10)|1023&S.charCodeAt(++pe)),B()[z>>>2>>>0]=Ae,(z+=4)+4>Y)break}return B()[z>>>2>>>0]=0,z-ie},Kn=S=>{for(var z=0,Y=0;Y=ie&&++Y,z+=4}return z};function Pe(S,z,Y){if(S>>>=0,z>>>=0,Y=Ii(Y>>>=0),z===2)var ie=An,pe=sr,Ae=yr,rt=Mt=>te()[Mt>>>1>>>0];else z===4&&(ie=Xi,pe=yi,Ae=Kn,rt=Mt=>le()[Mt>>>2>>>0]);ue(S,{name:Y,fromWireType:Mt=>{for(var kt,Gt=le()[Mt>>>2>>>0],hn=Mt+4,Fn=0;Fn<=Gt;++Fn){var wn=Mt+4+Fn*z;Fn!=Gt&&rt(wn)!=0||(hn=ie(hn,wn-hn),kt===void 0?kt=hn:(kt+="\0",kt+=hn),hn=wn+z)}return Jr(Mt),kt},toWireType:(Mt,kt)=>{if(typeof kt!="string")throw new Sr(`Cannot pass non-string to C++ string type ${Y}`);var Gt=Ae(kt),hn=no(4+Gt+z);return le()[hn>>>2>>>0]=Gt/z,pe(kt,hn+4,Gt+z),Mt!==null&&Mt.push(Jr,hn),hn},Cb:Ue,readValueFromPointer:sn,Db(Mt){Jr(Mt)}})}function V(S,z){ue(S>>>=0,{Tb:!0,name:z=Ii(z>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function fe(S){mr(S>>>0,!l,1,!o,131072,!1),nt()}var ve=S=>{if(!Q)try{if(S(),!(0<_e))try{u?No(E):Ee(E)}catch(z){z instanceof F||z=="unwind"||y(0,z)}}catch(z){z instanceof F||z=="unwind"||y(0,z)}};function Te(S){S>>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(B(),S>>>2,S).value.then(Be),S+=128,Atomics.store(B(),S>>>2,1))}var Be=()=>{var S=Fo();S&&(Te(S),ve(Uo))};function lt(S,z){(S>>>=0)==z>>>0?setTimeout(Be):u?postMessage({Gb:S,Bb:"checkMailbox"}):(S=bt[S])&&S.postMessage({Bb:"checkMailbox"})}var Ot=[];function Lt(S,z,Y,ie,pe){for(z>>>=0,ie/=2,Ot.length=ie,Y=pe>>>0>>>3,pe=0;pe>>0];return(z?ke[z]:Jc[S])(...Ot)}var Ft=()=>{_e=0};function Dt(S){S>>>=0,u?postMessage({Bb:"cleanupThread",hc:S}):_t(bt[S])}function Cn(S){}var cn=(S,z)=>{var Y=vr[S];if(Y===void 0)throw S=eu(S),Y=Ii(S),Jr(S),new Sr(`${z} has unknown type ${Y}`);return Y},pi=(S,z,Y)=>{var ie=[];return S=S.toWireType(ie,Y),ie.length&&(le()[z>>>2>>>0]=qt(ie)),S};function Gi(S,z,Y){return z>>>=0,Y>>>=0,S=Rt(S>>>0),z=cn(z,"emval::as"),pi(z,Y,S)}function ci(S,z){return z>>>=0,S=Rt(S>>>0),(z=cn(z,"emval::as")).toWireType(null,S)}var ui=S=>{try{S()}catch(z){Ne(z)}},mi=0,Oi=null,ys=0,Li=[],Br={},ei={},Mi=0,Ki=null,Or=[];function Qr(S){return function(z){if(!Q){if(mi===0){var Y=!1,ie=!1;z((pe=0)=>{if(!Q&&(ys=pe,Y=!0,ie)){mi=2,ui(()=>cs(Oi)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),pe=!1;try{var Ae=function(){var kt=B()[Oi+8>>>2>>>0];return kt=Xt[ei[kt]],--_e,kt()}()}catch(kt){Ae=kt,pe=!0}var rt=!1;if(!Oi){var Mt=Ki;Mt&&(Ki=null,(pe?Mt.reject:Mt.resolve)(Ae),rt=!0)}if(pe&&!rt)throw Ae}}),ie=!0,Y||(mi=1,Oi=function(){var pe=no(65548),Ae=pe+12;le()[pe>>>2>>>0]=Ae,le()[pe+4>>>2>>>0]=Ae+65536,Ae=Li[0];var rt=Br[Ae];return rt===void 0&&(rt=Mi++,Br[Ae]=rt,ei[rt]=Ae),Ae=rt,B()[pe+8>>>2>>>0]=Ae,pe}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),ui(()=>Bo(Oi)))}else mi===2?(mi=0,ui(Vs),Jr(Oi),Oi=null,Or.forEach(ve)):Ne(`invalid state: ${mi}`);return ys}}(z=>{S().then(z)})}function Ci(S){return S>>>=0,Qr(async()=>{var z=await Rt(S);return qt(z)})}var pr=[];function Yi(S,z,Y,ie){return Y>>>=0,ie>>>=0,(S=pr[S>>>0])(null,z=Rt(z>>>0),Y,ie)}var Bn={},ti=S=>{var z=Bn[S];return z===void 0?Ii(S):z};function Pi(S,z,Y,ie,pe){return Y>>>=0,ie>>>=0,pe>>>=0,(S=pr[S>>>0])(z=Rt(z>>>0),z[Y=ti(Y)],ie,pe)}var Fi=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ya(S){return(S>>>=0)==0?qt(Fi()):(S=ti(S),qt(Fi()[S]))}var Qa=S=>{var z=pr.length;return pr.push(S),z},Rl=(S,z)=>{for(var Y=Array(S),ie=0;ie>>2>>>0],"parameter "+ie);return Y},ha=(S,z)=>Object.defineProperty(z,"name",{value:S});function Do(S,z,Y){var ie=(z=Rl(S,z>>>0)).shift();S--;var pe=`return function (obj, func, destructorsRef, args) { +`,Ae=0,rt=[];Y===0&&rt.push("obj");for(var Mt=["retType"],kt=[ie],Gt=0;Gthn.name).join(", ")}) => ${ie.name}>`,Qa(ha(Y,S))}function pa(S){return S=ti(S>>>0),qt(i[S])}function pd(S,z){return z>>>=0,S=Rt(S>>>0),z=Rt(z),qt(S[z])}function md(S){9<(S>>>=0)&&(Ct[S+1]+=1)}function _d(){return qt([])}function Dl(S){S=Rt(S>>>0);for(var z=Array(S.length),Y=0;Y>>0))}function $c(){return qt({})}function vd(S){for(var z=Rt(S>>>=0);z.length;){var Y=z.pop();z.pop()(Y)}Nt(S)}function yd(S,z,Y){z>>>=0,Y>>>=0,S=Rt(S>>>0),z=Rt(z),Y=Rt(Y),S[z]=Y}function Vc(S,z){return z>>>=0,S=(S=cn(S>>>0,"_emval_take_value")).readValueFromPointer(z),qt(S)}function Gc(S,z){S=-9007199254740992>S||9007199254740992>>=0,S=new Date(1e3*S),B()[z>>>2>>>0]=S.getUTCSeconds(),B()[z+4>>>2>>>0]=S.getUTCMinutes(),B()[z+8>>>2>>>0]=S.getUTCHours(),B()[z+12>>>2>>>0]=S.getUTCDate(),B()[z+16>>>2>>>0]=S.getUTCMonth(),B()[z+20>>>2>>>0]=S.getUTCFullYear()-1900,B()[z+24>>>2>>>0]=S.getUTCDay(),S=(S.getTime()-Date.UTC(S.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,B()[z+28>>>2>>>0]=S}var Il=S=>S%4==0&&(S%100!=0||S%400==0),jc=[0,31,60,91,121,152,182,213,244,274,305,335],Ol=[0,31,59,90,120,151,181,212,243,273,304,334];function Th(S,z){S=-9007199254740992>S||9007199254740992>>=0,S=new Date(1e3*S),B()[z>>>2>>>0]=S.getSeconds(),B()[z+4>>>2>>>0]=S.getMinutes(),B()[z+8>>>2>>>0]=S.getHours(),B()[z+12>>>2>>>0]=S.getDate(),B()[z+16>>>2>>>0]=S.getMonth(),B()[z+20>>>2>>>0]=S.getFullYear()-1900,B()[z+24>>>2>>>0]=S.getDay();var Y=(Il(S.getFullYear())?jc:Ol)[S.getMonth()]+S.getDate()-1|0;B()[z+28>>>2>>>0]=Y,B()[z+36>>>2>>>0]=-60*S.getTimezoneOffset(),Y=new Date(S.getFullYear(),6,1).getTimezoneOffset();var ie=new Date(S.getFullYear(),0,1).getTimezoneOffset();S=0|(Y!=ie&&S.getTimezoneOffset()==Math.min(ie,Y)),B()[z+32>>>2>>>0]=S}function Ll(S){S>>>=0;var z=new Date(B()[S+20>>>2>>>0]+1900,B()[S+16>>>2>>>0],B()[S+12>>>2>>>0],B()[S+8>>>2>>>0],B()[S+4>>>2>>>0],B()[S>>>2>>>0],0),Y=B()[S+32>>>2>>>0],ie=z.getTimezoneOffset(),pe=new Date(z.getFullYear(),6,1).getTimezoneOffset(),Ae=new Date(z.getFullYear(),0,1).getTimezoneOffset(),rt=Math.min(Ae,pe);return 0>Y?B()[S+32>>>2>>>0]=+(pe!=Ae&&rt==ie):0>>2>>>0]=z.getDay(),Y=(Il(z.getFullYear())?jc:Ol)[z.getMonth()]+z.getDate()-1|0,B()[S+28>>>2>>>0]=Y,B()[S>>>2>>>0]=z.getSeconds(),B()[S+4>>>2>>>0]=z.getMinutes(),B()[S+8>>>2>>>0]=z.getHours(),B()[S+12>>>2>>>0]=z.getDate(),B()[S+16>>>2>>>0]=z.getMonth(),B()[S+20>>>2>>>0]=z.getYear(),S=z.getTime(),BigInt(isNaN(S)?-1:S/1e3)}function Fl(S,z,Y,ie,pe,Ae,rt){return u?ge(16,1,S,z,Y,ie,pe,Ae,rt):-52}function Wc(S,z,Y,ie,pe,Ae){if(u)return ge(17,1,S,z,Y,ie,pe,Ae)}var zs={},Hc=()=>performance.timeOrigin+performance.now();function qc(S,z){if(u)return ge(18,1,S,z);if(zs[S]&&(clearTimeout(zs[S].id),delete zs[S]),!z)return 0;var Y=setTimeout(()=>{delete zs[S],ve(()=>zo(S,performance.timeOrigin+performance.now()))},z);return zs[S]={id:Y,qc:z},0}function Md(S,z,Y,ie){S>>>=0,z>>>=0,Y>>>=0,ie>>>=0;var pe=new Date().getFullYear(),Ae=new Date(pe,0,1).getTimezoneOffset();pe=new Date(pe,6,1).getTimezoneOffset();var rt=Math.max(Ae,pe);le()[S>>>2>>>0]=60*rt,B()[z>>>2>>>0]=+(Ae!=pe),S=(z=Mt=>{var kt=Math.abs(Mt);return`UTC${0<=Mt?"-":"+"}${String(Math.floor(kt/60)).padStart(2,"0")}${String(kt%60).padStart(2,"0")}`})(Ae),z=z(pe),peDate.now();function xd(S,z,Y){return 0<=S&&3>=S?(S===0?S=Date.now():S=performance.timeOrigin+performance.now(),J[Y>>>0>>>3]=BigInt(Math.round(1e6*S)),0):28}var kl=[],Xc=(S,z)=>{kl.length=0;for(var Y;Y=q()[S++>>>0];){var ie=Y!=105;z+=(ie&=Y!=112)&&z%8?4:0,kl.push(Y==112?le()[z>>>2>>>0]:Y==106?J[z>>>3]:Y==105?B()[z>>>2>>>0]:me()[z>>>3>>>0]),z+=ie?8:4}return kl};function Nl(S,z,Y){return S>>>=0,z=Xc(z>>>0,Y>>>0),ke[S](...z)}function Kc(S,z,Y){return S>>>=0,z=Xc(z>>>0,Y>>>0),ke[S](...z)}var wd=()=>{};function Io(S,z){return P(Pt(S>>>0,z>>>0))}var Zr=()=>{throw _e+=1,"unwind"};function Td(){return 4294901760}var Ed=()=>navigator.hardwareConcurrency;function Yc(){return Ne("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Sd(S){S>>>=0;var z=q().length;if(S<=z||4294901760=Y;Y*=2){var ie=z*(1+.2/Y);ie=Math.min(ie,S+100663296);e:{ie=(Math.min(4294901760,65536*Math.ceil(Math.max(S,ie)/65536))-w.buffer.byteLength+65535)/65536|0;try{w.grow(ie),Me();var pe=1;break e}catch{}pe=void 0}if(pe)return!0}return!1}var Za=()=>(Ne("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Us={},Bs=S=>{S.forEach(z=>{Za()})};function Ad(){var S=Error().stack.toString().split(` +`);return S[0]=="Error"&&S.shift(),Bs(S),Us.Lb=Za(),Us.cc=S,Us.Lb}function Cd(S,z,Y){if(S>>>=0,z>>>=0,Us.Lb==S)var ie=Us.cc;else(ie=Error().stack.toString().split(` +`))[0]=="Error"&&ie.shift(),Bs(ie);for(var pe=3;ie[pe]&&Za()!=S;)++pe;for(S=0;S>>2>>>0]=Za();return S}var zl,Oo={},Ja=()=>{if(!zl){var S,z={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(S in Oo)Oo[S]===void 0?delete z[S]:z[S]=Oo[S];var Y=[];for(S in z)Y.push(`${S}=${z[S]}`);zl=Y}return zl};function ma(S,z){if(u)return ge(19,1,S,z);S>>>=0,z>>>=0;var Y=0;return Ja().forEach((ie,pe)=>{var Ae=z+Y;for(pe=le()[S+4*pe>>>2>>>0]=Ae,Ae=0;Ae>>0]=ie.charCodeAt(Ae);W()[pe>>>0]=0,Y+=ie.length+1}),0}function _a(S,z){if(u)return ge(20,1,S,z);S>>>=0,z>>>=0;var Y=Ja();le()[S>>>2>>>0]=Y.length;var ie=0;return Y.forEach(pe=>ie+=pe.length+1),le()[z>>>2>>>0]=ie,0}function Qc(S){return u?ge(21,1,S):52}function ga(S,z,Y,ie){return u?ge(22,1,S,z,Y,ie):52}function Ul(S,z,Y,ie){return u?ge(23,1,S,z,Y,ie):70}var Zc=[null,[],[]];function eo(S,z,Y,ie){if(u)return ge(24,1,S,z,Y,ie);z>>>=0,Y>>>=0,ie>>>=0;for(var pe=0,Ae=0;Ae>>2>>>0],Mt=le()[z+4>>>2>>>0];z+=8;for(var kt=0;kt>>0],hn=Zc[S];Gt===0||Gt===10?((S===1?x:P)(gt(hn)),hn.length=0):hn.push(Gt)}pe+=Mt}return le()[ie>>>2>>>0]=pe,0}u||function(){for(var S=i.numThreads-1;S--;)vt();j.unshift(()=>{we++,function(z){u?z():Promise.all(je.map(ft)).then(z)}(()=>He())})}();for(var Lo=Array(256),to=0;256>to;++to)Lo[to]=String.fromCharCode(to);Ns=Lo,Sr=i.BindingError=class extends Error{constructor(S){super(S),this.name="BindingError"}},i.InternalError=class extends Error{constructor(S){super(S),this.name="InternalError"}},Ct.push(0,1,void 0,1,null,1,!0,1,!1,1),i.count_emval_handles=()=>Ct.length/2-5-wt.length;var Xt,Jc=[Ce,Ie,it,tn,rn,vi,On,ut,It,Bt,Vi,rr,ri,Ti,Er,zr,Fl,Wc,qc,ma,_a,Qc,ga,Ul,eo];(async function(){function S(ie,pe){return Xt=ie.exports,Xt=function(){var Ae=Xt,rt={};for(let[Mt,kt]of Object.entries(Ae))rt[Mt]=typeof kt=="function"?(...Gt)=>{Li.push(Mt);try{return kt(...Gt)}finally{Q||(Li.pop(),Oi&&mi===1&&Li.length===0&&(mi=0,_e+=1,ui(Vl),typeof Fibers<"u"&&Fibers.rc()))}}:kt;return rt}(),Xt=function(){var Ae=Xt,rt=kt=>Gt=>kt(Gt)>>>0,Mt=kt=>()=>kt()>>>0;return(Ae=Object.assign({},Ae)).Da=rt(Ae.Da),Ae.fb=Mt(Ae.fb),Ae.hb=rt(Ae.hb),Ae.tb=rt(Ae.tb),Ae.ub=Mt(Ae.ub),Ae.__cxa_get_exception_ptr=rt(Ae.__cxa_get_exception_ptr),Ae}(),ot.push(Xt.ib),C=pe,He(),Xt}we++;var z=We();if(i.instantiateWasm)return new Promise(ie=>{i.instantiateWasm(z,(pe,Ae)=>{S(pe,Ae),ie(pe.exports)})});if(u)return new Promise(ie=>{xe=pe=>{var Ae=new WebAssembly.Instance(pe,We());ie(S(Ae,pe))}});ae??=i.locateFile?i.locateFile?i.locateFile("ort-wasm-simd-threaded.jsep.wasm",b):b+"ort-wasm-simd-threaded.jsep.wasm":new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href;try{var Y=await async function(ie){var pe=ae;if(!ne&&typeof WebAssembly.instantiateStreaming=="function"&&!oe(pe))try{var Ae=fetch(pe,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(Ae,ie)}catch(rt){P(`wasm streaming compile failed: ${rt}`),P("falling back to ArrayBuffer instantiation")}return async function(rt,Mt){try{var kt=await async function(Gt){if(!ne)try{var hn=await h(Gt);return new Uint8Array(hn)}catch{}if(Gt==ae&&ne)Gt=new Uint8Array(ne);else{if(!_)throw"both async and sync fetching of the wasm failed";Gt=_(Gt)}return Gt}(rt);return await WebAssembly.instantiate(kt,Mt)}catch(Gt){P(`failed to asynchronously prepare wasm: ${Gt}`),Ne(Gt)}}(pe,ie)}(z);return S(Y.instance,Y.module)}catch(ie){return t(ie),Promise.reject(ie)}})();var eu=S=>(eu=Xt.Da)(S),Bl=()=>(Bl=Xt.Ea)();i._OrtInit=(S,z)=>(i._OrtInit=Xt.Fa)(S,z),i._OrtGetLastError=(S,z)=>(i._OrtGetLastError=Xt.Ga)(S,z),i._OrtCreateSessionOptions=(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt)=>(i._OrtCreateSessionOptions=Xt.Ha)(S,z,Y,ie,pe,Ae,rt,Mt,kt,Gt),i._OrtAppendExecutionProvider=(S,z,Y,ie,pe)=>(i._OrtAppendExecutionProvider=Xt.Ia)(S,z,Y,ie,pe),i._OrtAddFreeDimensionOverride=(S,z,Y)=>(i._OrtAddFreeDimensionOverride=Xt.Ja)(S,z,Y),i._OrtAddSessionConfigEntry=(S,z,Y)=>(i._OrtAddSessionConfigEntry=Xt.Ka)(S,z,Y),i._OrtReleaseSessionOptions=S=>(i._OrtReleaseSessionOptions=Xt.La)(S),i._OrtCreateSession=(S,z,Y)=>(i._OrtCreateSession=Xt.Ma)(S,z,Y),i._OrtReleaseSession=S=>(i._OrtReleaseSession=Xt.Na)(S),i._OrtGetInputOutputCount=(S,z,Y)=>(i._OrtGetInputOutputCount=Xt.Oa)(S,z,Y),i._OrtGetInputOutputMetadata=(S,z,Y,ie)=>(i._OrtGetInputOutputMetadata=Xt.Pa)(S,z,Y,ie),i._OrtFree=S=>(i._OrtFree=Xt.Qa)(S),i._OrtCreateTensor=(S,z,Y,ie,pe,Ae)=>(i._OrtCreateTensor=Xt.Ra)(S,z,Y,ie,pe,Ae),i._OrtGetTensorData=(S,z,Y,ie,pe)=>(i._OrtGetTensorData=Xt.Sa)(S,z,Y,ie,pe),i._OrtReleaseTensor=S=>(i._OrtReleaseTensor=Xt.Ta)(S),i._OrtCreateRunOptions=(S,z,Y,ie)=>(i._OrtCreateRunOptions=Xt.Ua)(S,z,Y,ie),i._OrtAddRunConfigEntry=(S,z,Y)=>(i._OrtAddRunConfigEntry=Xt.Va)(S,z,Y),i._OrtReleaseRunOptions=S=>(i._OrtReleaseRunOptions=Xt.Wa)(S),i._OrtCreateBinding=S=>(i._OrtCreateBinding=Xt.Xa)(S),i._OrtBindInput=(S,z,Y)=>(i._OrtBindInput=Xt.Ya)(S,z,Y),i._OrtBindOutput=(S,z,Y,ie)=>(i._OrtBindOutput=Xt.Za)(S,z,Y,ie),i._OrtClearBoundOutputs=S=>(i._OrtClearBoundOutputs=Xt._a)(S),i._OrtReleaseBinding=S=>(i._OrtReleaseBinding=Xt.$a)(S),i._OrtRunWithBinding=(S,z,Y,ie,pe)=>(i._OrtRunWithBinding=Xt.ab)(S,z,Y,ie,pe),i._OrtRun=(S,z,Y,ie,pe,Ae,rt,Mt)=>(i._OrtRun=Xt.bb)(S,z,Y,ie,pe,Ae,rt,Mt),i._OrtEndProfiling=S=>(i._OrtEndProfiling=Xt.cb)(S),i._JsepOutput=(S,z,Y)=>(i._JsepOutput=Xt.db)(S,z,Y),i._JsepGetNodeName=S=>(i._JsepGetNodeName=Xt.eb)(S);var Fo=()=>(Fo=Xt.fb)(),Jr=i._free=S=>(Jr=i._free=Xt.gb)(S),no=i._malloc=S=>(no=i._malloc=Xt.hb)(S),mr=(S,z,Y,ie,pe,Ae)=>(mr=Xt.kb)(S,z,Y,ie,pe,Ae),va=()=>(va=Xt.lb)(),ko=(S,z,Y,ie,pe)=>(ko=Xt.mb)(S,z,Y,ie,pe),$l=S=>($l=Xt.nb)(S),No=S=>(No=Xt.ob)(S),zo=(S,z)=>(zo=Xt.pb)(S,z),Uo=()=>(Uo=Xt.qb)(),tu=(S,z)=>(tu=Xt.rb)(S,z),io=S=>(io=Xt.sb)(S),Ms=S=>(Ms=Xt.tb)(S),ro=()=>(ro=Xt.ub)(),$s=i.dynCall_ii=(S,z)=>($s=i.dynCall_ii=Xt.vb)(S,z),Bo=S=>(Bo=Xt.wb)(S),Vl=()=>(Vl=Xt.xb)(),cs=S=>(cs=Xt.yb)(S),Vs=()=>(Vs=Xt.zb)();return i.stackSave=()=>ro(),i.stackRestore=S=>io(S),i.stackAlloc=S=>Ms(S),i.setValue=function(S,z,Y="i8"){switch(Y.endsWith("*")&&(Y="*"),Y){case"i1":case"i8":W()[S>>>0]=z;break;case"i16":G()[S>>>1>>>0]=z;break;case"i32":B()[S>>>2>>>0]=z;break;case"i64":J[S>>>3]=BigInt(z);break;case"float":ye()[S>>>2>>>0]=z;break;case"double":me()[S>>>3>>>0]=z;break;case"*":le()[S>>>2>>>0]=z;break;default:Ne(`invalid type for setValue: ${Y}`)}},i.getValue=function(S,z="i8"){switch(z.endsWith("*")&&(z="*"),z){case"i1":case"i8":return W()[S>>>0];case"i16":return G()[S>>>1>>>0];case"i32":return B()[S>>>2>>>0];case"i64":return J[S>>>3];case"float":return ye()[S>>>2>>>0];case"double":return me()[S>>>3>>>0];case"*":return le()[S>>>2>>>0];default:Ne(`invalid type for getValue: ${z}`)}},i.UTF8ToString=Pt,i.stringToUTF8=ln,i.lengthBytesUTF8=Pn,function S(){if(0{EM(),N0=typeof location>"u"?void 0:location.origin,my=import.meta.url>"file:"&&import.meta.url<"file;",Qb=()=>{{if(my){let n=URL;return new URL(new n("ort.bundle.min.mjs",import.meta.url).href,N0).href}return import.meta.url}},Ds=Qb(),hS=()=>{if(Ds&&!Ds.startsWith("blob:"))return Ds.substring(0,Ds.lastIndexOf("/")+1)},K_=(n,e)=>{try{let t=e??Ds;return(t?new URL(n,t):new URL(n)).origin===N0}catch{return!1}},Zb=(n,e)=>{let t=e??Ds;try{return(t?new URL(n,t):new URL(n)).href}catch{return}},Jb=(n,e)=>`${e??"./"}${n}`,z0=async n=>{let e=await(await fetch(n,{credentials:"same-origin"})).blob();return URL.createObjectURL(e)},ex=async n=>(await import(n)).default,U0=(ID(),qm(cS)).default,pS=async()=>{if(!Ds)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(K_(Ds))return[void 0,U0()];let n=await z0(Ds);return[n,U0(n)]},B0=(OD(),qm(dS)).default,mS=async(n,e,t)=>{if(!n&&!e&&B0&&Ds&&K_(Ds))return[void 0,B0];{let i="ort-wasm-simd-threaded.jsep.mjs",s=n??Zb(i,e),o=t&&s&&!K_(s,e),l=o?await z0(s):s??Jb(i,e);return[o?l:void 0,await ex(l)]}}}),$0,Y_,wm,V0,tx,nx,ix,AM,Ai,fd=At(()=>{SM(),Y_=!1,wm=!1,V0=!1,tx=()=>{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}},nx=()=>{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}},ix=()=>{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}},AM=async n=>{if(Y_)return Promise.resolve();if(wm)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(V0)throw new Error("previous call to 'initializeWebAssembly()' failed.");wm=!0;let e=n.initTimeout,t=n.numThreads;if(n.simd!==!1){if(n.simd==="relaxed"){if(!ix())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!nx())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=tx();t>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),n.numThreads=t=1);let s=n.wasmPaths,o=typeof s=="string"?s:void 0,l=s?.mjs,u=l?.href??l,d=s?.wasm,f=d?.href??d,m=n.wasmBinary,[h,_]=await mS(u,o,t>1),g=!1,y=[];if(e>0&&y.push(new Promise(b=>{setTimeout(()=>{g=!0,b()},e)})),y.push(new Promise((b,T)=>{let v={numThreads:t};if(m)v.wasmBinary=m;else if(f||o)v.locateFile=x=>f??o+x;else if(u&&u.indexOf("blob:")!==0)v.locateFile=x=>new URL(x,u).href;else if(h){let x=hS();x&&(v.locateFile=P=>x+P)}_(v).then(x=>{wm=!1,Y_=!0,$0=x,b(),h&&URL.revokeObjectURL(h)},x=>{wm=!1,V0=!0,T(x)})})),await Promise.race(y),g)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},Ai=()=>{if(Y_&&$0)return $0;throw new Error("WebAssembly is not initialized yet.")}}),Va,jg,hi,CM=At(()=>{fd(),Va=(n,e)=>{let t=Ai(),i=t.lengthBytesUTF8(n)+1,s=t._malloc(i);return t.stringToUTF8(n,s,i),e.push(s),s},jg=(n,e,t,i)=>{if(typeof n=="object"&&n!==null){if(t.has(n))throw new Error("Circular reference in options");t.add(n)}Object.entries(n).forEach(([s,o])=>{let l=e?e+s:s;if(typeof o=="object")jg(o,l+".",t,i);else if(typeof o=="string"||typeof o=="number")i(l,o.toString());else if(typeof o=="boolean")i(l,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},hi=n=>{let e=Ai(),t=e.stackSave();try{let i=e.PTR_SIZE,s=e.stackAlloc(2*i);e._OrtGetLastError(s,s+i);let o=Number(e.getValue(s,i===4?"i32":"i64")),l=e.getValue(s+i,"*"),u=l?e.UTF8ToString(l):"";throw new Error(`${n} ERROR_CODE: ${o}, ERROR_MESSAGE: ${u}`)}finally{e.stackRestore(t)}}}),_S,LD=At(()=>{fd(),CM(),_S=n=>{let e=Ai(),t=0,i=[],s=n||{};try{if(n?.logSeverityLevel===void 0)s.logSeverityLevel=2;else if(typeof n.logSeverityLevel!="number"||!Number.isInteger(n.logSeverityLevel)||n.logSeverityLevel<0||n.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${n.logSeverityLevel}`);if(n?.logVerbosityLevel===void 0)s.logVerbosityLevel=0;else if(typeof n.logVerbosityLevel!="number"||!Number.isInteger(n.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${n.logVerbosityLevel}`);n?.terminate===void 0&&(s.terminate=!1);let o=0;return n?.tag!==void 0&&(o=Va(n.tag,i)),t=e._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,o),t===0&&hi("Can't create run options."),n?.extra!==void 0&&jg(n.extra,"",new WeakSet,(l,u)=>{let d=Va(l,i),f=Va(u,i);e._OrtAddRunConfigEntry(t,d,f)!==0&&hi(`Can't set a run config entry: ${l} - ${u}.`)}),[t,i]}catch(o){throw t!==0&&e._OrtReleaseRunOptions(t),i.forEach(l=>e._free(l)),o}}}),rx,sx,ax,Tm,ox,gS,FD=At(()=>{fd(),CM(),rx=n=>{switch(n){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${n}`)}},sx=n=>{switch(n){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${n}`)}},ax=n=>{n.extra||(n.extra={}),n.extra.session||(n.extra.session={});let e=n.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1"),n.executionProviders&&n.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(n.enableMemPattern=!1)},Tm=(n,e,t,i)=>{let s=Va(e,i),o=Va(t,i);Ai()._OrtAddSessionConfigEntry(n,s,o)!==0&&hi(`Can't set a session config entry: ${e} - ${t}.`)},ox=async(n,e,t)=>{for(let i of e){let s=typeof i=="string"?i:i.name,o=[];switch(s){case"webnn":if(s="WEBNN",typeof i!="string"){let m=i?.deviceType;m&&Tm(n,"deviceType",m,t)}break;case"webgpu":if(s="JS",typeof i!="string"){let m=i;if(m?.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);Tm(n,"preferredLayout",m.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let l=Va(s,t),u=o.length,d=0,f=0;if(u>0){d=Ai()._malloc(u*Ai().PTR_SIZE),t.push(d),f=Ai()._malloc(u*Ai().PTR_SIZE),t.push(f);for(let m=0;m{let e=Ai(),t=0,i=[],s=n||{};ax(s);try{let o=rx(s.graphOptimizationLevel??"all"),l=sx(s.executionMode??"sequential"),u=typeof s.logId=="string"?Va(s.logId,i):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let f=s.logVerbosityLevel??0;if(!Number.isInteger(f)||f<0||f>4)throw new Error(`log verbosity level is not valid: ${f}`);let m=typeof s.optimizedModelFilePath=="string"?Va(s.optimizedModelFilePath,i):0;if(t=e._OrtCreateSessionOptions(o,!!s.enableCpuMemArena,!!s.enableMemPattern,l,!!s.enableProfiling,0,u,d,f,m),t===0&&hi("Can't create session options."),s.executionProviders&&await ox(t,s.executionProviders,i),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);Tm(t,"enableGraphCapture",s.enableGraphCapture.toString(),i)}if(s.freeDimensionOverrides)for(let[h,_]of Object.entries(s.freeDimensionOverrides)){if(typeof h!="string")throw new Error(`free dimension override name must be a string: ${h}`);if(typeof _!="number"||!Number.isInteger(_)||_<0)throw new Error(`free dimension override value must be a non-negative integer: ${_}`);let g=Va(h,i);e._OrtAddFreeDimensionOverride(t,g,_)!==0&&hi(`Can't set a free dimension override: ${h} - ${_}.`)}return s.extra!==void 0&&jg(s.extra,"",new WeakSet,(h,_)=>{Tm(t,h,_,i)}),[t,i]}catch(o){throw t!==0&&e._OrtReleaseSessionOptions(t)!==0&&hi("Can't release session options."),i.forEach(l=>e._free(l)),o}}}),nh,bl,td,PM,Wg,RM,DM,_y,fn=At(()=>{nh=n=>{switch(n){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: ${n}`)}},bl=n=>{switch(n){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: ${n}`)}},td=(n,e)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][n],i=typeof e=="number"?e:e.reduce((s,o)=>s*o,1);return t>0?Math.ceil(i*t):void 0},PM=n=>{switch(n){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${n}`)}},Wg=n=>{switch(n){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: ${n}`)}},RM=n=>n==="float32"||n==="float16"||n==="int32"||n==="int64"||n==="uint32"||n==="uint8"||n==="bool"||n==="uint4"||n==="int4",DM=n=>n==="float32"||n==="float16"||n==="int32"||n==="int64"||n==="uint32"||n==="uint64"||n==="int8"||n==="uint8"||n==="bool"||n==="uint4"||n==="int4",_y=n=>{switch(n){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: ${n}`)}}}),IM,vS=At(()=>{EM(),IM=async n=>{if(typeof n=="string"){let e=await fetch(n);if(!e.ok)throw new Error(`failed to load external data file: ${n}`);let t=e.headers.get("Content-Length"),i=t?parseInt(t,10):0;if(i<1073741824)return new Uint8Array(await e.arrayBuffer());{if(!e.body)throw new Error(`failed to load external data file: ${n}, no response body.`);let s=e.body.getReader(),o;try{o=new ArrayBuffer(i)}catch(u){if(u instanceof RangeError){let d=Math.ceil(i/65536);o=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let l=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let f=d.byteLength;new Uint8Array(o,l,f).set(d),l+=f}return new Uint8Array(o,0,i)}}else return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n instanceof Uint8Array?n:new Uint8Array(n)}}),lx,cx,ux,dx,OM,fx,qn,Cl=At(()=>{fn(),lx=["V","I","W","E","F"],cx=(n,e)=>{console.log(`[${lx[n]},${new Date().toISOString()}]${e}`)},OM=(n,e)=>{ux=n,dx=e},fx=(n,e)=>{let t=Wg(n),i=Wg(ux);t>=i&&cx(t,typeof e=="function"?e():e)},qn=(...n)=>{dx&&fx(...n)}}),hx,uh,et,Hg,yS,MS,bS,Mn=At(()=>{hx=class{static calcMatMulShape(n,e){return n[1]!==e[0]?void 0:[n[0],e[1]]}},uh=class{static calcShape(n,e,t=!1){let i=n.length,s=e.length;if(i===0)return e;if(s===0)return n;let o=Math.max(n.length,e.length),l=new Array(o);if(t){if(i<2||s<2)return;let u=hx.calcMatMulShape([n[i-2],n[i-1]],[e[s-2],e[s-1]]);if(u===void 0)return;[l[o-2],l[o-1]]=u}for(let u=t?3:1;u<=o;u++){let d=i-u<0?1:n[i-u],f=s-u<0?1:e[s-u];if(d!==f&&d>1&&f>1)return;let m=Math.max(d,f);if(d&&f)l[o-u]=Math.max(d,f);else{if(m>1)return;l[o-u]=0}}return l}static isValidBroadcast(n,e){let t=n.length,i=e.length;if(t>i)return!1;for(let s=1;s<=t;s++)if(n[t-s]!==1&&n[t-s]!==e[i-s])return!1;return!0}},et=class Fg{static size(e){return Fg.getSizeFromDimensionRange(e,0,e.length)}static convertShape(e,t=4){let i=e.length;if(i===0)return[];let s=new Array(i),o=i-1;for(;o>=0;){if(e[o]%t===0){s[o]=e[o]/t;break}if(t%e[o]!==0)throw new Error("cannot convert shape");s[o]=1,t/=e[o],o--}for(o--;o>=0;o--)s[o]=e[o];return s}static sizeFromDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${e.length} dimensions.`);return Fg.getSizeFromDimensionRange(e,t,e.length)}static sizeToDimension(e,t){if(t<0||t>e.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${e.length} dimensions.`);return Fg.getSizeFromDimensionRange(e,0,t)}static getSizeFromDimensionRange(e,t,i){let s=1;for(let o=t;o=0;--s)i[s]=i[s+1]*e[s+1];return i}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(i=>this.normalizeAxis(i,t??e.length))}static sortBasedOnPerm(e,t){return t?t.map(i=>e[i]):e.slice().reverse()}static padShape(e,t){let i=e.length;return e.map((s,o)=>s+t[o]+t[o+i])}static areEqual(e,t){return e.length!==t.length?!1:e.every((i,s)=>i===t[s])}},Hg=class Um{static adjustPoolAttributes(e,t,i,s,o,l){if(!e&&i.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 u=0;u=i.length?i.push(t[u+2]):i[u]=t[u+2];for(let u=0;u=i[u]||l[u+i.length]>=i[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(e,t,i,s,o,l,u){if(u){if(o.length!==2*(e.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==e.length-2)throw new Error("length of strides should be the length of data dimensions");if(s.length!==e.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{fn(),LM=(n,e)=>new(PM(e))(n)}),gy,G0,px,j0,mx,W0,H0,q0,_x,wS,kD=At(()=>{Cl(),gy=(n,e=!0)=>{if(n.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=n.byteLength/8,i=new BigInt64Array(n.buffer,n.byteOffset,t),s=new Int32Array(t);for(let o=0;o2147483647n||l<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${l}`);s[o]=Number(l)}return e?new Uint8Array(s.buffer):s},G0=(n,e=!0)=>{if(n.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=n.byteLength/4,i=new Int32Array(n.buffer,n.byteOffset,t),s=BigInt64Array.from(i,BigInt);return e?new Uint8Array(s.buffer):s},px=1,j0=()=>px++,mx=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),W0=(n,e)=>{let t=mx.get(n);if(!t)throw new Error("Unsupported data type.");return e.length>0?Math.ceil(e.reduce((i,s)=>i*s)*t/8):0},H0=class{constructor(n){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:e,context:t,tensor:i,dataType:s,shape:o,shouldConvertInt64toInt32:l=!1}=n;this.sessionId=e,this.mlContext=t,this.mlTensor=i,this.dataType=s,this.tensorShape=o,this.shouldConvertInt64toInt32=l}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return W0(this.dataType,this.tensorShape)}destroy(){qn("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(n){this.mlContext.writeTensor(this.mlTensor,n)}async read(n,e){if(n){let t=await this.mlContext.readTensor(this.mlTensor),i=G0(new Uint8Array(t));if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(i);return}else return i.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(n,e,t){return this.mlContext===n&&this.dataType===e&&this.tensorShape.length===t.length&&this.tensorShape.every((i,s)=>i===t[s])}setIsInt64ToInt32Converted(n){this.isInt64ToInt32Converted=n}},q0=class{constructor(n,e){this.tensorManager=n,this.wrapper=e}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(n,e,t,i){let s=e,o=this.tensorManager.getMLContext(n),l=s==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(l&&(s="int32",qn("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(o,s,t))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==W0(s,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let u=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(n,s,t,u,!0,!0,l),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(n){let e=n;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(e=gy(n,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else qn("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(n){if(this.activeUpload){let e=this.wrapper?.isInt64ToInt32Converted?G0(this.activeUpload):this.activeUpload;if(n){n instanceof ArrayBuffer?new Uint8Array(n).set(e):new Uint8Array(n.buffer,n.byteOffset,n.byteLength).set(e);return}else return e.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return n?this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32,n):this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32)}},_x=class{constructor(n){this.backend=n,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(n){let e=this.backend.getMLContext(n);if(!e)throw new Error("MLContext not found for session.");return e}reserveTensorId(){let n=j0();return this.tensorTrackersById.set(n,new q0(this)),n}releaseTensorId(n){let e=this.tensorTrackersById.get(n);e&&(this.tensorTrackersById.delete(n),e.tensorWrapper&&this.releaseTensor(e.tensorWrapper))}async ensureTensor(n,e,t,i,s){qn("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${i}, copyOld: ${s}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(n,t,i,s)}upload(n,e){let t=this.tensorTrackersById.get(n);if(!t)throw new Error("Tensor not found.");t.upload(e)}async download(n,e){qn("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${n}, dstBuffer: ${e?.byteLength}}`);let t=this.tensorTrackersById.get(n);if(!t)throw new Error("Tensor not found.");return t.download(e)}releaseTensorsForSession(n){for(let e of this.freeTensors)e.sessionId===n&&e.destroy();this.freeTensors=this.freeTensors.filter(e=>e.sessionId!==n)}registerTensor(n,e,t,i){let s=this.getMLContext(n),o=j0(),l=new H0({sessionId:n,context:s,tensor:e,dataType:t,shape:i});return this.tensorTrackersById.set(o,new q0(this,l)),this.externalTensors.add(l),o}async getCachedTensor(n,e,t,i,s,o,l=!1){let u=this.getMLContext(n);for(let[f,m]of this.freeTensors.entries())if(m.canReuseTensor(u,e,t)){qn("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let h=this.freeTensors.splice(f,1)[0];return h.sessionId=n,h}qn("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let d=await u.createTensor({dataType:e,shape:t,dimensions:t,usage:i,writable:s,readable:o});return new H0({sessionId:n,context:u,tensor:d,dataType:e,shape:t,shouldConvertInt64toInt32:l})}releaseTensor(n){this.externalTensors.has(n)&&this.externalTensors.delete(n),this.freeTensors.push(n)}},wS=(...n)=>new _x(...n)}),Q_,gx,TS,ND=At(()=>{fn(),fd(),xS(),kD(),Cl(),Q_=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),gx=(n,e)=>{if(n===e)return!0;if(n===void 0||e===void 0)return!1;let t=Object.keys(n).sort(),i=Object.keys(e).sort();return t.length===i.length&&t.every((s,o)=>s===i[o]&&n[s]===e[s])},TS=class{constructor(n){this.tensorManager=wS(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,OM(n.logLevel,!!n.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(n){qn("verbose",()=>`[WebNN] onRunStart {sessionId: ${n}}`),this.activeSessionId=n}onRunEnd(n){qn("verbose",()=>`[WebNN] onRunEnd {sessionId: ${n}}`);let e=this.temporarySessionTensorIds.get(n);if(e){for(let t of e)qn("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(n),this.activeSessionId=void 0}}async createMLContext(n){if(n instanceof GPUDevice){let t=this.mlContextCache.findIndex(i=>i.gpuDevice===n);if(t!==-1)return this.mlContextCache[t].mlContext;{let i=await navigator.ml.createContext(n);return this.mlContextCache.push({gpuDevice:n,mlContext:i}),i}}else if(n===void 0){let t=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let e=this.mlContextCache.findIndex(t=>gx(t.options,n));if(e!==-1)return this.mlContextCache[e].mlContext;{let t=await navigator.ml.createContext(n);return this.mlContextCache.push({options:n,mlContext:t}),t}}registerMLContext(n,e){this.mlContextBySessionId.set(n,e);let t=this.sessionIdsByMLContext.get(e);t||(t=new Set,this.sessionIdsByMLContext.set(e,t)),t.add(n),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(n,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(n){this.sessionGraphInputs.delete(n);let e=this.mlContextBySessionId.get(n);if(!e)return;this.tensorManager.releaseTensorsForSession(n),this.mlContextBySessionId.delete(n);let t=this.sessionIdsByMLContext.get(e);if(t.delete(n),t.size===0){this.sessionIdsByMLContext.delete(e);let i=this.mlContextCache.findIndex(s=>s.mlContext===e);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(n){return this.mlContextBySessionId.get(n)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(n){qn("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n)}async ensureTensor(n,e,t,i,s){let o=Q_.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(n??this.currentSessionId,e,o,i,s)}async createTemporaryTensor(n,e,t){qn("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${e}, shape: ${t}}`);let i=Q_.get(e);if(!i)throw new Error(`Unsupported ONNX data type: ${e}`);let s=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(n,s,i,t,!1);let o=this.temporarySessionTensorIds.get(n);return o?o.push(s):this.temporarySessionTensorIds.set(n,[s]),s}uploadTensor(n,e){if(!Ai().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");qn("verbose",()=>`[WebNN] uploadTensor {tensorId: ${n}, data: ${e.byteLength}}`),this.tensorManager.upload(n,e)}async downloadTensor(n,e){return this.tensorManager.download(n,e)}createMLTensorDownloader(n,e){return async()=>{let t=await this.tensorManager.download(n);return LM(t,e)}}registerMLTensor(n,e,t,i){let s=Q_.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(n,e,s,i);return qn("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${s}, dimensions: ${i}} -> {tensorId: ${o}}`),o}registerMLConstant(n,e,t,i,s,o,l=!1){if(!o)throw new Error("External mounted files are not available.");let u=n;n.startsWith("./")&&(u=n.substring(2));let d=o.get(u);if(!d)throw new Error(`File with name ${u} not found in preloaded files.`);if(e+t>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let f=d.slice(e,e+t).buffer,m;switch(s.dataType){case"float32":m=new Float32Array(f);break;case"float16":m=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(f):new Uint16Array(f);break;case"int32":m=new Int32Array(f);break;case"uint32":m=new Uint32Array(f);break;case"int64":l?(m=gy(new Uint8Array(f),!1),s.dataType="int32"):m=new BigInt64Array(f);break;case"uint64":m=new BigUint64Array(f);break;case"int8":m=new Int8Array(f);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(f);break;default:throw new Error(`Unsupported data type: ${s.dataType} in creating WebNN Constant from external data.`)}return qn("verbose",()=>`[WebNN] registerMLConstant {dataType: ${s.dataType}, shape: ${s.shape}}} ${l?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(s,m)}registerGraphInput(n){this.temporaryGraphInputs.push(n)}isGraphInput(n,e){let t=this.sessionGraphInputs.get(n);return t?t.includes(e):!1}isInt64Supported(n){return!!this.mlContextBySessionId.get(n)?.opSupportLimits().input.dataTypes.includes("int64")}flush(){}}}),FM=At(()=>{}),X0,Z_,J_,vx,yx,K0,vy,Mx,ES,zD=At(()=>{Cl(),FM(),X0=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]]),Z_=[],J_=n=>Math.ceil(Number(n)/16)*16,vx=n=>{for(let e=0;eyx++,vy=async(n,e,t,i)=>{let s=J_(t),o=n.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let l=n.getCommandEncoder();n.endComputePass(),l.copyBufferToBuffer(e,0,o,0,s),n.flush(),await o.mapAsync(GPUMapMode.READ);let u=o.getMappedRange();if(i){let d=i();return d.set(new Uint8Array(u,0,t)),d}else return new Uint8Array(u.slice(0,t))}finally{o.destroy()}},Mx=class{constructor(n){this.backend=n,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[e]of X0)Z_.push(e),this.freeBuffers.set(e,[]),this.freeUniformBuffers.set(e,[]);this.sessionCount=0}upload(n,e){let t=e.buffer,i=e.byteOffset,s=e.byteLength,o=J_(s),l=this.storageCache.get(n);if(!l)throw new Error("gpu data for uploading does not exist");if(Number(l.originalSize)!==s)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${s}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(t,i,s)),u.unmap();let f=this.backend.device.createCommandEncoder();f.copyBufferToBuffer(u,0,l.gpuData.buffer,0,o),this.backend.device.queue.submit([f.finish()]),u.destroy(),qn("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${n})`)}memcpy(n,e){let t=this.storageCache.get(n);if(!t)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(e);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=J_(t.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(t.gpuData.buffer,0,i.gpuData.buffer,0,s)}registerExternalBuffer(n,e,t){let i;if(t){if(i=t[0],n===t[1])return qn("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => 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. + Please use the previous external buffer!`)}else i=K0();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:n},originalSize:e}),qn("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${e}) => id=${i}, registered.`),i}unregisterExternalBuffer(n){n!==void 0&&(this.storageCache.delete(n),qn("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${n}`))}create(n,e=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=vx(n),i,s=(e&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(e&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||o){let u=(s?this.freeBuffers:this.freeUniformBuffers).get(t);u?u.length>0?i=u.pop():i=this.backend.device.createBuffer({size:t,usage:e}):i=this.backend.device.createBuffer({size:t,usage:e})}else i=this.backend.device.createBuffer({size:t,usage:e});let l={id:K0(),type:0,buffer:i};return this.storageCache.set(l.id,{gpuData:l,originalSize:Number(n)}),qn("verbose",()=>`[WebGPU] GpuDataManager.create(size=${n}) => id=${l.id}`),l}get(n){return this.storageCache.get(n)?.gpuData}release(n){let e=typeof n=="bigint"?Number(n):n,t=this.storageCache.get(e);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return qn("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(n,e){let t=this.storageCache.get(Number(n));if(!t)throw new Error("data does not exist");await vy(this.backend,t.gpuData.buffer,t.originalSize,e)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let n of this.buffersPending){let e=X0.get(n.size);if((n.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(n.size)||[];e===void 0||t.length>=e?n.destroy():t.push(n)}else if((n.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(n.size)||[];e===void 0||t.length>=e?n.destroy():t.push(n)}else n.destroy()}this.buffersPending=[]}else{let n=this.capturedPendingBuffers.get(this.backend.currentSessionId);n||(n=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,n));for(let e of this.buffersPending)n.push(e);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(n=>{n.forEach(e=>{e.destroy()})}),this.freeUniformBuffers.forEach(n=>{n.forEach(e=>{e.destroy()})}),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(n=>{n.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(n){let e=this.capturedPendingBuffers.get(n);e&&(e.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(n)),this.sessionCount-=1,this.sessionCount===0&&(qn("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ES=(...n)=>new Mx(...n)}),bx,ii,ir=At(()=>{bx=class{constructor(n){Object.assign(this,n)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(n=>`${this[n]}`).join(";")),this.key}},ii=n=>new bx(n)}),dh,eg,xr,Kr,en,qi,yy,rh,Nc,Yt,Em,at,Ht,SS,kM,xx,AS,xn=At(()=>{fn(),Mn(),dh=64,eg=(n,e)=>{if(e===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(n)){case 10:return e>1?`vec${e}`:"f16";case 1:return e>1?`vec${e}`:"f32";case 6:return e>1?`vec${e}`:"i32";case 12:return e>1?`vec${e}`:"u32";case 7:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(e>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(e!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${n}`)}},xr=(n,e=1)=>{let t=eg(n,e);return typeof t=="string"?t:t[0]},Kr=(n,e=1)=>{let t=eg(n,e);return typeof t=="string"?t:t[1]},en=(...n)=>{let e=[];return n.forEach(t=>{t.length!==0&&e.push({type:12,data:t},{type:12,data:et.computeStrides(t)})}),e},qi=n=>n%4===0?4:n%2===0?2:1,yy=(n="f32",e,t="0")=>!e||e===1?`${n}(${t})`:`vec${e}<${n}>(${t})`,rh=(n,e,t)=>n==="f32"?t:e===1?`f32(${t})`:`vec${e}(${t})`,Nc=(n,e)=>e===4?`(${n}.x + ${n}.y + ${n}.z + ${n}.w)`:e===2?`(${n}.x + ${n}.y)`:e===3?`(${n}.x + ${n}.y + ${n}.z)`:n,Yt=(n,e,t,i)=>n.startsWith("uniforms.")&&t>4?typeof e=="string"?i==="f16"?`${n}[(${e}) / 8][(${e}) % 8 / 4][(${e}) % 8 % 4]`:`${n}[(${e}) / 4][(${e}) % 4]`:i==="f16"?`${n}[${Math.floor(e/8)}][${Math.floor(e%8/4)}][${e%8%4}]`:`${n}[${Math.floor(e/4)}][${e%4}]`:t>1?`${n}[${e}]`:n,Em=(n,e,t,i,s)=>{let o=typeof t=="number",l=o?t:t.length,u=[...new Array(l).keys()],d=l<2?"u32":l<=4?`vec${l}`:`array`,f=eg(e,s),m=typeof f=="string"?f:f[1],h=typeof f=="string"?f:f[0],_={indices:d,value:m,storage:h,tensor:e},g=q=>typeof q=="string"?q:`${q}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},b=o?"uniforms.":"",T=`${b}${n}_shape`,v=`${b}${n}_strides`,x="";for(let q=0;q ${_.indices} { + var indices: ${_.indices}; + var current = offset; + ${x} + return indices; + }`,w=q=>(y.offsetToIndices=!0,l<2?q:`o2i_${n}(${q})`),C=[];if(l>=2)for(let q=l-1;q>=0;q--)C.push(`${Yt(v,q,l)} * (indices[${q}])`);let E=l<2?"":` + fn i2o_${n}(indices: ${_.indices}) -> u32 { + return ${C.join("+")}; + }`,A=q=>(y.indicesToOffset=!0,l<2?q:`i2o_${n}(${q})`),L=(...q)=>l===0?"0u":`${_.indices}(${q.map(g).join(",")})`,I=(q,G)=>l<2?`${q}`:`${Yt(q,G,l)}`,O=(q,G,te)=>l<2?`${q}=${te};`:`${Yt(q,G,l)}=${te};`,H={},Z=(q,G)=>{y.broadcastedIndicesToOffset=!0;let te=`${G.name}broadcastedIndicesTo${n}Offset`;if(te in H)return`${te}(${q})`;let B=[];for(let le=l-1;le>=0;le--){let ye=G.indicesGet("outputIndices",le+G.rank-l);B.push(`${I(v,le)} * (${ye} % ${I(T,le)})`)}return H[te]=`fn ${te}(outputIndices: ${G.type.indices}) -> u32 { + return ${B.length>0?B.join("+"):"0u"}; + }`,`${te}(${q})`},$=(q,G)=>(()=>{if(_.storage===_.value)return`${n}[${q}]=${G};`;if(_.storage==="vec2"&&_.value==="i32")return`${n}[${q}]=vec2(u32(${G}), select(0u, 0xFFFFFFFFu, ${G} < 0));`;if(_.storage==="vec2"&&_.value==="u32")return`${n}[${q}]=vec2(u32(${G}), 0u);`;if(_.storage==="u32"&&_.value==="vec4")return`${n}[${q}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${G}));`;throw new Error(`not supported combination of storage type ${_.storage} and value type ${_.value} yet`)})(),J=q=>(()=>{if(_.storage===_.value)return`${n}[${q}]`;if(_.storage==="vec2"&&_.value==="i32")return`i32(${n}[${q}].x)`;if(_.storage==="vec2"&&_.value==="u32")return`u32(${n}[${q}].x)`;if(_.storage==="u32"&&_.value==="vec4")return`vec4(bool(${n}[${q}] & 0xFFu), bool(${n}[${q}] & 0xFF00u), bool(${n}[${q}] & 0xFF0000u), bool(${n}[${q}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${_.storage} and value type ${_.value} yet`)})(),ee=l<2?"":` + fn get_${n}ByIndices(indices: ${_.indices}) -> ${m} { + return ${J(`i2o_${n}(indices)`)}; + }`,X=l<2?"":(()=>{let q=u.map(te=>`d${te}: u32`).join(", "),G=u.map(te=>`d${te}`).join(", ");return` + fn get_${n}(${q}) -> ${m} { + return get_${n}ByIndices(${L(G)}); + }`})(),ne=(...q)=>{if(q.length!==l)throw new Error(`indices length must be ${l}`);let G=q.map(g).join(",");return l===0?J("0u"):l===1?J(G[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${n}(${G})`)},Q=q=>l<2?J(q):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${n}ByIndices(${q})`),oe=l<2?"":` + fn set_${n}ByIndices(indices: ${_.indices}, value: ${m}) { + ${$(`i2o_${n}(indices)`,"value")} + }`,W=l<2?"":(()=>{let q=u.map(te=>`d${te}: u32`).join(", "),G=u.map(te=>`d${te}`).join(", ");return` + fn set_${n}(${q}, value: ${m}) { + set_${n}ByIndices(${L(G)}, value); + }`})();return{impl:()=>{let q=[],G=!1;return y.offsetToIndices&&(q.push(P),G=!0),y.indicesToOffset&&(q.push(E),G=!0),y.broadcastedIndicesToOffset&&(Object.values(H).forEach(te=>q.push(te)),G=!0),y.set&&(q.push(W),G=!0),y.setByIndices&&(q.push(oe),G=!0),y.get&&(q.push(X),G=!0),y.getByIndices&&(q.push(ee),G=!0),!o&&G&&q.unshift(`const ${T} = ${_.indices}(${t.join(",")});`,`const ${v} = ${_.indices}(${et.computeStrides(t).join(",")});`),q.join(` +`)},type:_,offsetToIndices:w,indicesToOffset:A,broadcastedIndicesToOffset:Z,indices:L,indicesGet:I,indicesSet:O,set:(...q)=>{if(q.length!==l+1)throw new Error(`indices length must be ${l}`);let G=q[l];if(typeof G!="string")throw new Error("value must be string");let te=q.slice(0,l).map(g).join(",");return l===0?$("0u",G):l===1?$(te[0],G):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${n}(${te}, ${G})`)},setByOffset:$,setByIndices:(q,G)=>l<2?$(q,G):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${n}ByIndices(${q}, ${G});`),get:ne,getByOffset:J,getByIndices:Q,usage:i,name:n,strides:v,shape:T,rank:l}},at=(n,e,t,i=1)=>Em(n,e,t,"input",i),Ht=(n,e,t,i=1)=>Em(n,e,t,"output",i),SS=(n,e,t)=>Em(n,e,t,"atomicOutput",1),kM=(n,e,t,i=1)=>Em(n,e,t,"internal",i),xx=class{constructor(n,e){this.normalizedDispatchGroup=n,this.limits=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(n){return`if (global_idx >= ${typeof n=="number"?`${n}u`:n}) { return; }`}mainStart(n=dh){let e=typeof n=="number"?n:n[0],t=typeof n=="number"?1:n[1],i=typeof n=="number"?1:n[2];if(e>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${e}, ${t}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(e*t*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${e}, ${t}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=s?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,l=s?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${e*t*i}u + local_idx;`;return`@compute @workgroup_size(${e}, ${t}, ${i}) + fn main(${o}) { + ${l} + `}appendVariableUniforms(n){n.rank!==0&&(n.shape.startsWith("uniforms.")&&this.uniforms.push({name:n.shape.replace("uniforms.",""),type:"u32",length:n.rank}),n.strides.startsWith("uniforms.")&&this.uniforms.push({name:n.strides.replace("uniforms.",""),type:"u32",length:n.rank}))}declareVariable(n,e){if(n.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(n),this.appendVariableUniforms(n);let t=n.usage==="input"?"read":"read_write",i=n.usage==="atomicOutput"?"atomic":n.type.storage;return`@group(0) @binding(${e}) var ${n.name}: array<${i}>;`}declareVariables(...n){return n.map(e=>this.declareVariable(e,this.variableIndex++)).join(` +`)}registerInternalVariable(n){if(n.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(n),this.appendVariableUniforms(n)}registerInternalVariables(...n){return n.forEach(e=>this.registerInternalVariable(e)),this}registerUniform(n,e,t=1){return this.uniforms.push({name:n,type:e,length:t}),this}registerUniforms(n){return this.uniforms=this.uniforms.concat(n),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let n=[];for(let{name:e,type:t,length:i}of this.uniforms)if(i&&i>4)t==="f16"?n.push(`@align(16) ${e}:array, ${Math.ceil(i/8)}>`):n.push(`${e}:array, ${Math.ceil(i/4)}>`);else{let s=i==null||i===1?t:`vec${i}<${t}>`;n.push(`${e}:${s}`)}return` + struct Uniforms { ${n.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(n=>n.impl()).join(` +`)+this.internalVariables.map(n=>n.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let n=e=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(e)];return this.uniforms.map(e=>[n(e.type),e.length??1])}},AS=(n,e)=>new xx(n,e)}),wx,Y0,Tx,Ex,Sx,Ax,Ls,CS,PS,Bc=At(()=>{fn(),Mn(),ir(),xn(),wx=(n,e)=>{if(!n||n.length!==1)throw new Error("Transpose requires 1 input.");if(e.length!==0&&e.length!==n[0].dims.length)throw new Error(`perm size ${e.length} does not match input rank ${n[0].dims.length}`)},Y0=(n,e)=>e.length!==0?e:[...new Array(n).keys()].reverse(),Tx=(n,e)=>et.sortBasedOnPerm(n,Y0(n.length,e)),Ex=(n,e,t,i)=>{let s=`fn perm(i: ${i.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let o=0;o{let t=[],i=[];for(let s=0;s{let t=0;for(let i=0;i{let t=n.dataType,i=n.dims.length,s=Y0(i,e),o=Tx(n.dims,s),l=n.dims,u=o,d=i<2||Ax(s,n.dims),f;if(d)return f=y=>{let b=at("input",t,l,4),T=Ht("output",t,u,4);return` + ${y.registerUniform("output_size","u32").declareVariables(b,T)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let y=et.size(o);return{outputs:[{dims:o,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(y/64/4)},programUniforms:[{type:12,data:Math.ceil(y/4)}]}},getShaderSource:f};let{newShape:m,newPerm:h}=Sx(n.dims,s),_=et.areEqual(h,[2,3,1]),g=et.areEqual(h,[3,1,2]);if(m.length===2||_||g){l=_?[m[0],m[1]*m[2]]:g?[m[0]*m[1],m[2]]:m,u=[l[1],l[0]];let y=16;return f=b=>{let T=at("a",t,l.length),v=Ht("output",t,u.length);return` + ${b.registerUniform("output_size","u32").declareVariables(T,v)} + var tile : array, ${y}>; + ${b.mainStart([y,y,1])} + let stride = (uniforms.output_shape[1] - 1) / ${y} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${y}u + local_id.x; + let input_row = workgroup_id_x * ${y}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${T.getByIndices(`${T.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${y}u + local_id.x; + let output_row = workgroup_id_y * ${y}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let b=et.size(o);return{outputs:[{dims:o,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(u[1]/y),y:Math.ceil(u[0]/y)},programUniforms:[{type:12,data:b},...en(l,u)]}},getShaderSource:f}}return f=y=>{let b=at("a",t,l.length),T=Ht("output",t,u.length);return` + ${y.registerUniform("output_size","u32").declareVariables(b,T)} + + ${Ex(s,i,b,T)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${T.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${T.setByOffset("global_idx",b.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${e}`,inputDependencies:["rank"]},getRunData:()=>{let y=et.size(o);return{outputs:[{dims:o,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...en(l,u)]}},getShaderSource:f}},CS=(n,e)=>{wx(n.inputs,e.perm),n.compute(Ls(n.inputs[0],e.perm))},PS=n=>ii({perm:n.perm})}),Cx,Px,Rx,Dx,Ix,Ox,Lx,Fx,kx,Nx,Oa,RS,DS,IS,OS,LS,FS,kS,NS,zS,US,UD=At(()=>{fn(),Mn(),xn(),NM(),Bc(),Cx={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"},Px={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"},Rx={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Dx={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ix=(n,e)=>{let t=[];for(let i=e-n;i{let t=[],i=n.length;for(let o=0;on[o]);return[t,s]},Lx=(n,e)=>{let t=n.length+e.length,i=[],s=0;for(let o=0;o{for(let t=0;t{let t=[];if(!Fx(n,e)){for(let i=0;it.push(i))}return t},Nx=(n,e,t,i,s,o,l)=>{let u=t[0].dims,d=et.size(o),f=et.size(l),m=at("_A",t[0].dataType,u),h=Ht("output",s,o),_=64;d===1&&(_=256);let g=` + var aBestValues : array; + `,y=b=>` + ${b.registerUniform("reduceSize","u32").declareVariables(m,h)} + ${g} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${b.mainStart(_)} + + let outputIndex = global_idx / ${_}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Rx[i]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${_}) { + let candidate = f32(${m.getByOffset("offset + k")}); + bestValue = ${Cx[i]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${_}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${Px[i]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${h.setByOffset("outputIndex",`${i==="mean"?`${h.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${h.type.storage}(${Dx[i]})`}`)}; + } + }`;return{name:n,shaderCache:{hint:`${e};${_}`,inputDependencies:["type"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:o,dataType:s}],dispatchGroup:{x:d},programUniforms:[{type:12,data:f}]})}},Oa=(n,e,t,i)=>{let s=n.inputs.length===1?t:My(n.inputs,t),o=s.axes;o.length===0&&!s.noopWithEmptyAxes&&(o=n.inputs[0].dims.map((g,y)=>y));let l=et.normalizeAxes(o,n.inputs[0].dims.length),u=l,d=n.inputs[0],f=kx(u,n.inputs[0].dims.length);f.length>0&&(d=n.compute(Ls(n.inputs[0],f),{inputs:[0],outputs:[-1]})[0],u=Ix(u.length,d.dims.length));let[m,h]=Ox(d.dims,u),_=m;s.keepDims&&(_=Lx(m,l)),n.compute(Nx(e,s.cacheKey,[d],i,n.inputs[0].dataType,_,h),{inputs:[d]})},RS=(n,e)=>{Oa(n,"ReduceMeanShared",e,"mean")},DS=(n,e)=>{Oa(n,"ReduceL1Shared",e,"l1")},IS=(n,e)=>{Oa(n,"ReduceL2Shared",e,"l2")},OS=(n,e)=>{Oa(n,"ReduceLogSumExpShared",e,"logSumExp")},LS=(n,e)=>{Oa(n,"ReduceMaxShared",e,"max")},FS=(n,e)=>{Oa(n,"ReduceMinShared",e,"min")},kS=(n,e)=>{Oa(n,"ReduceProdShared",e,"prod")},NS=(n,e)=>{Oa(n,"ReduceSumShared",e,"sum")},zS=(n,e)=>{Oa(n,"ReduceSumSquareShared",e,"sumSquare")},US=(n,e)=>{Oa(n,"ReduceLogSumShared",e,"logSum")}}),La,zx,qg,My,Fa,Ux,Bx,$x,Vx,Gx,jx,Wx,Hx,qx,Xx,ka,BS,$S,VS,GS,jS,WS,HS,qS,XS,KS,NM=At(()=>{fn(),Mn(),ir(),xn(),UD(),La=n=>{if(!n||n.length===0||n.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(n.length===2&&n[1].dims.length!==1)throw new Error("Invalid axes input dims.")},zx=n=>["","",`var value = ${n.getByIndices("input_indices")};`,""],qg=(n,e,t,i,s,o,l=!1,u=!1)=>{let d=[],f=t[0].dims,m=f.length,h=et.normalizeAxes(s,m),_=!u&&h.length===0;f.forEach((b,T)=>{_||h.indexOf(T)>=0?l&&d.push(1):d.push(b)});let g=d.length,y=et.size(d);return{name:n,shaderCache:e,getShaderSource:b=>{let T=[],v=at("_A",t[0].dataType,m),x=Ht("output",o,g),P=i(v,x,h),w=P[2];for(let C=0,E=0;C=0?(l&&E++,w=`for(var j${C}: u32 = 0; j${C} < ${f[C]}; j${C}++) { + ${P[2].includes("last_index")?`let last_index = j${C};`:""} + ${v.indicesSet("input_indices",C,`j${C}`)} + ${w} + }`):(T.push(`${v.indicesSet("input_indices",C,x.indicesGet("output_indices",E))};`),E++);return` + + ${b.registerUniform("output_size","u32").declareVariables(v,x)} + + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${v.type.indices}; + let output_indices = ${x.offsetToIndices("global_idx")}; + + ${T.join(` +`)} + ${P[0]} // init ops for reduce max/min + ${P[1]} + ${w} + ${P[3]} + ${P.length===4?x.setByOffset("global_idx","value"):P.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:d,dataType:o}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},...en(f,d)]})}},My=(n,e)=>{let t=[];return n[1].dims[0]>0&&n[1].getBigInt64Array().forEach(i=>t.push(Number(i))),ii({axes:t,keepDims:e.keepDims,noopWithEmptyAxes:e.noopWithEmptyAxes})},Fa=(n,e,t,i)=>{let s=n.inputs,o=s.length===1?t:My(s,t);n.compute(qg(e,{hint:o.cacheKey,inputDependencies:["rank"]},[s[0]],o.noopWithEmptyAxes&&o.axes.length===0?zx:i,o.axes,s[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Ux=(n,e)=>{La(n.inputs),Fa(n,"ReduceLogSum",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Bx=(n,e)=>{La(n.inputs),Fa(n,"ReduceL1",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},$x=(n,e)=>{La(n.inputs),Fa(n,"ReduceL2",e,(t,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Vx=(n,e)=>{La(n.inputs),Fa(n,"ReduceLogSumExp",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Gx=(n,e)=>{La(n.inputs),Fa(n,"ReduceMax",e,(t,i,s)=>{let o=[];for(let l=0;l=0||s.length===0)&&o.push(t.indicesSet("input_indices",l,0));return[`${o.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},jx=(n,e)=>{La(n.inputs),Fa(n,"ReduceMean",e,(t,i,s)=>{let o=1;for(let l=0;l=0||s.length===0)&&(o*=n.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${o});`]})},Wx=(n,e)=>{La(n.inputs),Fa(n,"ReduceMin",e,(t,i,s)=>{let o=[];for(let l=0;l=0||s.length===0)&&o.push(`input_indices[${l}] = 0;`);return[`${o.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Hx=(n,e)=>{La(n.inputs),Fa(n,"ReduceProd",e,(t,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},qx=(n,e)=>{La(n.inputs),Fa(n,"ReduceSum",e,(t,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Xx=(n,e)=>{La(n.inputs),Fa(n,"ReduceSumSquare",e,(t,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},ka=(n,e,t)=>{if(e.length===0)return t;let i=1,s=1;for(let o=0;o1024},BS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?jx(n,e):RS(n,e)},$S=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Bx(n,e):DS(n,e)},VS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?$x(n,e):IS(n,e)},GS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Vx(n,e):OS(n,e)},jS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Gx(n,e):LS(n,e)},WS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Wx(n,e):FS(n,e)},HS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Hx(n,e):kS(n,e)},qS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?qx(n,e):NS(n,e)},XS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Xx(n,e):zS(n,e)},KS=(n,e)=>{ka(n.inputs[0].dims,e.axes,e.noopWithEmptyAxes)?Ux(n,e):US(n,e)}}),Q0,YS,QS,by,BD=At(()=>{fn(),ir(),NM(),Q0=n=>{if(!n||n.length===0||n.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(n[0].dataType!==1)throw new Error("Invalid input type.")},YS=(n,e)=>{Q0(n.inputs);let t=(i,s,o)=>{let l=[];for(let u=0;u=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(` +`)}`,`var value = ${i.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${e.selectLastIndex>0?"<=":"<"} value) { + value = ${i.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",s.setByOffset("global_idx","best_index")]};n.compute(qg("ArgMin",{hint:e.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],t,[e.axis],7,e.keepDims),{inputs:[0]})},QS=(n,e)=>{Q0(n.inputs);let t=(i,s,o)=>{let l=[];for(let u=0;u=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(` +`)}`,`var value = ${i.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${e.selectLastIndex>0?">=":">"} value) { + value = ${i.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",s.setByOffset("global_idx","best_index")]};n.compute(qg("argMax",{hint:e.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],t,[e.axis],7,e.keepDims),{inputs:[0]})},by=n=>ii(n)}),Kx,tg,Yx,Qx,Zx,Km,Jx,ZS,zM=At(()=>{fn(),Mn(),FM(),xn(),Kx=(n,e)=>{let t=n[0],i=n[1],s=n[2],o=n[3],l=n[4],u=n[5];if(l&&u)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=t.dims[0],f=t.dims[1],m=t.dims[2];if(s.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(i.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(i.dims[0]!==m)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let h=s.dims[0]/3,_=h,g=_;if(e.qkvHiddenSizes.length>0){if(e.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let P of e.qkvHiddenSizes)if(P%e.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");h=e.qkvHiddenSizes[0],_=e.qkvHiddenSizes[1],g=e.qkvHiddenSizes[2]}let y=f;if(h!==_)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==h+_+g)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let b=0;if(l){if(_!==g)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(l.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(l.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(l.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(l.dims[2]!==e.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(l.dims[4]!==_/e.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');e.pastPresentShareBuffer||(b=l.dims[3])}let T=y+b,v=-1,x=0;if(o)throw new Error("Mask not supported");if(l)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==e.numHeads||u.dims[2]!==f||u.dims[3]!==T)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:f,pastSequenceLength:b,kvSequenceLength:y,totalSequenceLength:T,maxSequenceLength:v,inputHiddenSize:m,hiddenSize:h,vHiddenSize:g,headSize:Math.floor(h/e.numHeads),vHeadSize:Math.floor(g/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:x,scale:e.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},tg=(n,e,t)=>e&&n?` + let total_sequence_length_input = u32(${e.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${n?.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,Yx=(n,e,t,i,s,o,l,u)=>{let d=qi(l?1:o),f=64,m=o/d;m{let x=Ht("x",n.dataType,n.dims,d),P=[x],w=l?at("seq_lens",l.dataType,l.dims):void 0;w&&P.push(w);let C=u?at("total_sequence_length_input",u.dataType,u.dims):void 0;C&&P.push(C);let E=Kr(n.dataType),A=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${v.registerUniforms(A).declareVariables(...P)} + ${v.mainStart([f,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${tg(w,C,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${f}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${l?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${y}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${y}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(d){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: ${d}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${f}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${y}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${y}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(d){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: ${d}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${f}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${x.type.value}(${E}(1.0) / ${E}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${y}(x[offset + i]); + x[offset + i] = ${x.type.value}(exp(f32input - max_value) / sum); + } + } + ${l?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${x.type.value}(${E}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${f};${g};${d}`,inputDependencies:b},getShaderSource:T,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:s,z:e*t},programUniforms:_})}},Qx=(n,e,t,i,s,o,l,u,d)=>{let f=l+o.kvSequenceLength,m=[o.batchSize,o.numHeads,o.sequenceLength,f],h=n>1&&i,_=o.kvNumHeads?o.kvNumHeads:o.numHeads,g=h?[o.batchSize,_,f,o.headSize]:void 0,y=o.nReps?o.nReps:1,b=o.scale===0?1/Math.sqrt(o.headSize):o.scale,T=qi(o.headSize),v=o.headSize/T,x=12,P={x:Math.ceil(f/x),y:Math.ceil(o.sequenceLength/x),z:o.batchSize*o.numHeads},w=[{type:12,data:o.sequenceLength},{type:12,data:v},{type:12,data:f},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:b},{type:12,data:l},{type:12,data:o.kvSequenceLength},{type:12,data:y}],C=h&&i&&et.size(i.dims)>0,E=["type","type"];C&&E.push("type"),s&&E.push("type"),u&&E.push("type"),d&&E.push("type");let A=[{dims:m,dataType:e.dataType,gpuDataType:0}];h&&A.push({dims:g,dataType:e.dataType,gpuDataType:0});let L=I=>{let O=at("q",e.dataType,e.dims,T),H=at("key",t.dataType,t.dims,T),Z=[O,H];if(C){let oe=at("past_key",i.dataType,i.dims,T);Z.push(oe)}s&&Z.push(at("attention_bias",s.dataType,s.dims));let $=u?at("seq_lens",u.dataType,u.dims):void 0;$&&Z.push($);let J=d?at("total_sequence_length_input",d.dataType,d.dims):void 0;J&&Z.push(J);let ee=Ht("output",e.dataType,m),X=[ee];h&&X.push(Ht("present_key",e.dataType,g,T));let ne=Kr(1,T),Q=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${x}u; + + var tileQ: array<${O.type.storage}, ${x*x}>; + var tileK: array<${O.type.storage}, ${x*x}>; + ${I.registerUniforms(Q).declareVariables(...Z,...X)} + ${I.mainStart([x,x,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${y===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${y===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${tg($,J,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${C&&h?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${h?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${ne}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${C&&h?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${h?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${ne}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(T){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: ${T}`)}})()}; + output[outputIdx] = ${ee.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${T};${s!==void 0};${i!==void 0};${n}`,inputDependencies:E},getRunData:()=>({outputs:A,dispatchGroup:P,programUniforms:w}),getShaderSource:L}},Zx=(n,e,t,i,s,o,l=void 0,u=void 0)=>{let d=o+s.kvSequenceLength,f=s.nReps?s.nReps:1,m=s.vHiddenSize*f,h=n>1&&i,_=s.kvNumHeads?s.kvNumHeads:s.numHeads,g=h?[s.batchSize,_,d,s.headSize]:void 0,y=[s.batchSize,s.sequenceLength,m],b=12,T={x:Math.ceil(s.vHeadSize/b),y:Math.ceil(s.sequenceLength/b),z:s.batchSize*s.numHeads},v=[{type:12,data:s.sequenceLength},{type:12,data:d},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:s.headSize},{type:12,data:m},{type:12,data:o},{type:12,data:s.kvSequenceLength},{type:12,data:f}],x=h&&i&&et.size(i.dims)>0,P=["type","type"];x&&P.push("type"),l&&P.push("type"),u&&P.push("type");let w=[{dims:y,dataType:e.dataType,gpuDataType:0}];h&&w.push({dims:g,dataType:e.dataType,gpuDataType:0});let C=E=>{let A=at("probs",e.dataType,e.dims),L=at("v",t.dataType,t.dims),I=[A,L];x&&I.push(at("past_value",i.dataType,i.dims));let O=l?at("seq_lens",l.dataType,l.dims):void 0;l&&I.push(O);let H=u?at("total_sequence_length_input",u.dataType,u.dims):void 0;u&&I.push(H);let Z=[Ht("output",e.dataType,y)];h&&Z.push(Ht("present_value",e.dataType,g));let $=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${b}u; + var tileQ: array<${A.type.value}, ${b*b}>; + var tileV: array<${A.type.value}, ${b*b}>; + ${E.registerUniforms($).declareVariables(...I,...Z)} + ${E.mainStart([b,b,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${f===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${tg(O,H,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${x&&h?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${h?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${A.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${x&&h?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${h?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${n}`,inputDependencies:P},getRunData:()=>({outputs:w,dispatchGroup:T,programUniforms:v}),getShaderSource:C}},Km=(n,e,t,i,s,o,l,u,d,f,m=void 0,h=void 0)=>{let _=Math.min(n.outputCount,1+(l?1:0)+(u?1:0)),g=_>1?f.pastSequenceLength:0,y=g+f.kvSequenceLength,b=d&&et.size(d.dims)>0?d:void 0,T=[e,t];_>1&&l&&et.size(l.dims)>0&&T.push(l),b&&T.push(b),m&&T.push(m),h&&T.push(h);let v=n.compute(Qx(_,e,t,l,b,f,g,m,h),{inputs:T,outputs:_>1?[-1,1]:[-1]})[0];n.compute(Yx(v,f.batchSize,f.numHeads,g,f.sequenceLength,y,m,h),{inputs:m&&h?[v,m,h]:[v],outputs:[]});let x=[v,i];_>1&&u&&et.size(u.dims)>0&&x.push(u),m&&x.push(m),h&&x.push(h),n.compute(Zx(_,v,i,u,f,g,m,h),{inputs:x,outputs:_>1?[0,2]:[0]})},Jx=(n,e)=>{let t=[e.batchSize,e.numHeads,e.sequenceLength,e.headSize],i=e.sequenceLength,s=e.inputHiddenSize,o=e.headSize,l=12,u={x:Math.ceil(e.headSize/l),y:Math.ceil(e.sequenceLength/l),z:e.batchSize*e.numHeads},d=[n.inputs[0],n.inputs[1],n.inputs[2]],f=[{type:12,data:i},{type:12,data:s},{type:12,data:o},{type:12,data:e.numHeads},{type:12,data:e.headSize},{type:12,data:e.hiddenSize},{type:12,data:e.hiddenSize+e.hiddenSize+e.vHiddenSize}],m=h=>{let _=Ht("output_q",d[0].dataType,t),g=Ht("output_k",d[0].dataType,t),y=Ht("output_v",d[0].dataType,t),b=at("input",d[0].dataType,d[0].dims),T=at("weight",d[1].dataType,d[1].dims),v=at("bias",d[2].dataType,d[2].dims),x=b.type.storage,P=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${l}u; + var tileInput: array<${x}, ${l*l}>; + var tileWeightQ: array<${x}, ${l*l}>; + var tileWeightK: array<${x}, ${l*l}>; + var tileWeightV: array<${x}, ${l*l}>; + ${h.registerUniforms(P).declareVariables(b,T,v,_,g,y)} + ${h.mainStart([l,l,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${x}(0); + var valueK = ${x}(0); + var valueV = ${x}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:n.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:f}),getShaderSource:m},{inputs:d,outputs:[-1,-1,-1]})},ZS=(n,e)=>{let t=Kx(n.inputs,e),[i,s,o]=Jx(n,t);return Km(n,i,s,o,n.inputs[4],void 0,void 0,void 0,n.inputs[5],t)}}),ew,tw,nw,JS,$D=At(()=>{Ka(),fn(),Mn(),ir(),xn(),ew=(n,e)=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(i,s,o)=>{let l=s.length;if(l!==i.length)throw new Error(`${o}: num dimensions != ${l}`);s.forEach((u,d)=>{if(u!==i[d])throw new Error(`${o}: dim[${d}] do not match`)})};if(n[0].dims.length>1){let i=e.format==="NHWC"?e.spatial?n[0].dims.slice(-1):n[0].dims.slice(-1).concat(n[0].dims.slice(1,n[0].dims.length-1)):n[0].dims.slice(1,e.spatial?2:void 0);t(n[1].dims,i,"Invalid input scale"),t(n[2].dims,i,"Invalid input B"),t(n[3].dims,i,"Invalid input mean"),t(n[4].dims,i,"Invalid input var")}else t(n[1].dims,[1],"Invalid input scale"),t(n[2].dims,[1],"Invalid input B"),t(n[3].dims,[1],"Invalid input mean"),t(n[4].dims,[1],"Invalid input var")},tw=(n,e)=>{let{epsilon:t,spatial:i,format:s}=e,o=n[0].dims,l=i?qi(o[o.length-1]):1,u=s==="NHWC"&&o.length>1?l:1,d=et.size(o)/l,f=i,m=f?o.length:o,h=at("x",n[0].dataType,n[0].dims,l),_=at("scale",n[1].dataType,n[1].dims,u),g=at("bias",n[2].dataType,n[2].dims,u),y=at("inputMean",n[3].dataType,n[3].dims,u),b=at("inputVar",n[4].dataType,n[4].dims,u),T=Ht("y",n[0].dataType,m,l),v=()=>{let P="";if(i)P=`let cOffset = ${o.length===1?"0u":s==="NHWC"?`outputIndices[${o.length-1}] / ${l}`:"outputIndices[1]"};`;else if(s==="NCHW")P=` + ${T.indicesSet("outputIndices","0","0")} + let cOffset = ${T.indicesToOffset("outputIndices")};`;else{P=`var cIndices = ${_.type.indices}(0); + cIndices[0] = outputIndices[${o.length-1}];`;for(let w=1;w<_.rank;w++)P+=`cIndices[${w}] = outputIndices[${w}];`;P+=`let cOffset = ${_.indicesToOffset("cIndices")};`}return P},x=P=>` + const epsilon = ${t}; + ${P.registerUniform("outputSize","u32").declareVariables(h,_,g,y,b,T)} + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${T.offsetToIndices(`global_idx * ${l}`)}; + ${v()} + let scale = ${_.getByOffset("cOffset")}; + let bias = ${g.getByOffset("cOffset")}; + let inputMean = ${y.getByOffset("cOffset")}; + let inputVar = ${b.getByOffset("cOffset")}; + let x = ${h.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${T.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${e.epsilon}_${e.format}_${i}_${l}`,inputDependencies:f?["rank","type","type","type","type"]:void 0},getShaderSource:x,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f?[{type:12,data:d},...en(o)]:[{type:12,data:d}]})}},nw=n=>ii(n),JS=(n,e)=>{let{inputs:t,outputCount:i}=n,s=nw({...e,outputCount:i});if(Di.webgpu.validateInputContent&&ew(t,s),e.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");n.compute(tw(t,s))}}),iw,rw,eA,VD=At(()=>{Mn(),xn(),iw=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(n[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},rw=n=>{let e=n[0].dims,t=n[0].dims[2],i=et.size(e)/4,s=n[0].dataType,o=at("input",s,e,4),l=at("bias",s,[t],4),u=at("residual",s,e,4),d=Ht("output",s,e,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:e,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:f=>` + const channels = ${t}u / 4; + ${f.declareVariables(o,l,u,d)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes(i)} + let value = ${o.getByOffset("global_idx")} + + ${l.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${d.setByOffset("global_idx","value")} + }`}},eA=n=>{iw(n.inputs),n.compute(rw(n.inputs))}}),sw,Zn,tA,nA,iA,rA,sA,aA,oA,lA,cA,aw,uA,dA,fA,hA,Bm,pA,kg,mA,_A,gA,vA,yA,MA,bA,xA,wA,TA,EA,SA,AA,CA,PA,RA,Z0,DA,xy,wy,IA,OA,LA,ow,lw,FA,UM=At(()=>{fn(),Mn(),ir(),xn(),sw=(n,e,t,i,s,o,l)=>{let u=Math.ceil(e/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let f=at("inputData",t,[u],4),m=Ht("outputData",i,[u],4),h=[{name:"vec_size",type:"u32"}];return l&&h.push(...l),` + ${n.registerUniforms(h).declareVariables(f,m)} + + ${o??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${f.getByOffset("global_idx")}; + ${m.setByOffset("global_idx",d)} + }`},Zn=(n,e,t,i,s,o=n.dataType,l,u)=>{let d=[{type:12,data:Math.ceil(et.size(n.dims)/4)}];return l&&d.push(...l),{name:e,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:f=>sw(f,et.size(n.dims),n.dataType,o,t,i,u),getRunData:f=>({outputs:[{dims:n.dims,dataType:o}],dispatchGroup:{x:Math.ceil(et.size(f[0].dims)/64/4)},programUniforms:d})}},tA=n=>{n.compute(Zn(n.inputs[0],"Abs","abs"))},nA=n=>{n.compute(Zn(n.inputs[0],"Acos","acos"))},iA=n=>{n.compute(Zn(n.inputs[0],"Acosh","acosh"))},rA=n=>{n.compute(Zn(n.inputs[0],"Asin","asin"))},sA=n=>{n.compute(Zn(n.inputs[0],"Asinh","asinh"))},aA=n=>{n.compute(Zn(n.inputs[0],"Atan","atan"))},oA=n=>{n.compute(Zn(n.inputs[0],"Atanh","atanh"))},lA=n=>ii(n),cA=(n,e)=>{let t;switch(e.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${e.to}`)}n.compute(Zn(n.inputs[0],"Cast",t,void 0,e.cacheKey,e.to))},aw=n=>{let e,t,i=n.length>=2&&n[1].data!==0,s=n.length>=3&&n[2].data!==0;switch(n[0].dataType){case 1:e=i?n[1].getFloat32Array()[0]:-34028234663852886e22,t=s?n[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:e=i?n[1].getUint16Array()[0]:64511,t=s?n[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return ii({min:e,max:t})},uA=(n,e)=>{let t=e||aw(n.inputs),i=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"Clip",s=>`clamp(${s}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:n.inputs[0].dataType,data:t.min},{type:n.inputs[0].dataType,data:t.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},dA=n=>{n.compute(Zn(n.inputs[0],"Ceil","ceil"))},fA=n=>{n.compute(Zn(n.inputs[0],"Cos","cos"))},hA=n=>{n.compute(Zn(n.inputs[0],"Cosh","cosh"))},Bm=n=>ii(n),pA=(n,e)=>{let t=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"Elu",i=>`elu_vf32(${i})`,` + const elu_alpha_ = ${t}(${e.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,e.cacheKey))},kg=(n="f32")=>` +const r0: ${n} = 0.3275911; +const r1: ${n} = 0.254829592; +const r2: ${n} = -0.284496736; +const r3: ${n} = 1.421413741; +const r4: ${n} = -1.453152027; +const r5: ${n} = 1.061405429; + +fn erf_vf32(v: vec4<${n}>) -> vec4<${n}> { + let absv = abs(v); + let x = 1.0 / (1.0 + r0 * absv); + return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); +}`,mA=n=>{let e=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"Erf",t=>`erf_vf32(${t})`,kg(e)))},_A=n=>{n.compute(Zn(n.inputs[0],"Exp","exp"))},gA=n=>{n.compute(Zn(n.inputs[0],"Floor","floor"))},vA=n=>{let e=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,kg(e)))},yA=(n,e)=>{let t=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${e.alpha});`,e.cacheKey))},MA=n=>{n.compute(Zn(n.inputs[0],"Not",e=>`!${e}`))},bA=n=>{n.compute(Zn(n.inputs[0],"Neg",e=>`-${e}`))},xA=n=>{n.compute(Zn(n.inputs[0],"Reciprocal",e=>`1.0/${e}`))},wA=n=>{let e=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"Relu",t=>`select(vec4<${e}>(0.0), ${t}, ${t} > vec4<${e}>(0.0))`))},TA=n=>{n.compute(Zn(n.inputs[0],"Sigmoid",e=>`(1.0 / (1.0 + exp(-${e})))`))},EA=n=>ii(n),SA=(n,e)=>{let t=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"HardSigmoid",i=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${e.alpha} * ${i} + vec4<${t}>(${e.beta})))`,void 0,e.cacheKey))},AA=n=>{n.compute(Zn(n.inputs[0],"Sin","sin"))},CA=n=>{n.compute(Zn(n.inputs[0],"Sinh","sinh"))},PA=n=>{n.compute(Zn(n.inputs[0],"Sqrt","sqrt"))},RA=n=>{n.compute(Zn(n.inputs[0],"Tan","tan"))},Z0=n=>`sign(${n}) * (1 - exp(-2 * abs(${n}))) / (1 + exp(-2 * abs(${n})))`,DA=n=>{n.compute(Zn(n.inputs[0],"Tanh",Z0))},xy=(n="f32")=>` +const fast_gelu_a: ${n} = 0.5; +const fast_gelu_b: ${n} = 0.7978845608028654; +const fast_gelu_c: ${n} = 0.035677408136300125; + +fn tanh_v(v: vec4<${n}>) -> vec4<${n}> { + return ${Z0("v")}; +} +`,wy=n=>`(fast_gelu_a + fast_gelu_a * tanh_v(${n} * (fast_gelu_c * ${n} * ${n} + fast_gelu_b))) * ${n}`,IA=n=>{let e=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"FastGelu",wy,xy(e),void 0,n.inputs[0].dataType))},OA=(n,e)=>{let t=Kr(n.inputs[0].dataType);return n.compute(Zn(n.inputs[0],"ThresholdedRelu",i=>`select(vec4<${t}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${e.alpha});`,e.cacheKey)),0},LA=n=>{n.compute(Zn(n.inputs[0],"Log","log"))},ow=(n,e)=>` +const alpha = vec4<${n}>(${e}); +const one = ${n}(1.0); +const zero = ${n}(0.0); + +fn quick_gelu_impl(x: vec4<${n}>) -> vec4<${n}> { + let v = x *alpha; + var x1 : vec4<${n}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,lw=n=>`quick_gelu_impl(${n})`,FA=(n,e)=>{let t=Kr(n.inputs[0].dataType);n.compute(Zn(n.inputs[0],"QuickGelu",lw,ow(t,e.alpha),e.cacheKey,n.inputs[0].dataType))}}),cw,uw,kA,GD=At(()=>{Mn(),xn(),UM(),cw=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(n[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},uw=n=>{let e=n[0].dims.slice();e[2]=e[2]/2;let t=at("input",n[0].dataType,n[0].dims,4),i=at("bias",n[0].dataType,[n[0].dims[2]],4),s=Ht("output",n[0].dataType,e,4),o=et.size(e)/4,l=xr(n[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:e,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${n[0].dims[2]/4/2}u; + + ${u.declareVariables(t,i,s)} + + ${kg(l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(o)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${s.setByOffset("global_idx","valueLeft * geluRight")} + }`}},kA=n=>{cw(n.inputs),n.compute(uw(n.inputs))}}),dw,fw,Na,NA,zA,UA,BA,$A,VA,GA,jA,WA,HA,jD=At(()=>{fn(),Mn(),xn(),dw=(n,e,t,i,s,o,l,u,d,f,m,h)=>{let _,g;typeof u=="string"?_=g=(x,P)=>`${u}((${x}),(${P}))`:typeof u=="function"?_=g=u:(_=u.scalar,g=u.vector);let y=Ht("outputData",m,i.length,4),b=at("aData",d,e.length,4),T=at("bData",f,t.length,4),v;if(s)if(o){let x=et.size(e)===1,P=et.size(t)===1,w=e.length>0&&e[e.length-1]%4===0,C=t.length>0&&t[t.length-1]%4===0;x||P?v=y.setByOffset("global_idx",g(x?`${b.type.value}(${b.getByOffset("0")}.x)`:b.getByOffset("global_idx"),P?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"))):v=` + let outputIndices = ${y.offsetToIndices("global_idx * 4u")}; + let offsetA = ${b.broadcastedIndicesToOffset("outputIndices",y)}; + let offsetB = ${T.broadcastedIndicesToOffset("outputIndices",y)}; + ${y.setByOffset("global_idx",g(l||w?b.getByOffset("offsetA / 4u"):`${b.type.value}(${b.getByOffset("offsetA / 4u")}[offsetA % 4u])`,l||C?T.getByOffset("offsetB / 4u"):`${T.type.value}(${T.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else v=y.setByOffset("global_idx",g(b.getByOffset("global_idx"),T.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let x=(P,w,C="")=>{let E=`aData[indexA${w}][componentA${w}]`,A=`bData[indexB${w}][componentB${w}]`;return` + let outputIndices${w} = ${y.offsetToIndices(`global_idx * 4u + ${w}u`)}; + let offsetA${w} = ${b.broadcastedIndicesToOffset(`outputIndices${w}`,y)}; + let offsetB${w} = ${T.broadcastedIndicesToOffset(`outputIndices${w}`,y)}; + let indexA${w} = offsetA${w} / 4u; + let indexB${w} = offsetB${w} / 4u; + let componentA${w} = offsetA${w} % 4u; + let componentB${w} = offsetB${w} % 4u; + ${P}[${w}] = ${C}(${_(E,A)}); + `};m===9?v=` + var data = vec4(0); + ${x("data",0,"u32")} + ${x("data",1,"u32")} + ${x("data",2,"u32")} + ${x("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:v=` + ${x("outputData[global_idx]",0)} + ${x("outputData[global_idx]",1)} + ${x("outputData[global_idx]",2)} + ${x("outputData[global_idx]",3)} + `}return` + ${n.registerUniform("vec_size","u32").declareVariables(b,T,y)} + + ${h??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v} + }`},fw=(n,e,t,i,s,o,l=t.dataType)=>{let u=t.dims.map(b=>Number(b)??1),d=i.dims.map(b=>Number(b)??1),f=!et.areEqual(u,d),m=u,h=et.size(u),_=!1,g=!1,y=[f];if(f){let b=uh.calcShape(u,d,!1);if(!b)throw new Error("Can't perform binary op on the given tensors");m=b.slice(),h=et.size(m);let T=et.size(u)===1,v=et.size(d)===1,x=u.length>0&&u[u.length-1]%4===0,P=d.length>0&&d[d.length-1]%4===0;y.push(T),y.push(v),y.push(x),y.push(P);let w=1;for(let C=1;Cb.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:b=>dw(b,u,d,m,_,f,g,s,t.dataType,i.dataType,l,o),getRunData:()=>({outputs:[{dims:m,dataType:l}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(et.size(m)/4)},...en(u,d,m)]})}},Na=(n,e,t,i,s,o)=>{n.compute(fw(e,s??"",n.inputs[0],n.inputs[1],t,i,o))},NA=n=>{Na(n,"Add",(e,t)=>`${e}+${t}`)},zA=n=>{Na(n,"Div",(e,t)=>`${e}/${t}`)},UA=n=>{Na(n,"Equal",{scalar:(e,t)=>`u32(${e}==${t})`,vector:(e,t)=>`vec4(${e}==${t})`},void 0,void 0,9)},BA=n=>{Na(n,"Mul",(e,t)=>`${e}*${t}`)},$A=n=>{let e=at("input",n.inputs[0].dataType,n.inputs[0].dims).type.value;Na(n,"Pow",{scalar:(t,i)=>`pow_custom(${t},${i})`,vector:(t,i)=>`pow_vector_custom(${t},${i})`},` + fn pow_custom(a : ${e}, b : ${e}) -> ${e} { + if (b == ${e}(0.0)) { + return ${e}(1.0); + } else if (a < ${e}(0.0) && f32(b) != floor(f32(b))) { + return ${e}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${e}(1.0), round(f32(abs(b) % ${e}(2.0))) != 1.0) * ${e}(${e==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${e}>, b : vec4<${e}>) -> vec4<${e}> { + // TODO: implement vectorized pow + return vec4<${e}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},VA=n=>{Na(n,"Sub",(e,t)=>`${e}-${t}`)},GA=n=>{Na(n,"Greater",{scalar:(e,t)=>`u32(${e}>${t})`,vector:(e,t)=>`vec4(${e}>${t})`},void 0,void 0,9)},jA=n=>{Na(n,"Less",{scalar:(e,t)=>`u32(${e}<${t})`,vector:(e,t)=>`vec4(${e}<${t})`},void 0,void 0,9)},WA=n=>{Na(n,"GreaterOrEqual",{scalar:(e,t)=>`u32(${e}>=${t})`,vector:(e,t)=>`vec4(${e}>=${t})`},void 0,void 0,9)},HA=n=>{Na(n,"LessOrEqual",{scalar:(e,t)=>`u32(${e}<=${t})`,vector:(e,t)=>`vec4(${e}<=${t})`},void 0,void 0,9)}}),hw,pw,mw,_w,qA,XA,WD=At(()=>{fn(),Mn(),ir(),xn(),hw=(n,e)=>{if(!n||n.length<1)throw new Error("too few inputs");let t=0,i=n[t],s=i.dataType,o=i.dims.length;n.forEach((l,u)=>{if(u!==t){if(l.dataType!==s)throw new Error("input tensors should be one type");if(l.dims.length!==o)throw new Error("input tensors should have the same shape");l.dims.forEach((d,f)=>{if(f!==e&&d!==i.dims[f])throw new Error("non concat dimensions must match")})}})},pw=(n,e)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${e}); + for (var i: u32 = 0u; i < ${n}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${n}u; + }`,mw=(n,e)=>{let t=n.length,i=[];for(let s=0;s{let s=et.size(t),o=new Array(n.length),l=new Array(n.length),u=0,d=[],f=[],m=[{type:12,data:s}];for(let b=0;b`uniforms.sizeInConcatAxis${b}`).join(","),y=b=>` + + ${(()=>{b.registerUniform("outputSize","u32");for(let T=0;T(${g}); + ${_} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${mw(l,h)} + }`;return{name:"Concat",shaderCache:{hint:`${e}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:t,dataType:i}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:m}),getShaderSource:y}},qA=(n,e)=>{let t=n.inputs,i=t[0].dims,s=et.normalizeAxis(e.axis,i.length);hw(t,s);let o=i.slice();o[s]=t.reduce((u,d)=>u+(d.dims.length>s?d.dims[s]:0),0);let l=t.filter(u=>et.size(u.dims)>0);n.compute(_w(l,s,o,t[0].dataType),{inputs:l})},XA=n=>ii({axis:n.axis})}),od,ld,cd,BM,hd=At(()=>{fn(),Mn(),od=(n,e,t="f32")=>{switch(n.activation){case"Relu":return`value = max(value, ${e}(0.0));`;case"Sigmoid":return`value = (${e}(1.0) / (${e}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${e}(${t}(uniforms.clip_min)), ${e}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${e}(0.0), min(${e}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${e}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${n.activation}`)}},ld=(n,e)=>{n.activation==="Clip"?e.push({type:1,data:n.clipMax},{type:1,data:n.clipMin}):n.activation==="HardSigmoid"?e.push({type:1,data:n.alpha},{type:1,data:n.beta}):n.activation==="LeakyRelu"&&e.push({type:1,data:n.alpha})},cd=(n,e)=>{n.activation==="Clip"?e.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):n.activation==="HardSigmoid"?e.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):n.activation==="LeakyRelu"&&e.push({name:"alpha",type:"f32"})},BM=n=>{let e=n?.activation||"";if(e==="HardSigmoid"){let[t,i]=n?.activation_params||[.2,.5];return{activation:e,alpha:t,beta:i}}else if(e==="Clip"){let[t,i]=n?.activation_params||[MS,bS];return{activation:e,clipMax:i,clipMin:t}}else if(e==="LeakyRelu"){let[t]=n?.activation_params||[.01];return{activation:e,alpha:t}}return{activation:e}}}),Ir,KA,$M=At(()=>{Ir=(n,e)=>{switch(n){case 1:return e;case 2:return`vec2<${e}>`;case 3:return`vec3<${e}>`;case 4:return`vec4<${e}>`;default:throw new Error(`${n}-component is not supported.`)}},KA=n=>` + ${n?"value = value + getBiasByOutputCoords(coords);":""} + `}),YA,HD=At(()=>{YA=n=>` +fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { + return dot(coords, vec4( + shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); +} +fn getOutputIndexFromCoords(coords : vec4) -> i32 { + return dot(coords, vec4( + i32(${n}.x), i32(${n}.y), i32(${n}.z), 1)); +} +`}),jm,VM,GM=At(()=>{fn(),Mn(),xn(),hd(),jm=(n,e,t,i,s)=>{let o=i-t;return` + ${Array.from({length:t}).map((l,u)=>` + if (${Yt(e.shape,u,e.rank)} != 1) { + ${e.indicesSet(n,u,Yt(s,u+o,i))} + } else { + ${e.indicesSet(n,u,0)} + }`).join("")} +`},VM=(n,e,t,i,s=!1,o)=>{let l=n[0].dims,u=n[1].dims,d=l[l.length-2],f=u[u.length-1],m=l[l.length-1],h=qi(f),_=qi(m),g=qi(d),y=et.size(t)/h/g,b=n.length>2,T=i?i.slice(0,-2):t.slice(0,-2),v=[et.size(T),d,f],x=[{type:12,data:y},{type:12,data:d},{type:12,data:f},{type:12,data:m}];ld(e,x),x.push(...en(T,l,u)),b&&x.push(...en(n[2].dims)),x.push(...en(v));let P=w=>{let C=kM("batch_dims",n[0].dataType,T.length),E=at("a",n[0].dataType,l.length,_),A=at("b",n[1].dataType,u.length,h),L=Ht("output",n[0].dataType,v.length,h),I=xr(L.type.tensor),O=od(e,L.type.value,I),H=[E,A],Z="";if(b){let ee=s?h:1;H.push(at("bias",n[2].dataType,n[2].dims.length,ee)),Z=`${s?`value += bias[col / ${ee}];`:`value += ${L.type.value}(bias[row + i]);`}`}let $=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];cd(e,$);let J=()=>{let ee=`var a_data: ${E.type.value};`;for(let X=0;X<_;X++)ee+=` + let b_data${X} = b[(b_offset + (k + ${X}) * uniforms.N + col) / ${h}];`;for(let X=0;X; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${_}) { + ${J()} + } + for (var i = 0u; i < ${g}u; i++) { + var value = values[i]; + ${Z} + ${O} + let cur_indices = ${L.type.indices}(batch, row + i, col); + let offset = ${L.indicesToOffset("cur_indices")}; + ${L.setByOffset(`offset / ${h}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${e.activation};${h};${_};${g};${s}`,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:x}),getShaderSource:P}}}),gw,vw,Ty,J0,yw,Ey,Mw,Xg,jM=At(()=>{fn(),Mn(),xn(),hd(),GM(),$M(),gw=(n,e)=>n?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${e?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${e?", batchIndices":""}); + `,vw=(n,e)=>n?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${e===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${e===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${e===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Ty=(n,e,t="f32",i,s=!1,o=32,l=!1,u=32)=>{let d=e[1]*n[1],f=e[0]*n[0],m=s?d:o,h=s?o:d,_=m/e[0],g=o/e[1];if(!((s&&_===4&&n[1]===4||!s&&(_===3||_===4))&&m%e[0]===0&&o%e[1]===0&&n[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${_} and workPerThread[1] ${n[1]} must be 4. + Otherwise, innerElementSize ${_} must be 3 or 4. + tileAWidth ${m} must be divisible by workgroupSize[0]${e[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${e[1]}. colPerThread ${n[0]} must be 4.`);return` +var mm_Asub: array, ${m/_}>, ${h}>; +var mm_Bsub: array, ${f/n[0]}>, ${o}>; + +const rowPerThread = ${n[1]}; +const colPerThread = ${n[0]}; +const innerElementSize = ${_}; +const tileInner = ${o}; + +@compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${l?"0":"i32(globalId.z)"}; + ${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${d}; + + let num_tiles = ${l?`${Math.ceil(u/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${l?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${g}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${gw(s,i)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${i?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${_===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${vw(s,_)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},J0=(n,e)=>n?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${e?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${e?", batchIndices":""}); + `,yw=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ey=(n,e,t="f32",i,s=!1,o=32,l=!1,u=32,d=!1)=>{let f=n[1]*e[1],m=n[0]*e[0],h=s?f:o,_=s?o:f;if(!(_%e[1]===0&&h%e[0]===0&&o%e[1]===0))throw new Error(`tileAHight ${_} must be divisible by workgroupSize[1]${e[1]}, tileAWidth ${h} must be divisible by workgroupSize[0]${e[0]}, tileInner ${o} must be divisible by workgroupSize[1]${e[1]}`);let g=_/e[1],y=h/e[0],b=o/e[1],T=d?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${f}; + let globalColStart = i32(workgroupId.x) * ${m}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${_}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${h}; inputCol = inputCol + ${e[0]}) { + ${J0(s,i)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${e[1]}) { + for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${e[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${i?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${e[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${s?`mm_Asub[k][localRow + innerRow * ${e[1]}];`:`mm_Asub[localRow + innerRow * ${e[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${e[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${e[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${f}; + +let tileRowA = i32(localId.y) * ${g}; +let tileColA = i32(localId.x) * ${y}; +let tileRowB = i32(localId.y) * ${b}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${g}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${J0(s,i)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${i?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${yw(s)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${_}>; + var mm_Bsub : array, ${o}>; + const rowPerThread = ${n[1]}; + const colPerThread = ${n[0]}; + const tileInner = ${o}; + +@compute @workgroup_size(${e[0]}, ${e[1]}, ${e[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${l?"0":"i32(globalId.z)"}; + ${i?`let batchIndices = ${i.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${l?`${Math.ceil(u/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${l?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${T} + } +`},Mw=(n,e,t,i,s=!1)=>{let[o,l,u,d]=i,f=xr(i[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${Ir(n,f)} { + var value = ${Ir(n,f)}(0.0); + let col = colIn * ${n}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${l.type.indices}; + ${jm("aIndices",l,l.rank-2,o.rank,"batchIndices")} + ${l.indicesSet("aIndices",l.rank-2,"u32(row)")} + ${l.indicesSet("aIndices",l.rank-1,"u32(colIn)")} + value = ${l.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${Ir(n,f)} { + var value = ${Ir(n,f)}(0.0); + let col = colIn * ${n}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${u.type.indices}; + ${jm("bIndices",u,u.rank-2,o.rank,"batchIndices")} + ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} + ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ir(n,f)}) { + let col = colIn * ${n}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${e?`value = value + ${s?"bias[colIn]":`${Ir(n,f)}(bias[row])`};`:""} + ${t} + ${d.setByIndices("vec3(coords)","value")} + } + } + `},Xg=(n,e,t,i,s=!1,o)=>{let l=n[0].dims,u=n[1].dims,d=l.slice(0,-2),f=u.slice(0,-2),m=i?i.slice(0,-2):t.slice(0,-2),h=et.size(m),_=l[l.length-2],g=l[l.length-1],y=u[u.length-1],b=g%4===0&&y%4===0,T=_<=8?[4,1,1]:[4,4,1],v=[8,8,1],x=[Math.ceil(y/v[0]/T[0]),Math.ceil(_/v[1]/T[1]),Math.ceil(h/v[2]/T[2])],P=b?4:1,w=[...d,_,g/P],C=w.length,E=[...f,g,y/P],A=E.length,L=[h,_,y/P],I=[{type:6,data:_},{type:6,data:y},{type:6,data:g}];ld(e,I),I.push(...en(m,w,E));let O=["rank","rank"],H=n.length>2;H&&(I.push(...en(n[2].dims)),O.push("rank")),I.push(...en(L));let Z=$=>{let J=m.length,ee=kM("batchDims",n[0].dataType,J,1),X=xr(n[0].dataType),ne=at("a",n[0].dataType,C,P),Q=at("b",n[1].dataType,A,P),oe=Ht("result",n[0].dataType,L.length,P),W=[ne,Q];if(H){let le=s?P:1;W.push(at("bias",n[2].dataType,n[2].dims.length,le))}let q=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];cd(e,q);let G=xr(oe.type.tensor),te=od(e,oe.type.value,G),B=Mw(P,H,te,[ee,ne,Q,oe],s);return` + ${$.registerUniforms(q).registerInternalVariables(ee).declareVariables(...W,oe)} + ${B} + ${b?Ty(T,v,X,ee):Ey(T,v,X,ee)} + `};return{name:"MatMul",shaderCache:{hint:`${T};${e.activation};${b};${s}`,inputDependencies:O},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:n[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:I}),getShaderSource:Z}}}),bw,QA,qD=At(()=>{fn(),Cl(),xn(),hd(),$M(),HD(),jM(),bw=(n,e,t,i,s=!1,o,l=4,u=4,d=4,f="f32")=>{let m=I=>{switch(I){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${f}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${I} is not supported.`)}},h=I=>{switch(I){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 ${I} is not supported.`)}},_=n?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,g=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,y=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",b=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",T=n?"row":"col",v=n?"col":"row",x=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${T} / outWidth; + let outCol = ${T} % outWidth; + + let WRow = ${v} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${v} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${v} % inChannels; + var resData = ${Ir(l,f)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${b}) { + ${_} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${m(l)} + } + return resData;`,P=n?e&&i?` + let col = colIn * ${l}; + ${x}`:` + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${x} + } + return ${Ir(l,f)}(0.0);`:i&&t?` + let col = colIn * ${l}; + ${x}`:` + let col = colIn * ${l}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${x} + } + return ${Ir(l,f)}(0.0);`,w=n?i&&t?h(u):` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${h(u)} + } + return ${Ir(u,f)}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${h(u)} + } + return ${Ir(u,f)}(0.0);`,C=Ir(d,f),E=Ir(n?l:u,f),A=Ir(n?u:l,f),L=od(o,C,f);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${E} { + ${n?P:w} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${A} { + ${n?w:P} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${C}) { + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${g} + ${KA(s)} + ${L} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},QA=(n,e,t,i,s,o,l,u,d)=>{let f=e.format==="NHWC",m=f?n[0].dims[3]:n[0].dims[1],h=t[0],_=f?t[2]:t[3],g=f?t[1]:t[2],y=f?t[3]:t[1],b=f&&(m%4===0||m%3===0)&&y%4===0,T=f?y:_*g,v=f?_*g:y,x=[8,8,1],P=i<=8?[4,1,1]:[4,4,1],w=[Math.ceil(T/x[0]/P[0]),Math.ceil(v/x[1]/P[1]),Math.ceil(h/x[2]/P[2])];qn("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${w}`);let C=b?f&&m%4!==0?3:4:1,E=x[1]*P[1],A=x[0]*P[0],L=Math.max(x[0]*C,x[1]),I=i%E===0,O=s%A===0,H=o%L===0,Z=b?[C,4,4]:[1,1,1],$=[{type:6,data:i},{type:6,data:s},{type:6,data:o},{type:6,data:[e.pads[0],e.pads[1]]},{type:6,data:e.strides},{type:6,data:e.dilations}];ld(e,$),$.push(...en(n[0].dims,n[1].dims));let J=["rank","rank"];l&&($.push(...en(n[2].dims)),J.push("rank")),$.push(...en(t));let ee=X=>{let ne=[{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}];cd(e,ne);let Q=b?4:1,oe=xr(n[0].dataType),W=` + fn setOutputAtIndex(flatIndex : i32, value : ${b?`vec4<${oe}>`:oe}) { + result[flatIndex] = ${b?`vec4<${oe}>`:oe}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${b?`vec4<${oe}>`:oe}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${b?"/ 4":""}, value); + }`,q=at("x",n[0].dataType,n[0].dims.length,C===3?1:C),G=at("w",n[1].dataType,n[1].dims.length,Q),te=[q,G],B=Ht("result",n[0].dataType,t.length,Q);if(l){let le=at("bias",n[2].dataType,n[2].dims.length,Q);te.push(le),W+=` + fn getBiasByOutputCoords(coords : vec4) -> ${b?`vec4<${oe}>`:oe} { + return bias[coords.${f?"w":"y"}${b?"/ 4":""}]; + }`}return` + ${YA("uniforms.result_strides")} + //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, + // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, + // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${X.registerUniforms(ne).declareVariables(...te,B)} + ${W} + ${bw(f,I,O,H,l,e,Z[0],Z[1],Z[2],oe)} + ${b?Ty(P,x,oe,void 0,!f,L):Ey(P,x,oe,void 0,!f,L,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${e.cacheKey};${C};${b};${I};${O};${H};${E};${A};${L}`,inputDependencies:J},getRunData:()=>({outputs:[{dims:d?d(t):t,dataType:n[0].dataType}],dispatchGroup:{x:w[0],y:w[1],z:w[2]},programUniforms:$}),getShaderSource:ee}}}),xw,ev,Sm,ww,tv,Tw,ZA,JA,XD=At(()=>{fn(),Cl(),Mn(),xn(),hd(),$M(),xw=n=>{let e=1;for(let t=0;ttypeof n=="number"?[n,n,n]:n,Sm=(n,e)=>e<=1?n:n+(n-1)*(e-1),ww=(n,e,t,i=1)=>{let s=Sm(e,i);return Math.floor((n[0]*(t-1)-t+s)/2)},tv=(n,e,t,i,s)=>{s==null&&(s=ww(n,e[0],i[0]));let o=[0,0,0,t];for(let l=0;l<3;l++)n[l]+2*s>=e[l]&&(o[l]=Math.trunc((n[l]-e[l]+2*s)/i[l]+1));return o},Tw=(n,e,t,i,s,o,l,u,d,f)=>{let m,h,_,g;if(n==="VALID"&&(n=0),typeof n=="number"){m={top:n,bottom:n,left:n,right:n,front:n,back:n};let y=tv([e,t,i,1],[u,d,f],1,[s,o,l],n);h=y[0],_=y[1],g=y[2]}else if(Array.isArray(n)){if(!n.every((b,T,v)=>b===v[0]))throw Error(`Unsupported padding parameter: ${n}`);m={top:n[0],bottom:n[1],left:n[2],right:n[3],front:n[4],back:n[5]};let y=tv([e,t,i,1],[u,d,f],1,[s,o,l],n[0]);h=y[0],_=y[1],g=y[2]}else if(n==="SAME_UPPER"){h=Math.ceil(e/s),_=Math.ceil(t/o),g=Math.ceil(i/l);let y=(h-1)*s+u-e,b=(_-1)*o+d-t,T=(g-1)*l+f-i,v=Math.floor(y/2),x=y-v,P=Math.floor(b/2),w=b-P,C=Math.floor(T/2),E=T-C;m={top:P,bottom:w,left:C,right:E,front:v,back:x}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:m,outDepth:h,outHeight:_,outWidth:g}},ZA=(n,e,t,i,s,o=!1,l="channelsLast")=>{let u,d,f,m,h;if(l==="channelsLast")[u,d,f,m,h]=n;else if(l==="channelsFirst")[u,h,d,f,m]=n;else throw new Error(`Unknown dataFormat ${l}`);let[_,,g,y,b]=e,[T,v,x]=ev(t),[P,w,C]=ev(i),E=Sm(g,P),A=Sm(y,w),L=Sm(b,C),{padInfo:I,outDepth:O,outHeight:H,outWidth:Z}=Tw(s,d,f,m,T,v,x,E,A,L),$=o?_*h:_,J=[0,0,0,0,0];return l==="channelsFirst"?J=[u,$,O,H,Z]:l==="channelsLast"&&(J=[u,O,H,Z,$]),{batchSize:u,dataFormat:l,inDepth:d,inHeight:f,inWidth:m,inChannels:h,outDepth:O,outHeight:H,outWidth:Z,outChannels:$,padInfo:I,strideDepth:T,strideHeight:v,strideWidth:x,filterDepth:g,filterHeight:y,filterWidth:b,effectiveFilterDepth:E,effectiveFilterHeight:A,effectiveFilterWidth:L,dilationDepth:P,dilationHeight:w,dilationWidth:C,inShape:n,outShape:J,filterShape:e}},JA=(n,e,t,i,s,o)=>{let l=o==="channelsLast";l?n[0].dims[3]:n[0].dims[1];let u=[64,1,1],d={x:t.map((T,v)=>v)},f=[Math.ceil(xw(d.x.map(T=>t[T]))/u[0]),1,1];qn("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${f}`);let m=1,h=et.size(t),_=[{type:12,data:h},{type:12,data:i},{type:12,data:s},{type:12,data:e.strides},{type:12,data:e.dilations}];ld(e,_),_.push(...en(n[0].dims,n[1].dims));let g=["rank","rank"],y=n.length===3;y&&(_.push(...en(n[2].dims)),g.push("rank")),_.push(...en(t));let b=T=>{let v=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:e.strides.length},{name:"dilations",type:"u32",length:e.dilations.length}];cd(e,v);let x=1,P=xr(n[0].dataType),w=at("x",n[0].dataType,n[0].dims.length,m),C=at("W",n[1].dataType,n[1].dims.length,x),E=[w,C],A=Ht("result",n[0].dataType,t.length,x),L="";if(y){let H=at("bias",n[2].dataType,n[2].dims.length,x);E.push(H),L+=` + fn getBiasByOutputCoords(coords : array) -> ${P} { + return bias[${l?Yt("coords",4,5):Yt("coords",1,5)}]; + }`}let I=Ir(m,P),O=od(e,I,P);return` + ${L} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${w.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${C.getByIndices("aIndices")}; + } + ${T.registerUniforms(v).declareVariables(...E,A)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${A.offsetToIndices("global_idx")}; + let batch = ${Yt("coords",0,w.rank)}; + let d2 = ${l?Yt("coords",w.rank-1,w.rank):Yt("coords",1,w.rank)}; + let xFRCCorner = vec3(${l?Yt("coords",1,w.rank):Yt("coords",2,w.rank)}, + ${l?Yt("coords",2,w.rank):Yt("coords",3,w.rank)}, + ${l?Yt("coords",3,w.rank):Yt("coords",4,w.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${l?Yt("uniforms.x_shape",1,w.rank):Yt("uniforms.x_shape",2,w.rank)}; + let xShapeZ = ${l?Yt("uniforms.x_shape",2,w.rank):Yt("uniforms.x_shape",3,w.rank)}; + let xShapeW = ${l?Yt("uniforms.x_shape",3,w.rank):Yt("uniforms.x_shape",4,w.rank)}; + let xShapeU = ${l?Yt("uniforms.x_shape",4,w.rank):Yt("uniforms.x_shape",1,w.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${l?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${l?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${l?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${l?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${y?"value = value + getBiasByOutputCoords(coords)":""}; + ${O} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${e.cacheKey};${l};${m};${y}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:f[0],y:f[1],z:f[2]},programUniforms:_}),getShaderSource:b}}}),e2,t2,KD=At(()=>{fn(),Mn(),xn(),hd(),e2=(n,e,t,i)=>{let s=n.length>2,o=s?"value += b[output_channel];":"",l=n[0].dims,u=n[1].dims,d=e.format==="NHWC",f=d?t[3]:t[1],m=f/e.group,h=d&&m>=4?qi(f):1,_=et.size(t)/h,g=[{type:12,data:_},{type:12,data:e.dilations},{type:12,data:[e.strides[0],e.strides[1]]},{type:12,data:[e.pads[0],e.pads[1]]},{type:12,data:m}];ld(e,g),g.push(...en(l,[u[0],u[1],u[2],u[3]/h]));let y=s?["rank","rank","rank"]:["rank","rank"];g.push(...en([t[0],t[1],t[2],t[3]/h]));let b=T=>{let v=Ht("output",n[0].dataType,t.length,h),x=xr(v.type.tensor),P=od(e,v.type.value,x),w=at("x",n[0].dataType,l.length),C=at("w",n[1].dataType,u.length,h),E=[w,C];s&&E.push(at("b",n[2].dataType,n[2].dims,h));let A=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:e.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];cd(e,A);let L=d?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${w.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${C.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${w.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${C.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${T.registerUniforms(A).declareVariables(...E,v)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${v.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${d?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${h} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; + + var value: ${v.type.value} = ${v.type.value}(0); + ${L} + ${o} + ${P} + ${v.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${e.cacheKey}_${h}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:i?i(t):t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:g}),getShaderSource:b}},t2=(n,e,t,i)=>{let s=n.length>2,o=qi(t[3]),l=qi(t[2]),u=et.size(t)/o/l,d=[n[0].dims[0],n[0].dims[1],n[0].dims[2],n[0].dims[3]/o],f=[n[1].dims[0],n[1].dims[1],n[1].dims[2],n[1].dims[3]/o],m=[t[0],t[1],t[2],t[3]/o],h=[{type:12,data:u},{type:6,data:[e.strides[0],e.strides[1]]},{type:6,data:[e.pads[0],e.pads[1]]}];ld(e,h),h.push(...en(d,f,m));let _=(l-1)*e.strides[1]+f[1],g=y=>{let b=Ht("output",n[0].dataType,m.length,o),T=xr(b.type.tensor),v=od(e,b.type.value,T),x=at("x",n[0].dataType,d.length,o),P=at("w",n[1].dataType,f.length,o),w=[x,P];s&&w.push(at("b",n[2].dataType,n[2].dims,o));let C=s?"value += b[output_channel];":"",E=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return cd(e,E),` + ${y.registerUniforms(E).declareVariables(...w,b)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${l}u; + let col = (index1 % width1) * ${l}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${x.type.value}, ${_}>; + var values: array<${b.type.value}, ${l}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${f[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${_}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${x.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${x.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${f[1]}; w_width++) { + let w_val = ${P.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${l}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${l}u; i++) { + var value = values[i]; + ${C} + ${v} + ${b.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${e.cacheKey};${o};${l};${_};${f[0]};${f[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(t):t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h}),getShaderSource:g}}}),Ew,ng,Sw,ig,Sy,nv,Aw,Cw,Ay,YD=At(()=>{Mn(),qD(),XD(),jM(),KD(),hd(),GM(),Bc(),Ew=(n,e,t,i,s,o)=>{let l=n[0],u=n.slice(o?1:2,o?3:4),d=u.length,f=e[0],m=e.slice(2).map((_,g)=>_+(_-1)*(t[g]-1)),h=u.map((_,g)=>_+i[g]+i[g+d]).map((_,g)=>Math.floor((_-m[g]+s[g])/s[g]));return h.splice(0,0,l),h.splice(o?3:1,0,f),h},ng=[2,3,1,0],Sw=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length>5)throw new Error("greater than 5D is not supported");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let t=n[0].dims[e.format==="NHWC"?n[0].dims.length-1:1],i=n[1].dims[1]*e.group;if(t!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(n.length===3&&(n[2].dims.length!==1||n[1].dims[0]!==n[2].dims[0]))throw new Error("invalid bias");let s=n[0].dims.length-2;if(e.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(e.strides.length!==s)throw new Error(`strides should be ${s}D`);if(e.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape")},ig=(n,e)=>{let t=n.kernelShape.slice();t.length{let e=BM(n),t=n.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],s=n.dilations,o=n.group,l=n.kernel_shape,u=n.pads,d=n.strides,f=n.w_is_const();return{autoPad:i,format:t,dilations:s,group:o,kernelShape:l,pads:u,strides:d,wIsConst:f,...e,cacheKey:`${n.format};${e.activation};`}},nv=(n,e,t,i)=>{let s=t.format==="NHWC",o=Ew(e[0].dims,e[1].dims,t.dilations,t.pads,t.strides,s);if(t.group!==1){let E=[e[0]];if(s){let A=n.kernelCustomData.wT??n.compute(Ls(e[1],ng),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=A),E.push(A)}else E.push(e[1]);e.length===3&&E.push(e[2]),!n.adapterInfo.isArchitecture("ampere")&&s&&e[1].dims[0]===t.group&&e[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?n.compute(t2(E,t,o,i),{inputs:E}):n.compute(e2(E,t,o,i),{inputs:E});return}let l=e.length===3,u=e[0].dims[s?1:2],d=e[0].dims[s?2:3],f=e[0].dims[s?3:1],m=e[1].dims[2],h=e[1].dims[3],_=o[s?1:2],g=o[s?2:3],y=o[s?3:1],b=s&&m===u&&h===d&&t.pads[0]===0&&t.pads[1]===0;if(b||m===1&&h===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let E=o[0],A,L,I,O=[];if(s){let $=n.kernelCustomData.wT??n.compute(Ls(e[1],ng),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=$),b){let J=u*d*f;A=e[0].reshape([1,E,J]),L=$.reshape([1,J,y]),I=[1,E,y]}else A=e[0].reshape([E,u*d,f]),L=$.reshape([1,f,y]),I=[E,_*g,y];O.push(A),O.push(L)}else A=e[0].reshape([E,f,u*d]),L=e[1].reshape([1,y,f]),I=[E,y,_*g],O.push(L),O.push(A);l&&O.push(e[2]);let H=I[2],Z=O[0].dims[O[0].dims.length-1];H<8&&Z<8?n.compute(VM(O,t,o,I,s,i),{inputs:O}):n.compute(Xg(O,t,o,I,s,i),{inputs:O});return}let T=!0,v=n.kernelCustomData.wT??n.compute(Ls(e[1],ng),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=v);let x=[e[0],v];l&&x.push(e[2]);let P=s?_*g:y,w=s?y:_*g,C=m*h*f;n.compute(QA(x,t,o,P,w,C,l,T,i),{inputs:x})},Aw=(n,e)=>{let t=e.format==="NHWC",i=[n.inputs[0].reshape(t?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&i.push(n.inputs[2]);let s=[0,e.pads[0],0,e.pads[1]],o=[1].concat(e.strides),l=[1].concat(e.dilations),u=[1].concat(e.kernelShape),d=ig({...e,pads:s,strides:o,dilations:l,kernelShape:u},i);nv(n,i,d,f=>t?[f[0],f[2],f[3]]:[f[0],f[1],f[3]])},Cw=(n,e,t)=>{let i=t.format==="NHWC"?"channelsLast":"channelsFirst",s=ig(t,e),o=t.autoPad==="NOTSET"?t.pads:t.autoPad,l=ZA(e[0].dims,e[1].dims,t.strides,t.dilations,o,!1,i);n.compute(JA(e,s,l.outShape,[l.filterDepth,l.filterHeight,l.filterWidth],[l.padInfo.front,l.padInfo.top,l.padInfo.left],i))},Ay=(n,e)=>{if(Sw(n.inputs,e),n.inputs[0].dims.length===3)Aw(n,e);else if(n.inputs[0].dims.length===5)Cw(n,n.inputs,e);else{let t=ig(e,n.inputs);nv(n,n.inputs,t)}}}),n2,QD=At(()=>{fn(),Cl(),Mn(),xn(),n2=(n,e,t)=>{let i=n.length>2,s=e.outputShape,o=e.format==="NHWC",l=e.group,u=n[1].dims,d=u[2]/l,f=u[3],m=o?qi(d):1,h=o&&f===1&&d>=4,_=h?Math.floor(d/4)*4:Math.floor(d/m)*m,g=d-_,y=o?qi(f):1,b=o?f===1?m:y:1,T=et.size(s)/y,v=[Math.ceil(T/64),1,1];qn("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${v}`);let x=["rank","rank"],P=[e.strides[0],e.strides[1]],w=[e.kernelShape[o?1:2],e.kernelShape[o?2:3]],C=[e.dilations[0],e.dilations[1]],E=[w[0]+(e.dilations[0]<=1?0:(e.kernelShape[o?1:2]-1)*(e.dilations[0]-1)),w[1]+(e.dilations[1]<=1?0:(e.kernelShape[o?2:3]-1)*(e.dilations[1]-1))],A=[E[0]-1-Math.floor((e.pads[0]+e.pads[2])/2),E[1]-1-Math.floor((e.pads[1]+e.pads[3])/2)],L=[{type:12,data:T},{type:12,data:P},{type:12,data:w},{type:12,data:C},{type:12,data:E},{type:6,data:A},{type:12,data:_},{type:12,data:d},{type:12,data:f},...en(n[0].dims,n[1].dims)];i&&(L.push(...en(n[2].dims)),x.push("rank")),L.push(...en(s));let I=O=>{let H=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:P.length},{name:"filter_dims",type:"u32",length:w.length},{name:"dilations",type:"u32",length:w.length},{name:"effective_filter_dims",type:"u32",length:E.length},{name:"pads",type:"i32",length:A.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Z=xr(n[0].dataType),$=o?1:2,J=o?2:3,ee=o?3:1,X=at("W",n[1].dataType,n[1].dims.length,b),ne=at("Dy",n[0].dataType,n[0].dims.length,m),Q=[ne,X];i&&Q.push(at("bias",n[2].dataType,[s[ee]].length,y));let oe=Ht("result",n[0].dataType,s.length,y),W=()=>{let te="";if(h)m===4?te+=` + let xValue = ${ne.getByOffset("x_offset")}; + let wValue = ${X.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:m===2?te+=` + dotProd = dotProd + dot(vec4<${Z}>(${ne.getByOffset("x_offset")}, ${ne.getByOffset("x_offset + 1u")}), vec4<${Z}>(${X.getByOffset("w_offset")}, ${X.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:m===1&&(te+=` + dotProd = dotProd + dot(vec4<${Z}>(${ne.getByOffset("x_offset")}, ${ne.getByOffset("x_offset + 1u")}, ${ne.getByOffset("x_offset + 2u")}, ${ne.getByOffset("x_offset + 3u")}), vec4<${Z}>(${X.getByOffset("w_offset")}, ${X.getByOffset("w_offset + 1u")}, ${X.getByOffset("w_offset + 2u")}, ${X.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(te+=` + let xValue = ${o?ne.getByOffset(`${ne.indicesToOffset(`${ne.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m}`):ne.get("batch","inputChannel","idyR","idyC")}; + `,m===1)te+=` + let w_offset = ${X.indicesToOffset(`${X.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${X.getByOffset(`w_offset / ${b}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let B=0;B{if(g===0)return"";if(!h)throw new Error(`packInputAs4 ${h} is not true.`);let te="";if(m===1){te+="dotProd = dotProd";for(let B=0;B(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${oe.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${Z}(dyRCorner) + ${Z}(wR)) / ${Z}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${Z}(uniforms.Dy_shape[${$}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${Z}(dyCCorner) + ${Z}(wC)) / ${Z}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${Z}(uniforms.Dy_shape[${J}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${h?` + var x_offset = ${ne.indicesToOffset(`${ne.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${m}; + var w_offset = ${X.indicesToOffset(`${X.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${b}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${h?4:m}) { + ${W()} + inputChannel = inputChannel + ${h?4:m}; + } + ${q()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${i?` + bias[d1 / ${y}]`:""}; + ${oe.setByOffset("global_idx","value")}; + `;return` + ${O.registerUniforms(H).declareVariables(...Q,oe)} + ${O.mainStart()} + ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${G}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${e.cacheKey};${m}${b}${y}${h}${g}`,inputDependencies:x},getRunData:()=>({dispatchGroup:{x:v[0],y:v[1],z:v[2]},outputs:[{dims:t?t(s):s,dataType:n[0].dataType}],programUniforms:L}),getShaderSource:I}}}),Pw,Rw,Dw,iv,i2,Iw,rv,Ow,r2,ZD=At(()=>{QD(),hd(),Bc(),Pw=(n,e,t,i,s,o)=>(n-1)*e+t+(i-1)*s+1-o,Rw=(n,e,t,i,s)=>{let o=Math.floor(n/2);e==="SAME_UPPER"?(t[i]=o,t[s]=n-o):e==="SAME_LOWER"&&(t[i]=n-o,t[s]=o)},Dw=(n,e,t,i,s,o,l,u,d,f)=>{let m=n.length-2,h=f.length===0;d.length{let t=n.kernelShape.slice();if(n.kernelShape.length===0||n.kernelShape.reduce((h,_)=>h*_,1)===0){t.length=0;for(let h=2;hh+_,0)===0){let h=e[0].dims.length-2;d=new Array(h).fill(1)}let f=n.strides.slice();if(f.reduce((h,_)=>h+_,0)===0){let h=e[0].dims.length-2;f=new Array(h).fill(1)}Dw(u,t,d,n.autoPad,n.group,s,f,i,l,o);let m=Object.assign({},n);return Object.assign(m,{kernelShape:t,pads:s,outputPadding:l,outputShape:o,dilations:d,strides:f}),m},i2=n=>{let e=BM(n),t=n.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof n.autoPad>"u"?0:n.autoPad],s=n.dilations,o=n.group,l=n.kernelShape,u=n.pads,d=n.strides,f=n.wIsConst(),m=n.outputPadding,h=n.outputShape;return{autoPad:i,format:t,dilations:s,group:o,kernelShape:l,outputPadding:m,outputShape:h,pads:u,strides:d,wIsConst:f,...e,cacheKey:`${n.format};${e.activation};`}},Iw=(n,e)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let t=n[0].dims[e.format==="NHWC"?n[0].dims.length-1:1],i=n[1].dims[0];if(t!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let s=n[1].dims[1]*e.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==s))throw new Error("invalid bias");let o=n[0].dims.length-2;if(e.dilations.reduce((l,u)=>l+u,0)>0&&e.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(e.strides.reduce((l,u)=>l+u,0)>0&&e.strides.length!==o)throw new Error(`strides should be ${o}D`);if(e.pads.reduce((l,u)=>l+u,0)>0&&e.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(e.outputPadding.length!==o&&e.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(e.kernelShape.reduce((l,u)=>l+u,0)>0&&e.kernelShape.length!==0&&e.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(e.outputShape.length!==0&&e.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape")},rv=(n,e,t,i)=>{let s=n.kernelCustomData.wT??n.compute(Ls(e[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=s);let o=[e[0],s];e.length===3&&o.push(e[2]),n.compute(n2(o,t,i),{inputs:o})},Ow=(n,e)=>{let t=e.format==="NHWC",i=[n.inputs[0].reshape(t?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&i.push(n.inputs[2]);let s=e.kernelShape;(s.length===0||s[0]===0)&&(s=[n.inputs[1].dims[2]]);let o=e.dilations;(o.length===0||o[0]===0)&&(o=[1]);let l=e.strides;(l.length===0||l[0]===0)&&(l=[1]);let u=e.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],l=[1].concat(l),o=[1].concat(o),s=[1].concat(s);let d=e.outputPadding;d=[0].concat(d);let f=iv({...e,pads:u,strides:l,dilations:o,kernelShape:s,outputPadding:d},i);rv(n,i,f,m=>t?[m[0],m[2],m[3]]:[m[0],m[1],m[3]])},r2=(n,e)=>{if(Iw(n.inputs,e),n.inputs[0].dims.length===3)Ow(n,e);else{let t=iv(e,n.inputs);rv(n,n.inputs,t)}}}),Lw,s2,a2,JD=At(()=>{fn(),Mn(),ir(),xn(),Lw=(n,e,t,i)=>{let s=et.size(e),o=e.length,l=at("input",n,o),u=Ht("output",n,o),d=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),f=et.normalizeAxis(d,o),m=h=>{let _=` i32(${l.indicesGet("inputIndices","uniforms.axis")}) `,g=Yt("uniforms.input_shape","uniforms.axis",o),y=i.reverse?_+(i.exclusive?" + 1":""):"0",b=i.reverse?g:_+(i.exclusive?"":" + 1");return` + ${h.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(l,u)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${y}; + let last : i32 = ${b}; + for (var i : i32 = first; i < last; i++) { + ${l.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${l.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:e,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:[{type:12,data:s},{type:12,data:f},...en(e,e)]}),getShaderSource:m}},s2=(n,e)=>{let t=n.inputs[0].dims,i=n.inputs[0].dataType,s=n.inputs[1];n.compute(Lw(i,t,s,e),{inputs:[0]})},a2=n=>{let e=n.exclusive===1,t=n.reverse===1;return ii({exclusive:e,reverse:t})}}),Fw,kw,Nw,o2,l2,e3=At(()=>{fn(),Mn(),ir(),xn(),Fw=n=>{if(!n||n.length!==1)throw new Error("DepthToSpace requires 1 input.");if(n[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},kw=(n,e,t,i)=>{let s=[];s.push(`fn perm(i: ${i.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let o=0;o{let t,i,s,o,l,u,d=e.format==="NHWC",f=e.blocksize,m=e.mode==="DCR";d?([t,i,s,o]=n.dims,l=m?[t,i,s,f,f,o/f**2]:[t,i,s,o/f**2,f,f],u=m?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,i,s,o]=[n.dims[0],n.dims[2],n.dims[3],n.dims[1]],l=m?[t,f,f,o/f**2,i,s]:[t,o/f**2,f,f,i,s],u=m?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let h=n.reshape(l),_=h.dims.length,g=n.dataType,y=at("a",g,_),b=Ht("output",g,_),T=v=>` + ${v.registerUniform("output_size","u32").declareVariables(y,b)} + + ${kw(u,_,y,b)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${b.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${b.setByOffset("global_idx",y.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${n.dims};${e.blocksize};${e.mode}`,inputDependencies:["rank"]},getRunData:v=>{let x=d?[t,i*f,s*f,o/f**2]:[t,o/f**2,i*f,s*f],P=et.size(x),w=h.dims,C=et.sortBasedOnPerm(w,u);return{outputs:[{dims:x,dataType:v[0].dataType}],dispatchGroup:{x:Math.ceil(P/64)},programUniforms:[{type:12,data:P},...en(w,C)]}},getShaderSource:T}},o2=(n,e)=>{Fw(n.inputs),n.compute(Nw(n.inputs[0],e))},l2=n=>ii({blocksize:n.blocksize,mode:n.mode,format:n.format})}),rg,Am,sv,zw,Uw,Bw,$w,av,Vw,c2,u2,t3=At(()=>{fn(),Mn(),ir(),xn(),rg="[a-zA-Z]|\\.\\.\\.",Am="("+rg+")+",sv="^"+Am+"$",zw="("+Am+",)*"+Am,Uw="^"+zw+"$",Bw=class{constructor(n=-1){this.symbolToIndices=new Map,this.inputIndex=n}addSymbol(n,e){let t=this.symbolToIndices.get(n);t===void 0?t=[e]:t.push(e),this.symbolToIndices.set(n,t)}},$w=class{constructor(n,e){this.equation=e,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,i]=e.includes("->")?e.split("->",2):[e,""];if(!t.match(RegExp(Uw)))throw new Error("Invalid LHS term");if(t.split(",").forEach((s,o)=>{let l=n[o].dims.slice();if(!s.match(RegExp(sv)))throw new Error("Invalid LHS term");let u=this.processTerm(s,!0,l,o);this.lhs.push(u)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([s,o])=>o.count===1||s==="...").map(([s])=>s).join("");else if(!i.match(RegExp(Am)))throw new Error("Invalid RHS");i.match(RegExp(rg,"g"))?.forEach(s=>{if(s==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(s);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(n,e,t){let i=this.symbolToInfo.get(n);if(i!==void 0){if(i.dimValue!==e&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(t)}else i={count:1,dimValue:e,inputIndices:[t]};this.symbolToInfo.set(n,i)}processTerm(n,e,t,i=-1){let s=t.length,o=!1,l=[],u=0;if(!n.match(RegExp(sv))&&!e&&n!=="")throw new Error("Invalid LHS term");let d=n.match(RegExp(rg,"g")),f=new Bw(i);return d?.forEach((m,h)=>{if(m==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let _=s-d.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(l=t.slice(u,u+_),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(e)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let g=0;gn+"_max",Vw=(n,e,t,i)=>{let s=n.map(f=>f.length).map((f,m)=>at(`input${m}`,e,f)),o=et.size(i),l=Ht("output",e,i.length),u=[...t.symbolToInfo.keys()].filter(f=>!t.rhs.symbolToIndices.has(f)),d=f=>{let m=[],h="var prod = 1.0;",_="var sum = 0.0;",g="sum += prod;",y=[],b=[],T=[],v=[],x=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((w,C)=>{if(t.rhs.symbolToIndices.has(C)){let E=t.rhs.symbolToIndices.get(C)?.[0];E!==void 0&&t.lhs.forEach((A,L)=>{if(w.inputIndices.includes(L)){let I=A.symbolToIndices.get(C);if(I===void 0)throw new Error("Invalid symbol error");I.forEach(O=>{m.push(`${s[L].indicesSet(`input${L}Indices`,O,l.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,A)=>{if(w.inputIndices.includes(A)){let L=E.symbolToIndices.get(C);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(I=>{y.push(`${s[A].indicesSet(`input${A}Indices`,I,`${C}`)}`)}),v.push(`prod *= ${s[A].getByIndices(`input${A}Indices`)};`)}}),b.push(`for(var ${C}: u32 = 0; ${C} < uniforms.${av(C)}; ${C}++) {`),T.push("}")});let P=x?[...m,`let sum = ${s.map((w,C)=>w.getByIndices(`input${C}Indices`)).join(" * ")};`]:[...m,_,...b,...y,h,...v,g,...T];return` + ${f.registerUniforms(u.map(w=>({name:`${av(w)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,l)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${l.offsetToIndices("global_idx")}; + ${s.map((w,C)=>`var input${C}Indices: ${s[C].type.indices};`).join(` +`)} + ${P.join(` +`)}; + ${l.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:n.map(()=>"rank")},getRunData:()=>{let f=u.filter(h=>t.symbolToInfo.has(h)).map(h=>({type:12,data:t.symbolToInfo.get(h)?.dimValue||0}));f.push({type:12,data:o});let m=n.map((h,_)=>[...en(h)]).reduce((h,_)=>h.concat(_),f);return m.push(...en(i)),{outputs:[{dims:i,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}},getShaderSource:d}},c2=(n,e)=>{let t=new $w(n.inputs,e.equation),i=t.outputDims,s=n.inputs.map((o,l)=>o.dims);n.compute(Vw(s,n.inputs[0].dataType,t,i))},u2=n=>{let e=n.equation.replace(/\s+/g,"");return ii({equation:e})}}),Gw,ov,jw,Ww,d2,n3=At(()=>{fn(),Mn(),xn(),Gw=n=>{if(!n||n.length!==2)throw new Error("Expand requires 2 input.");let e=n[0].dims,t=Array.from(n[1].getBigInt64Array(),Number),i=t.length{let t=n.length-e.length,i=[];for(let s=0;sn.length>e.length?ov(n,e):ov(e,n),Ww=n=>{let e=n[0].dims,t=Array.from(n[1].getBigInt64Array(),Number),i=jw(e,t),s=n[0].dataType,o=s===9||et.size(e)===1,l=s===9||e.length>0&&e[e.length-1]%4===0?4:1,u=o||i.length>0&&i[i.length-1]%4===0?4:1,d=Math.ceil(et.size(i)/u),f=h=>{let _=at("input",s,e.length,l),g=Ht("output",s,i.length,u),y;if(s===9){let b=(T,v,x="")=>` + let outputIndices${v} = ${g.offsetToIndices(`outputOffset + ${v}u`)}; + let offset${v} = ${_.broadcastedIndicesToOffset(`outputIndices${v}`,g)}; + let index${v} = offset${v} / 4u; + let component${v} = offset${v} % 4u; + ${T}[${v}] = ${x}(${_.getByOffset(`index${v}`)}[component${v}]); + `;y=` + let outputOffset = global_idx * ${u}; + var data = vec4(0); + ${b("data",0,"u32")} + ${b("data",1,"u32")} + ${b("data",2,"u32")} + ${b("data",3,"u32")} + ${g.setByOffset("global_idx","data")} + }`}else y=` + let outputIndices = ${g.offsetToIndices(`global_idx * ${u}`)}; + let inputOffset = ${_.broadcastedIndicesToOffset("outputIndices",g)}; + let data = ${g.type.value}(${_.getByOffset(`inputOffset / ${l}`)}); + ${g.setByOffset("global_idx","data")} + }`;return` + ${h.registerUniform("vec_size","u32").declareVariables(_,g)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${y}`},m=[{type:12,data:d},...en(e,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${l}${u}`,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:i,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m})}},d2=n=>{Gw(n.inputs),n.compute(Ww(n.inputs),{inputs:[0]})}}),Hw,f2,i3=At(()=>{fn(),Mn(),xn(),UM(),Hw=n=>{let e=n[0].dataType,t=et.size(n[0].dims),i=et.size(n[1].dims),s=i%4===0,o=l=>{let u=at("x",e,[1],4),d=at("bias",e,[1],4),f=Ht("y",e,[1],4),m=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],h=g=>` + let bias${g}_offset: u32 = (global_idx * 4 + ${g}) % uniforms.bias_size; + let bias${g} = ${d.getByOffset(`bias${g}_offset / 4`)}[bias${g}_offset % 4];`,_=s?` + let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${h(0)}${h(1)}${h(2)}${h(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${l.registerUniforms(m).declareVariables(u,d,f)} + + ${xy(Kr(e))} + + ${l.mainStart(dh)} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${_} + let x_in = x + bias; + ${f.setByOffset("global_idx",wy("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:l=>({outputs:[{dims:l[0].dims,dataType:l[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(t/dh/4)}})}},f2=n=>{n.inputs.length<2||et.size(n.inputs[1].dims)===0?IA(n):n.compute(Hw(n.inputs))}}),qw,Xw,h2,p2,r3=At(()=>{fn(),Mn(),ir(),xn(),qw=n=>{if(!n||n.length!==2)throw new Error("Gather requires 2 inputs.")},Xw=(n,e)=>{let t=n[0].dims,i=n[1].dims,s=t.length,o=et.normalizeAxis(e.axis,s),l=t.slice(0);l.splice(o,1,...i);let u=t[o],d=n[0].dataType===9?4:1,f=Math.ceil(et.size(l)/d),m=[{type:12,data:f},{type:6,data:u},{type:12,data:o},...en(n[0].dims,n[1].dims,l)],h=_=>{let g=at("data",n[0].dataType,n[0].dims.length,d),y=at("inputIndices",n[1].dataType,n[1].dims.length),b=Ht("output",n[0].dataType,l.length,d),T=x=>{let P=i.length,w=`var indicesIndices${x} = ${y.type.indices}(0);`;for(let C=0;C1?`indicesIndices${x}[${C}]`:`indicesIndices${x}`} = ${l.length>1?`outputIndices${x}[uniforms.axis + ${C}]`:`outputIndices${x}`};`;w+=` + var idx${x} = ${y.getByIndices(`indicesIndices${x}`)}; + if (idx${x} < 0) { + idx${x} = idx${x} + uniforms.axisDimLimit; + } + var dataIndices${x} : ${g.type.indices}; + `;for(let C=0,E=0;C1?`dataIndices${x}[${C}]`:`dataIndices${x}`} = u32(idx${x});`,E+=P):(w+=`${s>1?`dataIndices${x}[${C}]`:`dataIndices${x}`} = ${l.length>1?`outputIndices${x}[${E}]`:`outputIndices${x}`};`,E++);return w},v;if(n[0].dataType===9){let x=(P,w,C="")=>` + let outputIndices${w} = ${b.offsetToIndices(`outputOffset + ${w}u`)}; + ${T(w)}; + let offset${w} = ${g.indicesToOffset(`dataIndices${w}`)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${P}[${w}] = ${C}(${g.getByOffset(`index${w}`)}[component${w}]); + `;v=` + let outputOffset = global_idx * ${d}; + var value = vec4(0); + ${x("value",0,"u32")} + ${x("value",1,"u32")} + ${x("value",2,"u32")} + ${x("value",3,"u32")} + ${b.setByOffset("global_idx","value")} + `}else v=` + let outputIndices = ${b.offsetToIndices("global_idx")}; + ${T("")}; + let value = ${g.getByIndices("dataIndices")}; + ${b.setByOffset("global_idx","value")}; + `;return` + ${_.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,y,b)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${v} + }`};return{name:"Gather",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:l,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:m}),getShaderSource:h}},h2=n=>ii({axis:n.axis}),p2=(n,e)=>{let t=n.inputs;qw(t),n.compute(Xw(n.inputs,e))}}),Kw,m2,_2,s3=At(()=>{fn(),Mn(),xn(),Kw=(n,e,t,i,s,o,l,u,d)=>{let f=[{type:12,data:o},{type:12,data:i},{type:12,data:s},{type:12,data:t},{type:12,data:l},{type:12,data:u},{type:12,data:d}],m=[o];f.push(...en(e.dims,m));let h=_=>{let g=at("indices_data",e.dataType,e.dims.length),y=Ht("input_slice_offsets_data",12,1,1),b=[g,y],T=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:s.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${_.registerUniforms(T).declareVariables(...b)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${s.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return n.compute({name:"computeSliceOffsets",shaderCache:{hint:`${s.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:m,dataType:n.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:f}),getShaderSource:h},{inputs:[e],outputs:[-1]})[0]},m2=(n,e)=>{let t=n.inputs,i=t[0].dims,s=t[0].dataType,o=t[1].dims,l=o[o.length-1],u=et.sizeToDimension(o,o.length-1),d=et.sizeFromDimension(i,e.batchDims+l),f=et.sizeToDimension(i,e.batchDims),m=et.sizeFromDimension(i,e.batchDims),h=u/f,_=new Array(l),g=d;for(let w=0;wi.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let T=o.slice(0,-1).concat(i.slice(b)),v=et.size(T),x=[{type:12,data:v},{type:12,data:d},...en(t[0].dims,y.dims,T)],P=w=>{let C=at("data",t[0].dataType,t[0].dims.length),E=at("slice_offsets",12,y.dims.length),A=Ht("output",t[0].dataType,T.length);return` + ${w.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(C,E,A)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};n.compute({name:"GatherND",shaderCache:{hint:e.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:T,dataType:s}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:x}),getShaderSource:P},{inputs:[t[0],y]})},_2=n=>({batchDims:n.batch_dims,cacheKey:""})}),Yw,Qw,g2,v2,a3=At(()=>{fn(),Mn(),ir(),xn(),Yw=(n,e)=>{if(n.length<3||n.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=et.normalizeAxis(e.quantizeAxis,n[0].dims.length),i=e.blockSize,s=n[0],o=n[2],l=n.length===4?n[3]:void 0;if(o.dims.length!==s.dims.length||!s.dims.map((u,d)=>d===t?Math.ceil(u/i)===o.dims[d]:u===o.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(l){if(l.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(l.dims.length!==o.dims.length||!l.dims.map((u,d)=>u===o.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Qw=(n,e)=>{let t=n[0].dims,i=n[1].dims,s=t.length,o=et.normalizeAxis(e.gatherAxis,s),l=et.normalizeAxis(e.quantizeAxis,s),u=t.slice(0);u.splice(o,1,...i);let d=et.size(u),f=n[2].dataType,m=n[0].dataType===22,h=[{type:12,data:d},{type:12,data:l},{type:12,data:o},{type:12,data:e.blockSize},...en(...n.map((g,y)=>g.dims),u)],_=g=>{let y=at("data",n[0].dataType,n[0].dims.length),b=at("inputIndices",n[1].dataType,n[1].dims.length),T=at("scales",n[2].dataType,n[2].dims.length),v=n.length>3?at("zeroPoint",n[3].dataType,n[3].dims.length):void 0,x=Ht("output",f,u.length),P=[y,b,T];v&&P.push(v);let w=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${g.registerUniforms(w).declareVariables(...P,x)} + ${g.mainStart()} + let output_indices = ${x.offsetToIndices("global_idx")}; + var indices_indices = ${b.type.indices}(0); + ${i.length>1?` + for (var i: u32 = 0; i < ${i.length}; i++) { + let index = ${x.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${b.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${x.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${y.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${x.indicesGet("output_indices","i")}; + ${y.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${b.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[o]}; + } + ${y.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${x.indicesGet("output_indices",`i + ${i.length} - 1`)}; + ${y.indicesSet("data_indices","i","index")}; + } + let data_offset = ${y.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${y.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${T.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${T.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${T.getByIndices("scale_indices")}; + ${v?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${v.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${v.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Kr(f)}(quantized_data - zero_point) * scale; + ${x.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${e.cacheKey};${n.filter((g,y)=>y!==1).map(g=>g.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:n.length},(g,y)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:f}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}),getShaderSource:_}},g2=(n,e)=>{let t=n.inputs;Yw(t,e),n.compute(Qw(n.inputs,e))},v2=n=>ii({blockSize:n.blockSize,gatherAxis:n.gatherAxis,quantizeAxis:n.quantizeAxis})}),Zw,Jw,y2,M2,o3=At(()=>{fn(),Mn(),ir(),xn(),Zw=n=>{if(!n||n.length!==2)throw new Error("GatherElements requires 2 inputs.");if(n[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(n[0].dims.length!==n[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Jw=(n,e)=>{let t=n[0].dims,i=n[0].dataType,s=t.length,o=n[1].dims,l=n[1].dataType,u=et.normalizeAxis(e.axis,s),d=t[u],f=o.slice(0),m=et.size(f),h=at("input",i,s),_=at("indicesInput",l,o.length),g=Ht("output",i,f.length),y=[{type:12,data:m},{type:6,data:d},{type:12,data:u}];return y.push(...en(t,o,f)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:f,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:b=>` + ${b.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(h,_,g)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${g.offsetToIndices("global_idx")}; + + var idx = ${_.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${h.type.indices}(outputIndices); + ${h.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${h.getByIndices("inputIndices")}; + + ${g.setByOffset("global_idx","value")}; + }`}},y2=n=>ii({axis:n.axis}),M2=(n,e)=>{let t=n.inputs;Zw(t),n.compute(Jw(n.inputs,e))}}),eT,tT,b2,x2,l3=At(()=>{fn(),Mn(),xn(),eT=n=>{if(!n)throw new Error("Input is missing");if(n.length<2||n.length>3)throw new Error("Invaid input number.");if(n.length===3&&n[2].dims.length>2)throw new Error("Invalid input shape of C");if(n[0].dataType!==n[1].dataType||n.length===3&&n[0].dataType!==n[2].dataType)throw new Error("Input types are mismatched")},tT=(n,e)=>{let t=n[0].dims.slice(),i=n[1].dims.slice(),[s,o,l]=yS.getShapeOfGemmResult(t,e.transA,i,e.transB,n.length===3?n[2].dims:void 0),u=[s,o];if(!u)throw new Error("Can't use gemm on the given tensors");let d=16,f=Math.ceil(o/d),m=Math.ceil(s/d),h=!0,_=et.size(u),g=[{type:12,data:h?f:_},{type:12,data:s},{type:12,data:o},{type:12,data:l},{type:1,data:e.alpha},{type:1,data:e.beta}],y=["type","type"];n.length===3&&(g.push(...en(n[2].dims)),y.push("rank")),g.push(...en(u));let b=v=>{let x="";e.transA&&e.transB?x="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":e.transA&&!e.transB?x="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!e.transA&&e.transB?x="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!e.transA&&!e.transB&&(x="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let P=e.alpha===1?"":"value *= uniforms.alpha;",w=at("a",n[0].dataType,n[0].dims),C=at("b",n[1].dataType,n[1].dims),E=w.type.value,A=null,L=[w,C];n.length===3&&(A=at("c",n[2].dataType,n[2].dims.length),L.push(A));let I=Ht("output",n[0].dataType,u.length);L.push(I);let O=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${v.registerUniforms(O).declareVariables(...L)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${E}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${x} + } + + ${P} + ${A!=null?`let cOffset = ${A.broadcastedIndicesToOffset("vec2(m, n)",I)}; value += ${E}(uniforms.beta) * ${A.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},T=v=>{let x=at("a",n[0].dataType,n[0].dims),P=at("b",n[1].dataType,n[1].dims),w=null,C=[x,P];n.length===3&&(w=at("c",n[2].dataType,n[2].dims.length),C.push(w));let E=Ht("output",n[0].dataType,u.length);C.push(E);let A=[{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"}],L="",I="";e.transA&&e.transB?(I=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${x.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${P.type.value}(0); + } + `,L="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):e.transA&&!e.transB?(I=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${x.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${P.type.value}(0); + } + `,L="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!e.transA&&e.transB?(I=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${x.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${P.type.value}(0); + } + `,L="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!e.transA&&!e.transB&&(I=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${x.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${P.type.value}(0); + } + `,L="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let O=e.alpha===1?"":"value *= uniforms.alpha;";return` + ${v.registerUniforms(A).declareVariables(...C)} + var tile_a: array, ${d}>; + var tile_b: array, ${d}>; + ${v.mainStart([d,d,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d}; + let num_tiles = (uniforms.K - 1) / ${d} + 1; + var k_start = 0u; + var value = ${E.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${I} + k_start = k_start + ${d}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${d}; k++) { + ${L} + } + workgroupBarrier(); + } + + ${O} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${w!=null?`let cOffset = ${w.broadcastedIndicesToOffset("vec2(m, n)",E)}; value += ${E.type.value}(uniforms.beta) * ${w.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return h?{name:"GemmShared",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:f*m},programUniforms:g}),getShaderSource:T}:{name:"Gemm",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:g}),getShaderSource:b}},b2=n=>{let e=n.transA,t=n.transB,i=n.alpha,s=n.beta;return{transA:e,transB:t,alpha:i,beta:s,cacheKey:`${n.transA};${n.transB};${n.alpha===1}`}},x2=(n,e)=>{eT(n.inputs),n.compute(tT(n.inputs,e))}}),So,pl,$u,Vu,nT,iT,rT,sT,aT,oT,lT,cT,w2,T2,c3=At(()=>{fn(),Mn(),ir(),xn(),[So,pl,$u,Vu]=[0,1,2,3],nT=n=>{if(n[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(n[0].dims.length!==n[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(n[0].dims.length-2!==n[1].dims[n[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${n[0].dims.length-2}`);if(n[0].dims[0]!==n[1].dims[0])throw new Error("grid batch size must match input batch size")},iT=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,rT=n=>` + fn gs_bicubic_interpolate(p: mat4x4<${n}>, x: f32, y: f32) -> ${n} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${n}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,sT=n=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${n.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,aT=n=>` + ${n.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,oT=(n,e,t)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${e} { + var pixel = ${e}(0); + var indices = vec4(0); + indices[${So}] = batch; + indices[${pl}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${$u}] = u32(r); + indices[${Vu}] = u32(c); + } else { + return ${e}(0); + } + `;case"border":return` + indices[${$u}] = u32(clamp(r, 0, H - 1)); + indices[${Vu}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${$u}] = gs_reflect(r, border[1], border[3]); + indices[${Vu}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${n.getByIndices("indices")}; + } +`,lT=(n,e,t)=>(()=>{switch(t.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${So}], indices[${pl}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${So}], indices[${pl}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${So}], indices[${pl}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${So}], indices[${pl}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${So}], indices[${pl}], border); + + let dx2 = ${e}(f32(x2) - x); + let dx1 = ${e}(x - f32(x1)); + let dy2 = ${e}(f32(y2) - y); + let dy1 = ${e}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${e}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${So}], indices[${pl}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${n.setByOffset("global_idx","result")}`,cT=(n,e)=>{let t=at("x",n[0].dataType,n[0].dims.length),i=[n[1].dims[0],n[1].dims[1],n[1].dims[2]],s=at("grid",n[1].dataType,i.length,2),o=[n[0].dims[0],n[0].dims[1],n[1].dims[1],n[1].dims[2]];e.format==="NHWC"&&(o=[n[0].dims[0],n[1].dims[1],n[1].dims[2],n[0].dims[3]],[So,pl,$u,Vu]=[0,3,1,2]);let l=Ht("output",n[0].dataType,o.length),u=t.type.value,d=et.size(o),f=[{type:12,data:d},...en(n[0].dims,i,o)],m=h=>` + ${h.registerUniform("output_size","u32").declareVariables(t,s,l)} + ${iT} + ${rT(u)} + ${sT(e)} + ${aT(e)} + ${oT(t,u,e)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${$u}]); + let W_in = i32(uniforms.x_shape[${Vu}]); + + ${e.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${l.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${So}], indices[${$u}], indices[${Vu}]); + let nxy = ${s.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${lT(l,u,e)} + }`;return{name:"GridSample",shaderCache:{hint:`${e.cacheKey}`,inputDependencies:["type","type"]},getRunData:h=>{let _=et.size(o);return{outputs:[{dims:o,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:f}},getShaderSource:m}},w2=(n,e)=>{nT(n.inputs),n.compute(cT(n.inputs,e))},T2=n=>ii({alignCorners:n.align_corners,mode:n.mode,paddingMode:n.padding_mode,format:n.format})}),os,uT,E2,lv,dT,$m,S2,A2=At(()=>{fn(),Mn(),ir(),FM(),zM(),xn(),Bc(),os=(n,e)=>n.length>e&&n[e].dims.length>0?n[e]:void 0,uT=(n,e)=>{let t=n[0],i=os(n,1),s=os(n,2),o=os(n,3),l=os(n,4),u=os(n,5),d=os(n,6),f=os(n,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=t.dims[0],h=t.dims[1],_=t.dims.length===3?t.dims[2]:e.numHeads*t.dims[4],g=h,y=0,b=0,T=Math.floor(_/e.numHeads);if(d&&f&&et.size(d.dims)&&et.size(f.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==m||d.dims[1]!==e.numHeads||d.dims[3]!==T)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(f.dims[0]!==m||f.dims[1]!==e.numHeads||f.dims[3]!==T)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==f.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(f.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');y=d.dims[2],b=d.dims[2]}else if(d&&et.size(d.dims)||f&&et.size(f.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(i&&et.size(i.dims)>0){if(t.dims.length!==3)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(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(i.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');v=2,g=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==e.numHeads||i.dims[3]!==2||i.dims[4]!==T)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');v=5,g=i.dims[1]}else{if(i.dims[1]!==e.numHeads||i.dims[3]!==T)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');v=0,g=i.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==e.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}if(o&&et.size(o.dims)>0){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&i.dims.length===5&&i.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let x=y+g,P=0;if(l&&et.size(l.dims)>0){P=8;let A=l.dims;throw A.length===1?A[0]===m?P=1:A[0]===3*m+2&&(P=3):A.length===2&&A[0]===m&&A[1]===x&&(P=5),P===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let w=!1,C=_;if(s&&et.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(g!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');C=s.dims[2]}else{if(g!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');C=s.dims[1]*s.dims[3],w=!0}}let E=!1;if(l&&et.size(l.dims)>0)throw new Error("Key padding mask is not supported");if(u&&et.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==m||u.dims[1]!==e.numHeads||u.dims[2]!==h||u.dims[3]!==x)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:m,sequenceLength:h,pastSequenceLength:y,kvSequenceLength:g,totalSequenceLength:x,maxSequenceLength:b,inputHiddenSize:0,hiddenSize:_,vHiddenSize:C,headSize:T,vHeadSize:Math.floor(C/e.numHeads),numHeads:e.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:e.maskFilterValue,maskType:P,scale:e.scale,broadcastResPosBias:E,passPastInKv:w,qkvFormat:v}},E2=n=>ii({...n}),lv=ii({perm:[0,2,1,3]}),dT=(n,e,t,i,s,o,l)=>{let u=[i,s,o],d=et.size(u),f=[{type:12,data:d},{type:12,data:l},{type:12,data:o}],m=h=>{let _=Ht("qkv_with_bias",e.dataType,u),g=at("qkv",e.dataType,u),y=at("bias",t.dataType,u),b=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${h.registerUniforms(b).declareVariables(g,y,_)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return n.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:e.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}),getShaderSource:m},{inputs:[e,t],outputs:[-1]})[0]},$m=(n,e,t,i,s,o,l,u)=>{let d=o;if(l&&et.size(l.dims)>0){if(i===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=dT(n,o,l,e,i,t*s,u),d=d.reshape([e,i,t,s]),t===1||i===1?d:n.compute(Ls(d,lv.perm),{inputs:[d],outputs:[-1]})[0]}else return o.dims.length===3&&(d=o.reshape([e,i,t,s])),t===1||i===1?d:n.compute(Ls(d,lv.perm),{inputs:[d],outputs:[-1]})[0]},S2=(n,e)=>{let t=uT(n.inputs,e),i=n.inputs[0],s=os(n.inputs,1),o=os(n.inputs,2),l=os(n.inputs,3),u=os(n.inputs,4),d=os(n.inputs,5),f=os(n.inputs,6),m=os(n.inputs,7);if(i.dims.length===5)throw new Error("Packed QKV is not implemented");if(s?.dims.length===5)throw new Error("Packed KV is not implemented");let h=s&&o&&s.dims.length===4&&o.dims.length===4,_=$m(n,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,i,l,0);if(h)return Km(n,_,s,o,u,void 0,f,m,d,t);if(!s||!o)throw new Error("key and value must be provided");let g=$m(n,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,s,l,t.hiddenSize),y=$m(n,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,o,l,2*t.hiddenSize);Km(n,_,g,y,u,void 0,f,m,d,t)}}),fT,hT,pT,mT,Cy,C2,P2,R2=At(()=>{fn(),Mn(),ir(),xn(),fT=n=>{if(!n||n.length<1)throw new Error("too few inputs")},hT=(n,e)=>{let t=[],i=e.numOutputs;return n[1].dims[0]>0&&(n[1].getBigInt64Array().forEach(s=>t.push(Number(s))),i=t.length),ii({numOutputs:i,axis:e.axis,splitSizes:t})},pT=n=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${n}u; i += 1u ) { + if (index < ${Yt("uniforms.size_in_split_axis","i",n)}) { + return i; + } + } + return ${n}u; +}`,mT=n=>{let e=n.length,t=[];for(let i=0;i{let t=n[0].dims,i=et.size(t),s=n[0].dataType,o=et.normalizeAxis(e.axis,t.length),l=new Array(e.numOutputs),u=at("input",s,t.length),d=new Array(e.numOutputs),f=[],m=[],h=0,_=[{type:12,data:i}];for(let y=0;y` + ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...l)} + ${pT(d.length)} + ${mT(l)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",o)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Yt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; + ${u.indicesSet("indices",o,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:e.cacheKey,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:f,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:_})}},C2=(n,e)=>{fT(n.inputs);let t=n.inputs.length===1?e:hT(n.inputs,e);n.compute(Cy(n.inputs,t),{inputs:[0]})},P2=n=>{let e=n.axis,t=n.splitSizes,i=n.numOutputs<0?t.length:n.numOutputs;if(i!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ii({axis:e,numOutputs:i,splitSizes:t})}}),_T,Kg,D2,I2=At(()=>{fn(),Mn(),ir(),xn(),_T=(n,e)=>{let[t,i,s,o]=n,{numHeads:l,rotaryEmbeddingDim:u}=e;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!et.areEqual(i.dims,[])&&!et.areEqual(i.dims,[1])&&i.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${i.dims.length}`);if(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!et.areEqual(s.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&l===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=t.dims[0],f=t.dims[t.dims.length-2],m=s.dims[0],h=et.sizeFromDimension(t.dims,1)/f,_=u===0?s.dims[1]*2:h/l;if(u>_)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(d!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(f!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(_/2!==s.dims[1]&&u/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(f>m)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Kg=(n,e)=>{let{interleaved:t,numHeads:i,rotaryEmbeddingDim:s,scale:o}=e,l=n[0].dims[0],u=et.sizeFromDimension(n[0].dims,1),d=n[0].dims[n[0].dims.length-2],f=u/d,m=n[2].dims[1],h=s===0?m*2:f/i,_=new Array(l,d,f/h,h-m),g=et.computeStrides(_),y=[{type:1,data:o},{type:12,data:_},{type:12,data:g},...n[0].dims.length===3?new Array({type:12,data:[u,f,h,1]}):[],...n[0].dims.length===4?new Array({type:12,data:[u,h,d*h,1]}):[],...en(n[0].dims,n[1].dims,n[2].dims,n[3].dims,n[0].dims)],b=T=>{let v=at("input",n[0].dataType,n[0].dims.length),x=at("position_ids",n[1].dataType,n[1].dims.length),P=at("cos_cache",n[2].dataType,n[2].dims.length),w=at("sin_cache",n[3].dataType,n[3].dims.length),C=Ht("output",n[0].dataType,n[0].dims.length);return T.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:_.length},{name:"global_strides",type:"u32",length:g.length},{name:"input_output_strides",type:"u32",length:g.length}]),` + ${T.declareVariables(v,x,P,w,C)} + + ${T.mainStart(dh)} + let half_rotary_emb_dim = uniforms.${P.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${T.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${x.broadcastedIndicesToOffset("bsnh.xy",Ht("",x.type.tensor,2))}; + let position_id = + u32(${x.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${v.getByOffset("i")} * ${P.get("position_id","bsnh[3]")} - + ${v.getByOffset("j")} * ${w.get("position_id","bsnh[3]")}; + ${C.setByOffset("i","re")} + let im = ${v.getByOffset("i")} * ${w.get("position_id","bsnh[3]")} + + ${v.getByOffset("j")} * ${P.get("position_id","bsnh[3]")}; + ${C.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${C.setByOffset("k",v.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:ii({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(et.size(_)/dh)},programUniforms:y})}},D2=(n,e)=>{_T(n.inputs,e),n.compute(Kg(n.inputs,e))}}),gT,vT,cv,yT,O2,u3=At(()=>{ir(),fn(),zM(),A2(),R2(),Bc(),I2(),xn(),gT=(n,e)=>{if(e.doRotary&&n.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=n[0],i=n[1],s=n[2],o=n[3],l=n[4];if(e.doRotary!==0&&n.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(e.localWindowSize!==-1)throw new Error("Local attention is not supported");if(e.softcap!==0)throw new Error("Softcap is not supported");if(e.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(e.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=t.dims[0],f=t.dims[1],m=t.dims.length===3?u?t.dims[2]/3:t.dims[2]:e.numHeads*t.dims[4],h=f,_=0,g=!i||i.dims.length===0,y=Math.floor(g?m/(e.numHeads+2*e.kvNumHeads):m/e.numHeads);g&&(m=y*e.numHeads);let b=o&&o.dims.length!==0,T=l&&l.dims.length!==0;if(b&&o.dims.length===4&&o.dims[0]===d&&o.dims[1]!==e.kvNumHeads&&o.dims[2]===e.kvNumHeads&&o.dims[3]===y)throw new Error("BSNH pastKey/pastValue is not supported");if(b&&T){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=o.dims[2]}else if(b||T)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=1;if(i&&i.dims.length>0){if(t.dims.length!==3)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(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(t.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');h=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==e.numHeads||i.dims[3]!==2||i.dims[4]!==y)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');h=i.dims[1]}else{if(i.dims[1]!==e.numHeads||i.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');h=i.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==e.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let x=0,P=!1,w=e.kvNumHeads?y*e.kvNumHeads:m;if(s&&s.dims.length>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(h!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');w=s.dims[2]}else{if(h!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');w=s.dims[1]*s.dims[3],P=!0}}let C=n.length>4?n[5]:void 0;if(C&&C.dims.length!==1&&C.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:d,sequenceLength:f,pastSequenceLength:_,kvSequenceLength:h,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:m,vHiddenSize:w,headSize:y,vHeadSize:Math.floor(w/e.kvNumHeads),numHeads:e.numHeads,kvNumHeads:e.kvNumHeads,nReps:e.numHeads/e.kvNumHeads,pastPresentShareBuffer:!1,maskType:x,scale:e.scale,broadcastResPosBias:!1,passPastInKv:P,qkvFormat:v}},vT=ii({perm:[0,2,1,3]}),cv=(n,e,t)=>{let i=e,s=t.kvNumHeads;return e.dims.length===3&&t.kvSequenceLength!==0&&(i=e.reshape([t.batchSize,t.kvSequenceLength,s,t.headSize]),i=n.compute(Ls(i,vT.perm),{inputs:[i],outputs:[-1]})[0]),i},yT=(n,e,t,i)=>{let s=7,o=["type","type"],l=[n*e],u=n*e,d=[{type:12,data:u},{type:12,data:e},{type:12,data:n}],f=m=>{let h=at("seq_lens",t.dataType,t.dims),_=at("total_seq_lens",i.dataType,i.dims),g=Ht("pos_ids",s,l),y=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${m.registerUniforms(y).declareVariables(h,_,g)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${_.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${h.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${g.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${g.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${g.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${n};${e}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:f}},O2=(n,e)=>{let t=gT(n.inputs,e);if(n.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(n.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let i=n.inputs[0],s=n.inputs[1]&&n.inputs[1].dims.length>0?n.inputs[1]:void 0,o=n.inputs[2]&&n.inputs[2].dims.length>0?n.inputs[2]:void 0,l=n.inputs[3]&&n.inputs[3].dims.length!==0?n.inputs[3]:void 0,u=n.inputs[4]&&n.inputs[4].dims.length!==0?n.inputs[4]:void 0,d=n.inputs.length>4?n.inputs[5]:void 0,f=n.inputs.length>5?n.inputs[6]:void 0,m=t.kvNumHeads?t.kvNumHeads:t.numHeads,h=ii({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,m*t.headSize,m*t.headSize]}),[_,g,y]=!s&&!o?n.compute(Cy([i],h),{inputs:[i],outputs:[-1,-1,-1]}):[i,s,o],b,T;if(e.doRotary){let w=n.compute(yT(t.batchSize,t.sequenceLength,d,f),{inputs:[d,f],outputs:[-1]})[0],C=n.inputs[7],E=n.inputs[8],A=ii({interleaved:e.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:e.scale}),L=[_,w,C,E],I=[-1];b=n.compute(Kg(L,A),{inputs:L,outputs:I})[0],L.splice(0,1,g);let O=ii({interleaved:e.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:e.scale});T=n.compute(Kg(L,O),{inputs:L,outputs:I})[0]}let v=$m(n,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,e.doRotary?b:_,void 0,0),x=cv(n,e.doRotary?T:g,t),P=cv(n,y,t);Km(n,v,x,P,void 0,void 0,l,u,void 0,t,d,f)}}),uv,MT,bT,L2,d3=At(()=>{fn(),Mn(),Bc(),xn(),uv=(n,e,t,i,s,o,l,u)=>{let d=qi(o),f=d===1?"f32":`vec${d}f`,m=d===1?"vec2f":`mat2x${d}f`,h=s*l,_=64;h===1&&(_=256);let g=[s,l,o/d],y=[s,l,2],b=["rank","type","type"],T=[];T.push(...en(g,y));let v=x=>{let P=at("x",e.dataType,3,d),w=at("scale",t.dataType,t.dims),C=at("bias",i.dataType,i.dims),E=Ht("output",1,3,2),A=[P,w,C,E];return` + var workgroup_shared : array<${m}, ${_}>; + const workgroup_size = ${_}u; + ${x.declareVariables(...A)} + ${x.mainStart(_)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${f}(0); + var squared_sum = ${f}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${f}(${P.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${m}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Nc("workgroup_shared[0][0]",d)} / f32(hight * ${d}); + let squared_sum_final = ${Nc("workgroup_shared[0][1]",d)} / f32(hight * ${d}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return n.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u};${_}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:y,dataType:1}],dispatchGroup:{x:h},programUniforms:T}),getShaderSource:v},{inputs:[e,t,i],outputs:[-1]})[0]},MT=(n,e,t)=>{let i=e[0].dims,s=i,o=2,l=i[0],u=i[1],d=et.sizeFromDimension(i,o),f=qi(d),m=et.size(s)/f,h=uv(n,e[0],e[1],e[2],l,d,u,t.epsilon),_=[l,u,d/f],g=[l,u],y=["type","none"],b=T=>{let v=at("x",e[0].dataType,_.length,f),x=at("scale_shift",1,g.length,2),P=Ht("output",e[0].dataType,_.length,f),w=[v,x,P];return` + ${T.registerUniform("output_size","u32").declareVariables(...w)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${P.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${x.getByIndices("vec2(batch, channel)")}; + let value = ${v.getByOffset("global_idx")} * ${P.type.value}(scale_shift.x) + ${P.type.value}(scale_shift.y); + ${P.setByOffset("global_idx","value")}; + }`};n.compute({name:"InstanceNormalization",shaderCache:{hint:`${f}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...en(_,g,_)]}),getShaderSource:b},{inputs:[e[0],h]})},bT=(n,e,t)=>{let i=e[0].dims,s=i,o=i[0],l=i[i.length-1],u=et.sizeFromDimension(i,1)/l,d=qi(l),f=et.size(s)/d,m=[{type:12,data:u},{type:12,data:Math.floor(l/d)}],h=["type","type"],_=!1,g=[0,i.length-1];for(let v=0;vi[g[x]])),b=uv(n,y,e[1],e[2],o,u,l,t.epsilon),T=v=>{let x=xr(e[0].dataType),P=d===1?"vec2f":`mat${d}x2f`,w=A=>{let L=A===0?"x":"y",I=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${x}(${I}(scale.${L}))`;case 2:return`vec2<${x}>(${I}(scale[0].${L}, scale[1].${L}))`;case 4:return`vec4<${x}>(${I}(scale[0].${L}, scale[1].${L}, scale[2].${L}, scale[3].${L}))`;default:throw new Error(`Not supported compoents ${d}`)}},C=at("input",e[0].dataType,e[0].dims,d),E=Ht("output",e[0].dataType,s,d);return` + @group(0) @binding(0) var input : array<${C.type.storage}>; + @group(0) @binding(1) var scale_input : array<${P}>; + @group(0) @binding(2) var output : array<${E.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${v.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${w(0)}, ${w(1)}); + }`};n.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:m}),getShaderSource:T},{inputs:[e[0],b]})},L2=(n,e)=>{e.format==="NHWC"?bT(n,n.inputs,e):MT(n,n.inputs,e)}}),xT,wT,F2,f3=At(()=>{fn(),Mn(),xn(),xT=n=>{if(!n||n.length<2)throw new Error("layerNorm requires at least 2 inputs.")},wT=(n,e,t)=>{let i=e.simplified,s=n[0].dims,o=n[1],l=!i&&n[2],u=s,d=et.normalizeAxis(e.axis,s.length),f=et.sizeToDimension(s,d),m=et.sizeFromDimension(s,d),h=et.size(o.dims),_=l?et.size(l.dims):0;if(h!==m||l&&_!==m)throw new Error(`Size of X.shape()[axis:] == ${m}. + Size of scale and bias (if provided) must match this. + Got scale size of ${h} and bias size of ${_}`);let g=[];for(let C=0;C1,x=t>2,P=C=>{let E=xr(n[0].dataType),A=[at("x",n[0].dataType,n[0].dims,y),at("scale",o.dataType,o.dims,y)];l&&A.push(at("bias",l.dataType,l.dims,y)),A.push(Ht("output",n[0].dataType,u,y)),v&&A.push(Ht("mean_data_output",1,g)),x&&A.push(Ht("inv_std_output",1,g));let L=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${C.registerUniforms(L).declareVariables(...A)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${yy("f32",y)}; + var mean_square_vector = ${yy("f32",y)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${rh(E,y,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Nc("mean_vector",y)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Nc("mean_square_vector",y)} / uniforms.norm_size ${i?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${rh(E,y,"x[j + offset]")}; + let f32scale = ${rh(E,y,"scale[j]")}; + output[j + offset] = ${A[0].type.value}((f32input ${i?"":"- mean"}) * inv_std_dev * f32scale + ${l?`+ ${rh(E,y,"bias[j]")}`:""} + ); + } + + ${v?"mean_data_output[global_idx] = mean":""}; + ${x?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},w=[{dims:u,dataType:n[0].dataType}];return v&&w.push({dims:g,dataType:1}),x&&w.push({dims:g,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${y};${t};${i}`,inputDependencies:b},getRunData:()=>({outputs:w,dispatchGroup:{x:Math.ceil(f/64)},programUniforms:T}),getShaderSource:P}},F2=(n,e)=>{xT(n.inputs),n.compute(wT(n.inputs,e,n.outputCount))}}),TT,k2,h3=At(()=>{Mn(),GM(),jM(),TT=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.")},k2=n=>{TT(n.inputs);let e=uh.calcShape(n.inputs[0].dims,n.inputs[1].dims,!0);if(!e)throw new Error("Can't use matmul on the given tensors");let t=e[e.length-1],i=n.inputs[0].dims[n.inputs[0].dims.length-1];if(t<8&&i<8)n.compute(VM(n.inputs,{activation:""},e));else{let s=e[e.length-2],o=et.size(n.inputs[0].dims.slice(0,-2)),l=et.size(n.inputs[1].dims.slice(0,-2));if(o!==1&&s===1&&l===1){let u=n.inputs[0].reshape([1,o,i]),d=n.inputs[1].reshape([1,i,t]),f=[1,o,t],m=[u,d];n.compute(Xg(m,{activation:""},e,f),{inputs:m})}else n.compute(Xg(n.inputs,{activation:""},e))}}}),ET,ST,AT,N2,z2,p3=At(()=>{fn(),Mn(),ir(),xn(),ET=(n,e)=>{if(n.length<3||n.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=n[0],i=t.dims.length;if(t.dims[i-1]!==e.k)throw new Error("The last dim of input shape does not match the k value");let s=Math.floor((e.k+e.blockSize-1)/e.blockSize),o=e.blockSize/8*e.bits,l=n[1];if(!et.areEqual(l.dims,[e.n,s,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=n[2].dims;if(et.size(u)!==e.n*s)throw new Error("scales input size error.");if(n.length===4){let d=n[3].dims,f=e.bits>4?e.n*s:e.n*Math.floor((s+1)/2);if(et.size(d)!==f)throw new Error("zeroPoints input size error.")}},ST=(n,e)=>{let t=n[0].dims,i=t.length,s=t[i-2],o=e.k,l=e.n,u=t.slice(0,i-2),d=et.size(u),f=n[1].dims[2]/4,m=n[0].dataType,h=qi(e.k),_=qi(f),g=qi(l),y=u.concat([s,l]),b=s>1&&l/g%2===0?2:1,T=et.size(y)/g/b,v=64,x=[],P=[d,s,o/h],w=et.convertShape(n[1].dims).slice();w.splice(-1,1,f/_),x.push(...en(P)),x.push(...en(w)),x.push(...en(n[2].dims)),n.length===4&&x.push(...en(et.convertShape(n[3].dims)));let C=[d,s,l/g];x.push(...en(C));let E=A=>{let L=P.length,I=at("a",n[0].dataType,L,h),O=at("b",12,w.length,_),H=at("scales",n[2].dataType,n[2].dims.length),Z=[I,O,H],$=n.length===4?at("zero_points",12,n[3].dims.length):void 0;$&&Z.push($);let J=C.length,ee=Ht("output",n[0].dataType,J,g),X=xr(n[0].dataType),ne=(()=>{switch(h){case 1:return`array<${X}, 8>`;case 2:return`mat4x2<${X}>`;case 4:return`mat2x4<${X}>`;default:throw new Error(`${h}-component is not supported.`)}})(),Q=()=>{let q=` + // reuse a data + var input_offset = ${I.indicesToOffset(`${I.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ne}; + for (var j: u32 = 0; j < ${8/h}; j++) { + a_data[j] = ${I.getByOffset("input_offset")}; + input_offset++; + } + `;for(let G=0;G> 4) & b_mask); + b_quantized_values = ${ne}(${Array.from({length:4},(te,B)=>`${X}(b_value_lower[${B}]), ${X}(b_value_upper[${B}])`).join(", ")}); + b_dequantized_values = ${h===1?`${ne}(${Array.from({length:8},(te,B)=>`(b_quantized_values[${B}] - ${$?`zero_point${G}`:"zero_point"}) * scale${G}`).join(", ")});`:`(b_quantized_values - ${ne}(${Array(8).fill(`${$?`zero_point${G}`:"zero_point"}`).join(",")})) * scale${G};`}; + workgroup_shared[local_id.x * ${b} + ${Math.floor(G/g)}]${g>1?`[${G%g}]`:""} += ${Array.from({length:8/h},(te,B)=>`${h===1?`a_data[${B}] * b_dequantized_values[${B}]`:`dot(a_data[${B}], b_dequantized_values[${B}])`}`).join(" + ")}; + `;return q},oe=()=>{let q=` + var col_index = col * ${g}; + ${$?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${X}(8);`} + `;for(let G=0;G> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${$.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${G} = ${X}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return q},W=()=>{let q=`col_index = col * ${g};`;for(let G=0;G; + var b_value_upper: vec4; + var b_quantized_values: ${ne}; + var b_dequantized_values: ${ne};`,q};return` + var workgroup_shared: array<${ee.type.value}, ${b*v}>; + ${A.declareVariables(...Z,ee)} + ${A.mainStart([v,1,1])} + let output_indices = ${ee.offsetToIndices(`(global_idx / ${v}) * ${b}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) { + //process one block + var word_offset: u32 = block * ${e.blockSize/h}; + ${oe()} + for (var word: u32 = 0; word < ${f}; word += ${_}) { + ${W()} + for (var i: u32 = 0; i < ${_}; i++) { + ${Q()} + word_offset += ${8/h}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${b}) { + var output_value: ${ee.type.value} = ${ee.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${v}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${b}; + } + ${ee.setByIndices(`${ee.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${e.blockSize};${e.bits};${h};${_};${g};${b};${v}`,inputDependencies:Array(n.length).fill("rank")},getRunData:()=>({outputs:[{dims:y,dataType:m}],dispatchGroup:{x:T},programUniforms:x}),getShaderSource:E}},AT=(n,e)=>{let t=n[0].dims,i=t.length,s=t[i-2],o=e.k,l=e.n,u=t.slice(0,i-2),d=et.size(u),f=n[1].dims[2]/4,m=n[0].dataType,h=qi(e.k),_=qi(f),g=u.concat([s,l]),y=128,b=l%8===0?8:l%4===0?4:1,T=y/b,v=T*_*8,x=v/h,P=v/e.blockSize,w=et.size(g)/b,C=[],E=[d,s,o/h],A=et.convertShape(n[1].dims).slice();A.splice(-1,1,f/_),C.push(...en(E)),C.push(...en(A)),C.push(...en(n[2].dims)),n.length===4&&C.push(...en(et.convertShape(n[3].dims)));let L=[d,s,l];C.push(...en(L));let I=O=>{let H=E.length,Z=at("a",n[0].dataType,H,h),$=at("b",12,A.length,_),J=at("scales",n[2].dataType,n[2].dims.length),ee=[Z,$,J],X=n.length===4?at("zero_points",12,n[3].dims.length):void 0;X&&ee.push(X);let ne=L.length,Q=Ht("output",n[0].dataType,ne),oe=xr(n[0].dataType),W=()=>{switch(h){case 1:return` + let a_data0 = vec4<${oe}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${oe}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${oe}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${oe}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${h}-component is not supported.`)}};return` + var sub_a: array<${Z.type.value}, ${x}>; + var inter_results: array, ${b}>; + ${O.declareVariables(...ee,Q)} + ${O.mainStart([T,b,1])} + let output_indices = ${Q.offsetToIndices(`workgroup_index * ${b}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${P} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${x}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${x}; a_offset += ${y}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Z.getByIndices(`${Z.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Z.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${P} + local_id.x; + ${X?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${X.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${oe}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${oe}(8);`} + let scale = ${J.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${$.getByIndices(`${$.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${e.blockSize/h}; + for (var i: u32 = 0; i < ${_}; i++) { + ${W()} + let b_value = ${_===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${oe}>(${Array.from({length:4},(q,G)=>`${oe}(b_value_lower[${G}]), ${oe}(b_value_upper[${G}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${oe}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(q,G)=>`${`dot(a_data${G}, b_dequantized_values[${G}])`}`).join(" + ")}; + word_offset += ${8/h}; + } + workgroupBarrier(); + } + + if (local_idx < ${b}) { + var output_value: ${Q.type.value} = ${Q.type.value}(0); + for (var b = 0u; b < ${T}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Q.setByIndices(`${Q.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${e.blockSize};${h};${_};${T};${b}`,inputDependencies:Array(n.length).fill("rank")},getRunData:()=>({outputs:[{dims:g,dataType:m}],dispatchGroup:{x:w},programUniforms:C}),getShaderSource:I}},N2=(n,e)=>{ET(n.inputs,e),e.blockSize===32&&n.adapterInfo.isVendor("intel")&&n.adapterInfo.isArchitecture("gen-12lp")?n.compute(AT(n.inputs,e)):n.compute(ST(n.inputs,e))},z2=n=>ii(n)}),CT,PT,RT,DT,IT,OT,LT,FT,U2,m3=At(()=>{fn(),Mn(),xn(),CT=n=>{if(!n||n.length<1)throw new Error("Too few inputs");if(n[0].dataType!==1&&n[0].dataType!==10)throw new Error("Input type must be float or float16.");if(n.length>=2){let e=n[0].dims.length*2===n[1].dims[0];if(n.length===4&&(e=n[3].dims[0]*2===n[1].dims[0]),!e)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},PT=(n,e,t)=>{let i="";for(let s=e-1;s>=0;--s)i+=` + k = i32(${n.indicesGet("indices",s)}) - ${Yt("uniforms.pads",s,t)}; + if (k < 0) { + break; + } + if (k >= i32(${Yt("uniforms.x_shape",s,e)})) { + break; + } + offset += k * i32(${Yt("uniforms.x_strides",s,e)}); + `;return` + value = ${n.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${i} + value = x[offset]; + } + `},RT=(n,e,t)=>{let i="";for(let s=e-1;s>=0;--s)i+=` + k = i32(${n.indicesGet("indices",s)}) - ${Yt("uniforms.pads",s,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Yt("uniforms.x_shape",s,e)}) - 1); + k = k % _2n_1; + if(k >= i32(${Yt("uniforms.x_shape",s,e)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Yt("uniforms.x_strides",s,e)}); + `;return` + var offset = 0; + var k = 0; + ${i} + value = x[offset]; + `},DT=(n,e,t)=>{let i="";for(let s=e-1;s>=0;--s)i+=` + k = i32(${n.indicesGet("indices",s)}) - ${Yt("uniforms.pads",s,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Yt("uniforms.x_shape",s,e)})) { + k = i32(${Yt("uniforms.x_shape",s,e)}) - 1; + } + offset += k * i32(${Yt("uniforms.x_strides",s,e)}); + `;return` + var offset = 0; + var k = 0; + ${i} + value = x[offset]; + `},IT=(n,e,t)=>{let i="";for(let s=e-1;s>=0;--s)i+=` + k = i32(${n.indicesGet("indices",s)}) - ${Yt("uniforms.pads",s,t)}; + if (k < 0) { + k += i32(${Yt("uniforms.x_shape",s,e)}]); + } + if (k >= i32(${Yt("uniforms.x_shape",s,e)})) { + k -= i32(${Yt("uniforms.x_shape",s,e)}); + } + offset += k * i32(${Yt("uniforms.x_strides",s,e)}); + `;return` + var offset = 0; + var k = 0; + ${i} + value = x[offset]; + `},OT=(n,e,t)=>{switch(t.mode){case 0:return PT(n,e,t.pads.length);case 1:return RT(n,e,t.pads.length);case 2:return DT(n,e,t.pads.length);case 3:return IT(n,e,t.pads.length);default:throw new Error("Invalid mode")}},LT=(n,e)=>{let t=et.padShape(n[0].dims.slice(),e.pads),i=n[0].dims,s=et.size(t),o=[{type:12,data:s},{type:6,data:e.pads}],l=n.length>=3&&n[2].data;e.mode===0&&o.push({type:l?n[2].dataType:1,data:e.value}),o.push(...en(n[0].dims,t));let u=["rank"],d=f=>{let m=Ht("output",n[0].dataType,t.length),h=at("x",n[0].dataType,i.length),_=h.type.value,g=OT(m,i.length,e),y=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:e.pads.length}];return e.mode===0&&y.push({name:"constant_value",type:l?_:"f32"}),` + ${f.registerUniforms(y).declareVariables(h,m)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${m.offsetToIndices("global_idx")}; + + var value = ${_}(0); + ${g} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${e.mode}${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:t,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(et.size(t)/64)},programUniforms:o}),getShaderSource:d}},FT=(n,e)=>{if(n.length>1){let t=n[1].getBigInt64Array(),i=n.length>=3&&n[2].data?n[2].dataType===10?n[2].getUint16Array()[0]:n[2].getFloat32Array()[0]:0,s=n[0].dims.length,o=new Int32Array(2*s).fill(0);if(n.length>=4){let u=n[3].getBigInt64Array();for(let d=0;do[Number(d)]=Number(u));let l=[];return o.forEach(u=>l.push(u)),{mode:e.mode,value:i,pads:l}}else return e},U2=(n,e)=>{CT(n.inputs);let t=FT(n.inputs,e);n.compute(LT(n.inputs,t),{inputs:[0]})}}),Cm,dv,fv,hv,pv,kT,NT,mv,_v,B2,$2,gv,V2,G2,vv,j2,W2,H2,q2,_3=At(()=>{Ka(),fn(),Mn(),xn(),Cm=n=>{if(Di.webgpu.validateInputContent&&(!n||n.length!==1))throw new Error("Pool ops requires 1 input.")},dv=(n,e,t)=>{let i=e.format==="NHWC",s=n.dims.slice();i&&s.splice(1,0,s.pop());let o=Object.hasOwnProperty.call(e,"dilations"),l=e.kernelShape.slice(),u=e.strides.slice(),d=o?e.dilations.slice():[],f=e.pads.slice();Hg.adjustPoolAttributes(t,s,l,u,d,f);let m=Hg.computePoolOutputShape(t,s,u,d,l,f,e.autoPad),h=Object.assign({},e);o?Object.assign(h,{kernelShape:l,strides:u,pads:f,dilations:d,cacheKey:e.cacheKey}):Object.assign(h,{kernelShape:l,strides:u,pads:f,cacheKey:e.cacheKey});let _=m.slice();return _.push(_.splice(1,1)[0]),[h,i?_:m]},fv=(n,e)=>{let t=e.format==="NHWC",i=et.size(n),s=et.size(e.kernelShape),o=[{type:12,data:i},{type:12,data:s}],l=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(e.kernelShape.length<=2){let u=e.kernelShape[e.kernelShape.length-1],d=e.strides[e.strides.length-1],f=e.pads[e.pads.length/2-1],m=e.pads[e.pads.length-1],h=!!(f+m);o.push({type:12,data:u},{type:12,data:d},{type:12,data:f},{type:12,data:m}),l.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let _=!1;if(e.kernelShape.length===2){let g=e.kernelShape[e.kernelShape.length-2],y=e.strides[e.strides.length-2],b=e.pads[e.pads.length/2-2],T=e.pads[e.pads.length-2];_=!!(b+T),o.push({type:12,data:g},{type:12,data:y},{type:12,data:b},{type:12,data:T}),l.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,l,!0,h,_]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=et.computeStrides(e.kernelShape);o.push({type:12,data:u},{type:12,data:e.pads},{type:12,data:e.strides}),l.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:e.pads.length},{name:"strides",type:"u32",length:e.strides.length});let d=e.pads.reduce((f,m)=>f+m);return[o,l,!!d,!1,!1]}},hv=(n,e,t,i,s,o,l,u,d,f,m,h)=>{let _=s.format==="NHWC",g=e.type.value,y=Ht("output",e.type.tensor,i);if(s.kernelShape.length<=2){let b="",T="",v="",x=t-(_?2:1);if(m?b=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${x}] < 0 || xIndices[${x}] + >= uniforms.x_shape[${x}]) { + pad++; + continue; + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + }`:b=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + }`,s.kernelShape.length===2){let P=t-(_?3:2);h?T=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${P}] < 0 || xIndices[${P}] >= uniforms.x_shape[${P}]) { + pad += i32(uniforms.kw); + continue; + } + `:T=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j; + `,v=` + } + `}return` + ${n.registerUniforms(d).declareVariables(e,y)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${y.offsetToIndices("global_idx")}; + var xIndices = ${y.offsetToIndices("global_idx")}; + + var value = ${g}(${u}); + var pad = 0; + ${T} + ${b} + ${v} + ${l} + + output[global_idx] = value; + }`}else{if(_)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let b=s.kernelShape.length,T=s.pads.length,v="";return f?v=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + }`:v=` + } + let x_val = x[${e.indicesToOffset("xIndices")}]; + ${o} + `,` + ${n.registerUniforms(d).declareVariables(e,y)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${y.offsetToIndices("global_idx")}; + var xIndices = ${y.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${g}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${b-1}u; j++) { + offsets[j] = offset / ${Yt("uniforms.kernelStrides","j",b)}; + offset -= offsets[j] * ${Yt("uniforms.kernelStrides","j",b)}; + } + offsets[${b-1}] = offset; + + isPad = false; + for (var j = ${t-b}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${Yt("uniforms.strides",`j - ${t-b}u`,b)} + + offsets[j - ${t-b}u] - ${Yt("uniforms.pads","j - 2u",T)}; + ${v} + } + ${l} + + output[global_idx] = value; + }`}},pv=n=>`${n.format};${n.ceilMode};${n.autoPad};${n.kernelShape.length}`,kT=n=>`${pv(n)};${n.countIncludePad}`,NT=n=>`${pv(n)};${n.storageOrder};${n.dilations}`,mv=n=>({format:n.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],ceilMode:n.ceil_mode,kernelShape:n.kernel_shape,strides:n.strides,pads:n.pads}),_v=(n,e,t,i)=>{let[s,o]=dv(e,i,t),l=at("x",e.dataType,e.dims.length),u=l.type.value,d="value += x_val;",f="";s.countIncludePad?f+=`value /= ${u}(uniforms.kernelSize);`:f+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[m,h,_,g,y]=fv(o,s);m.push(...en(e.dims,o));let b=["rank"];return{name:n,shaderCache:{hint:`${i.cacheKey};${_};${g};${y}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(et.size(o)/64)},programUniforms:m}),getShaderSource:T=>hv(T,l,e.dims.length,o.length,s,d,f,0,h,_,g,y)}},B2=n=>{let e=n.count_include_pad!==0,t=mv(n);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let i={countIncludePad:e,...t,cacheKey:""};return{...i,cacheKey:kT(i)}},$2=(n,e)=>{Cm(n.inputs),n.compute(_v("AveragePool",n.inputs[0],!1,e))},gv={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},V2=n=>{let e=n.format;return{format:e,...gv,cacheKey:e}},G2=(n,e)=>{Cm(n.inputs),n.compute(_v("GlobalAveragePool",n.inputs[0],!0,e))},vv=(n,e,t,i)=>{let[s,o]=dv(e,i,t),l=` + value = max(x_val, value); + `,u="",d=at("x",e.dataType,e.dims.length),f=["rank"],[m,h,_,g,y]=fv(o,s);return m.push(...en(e.dims,o)),{name:n,shaderCache:{hint:`${i.cacheKey};${_};${g};${y}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(et.size(o)/64)},programUniforms:m}),getShaderSource:b=>hv(b,d,e.dims.length,o.length,s,l,u,e.dataType===10?-65504:-1e5,h,_,g,y)}},j2=(n,e)=>{Cm(n.inputs),n.compute(vv("MaxPool",n.inputs[0],!1,e))},W2=n=>{let e=n.storage_order,t=n.dilations,i=mv(n);if(e!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(i.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let s={storageOrder:e,dilations:t,...i,cacheKey:""};return{...s,cacheKey:NT(s)}},H2=n=>{let e=n.format;return{format:e,...gv,cacheKey:e}},q2=(n,e)=>{Cm(n.inputs),n.compute(vv("GlobalMaxPool",n.inputs[0],!0,e))}}),zT,UT,X2,K2,g3=At(()=>{fn(),Mn(),ir(),xn(),zT=(n,e)=>{if(n.length<2||n.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(n.length===3&&n[1].dims===n[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(n.length===3&&n[0].dataType!==n[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(n[0].dataType===6&&n.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(n[1].dims.length!==0&&n[1].dims.length!==1&&n[1].dims.length!==n[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(n.length>2){if(n[0].dataType!==n[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(n[1].dims.length!==n[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!n[1].dims.map((t,i)=>t===n[2].dims[i]).reduce((t,i)=>t&&i,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(e.blockSize>0){if(n[1].dims.length===0||n[1].dims.length===1&&n[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!n[1].dims.map((s,o)=>o===e.axis||s===n[0].dims[o]).reduce((s,o)=>s&&o,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(n[1].dims.length!==n[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=n[0].dims[e.axis],i=n[1].dims[e.axis];if(e.blockSizeMath.ceil(t/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},UT=(n,e)=>{let t=et.normalizeAxis(e.axis,n[0].dims.length),i=n[0].dataType,s=i===3,o=n[0].dims,l=n[1].dataType,u=et.size(o),d=i===3||i===2,f=d?[Math.ceil(et.size(n[0].dims)/4)]:n[0].dims,m=n[1].dims,h=n.length>2?n[2]:void 0,_=h?d?[Math.ceil(et.size(h.dims)/4)]:h.dims:void 0,g=m.length===0||m.length===1&&m[0]===1,y=g===!1&&m.length===1,b=qi(u),T=g&&(!d||b===4),v=T?b:1,x=T&&!d?b:1,P=at("input",d?12:i,f.length,x),w=at("scale",l,m.length),C=h?at("zero_point",d?12:i,_.length):void 0,E=Ht("output",l,o.length,v),A=[P,w];C&&A.push(C);let L=[f,m];h&&L.push(_);let I=[{type:12,data:u/v},{type:12,data:t},{type:12,data:e.blockSize},...en(...L,o)],O=H=>{let Z=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${H.registerUniforms(Z).declareVariables(...A,E)} + ${H.mainStart()} + ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${E.offsetToIndices("global_idx")}; + + // Set input x + ${d?` + let input = ${P.getByOffset("global_idx / 4")}; + let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${v===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${P.getByOffset("global_idx")};`}; + + // Set scale input + ${g?`let scale_value= ${w.getByOffset("0")}`:y?` + let scale_index = ${E.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${w.getByOffset("scale_index")};`:` + var scale_indices: ${w.type.indices} = output_indices; + let index = ${w.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${w.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${w.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${C?g?d?` + let zero_point_input = ${C.getByOffset("0")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${C.getByOffset("0")}`:y?d?` + let zero_point_index = ${E.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${C.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${E.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${C.getByOffset("zero_point_index")};`:d?` + let zero_point_offset = ${w.indicesToOffset("scale_indices")}; + let zero_point_input = ${C.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${C.getByIndices("scale_indices")};`:`let zero_point_value = ${d?s?"i32":"u32":P.type.value}(0);`}; + // Compute and write output + ${E.setByOffset("global_idx",`${E.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:e.cacheKey,inputDependencies:C?["rank","rank","rank"]:["rank","rank"]},getShaderSource:O,getRunData:()=>({outputs:[{dims:o,dataType:l}],dispatchGroup:{x:Math.ceil(u/v/64),y:1,z:1},programUniforms:I})}},X2=(n,e)=>{zT(n.inputs,e),n.compute(UT(n.inputs,e))},K2=n=>ii({axis:n.axis,blockSize:n.blockSize})}),BT,$T,Y2,v3=At(()=>{Ka(),fn(),xn(),BT=(n,e,t)=>{let i=n===e,s=ne&&t>0;if(i||s||o)throw new Error("Range these inputs' contents are invalid.")},$T=(n,e,t,i)=>{let s=Math.abs(Math.ceil((e-n)/t)),o=[s],l=s,u=[{type:12,data:l},{type:i,data:n},{type:i,data:t},...en(o)],d=f=>{let m=Ht("output",i,o.length),h=m.type.value,_=[{name:"outputSize",type:"u32"},{name:"start",type:h},{name:"delta",type:h}];return` + ${f.registerUniforms(_).declareVariables(m)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${h}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u})}},Y2=n=>{let e=0,t=0,i=0;n.inputs[0].dataType===6?(e=n.inputs[0].getInt32Array()[0],t=n.inputs[1].getInt32Array()[0],i=n.inputs[2].getInt32Array()[0]):n.inputs[0].dataType===1&&(e=n.inputs[0].getFloat32Array()[0],t=n.inputs[1].getFloat32Array()[0],i=n.inputs[2].getFloat32Array()[0]),Di.webgpu.validateInputContent&&BT(e,t,i),n.compute($T(e,t,i,n.inputs[0].dataType),{inputs:[]})}}),VT,yv,Mv,GT,Q2,Z2,y3=At(()=>{fn(),Mn(),ir(),xn(),VT=(n,e,t,i)=>{if(n!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${n}.`);let s=`{ + var oldValue = 0; + loop { + let newValueF32 =`,o=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${e}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(n){case"none":return`${e}=${t};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${e}, bitcast<${i}>(${t}));`:` + ${s}bitcast<${i}>(oldValue) + (${t})${o}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${e}, bitcast<${i}>(${t}));`:` + ${s}max(bitcast(oldValue), (${t}))${o}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${e}, bitcast<${i}>(${t}));`:`${s}min(bitcast<${i}>(oldValue), (${t}))${o}`;case"mul":return`${s}(bitcast<${i}>(oldValue) * (${t}))${o}`;default:throw new Error(`Reduction ${n} is not supported.`)}},yv=(n,e)=>`${n===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${e?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${e?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,Mv=(n,e,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${VT(n.reduction,"output[data_offset + i]","value",e)} + }`,GT=(n,e)=>{let t=n[0].dims,i=n[1].dims,s=t,o=1,l=Math.ceil(et.size(i)/o),u=i[i.length-1],d=et.sizeFromDimension(t,u),f=et.sizeFromDimension(i,0)/u,m=[{type:12,data:l},{type:12,data:u},{type:12,data:d},...en(n[1].dims,n[2].dims,s)],h=_=>{let g=at("indices",n[1].dataType,n[1].dims.length),y=at("updates",n[2].dataType,n[2].dims.length,o),b=e.reduction!=="none"&&e.reduction!==""?SS("output",n[0].dataType,s.length):Ht("output",n[0].dataType,s.length,o);return` + ${_.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(g,y,b)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${e.reduction==="none"}) { + for (var i = 0; i < ${f}; i = i + 1) { + for (var j = i + 1; j < ${f}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${e.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${f}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${yv(t.length,!1)} + } + ${Mv(e,b.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${yv(t.length,!0)} + } + ${Mv(e,b.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${e.cacheKey}_${e.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:m}),getShaderSource:h}},Q2=n=>ii({reduction:n.reduction}),Z2=(n,e)=>{n.compute(GT(n.inputs,e),{inputs:[n.inputs[1],n.inputs[2]],outputs:[]})}}),jT,WT,HT,bv,qT,XT,KT,YT,QT,ZT,JT,eE,xv,tE,nE,iE,rE,sE,J2,eC,M3=At(()=>{fn(),Mn(),ir(),xn(),jT=(n,e)=>{if(n.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),n.length>0){if(e.mode==="linear"){if(!(n.length===2||n.length===3||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1||n.length===5&&n[0]===1&&n[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(e.mode==="cubic"&&!(n.length===2||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},WT=(n,e,t)=>{e.every(s=>s>=0&&s{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(t).fill(1);return e.forEach((s,o)=>i[s]=n[o]),i},HT=(n,e,t,i,s,o)=>{let[l,u,d]=t>10?[1,2,3]:[-1,n.length>1?1:-1,-1],f=n[0].dims.length;if(l>0&&n.length>l&&n[l].dims.length>0)n[l].getFloat32Array().forEach(m=>o.push(m));else if(e.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&n.length>u&&n[u].dims.length===1&&n[u].dims[0]>0){if(n[u].getFloat32Array().forEach(m=>i.push(m)),i.length!==0&&i.length!==f&&t>=18&&i.length!==e.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");jT(i,e),e.axes.length>0&&WT(i,e.axes,f).forEach((m,h)=>i[h]=m)}if(d>0&&n.length>d&&n[d].dims.length===1&&n[d].dims[0]>0&&(n[d].getBigInt64Array().forEach(m=>s.push(Number(m))),s.length!==0&&s.length!==f&&t>=18&&s.length!==e.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(e.axes.length>0){if(i.length!==0&&i.length!==e.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(s.length!==0&&s.length!==e.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 s<"u"&&i.length>0&&s.length>f)throw new Error("Resize requires only of scales or sizes to be specified")},bv=(n,e,t,i)=>` + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let big = (${n}) * (${e}); + let whole = ${i}(big / (${t})); + let fract = ${i}(big % (${t})) / ${i}(${t}); + return whole + fract; +`,qT=(n,e)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${e} { `+(()=>{switch(n){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${e}(xResized) / ${e}(xScale); + } else { + ${bv("xResized","lengthOriginal","lengthResized",e)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${e}(xResized) + 0.5) / ${e}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${e}(xResized) + 0.5) / ${e}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${bv("xResized","lengthOriginal - 1","lengthResized - 1",e)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${e}(roiStart) * ${e}(lengthOriginal - 1) + + (${e}(xResized) * ${e}(roiEnd - roiStart) * ${e}(lengthOriginal - 1)) / + ${e}(lengthResized - 1); + } else { + return 0.5 * ${e}(roiStart + roiEnd) * ${e}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${e}xScale * ${e}(lengthResized); + const adjustment = ${e}(lengthResized) / outputWidth; + const center = ${e}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;case"half_pixel":return`return ((${e}(xResized) + 0.5) / ${e}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${n} is not supported`)}})()+"}",XT=(n,e,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(n){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(e<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${n} is not supported`)}})()+"}",KT=(n,e,t)=>{let i=new Array(t).fill(0).concat(new Array(t).fill(1)),s=n.length===0?i:n.slice();return e.length>0?(e.forEach((o,l)=>{i[o]=s[l],i[l+t]=s[e.length+l]}),i):s},YT=(n,e,t,i)=>{let s=[];if(t.length>0)if(i.length>0){if(n.forEach(o=>s.push(o)),Math.max(...i)>n.length)throw new Error("axes is out of bound");i.forEach((o,l)=>s[o]=t[l])}else t.forEach(o=>s.push(o));else{if(e.length===0)throw new Error("Resize requires either scales or sizes.");s=n.map((o,l)=>Math.round(o*e[l]))}return s},QT=(n,e,t)=>{let i=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(o=>e[o]),Number.MAX_VALUE):Math.min(...e,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(o=>e[o]),Number.MIN_VALUE):Math.max(...e,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();e.fill(1,0,e.length);let s=n.slice();return t.axes.length>0?(t.axes.forEach(o=>e[o]=i),t.axes.forEach(o=>s[o]=Math.round(n[o]*e[o]))):(e.fill(i,0,e.length),s.forEach((o,l)=>s[l]=Math.round(o*e[l]))),s},ZT=(n,e,t,i,s)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${n.type.indices}) -> array<${n.type.value}, ${t.length}> { + var original_indices: array<${n.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${n.indicesGet("output_indices","i")}; + var scale = ${Yt("uniforms.scales","i",i)}; + var roi_low = ${Yt("uniforms.roi","i",s)}; + var roi_hi = ${Yt("uniforms.roi",`i + ${e.length}`,s)}; + if (scale == 1.0) { + original_indices[i] = ${n.type.value}(output_index); + } else { + var input_shape_i = ${Yt("uniforms.input_shape","i",e.length)}; + var output_shape_i = ${Yt("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,JT=(n,e,t,i,s,o,l)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> ${n.type.indices} { + var input_indices: ${n.type.indices}; + for (var i:u32 = 0; i < ${i.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Yt("uniforms.scales","i",s)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Yt("uniforms.roi","i",o)}; + var roi_hi = ${Yt("uniforms.roi",`i + ${t.length}`,o)}; + var input_shape_i = ${Yt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Yt("uniforms.output_shape","i",i.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${l} || (original_idx >= 0 && original_idx < ${e.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${e.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${n.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,eE=(n,e)=>` + fn checkInputIndices(input_indices: ${n.type.indices}) -> bool { + for (var i:u32 = 0; i < ${e.length}; i++) { + var input_index = ${n.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${Yt("uniforms.input_shape","i",e.length)}) { + return false; + } + } + return true; + }`,xv=(n,e,t,i)=>n.rank>i?` + ${n.indicesSet("input_indices",e,"channel")}; + ${n.indicesSet("input_indices",t,"batch")}; +`:"",tE=(n,e,t,i,s)=>{let[o,l,u,d]=t.length===2?[-1,0,1,-1]:[0,2,3,1],f=n.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${f} { + var input_indices: ${n.type.indices}; + ${n.indicesSet("input_indices",l,`max(0, min(row, ${t[l]} - 1))`)}; + ${n.indicesSet("input_indices",u,`max(0, min(col, ${t[u]} - 1))`)}; + ${xv(n,d,o,2)} + return ${n.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${e.type.indices}) -> ${f} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${f} = originalIndices[${l}]; + var col:${f} = originalIndices[${u}]; + ${i?`if (row < 0 || row > (${t[l]} - 1) || col < 0 || col > (${t[u]} - 1)) { + return ${s}; + }`:""}; + row = max(0, min(row, ${t[l]} - 1)); + col = max(0, min(col, ${t[u]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${t.length>2?`u32(originalIndices[${d}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${o}])`:"0"}; + var x11: ${f} = getInputValue(batch, channel, row1, col1); + var x12: ${f} = getInputValue(batch, channel, row1, col2); + var x21: ${f} = getInputValue(batch, channel, row2, col1); + var x22: ${f} = getInputValue(batch, channel, row2, col2); + var dx1: ${f} = abs(row - ${f}(row1)); + var dx2: ${f} = abs(${f}(row2) - row); + var dy1: ${f} = abs(col - ${f}(col1)); + var dy2: ${f} = abs(${f}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},nE=(n,e,t,i,s,o,l,u,d,f)=>{let m=t.length===2,[h,_]=m?[0,1]:[2,3],g=n.type.value,y=b=>{let T=b===h?"row":"col";return` + fn ${T}CubicInterpolation(input_indices: ${n.type.indices}, output_indices: ${e.type.indices}) -> ${g} { + var output_index = ${e.indicesGet("output_indices",b)}; + var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[b]}, + ${i[b]}, ${t[b]}, ${o[b]}, ${o[b]} + ${t.length}); + var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${t[b]} - 1))) { + return ${d}; + } + var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${T}: ${g} = originalIdx + ${g}(i); + if (${T} < 0 || ${T} >= ${t[b]}) { + ${f?`coefs[i + 1] = 0.0; + continue;`:u?`return ${d};`:`${T} = max(0, min(${T}, ${t[b]} - 1));`}; + } + var input_indices_copy: ${n.type.indices} = input_indices; + ${n.indicesSet("input_indices_copy",b,`u32(${T})`)}; + data[i + 1] = ${b===h?n.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${y(h)}; + ${y(_)}; + fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> { + var absS = abs(s); + var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${g} = 1.0 - absS; + var twoMinusAbsS: ${g} = 2.0 - absS; + var onePlusAbsS: ${g} = 1.0 + absS; + coeffs[0] = ((${l} * onePlusAbsS - 5 * ${l}) * onePlusAbsS + 8 * ${l}) * onePlusAbsS - 4 * ${l}; + coeffs[1] = ((${l} + 2) * absS - (${l} + 3)) * absS * absS + 1; + coeffs[2] = ((${l} + 2) * oneMinusAbsS - (${l} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${l} * twoMinusAbsS - 5 * ${l}) * twoMinusAbsS + 8 * ${l}) * twoMinusAbsS - 4 * ${l}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${g}, 4>, coefs: array<${g}, 4>) -> ${g} { + var coefsSum: ${g} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${e.type.indices}) -> ${g} { + var input_indices: ${n.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},iE=(n,e,t,i,s)=>{let[o,l,u,d,f]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],m=n.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} { + var input_indices: ${n.type.indices}; + ${n.indicesSet("input_indices",l,`max(0, min(depth, ${t[l]} - 1))`)}; + ${n.indicesSet("input_indices",u,`max(0, min(height, ${t[u]} - 1))`)}; + ${n.indicesSet("input_indices",d,`max(0, min(width, ${t[d]} - 1))`)}; + ${xv(n,f,o,3)} + return ${n.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${e.type.indices}) -> ${m} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${m} = originalIndices[${l}]; + var height:${m} = originalIndices[${u}]; + var width:${m} = originalIndices[${d}]; + ${i?`if (depth < 0 || depth > (${t[l]} - 1) || height < 0 || height > (${t[u]} - 1) || width < 0 || (width > ${t[d]} - 1)) { + return ${s}; + }`:""}; + + depth = max(0, min(depth, ${t[l]} - 1)); + height = max(0, min(height, ${t[u]} - 1)); + width = max(0, min(width, ${t[d]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${f}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${o}])`:"0"}; + + var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${m} = abs(depth - ${m}(depth1)); + var dx2: ${m} = abs(${m}(depth2) - depth); + var dy1: ${m} = abs(height - ${m}(height1)); + var dy2: ${m} = abs(${m}(height2) - height); + var dz1: ${m} = abs(width - ${m}(width1)); + var dz2: ${m} = abs(${m}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},rE=(n,e,t,i,s,o)=>{let l=n.dims,u=KT(o,e.axes,l.length),d=YT(l,i,s,e.axes),f=i.slice();i.length===0&&(f=l.map((x,P)=>x===0?1:d[P]/x),e.keepAspectRatioPolicy!=="stretch"&&(d=QT(l,f,e)));let m=Ht("output",n.dataType,d.length),h=at("input",n.dataType,l.length),_=et.size(d),g=l.length===d.length&&l.every((x,P)=>x===d[P]),y=e.coordinateTransformMode==="tf_crop_and_resize",b=e.extrapolationValue,T=h.type.value,v=x=>` + ${g?"":` + ${qT(e.coordinateTransformMode,T)}; + ${(()=>{switch(e.mode){case"nearest":return` + ${eE(h,l)}; + ${XT(e.nearestMode,t,T)}; + ${JT(h,m,l,d,f.length,u.length,y)}; + `;case"linear":return` + ${ZT(m,l,d,f.length,u.length)}; + ${(()=>{if(l.length===2||l.length===4)return`${tE(h,m,l,y,b)}`;if(l.length===3||l.length===5)return`${iE(h,m,l,y,b)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(l.length===2||l.length===4)return`${nE(h,m,l,d,f,u,e.cubicCoeffA,y,e.extrapolationValue,e.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${x.registerUniform("output_size","u32").registerUniform("scales","f32",f.length).registerUniform("roi","f32",u.length).declareVariables(h,m)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${g?"output[global_idx] = input[global_idx];":` + let output_indices = ${m.offsetToIndices("global_idx")}; + var input_indices: ${h.type.indices}; + ${(()=>{switch(e.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${h.getByIndices("input_indices")}; + } else { + output[global_idx] = ${e.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${l.length===2||l.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${e.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${e.cacheKey}|${t}|${f.length>0?e.mode==="cubic"?f:f.length:""}|${s.length>0?s:""}|${u.length>0?u:""}|${g}|${e.mode==="nearest"?l.length:l}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:d,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},{type:1,data:f},{type:1,data:u},...en(l,d)]})}},sE=n=>{let e=n.customDataBuffer;return new Uint32Array(e,e.byteOffset,1)[0]},J2=(n,e)=>{let t=[],i=[],s=[],o=sE(n);if(e.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");HT(n.inputs,e,o,t,i,s),n.compute(rE(n.inputs[0],e,o,t,i,s),{inputs:[0]})},eC=n=>{let e=n.antialias,t=n.axes,i=n.coordinateTransformMode,s=n.cubicCoeffA,o=n.excludeOutside!==0,l=n.extrapolationValue,u=n.keepAspectRatioPolicy,d=n.mode,f=n.nearestMode===""?"simple":n.nearestMode;return ii({antialias:e,axes:t,coordinateTransformMode:i,cubicCoeffA:s,excludeOutside:o,extrapolationValue:l,keepAspectRatioPolicy:u,mode:d,nearestMode:f})}}),aE,oE,tC,b3=At(()=>{fn(),Mn(),xn(),aE=n=>{if(!n||n.length<3)throw new Error("layerNorm requires at least 3 inputs.");let e=n[0],t=n[1],i=n[2];if(e.dataType!==t.dataType||e.dataType!==i.dataType)throw new Error("All inputs must have the same data type");if(e.dims.length!==3&&e.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let s=e.dims[e.dims.length-1],o=e.dims[e.dims.length-2];if(t.dims[t.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(i.dims.length!==1)throw new Error("Gamma must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Gamma must have the same hidden size as input");if(n.length>3){let l=n[3];if(l.dims.length!==1)throw new Error("Beta must be 1D");if(l.dims[l.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(n.length>4){let l=n[4];if(l.dims.length!==1)throw new Error("Bias must be 1D");if(l.dims[l.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},oE=(n,e,t,i)=>{let s=e.simplified,o=n[0].dims,l=et.size(o),u=o,d=l,f=o.slice(-1)[0],m=i?o.slice(0,-1).concat(1):[],h=!s&&n.length>3,_=n.length>4,g=i&&t>1,y=i&&t>2,b=t>3,T=64,v=qi(f),x=[{type:12,data:d},{type:12,data:v},{type:12,data:f},{type:1,data:e.epsilon}],P=C=>{let E=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],A=[at("x",n[0].dataType,n[0].dims,v),at("skip",n[1].dataType,n[1].dims,v),at("gamma",n[2].dataType,n[2].dims,v)];h&&A.push(at("beta",n[3].dataType,n[3].dims,v)),_&&A.push(at("bias",n[4].dataType,n[4].dims,v)),A.push(Ht("output",n[0].dataType,u,v)),g&&A.push(Ht("mean_output",1,m)),y&&A.push(Ht("inv_std_output",1,m)),b&&A.push(Ht("input_skip_bias_sum",n[0].dataType,u,v));let L=xr(n[0].dataType),I=xr(1,v);return` + + ${C.registerUniforms(E).declareVariables(...A)} + var sum_shared : array<${I}, ${T}>; + var sum_squared_shared : array<${I}, ${T}>; + + ${C.mainStart([T,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${T}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${T}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${T-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${_?"bias[offset1d + i]":L+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${b?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${rh(L,v,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${T}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Nc("sum",v)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Nc("square_sum",v)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); + ${g?"mean_output[global_idx] = mean;":""} + ${y?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${s?"":`- ${L}(mean)`}) * + ${L}(inv_std_dev) * gamma[offset1d + i] + ${h?"+ beta[offset1d + i]":""}; + } + }`},w=[{dims:u,dataType:n[0].dataType}];return t>1&&w.push({dims:m,dataType:1}),t>2&&w.push({dims:m,dataType:1}),t>3&&w.push({dims:o,dataType:n[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${v};${g};${y};${b}`,inputDependencies:n.map((C,E)=>"type")},getShaderSource:P,getRunData:()=>({outputs:w,dispatchGroup:{x:Math.ceil(d/f)},programUniforms:x})}},tC=(n,e)=>{aE(n.inputs);let t=[0];n.outputCount>1&&t.push(-3),n.outputCount>2&&t.push(-3),n.outputCount>3&&t.push(3),n.compute(oE(n.inputs,e,n.outputCount,!1),{outputs:t})}}),lE,Pm,cE,wv,uE,dE,nC,iC,x3=At(()=>{fn(),Mn(),ir(),xn(),lE=(n,e)=>{if(!n||n.length<1)throw new Error("too few inputs");if(e.axes.length!==0){if(e.axes.length!==e.starts.length||e.axes.length!==e.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(e.starts.length!==e.ends.length)throw new Error("starts and ends must have the same length");n.slice(1).forEach((t,i)=>{if(n[i+1].dataType!==6&&n[i+1].dataType!==7)throw new Error(`Input ${i} must be an array of int32 or int64`)})},Pm=(n,e)=>{let t=[];if(n.length>e)if(n[e].dataType===7)n[e].getBigInt64Array().forEach(i=>t.push(Number(i)));else if(n[e].dataType===6)n[e].getInt32Array().forEach(i=>t.push(Number(i)));else throw new Error(`Input ${e} must be an array of int32 or int64`);return t},cE=(n,e)=>{if(n.length>1){let t=Pm(n,1),i=Pm(n,2),s=Pm(n,3);return s.length===0&&(s=[...Array(n[0].dims.length).keys()]),ii({starts:t,ends:i,axes:s})}else return e},wv=(n,e,t,i,s)=>{let o=n;return n<0&&(o+=t[i[e]]),s[e]<0?Math.max(0,Math.min(o,t[i[e]]-1)):Math.max(0,Math.min(o,t[i[e]]))},uE=(n,e,t)=>`fn calculateInputIndices(output_indices: ${e.type.indices}) -> ${n.type.indices} { + var input_indices: ${n.type.indices}; + var carry = 0u; + for (var i = ${t.length}; i >= 0; i--) { + let input_shape_i = ${Yt("uniforms.input_shape","i",t.length)}; + let steps_i = ${Yt("uniforms.steps","i",t.length)}; + let signs_i = ${Yt("uniforms.signs","i",t.length)}; + let starts_i = ${Yt("uniforms.starts","i",t.length)}; + var output_index = ${e.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${n.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,dE=(n,e)=>{let t=n[0].dims,i=et.size(t),s=e.axes.length>0?et.normalizeAxes(e.axes,t.length):[...Array(t.length).keys()],o=Pm(n,4);o.forEach(v=>v!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(s.length).fill(1));let l=e.starts.map((v,x)=>wv(v,x,t,s,o)),u=e.ends.map((v,x)=>wv(v,x,t,s,o));if(s.length!==l.length||s.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==t.length)for(let v=0;vMath.sign(v));o.forEach((v,x,P)=>{if(v<0){let w=(u[x]-l[x])/v,C=l[x],E=C+w*o[x];l[x]=E,u[x]=C,P[x]=-v}});let f=t.slice(0);s.forEach((v,x)=>{f[v]=Math.ceil((u[v]-l[v])/o[v])});let m={dims:f,dataType:n[0].dataType},h=Ht("output",n[0].dataType,f.length),_=at("input",n[0].dataType,n[0].dims.length),g=et.size(f),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:l.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:o.length}],b=[{type:12,data:g},{type:12,data:l},{type:6,data:d},{type:12,data:o},...en(n[0].dims,f)],T=v=>` + ${v.registerUniforms(y).declareVariables(_,h)} + ${uE(_,h,t)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${h.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${h.setByOffset("global_idx",_.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${l.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:T,getRunData:()=>({outputs:[m],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:b})}},nC=(n,e)=>{lE(n.inputs,e);let t=cE(n.inputs,e);n.compute(dE(n.inputs,t),{inputs:[0]})},iC=n=>{let e=n.starts,t=n.ends,i=n.axes;return ii({starts:e,ends:t,axes:i})}}),fE,hE,rC,sC,w3=At(()=>{fn(),Mn(),ir(),Bc(),xn(),fE=n=>{if(!n||n.length!==1)throw new Error("Softmax op requires 1 input.")},hE=(n,e)=>{let t=n.inputs[0],i=t.dims,s=et.size(i),o=i.length,l=et.normalizeAxis(e.axis,o),u=lL),f[l]=o-1,f[o-1]=l,d=n.compute(Ls(t,f),{inputs:[t],outputs:[-1]})[0]):d=t;let m=d.dims,h=m[o-1],_=s/h,g=qi(h),y=h/g,b=64;_===1&&(b=256);let T=(A,L)=>L===4?`max(max(${A}.x, ${A}.y), max(${A}.z, ${A}.w))`:L===2?`max(${A}.x, ${A}.y)`:L===3?`max(max(${A}.x, ${A}.y), ${A}.z)`:A,v=at("x",d.dataType,d.dims,g),x=Ht("result",d.dataType,d.dims,g),P=v.type.value,w=xr(d.dataType)==="f32"?`var threadMax = ${P}(-3.402823e+38f);`:`var threadMax = ${P}(-65504.0h);`,C=A=>` + var rowMaxShared : ${P}; + var rowSumShared : ${P}; + var threadShared : array<${P}, ${b}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${P} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${P}) { + let index = row * row_stride + col; + result[index] = value; + } + ${A.registerUniform("packedCols","i32").declareVariables(v,x)} + ${A.mainStart(b)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${b}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${w} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${P}(${T("threadShared[0]",g)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${P}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${P}(${Nc("threadShared[0]",g)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,E=n.compute({name:"Softmax",shaderCache:{hint:`${g};${b}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:m,dataType:d.dataType}],dispatchGroup:{x:_},programUniforms:[{type:6,data:y}]}),getShaderSource:C},{inputs:[d],outputs:[u?-1:0]})[0];u&&n.compute(Ls(E,f),{inputs:[E]})},rC=(n,e)=>{fE(n.inputs),hE(n,e)},sC=n=>ii({axis:n.axis})}),Tv,pE,mE,_E,aC,T3=At(()=>{fn(),Mn(),xn(),Tv=n=>Array.from(n.getBigInt64Array(),Number),pE=n=>{if(!n||n.length!==2)throw new Error("Tile requires 2 inputs.");if(n[0].dataType!==1&&n[0].dataType!==10&&n[0].dataType!==6&&n[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(n[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(n[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Tv(n[1]).length!==n[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},mE=(n,e)=>{let t=[];for(let i=0;i{let t=n[0].dims,i=e??Tv(n[1]),s=mE(t,i),o=et.size(s),l=n[0].dataType,u=at("input",l,t.length),d=Ht("output",l,s.length),f=m=>` + const inputShape = ${u.indices(...t)}; + ${m.registerUniform("output_size","u32").declareVariables(u,d)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${d.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; + + ${u.indicesSet("input_indices","i","input_dim_value")} + } + ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...en(n[0].dims,s)]}),getShaderSource:f}},aC=n=>{pE(n.inputs),n.compute(_E(n.inputs),{inputs:[0]})}}),gE,vE,oC,E3=At(()=>{fn(),Mn(),xn(),gE=(n,e,t,i,s)=>{let o=Ht("output_data",s,t.length,4),l=at("a_data",e[1].dataType,e[1].dims.length,4),u=at("b_data",e[2].dataType,e[2].dims.length,4),d=at("c_data",e[0].dataType,e[0].dims.length,4),f,m=(h,_,g)=>`select(${_}, ${h}, ${g})`;if(!i)f=o.setByOffset("global_idx",m(l.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let h=(_,g,y="")=>{let b=`a_data[index_a${g}][component_a${g}]`,T=`b_data[index_b${g}][component_b${g}]`,v=`bool(c_data[index_c${g}] & (0xffu << (component_c${g} * 8)))`;return` + let output_indices${g} = ${o.offsetToIndices(`global_idx * 4u + ${g}u`)}; + let offset_a${g} = ${l.broadcastedIndicesToOffset(`output_indices${g}`,o)}; + let offset_b${g} = ${u.broadcastedIndicesToOffset(`output_indices${g}`,o)}; + let offset_c${g} = ${d.broadcastedIndicesToOffset(`output_indices${g}`,o)}; + let index_a${g} = offset_a${g} / 4u; + let index_b${g} = offset_b${g} / 4u; + let index_c${g} = offset_c${g} / 4u; + let component_a${g} = offset_a${g} % 4u; + let component_b${g} = offset_b${g} % 4u; + let component_c${g} = offset_c${g} % 4u; + ${_}[${g}] = ${y}(${m(b,T,v)}); + `};s===9?f=` + var data = vec4(0); + ${h("data",0,"u32")} + ${h("data",1,"u32")} + ${h("data",2,"u32")} + ${h("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:f=` + ${h("output_data[global_idx]",0)} + ${h("output_data[global_idx]",1)} + ${h("output_data[global_idx]",2)} + ${h("output_data[global_idx]",3)} + `}return` + ${n.registerUniform("vec_size","u32").declareVariables(d,l,u,o)} + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${f} + }`},vE=n=>{let e=n[1].dims,t=n[2].dims,i=n[0].dims,s=n[1].dataType,o=!(et.areEqual(e,t)&&et.areEqual(t,i)),l=e,u=et.size(e);if(o){let f=uh.calcShape(uh.calcShape(e,t,!1),i,!1);if(!f)throw new Error("Can't perform where op on the given tensors");l=f,u=et.size(l)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:f=>gE(f,n,l,o,s),getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...en(i,e,t,l)]})}},oC=n=>{n.compute(vE(n.inputs))}}),lC,S3=At(()=>{BD(),zM(),$D(),VD(),GD(),jD(),WD(),YD(),ZD(),JD(),e3(),t3(),n3(),i3(),r3(),s3(),a3(),o3(),l3(),c3(),u3(),d3(),f3(),h3(),p3(),A2(),m3(),_3(),g3(),v3(),y3(),NM(),M3(),I2(),b3(),x3(),w3(),R2(),T3(),Bc(),UM(),E3(),lC=new Map([["Abs",[tA]],["Acos",[nA]],["Acosh",[iA]],["Add",[NA]],["ArgMax",[QS,by]],["ArgMin",[YS,by]],["Asin",[rA]],["Asinh",[sA]],["Atan",[aA]],["Atanh",[oA]],["Attention",[ZS]],["AveragePool",[$2,B2]],["BatchNormalization",[JS]],["BiasAdd",[eA]],["BiasSplitGelu",[kA]],["Cast",[cA,lA]],["Ceil",[dA]],["Clip",[uA]],["Concat",[qA,XA]],["Conv",[Ay,Sy]],["ConvTranspose",[r2,i2]],["Cos",[fA]],["Cosh",[hA]],["CumSum",[s2,a2]],["DepthToSpace",[o2,l2]],["DequantizeLinear",[X2,K2]],["Div",[zA]],["Einsum",[c2,u2]],["Elu",[pA,Bm]],["Equal",[UA]],["Erf",[mA]],["Exp",[_A]],["Expand",[d2]],["FastGelu",[f2]],["Floor",[gA]],["FusedConv",[Ay,Sy]],["Gather",[p2,h2]],["GatherElements",[M2,y2]],["GatherBlockQuantized",[g2,v2]],["GatherND",[m2,_2]],["Gelu",[vA]],["Gemm",[x2,b2]],["GlobalAveragePool",[G2,V2]],["GlobalMaxPool",[q2,H2]],["Greater",[GA]],["GreaterOrEqual",[WA]],["GridSample",[w2,T2]],["GroupQueryAttention",[O2]],["HardSigmoid",[SA,EA]],["InstanceNormalization",[L2]],["LayerNormalization",[F2]],["LeakyRelu",[yA,Bm]],["Less",[jA]],["LessOrEqual",[HA]],["Log",[LA]],["MatMul",[k2]],["MatMulNBits",[N2,z2]],["MaxPool",[j2,W2]],["Mul",[BA]],["MultiHeadAttention",[S2,E2]],["Neg",[bA]],["Not",[MA]],["Pad",[U2]],["Pow",[$A]],["QuickGelu",[FA,Bm]],["Range",[Y2]],["Reciprocal",[xA]],["ReduceMin",[WS]],["ReduceMean",[BS]],["ReduceMax",[jS]],["ReduceSum",[qS]],["ReduceProd",[HS]],["ReduceL1",[$S]],["ReduceL2",[VS]],["ReduceLogSum",[KS]],["ReduceLogSumExp",[GS]],["ReduceSumSquare",[XS]],["Relu",[wA]],["Resize",[J2,eC]],["RotaryEmbedding",[D2]],["ScatterND",[Z2,Q2]],["Sigmoid",[TA]],["Sin",[AA]],["Sinh",[CA]],["Slice",[nC,iC]],["SkipLayerNormalization",[tC]],["Split",[C2,P2]],["Sqrt",[PA]],["Softmax",[rC,sC]],["Sub",[VA]],["Tan",[RA]],["Tanh",[DA]],["ThresholdedRelu",[OA,Bm]],["Tile",[aC]],["Transpose",[CS,PS]],["Where",[oC]]])}),cC,A3=At(()=>{Ka(),Cl(),xn(),cC=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,e){this.repo.set(n,e)}run(n,e,t,i,s){Xa(n.programInfo.name);let o=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let f of e)u.push({binding:u.length,resource:{buffer:f.buffer}});for(let f of t)u.push({binding:u.length,resource:{buffer:f.buffer}});s&&u.push({binding:u.length,resource:s});let d=o.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:u,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let f={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:d,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(f)}l.setPipeline(n.computePipeline),l.setBindGroup(0,d),l.dispatchWorkgroups(...i),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),fa(n.programInfo.name)}dispose(){}build(n,e){Xa(n.name);let t=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(f=>{t.features.has(f.feature)&&i.push(`enable ${f.extension};`)});let s=AS(e,this.backend.device.limits),o=n.getShaderSource(s),l=`${i.join(` +`)} +${s.additionalImplementations} +${o}`,u=t.createShaderModule({code:l,label:n.name});qn("verbose",()=>`[WebGPU] ${n.name} shader code: ${l}`);let d=t.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:n.name});return fa(n.name),{programInfo:n,computePipeline:d,uniformVariablesInfo:s.variablesInfo}}normalizeDispatchGroupSize(n){let e=typeof n=="number"?n:n.x,t=typeof n=="number"?1:n.y||1,i=typeof n=="number"?1:n.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(e<=s&&t<=s&&i<=s)return[e,t,i];let o=e*t*i,l=Math.ceil(Math.sqrt(o));if(l>s){if(l=Math.ceil(Math.cbrt(o)),l>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}}),uC={};bh(uC,{WebGpuBackend:()=>dC});var yE,ME,bE,dC,C3=At(()=>{Ka(),fn(),Cl(),xS(),zD(),S3(),A3(),yE=(n,e)=>{if(e.length!==n.length)throw new Error(`inputDependencies length ${e.length} is not equal to inputTensors length ${n.length}.`);let t=[];for(let i=0;i{let i=n.name;return n.shaderCache?.hint&&(i+="["+n.shaderCache.hint+"]"),i+=":"+t+`:${yE(e,n.shaderCache?.inputDependencies??new Array(e.length).fill("dims"))}`,i},bE=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},dC=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,e){this.env=n;let t=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:e.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:e.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:e.limits.maxStorageBufferBindingSize,maxBufferSize:e.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:e.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:e.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:e.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:e.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},s=o=>e.features.has(o)&&t.push(o)&&!0;s("chromium-experimental-timestamp-query-inside-passes")||s("timestamp-query"),s("shader-f16"),s("subgroups"),this.device=await e.requestDevice(i),this.adapterInfo=new bE(e.info||await e.requestAdapterInfo()),this.gpuDataManager=ES(this),this.programManager=new cC(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,OM(n.logLevel,!!n.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:e,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 n=this.getCommandEncoder(),e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Xa(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{let e=new BigUint64Array(n.getMappedRange()),t=this.pendingQueries.get(n);for(let i=0;i"u"&&(this.queryTimeBase=_);let y=Number(_-this.queryTimeBase),b=Number(g-this.queryTimeBase);if(!Number.isSafeInteger(y)||!Number.isSafeInteger(b))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(T=>({dims:T.dims,dataType:bl(T.dataType)})),outputsMetadata:h.map(T=>({dims:T.dims,dataType:bl(T.dataType)})),kernelId:o,kernelType:u,kernelName:d,programName:f,startTime:y,endTime:b});else{let T="";m.forEach((x,P)=>{T+=`input[${P}]: [${x.dims}] | ${bl(x.dataType)}, `});let v="";h.forEach((x,P)=>{v+=`output[${P}]: [${x.dims}] | ${bl(x.dataType)}, `}),console.log(`[profiling] kernel "${o}|${u}|${d}|${f}" ${T}${v}execution time: ${b-y} ns`)}Xm("GPU",`${f}::${_}::${g}`)}n.unmap(),this.pendingQueries.delete(n)}),fa()}run(n,e,t,i,s,o){Xa(n.name);let l=[];for(let x=0;xP):t;if(m.length!==u.length)throw new Error(`Output size ${m.length} must be equal to ${u.length}.`);let h=[],_=[];for(let x=0;x=o)throw new Error(`Invalid output index: ${m[x]}`);if(m[x]===-3)continue;let P=m[x]===-1,w=m[x]===-2,C=P||w?s(u[x].dataType,u[x].dims):i(m[x],u[x].dataType,u[x].dims);if(h.push(C),C.data===0)continue;let E=this.gpuDataManager.get(C.data);if(!E)throw new Error(`no GPU data for output: ${C.data}`);if(P&&this.temporaryData.push(E),w){let A=this.kernelPersistentData.get(this.currentKernelId);A||(A=[],this.kernelPersistentData.set(this.currentKernelId,A)),A.push(E)}_.push(E)}if(l.length!==e.length||_.length!==h.length){if(_.length===0)return fa(n.name),h;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let g;if(f){let x=0,P=[];f.forEach(A=>{let L=typeof A.data=="number"?[A.data]:A.data;if(L.length===0)return;let I=A.type===10?2:4,O,H;A.type===10?(H=L.length>4?16:L.length>2?8:L.length*I,O=L.length>4?16:I*L.length):(H=L.length<=2?L.length*I:16,O=16),x=Math.ceil(x/H)*H,P.push(x);let Z=A.type===10?8:4;x+=L.length>4?Math.ceil(L.length/Z)*O:L.length*I});let w=16;x=Math.ceil(x/w)*w;let C=new ArrayBuffer(x);f.forEach((A,L)=>{let I=P[L],O=typeof A.data=="number"?[A.data]:A.data;if(A.type===6)new Int32Array(C,I,O.length).set(O);else if(A.type===12)new Uint32Array(C,I,O.length).set(O);else if(A.type===10)new Uint16Array(C,I,O.length).set(O);else if(A.type===1)new Float32Array(C,I,O.length).set(O);else throw new Error(`Unsupported uniform type: ${bl(A.type)}`)});let E=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(E.buffer,0,C,0,x),this.gpuDataManager.release(E.id),g={offset:0,size:x,buffer:E.buffer}}let y=this.programManager.normalizeDispatchGroupSize(d),b=y[1]===1&&y[2]===1,T=ME(n,e,b),v=this.programManager.getArtifact(T);if(v||(v=this.programManager.build(n,y),this.programManager.setArtifact(T,v),qn("info",()=>`[artifact] key: ${T}, programName: ${n.name}`)),f&&v.uniformVariablesInfo){if(f.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${f.length} in program "${v.programInfo.name}".`);for(let x=0;x`[ProgramManager] run "${n.name}" (key=${T}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let x={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:e,outputTensorViews:h};this.pendingKernels.push(x),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(x)}return this.programManager.run(v,l,_,y,g),fa(n.name),h}upload(n,e){this.gpuDataManager.upload(n,e)}memcpy(n,e){this.gpuDataManager.memcpy(n,e)}async download(n,e){await this.gpuDataManager.download(n,e)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,e,t,i){let s=lC.get(n);if(!s)throw new Error(`kernel not implemented: ${n}`);let o={kernelType:n,kernelName:i,kernelEntry:s[0],attributes:[s[1],t]};this.kernels.set(e,o)}releaseKernel(n){let e=this.kernelPersistentData.get(n);if(e){for(let t of e)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,e,t){let i=this.kernels.get(n);if(!i)throw new Error(`kernel not created: ${n}`);let s=i.kernelType,o=i.kernelName,l=i.kernelEntry,u=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${o}" is not allowed to be called recursively`);this.currentKernelId=n,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),qn("info",()=>`[WebGPU] Start to run kernel "[${s}] ${o}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),l(e,u[1]),0}catch(f){return t.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${o}" failed. ${f}`)),1}finally{d&&t.push(this.device.popErrorScope().then(f=>f?`GPU validation error for kernel "[${s}] ${o}": ${f.message}`:null));for(let f of this.temporaryData)this.gpuDataManager.release(f.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,e,t,i){let s=this.sessionExternalDataMapping.get(n);s||(s=new Map,this.sessionExternalDataMapping.set(n,s));let o=s.get(e),l=this.gpuDataManager.registerExternalBuffer(t,i,o);return s.set(e,[l,t]),l}unregisterBuffers(n){let e=this.sessionExternalDataMapping.get(n);e&&(e.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let e=this.gpuDataManager.get(n);if(!e)throw new Error(`no GPU data for buffer: ${n}`);return e.buffer}createDownloader(n,e,t){return async()=>{let i=await vy(this,n,e);return LM(i.buffer,t)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){qn("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(){qn("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){qn("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),e=this.capturedPendingKernels.get(this.currentSessionId),t=n.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),fC={};bh(fC,{init:()=>hC});var sg,xE,hC,P3=At(()=>{fn(),Cl(),Mn(),ND(),sg=class pC{constructor(e,t,i,s){this.module=e,this.dataType=t,this.data=i,this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let e=et.size(this.dims);return e===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,e)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let e=et.size(this.dims);return e===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,e)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let e=et.size(this.dims);return e===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,e)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let e=et.size(this.dims);return e===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,e)}reshape(e){if(et.size(e)!==et.size(this.dims))throw new Error("Invalid new shape");return new pC(this.module,this.dataType,this.data,e)}},xE=class{constructor(n,e,t){this.module=n,this.backend=e,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=e.adapterInfo;let i=n.PTR_SIZE,s=t/n.PTR_SIZE,o=i===4?"i32":"i64";this.opKernelContext=Number(n.getValue(i*s++,o));let l=Number(n.getValue(i*s++,o));this.outputCount=Number(n.getValue(i*s++,o)),this.customDataOffset=Number(n.getValue(i*s++,"*")),this.customDataSize=Number(n.getValue(i*s++,o));let u=[];for(let d=0;dtypeof l=="number"?this.inputs[l]:l)??this.inputs,i=e?.outputs??[],s=(l,u,d)=>new sg(this.module,u,this.output(l,d),d),o=(l,u)=>{let d=td(l,u);if(!d)throw new Error(`Unsupported data type: ${l}`);let f=d>0?this.backend.gpuDataManager.create(d).id:0;return new sg(this.module,l,f,u)};return this.backend.run(n,t,i,s,o,this.outputCount)}output(n,e){let t=this.module.stackSave();try{let i=this.module.PTR_SIZE,s=i===4?"i32":"i64",o=this.module.stackAlloc((1+e.length)*i);this.module.setValue(o,e.length,s);for(let l=0;l{let s=e.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let o=(C3(),qm(uC)).WebGpuBackend,l=new o;await l.initialize(t,i),s("webgpu",[l,u=>l.alloc(Number(u)),u=>l.free(u),(u,d,f,m=!1)=>{if(m)qn("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(u)}, dst=${Number(d)}, size=${Number(f)}`),l.memcpy(Number(u),Number(d));else{qn("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(u)}, gpuDataId=${Number(d)}, size=${Number(f)}`);let h=e.HEAPU8.subarray(Number(u>>>0),Number(u>>>0)+Number(f));l.upload(Number(d),h)}},async(u,d,f)=>{qn("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${d}, size=${f}`),await l.download(Number(u),()=>e.HEAPU8.subarray(Number(d)>>>0,Number(d+f)>>>0))},(u,d,f)=>l.createKernel(u,Number(d),f,e.UTF8ToString(e._JsepGetNodeName(Number(d)))),u=>l.releaseKernel(u),(u,d,f,m)=>{qn("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${f}, kernel=${u}, contextDataOffset=${d}`);let h=new xE(e,l,Number(d));return l.computeKernel(Number(u),h,m)},()=>l.captureBegin(),()=>l.captureEnd(),()=>l.replay()])}else{let o=new TS(t);s("webnn",[o,()=>o.reserveTensorId(),l=>o.releaseTensorId(l),async(l,u,d,f,m)=>o.ensureTensor(l,u,d,f,m),(l,u)=>{o.uploadTensor(l,u)},async(l,u)=>o.downloadTensor(l,u)])}}}),wE,WM,HM,Sc,TE,Ev,Yg,qM,XM,Sv,KM,YM,QM,mC=At(()=>{LD(),FD(),fn(),fd(),CM(),vS(),wE=(n,e)=>{Ai()._OrtInit(n,e)!==0&&hi("Can't initialize onnxruntime.")},WM=async n=>{wE(n.wasm.numThreads,Wg(n.logLevel))},HM=async(n,e)=>{Ai().asyncInit?.();{let t=(P3(),qm(fC)).init;if(e==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let i=n.webgpu.adapter;if(i){if(typeof i.limits!="object"||typeof i.features!="object"||typeof i.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let s=n.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let o=n.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(i=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:o}),!i)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",Ai(),n,i)}if(e==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Ai(),n)}}},Sc=new Map,TE=n=>{let e=Ai(),t=e.stackSave();try{let i=e.PTR_SIZE,s=e.stackAlloc(2*i);e._OrtGetInputOutputCount(n,s,s+i)!==0&&hi("Can't get session input/output count.");let o=i===4?"i32":"i64";return[Number(e.getValue(s,o)),Number(e.getValue(s+i,o))]}finally{e.stackRestore(t)}},Ev=(n,e)=>{let t=Ai(),i=t.stackSave(),s=0;try{let o=t.PTR_SIZE,l=t.stackAlloc(2*o);t._OrtGetInputOutputMetadata(n,e,l,l+o)!==0&&hi("Can't get session input/output metadata.");let u=Number(t.getValue(l,"*"));s=Number(t.getValue(l+o,"*"));let d=t.HEAP32[s/4];if(d===0)return[u,0];let f=t.HEAPU32[s/4+1],m=[];for(let h=0;h{let e=Ai(),t=e._malloc(n.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return e.HEAPU8.set(n,t),[t,n.byteLength]},qM=async(n,e)=>{let t,i,s=Ai();Array.isArray(n)?[t,i]=n:n.buffer===s.HEAPU8.buffer?[t,i]=[n.byteOffset,n.byteLength]:[t,i]=Yg(n);let o=0,l=0,u=0,d=[],f=[],m=[];try{if([l,d]=await gS(e),e?.externalData&&s.mountExternalData){let w=[];for(let C of e.externalData){let E=typeof C=="string"?C:C.path;w.push(IM(typeof C=="string"?C:C.data).then(A=>{s.mountExternalData(E,A)}))}await Promise.all(w)}for(let w of e?.executionProviders??[])if((typeof w=="string"?w:w.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,typeof w!="string"){let C=w,E=C?.context,A=C?.gpuDevice,L=C?.deviceType,I=C?.powerPreference;E?s.currentContext=E:A?s.currentContext=await s.webnnCreateMLContext(A):s.currentContext=await s.webnnCreateMLContext({deviceType:L,powerPreference:I})}else s.currentContext=await s.webnnCreateMLContext();break}o=await s._OrtCreateSession(t,i,l),s.webgpuOnCreateSession?.(o),o===0&&hi("Can't create a session."),s.jsepOnCreateSession?.(),s.currentContext&&(s.webnnRegisterMLContext(o,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[h,_]=TE(o),g=!!e?.enableGraphCapture,y=[],b=[],T=[],v=[],x=[];for(let w=0;ww==="gpu-buffer"||w==="ml-tensor")&&(u=s._OrtCreateBinding(o),u===0&&hi("Can't create IO binding."),P={handle:u,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(w=>_y(w))}),Sc.set(o,[o,f,m,P,g,!1]),[o,y,b,T,v]}catch(h){throw f.forEach(_=>s._OrtFree(_)),m.forEach(_=>s._OrtFree(_)),u!==0&&s._OrtReleaseBinding(u)!==0&&hi("Can't release IO binding."),o!==0&&s._OrtReleaseSession(o)!==0&&hi("Can't release session."),h}finally{s._free(t),l!==0&&s._OrtReleaseSessionOptions(l)!==0&&hi("Can't release session options."),d.forEach(h=>s._free(h)),s.unmountExternalData?.()}},XM=n=>{let e=Ai(),t=Sc.get(n);if(!t)throw new Error(`cannot release session. invalid session id: ${n}`);let[i,s,o,l,u]=t;l&&(u&&e._OrtClearBoundOutputs(l.handle)!==0&&hi("Can't clear bound outputs."),e._OrtReleaseBinding(l.handle)!==0&&hi("Can't release IO binding.")),e.jsepOnReleaseSession?.(n),e.webnnOnReleaseSession?.(n),e.webgpuOnReleaseSession?.(n),s.forEach(d=>e._OrtFree(d)),o.forEach(d=>e._OrtFree(d)),e._OrtReleaseSession(i)!==0&&hi("Can't release session."),Sc.delete(n)},Sv=async(n,e,t,i,s,o,l=!1)=>{if(!n){e.push(0);return}let u=Ai(),d=u.PTR_SIZE,f=n[0],m=n[1],h=n[3],_=h,g,y;if(f==="string"&&(h==="gpu-buffer"||h==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(l&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let v=n[2].gpuBuffer;y=td(nh(f),m);{let x=u.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=x(i,o,v,y)}}else if(h==="ml-tensor"){let v=n[2].mlTensor;y=td(nh(f),m);let x=u.webnnRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=x(i,v,nh(f),m)}else{let v=n[2];if(Array.isArray(v)){y=d*v.length,g=u._malloc(y),t.push(g);for(let x=0;xu.setValue(T+P*d,x,d===4?"i32":"i64"));let v=u._OrtCreateTensor(nh(f),g,y,T,m.length,_y(_));v===0&&hi(`Can't create tensor for input/output. session=${i}, index=${o}.`),e.push(v)}finally{u.stackRestore(b)}},KM=async(n,e,t,i,s,o)=>{let l=Ai(),u=l.PTR_SIZE,d=Sc.get(n);if(!d)throw new Error(`cannot run inference. invalid session id: ${n}`);let f=d[0],m=d[1],h=d[2],_=d[3],g=d[4],y=d[5],b=e.length,T=i.length,v=0,x=[],P=[],w=[],C=[],E=l.stackSave(),A=l.stackAlloc(b*u),L=l.stackAlloc(b*u),I=l.stackAlloc(T*u),O=l.stackAlloc(T*u);try{[v,x]=_S(o);for(let $=0;$me*xe,1);Q=bl(q);let ye=_?.outputPreferredLocations[i[$]];if(Q==="string"){if(ye==="gpu-buffer"||ye==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let me=[];for(let xe=0;xe0){let me=l.jsepGetBuffer;if(!me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=me(oe),ze=td(q,le);if(ze===void 0||!RM(Q))throw new Error(`Unsupported data type: ${Q}`);ne=!0,Z.push([Q,B,{gpuBuffer:xe,download:l.jsepCreateDownloader(xe,ze,Q),dispose:()=>{l._OrtReleaseTensor(J)!==0&&hi("Can't release tensor.")}},"gpu-buffer"])}else if(ye==="ml-tensor"&&le>0){let me=l.webnnEnsureTensor,xe=l.webnnIsInt64Supported;if(!me||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(td(q,le)===void 0||!DM(Q))throw new Error(`Unsupported data type: ${Q}`);if(Q==="int64"&&!xe(n))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let ze=await me(n,oe,q,B,!1);ne=!0,Z.push([Q,B,{mlTensor:ze,download:l.webnnCreateMLTensorDownloader(oe,Q),dispose:()=>{l.webnnReleaseTensorId(oe),l._OrtReleaseTensor(J)}},"ml-tensor"])}else{let me=PM(Q),xe=new me(le);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(l.HEAPU8.subarray(oe,oe+xe.byteLength)),Z.push([Q,B,xe,"cpu"])}}finally{l.stackRestore(ee),Q==="string"&&oe&&l._free(oe),ne||l._OrtReleaseTensor(J),l.webnnOnRunEnd?.(f)}}return _&&!g&&(l._OrtClearBoundOutputs(_.handle)!==0&&hi("Can't clear bound outputs."),Sc.set(n,[f,m,h,_,g,!1])),Z}finally{l.stackRestore(E),P.forEach(H=>l._OrtReleaseTensor(H)),w.forEach(H=>l._OrtReleaseTensor(H)),C.forEach(H=>l._free(H)),v!==0&&l._OrtReleaseRunOptions(v),x.forEach(H=>l._free(H))}},YM=n=>{let e=Ai(),t=Sc.get(n);if(!t)throw new Error("invalid session id");let i=t[0],s=e._OrtEndProfiling(i);s===0&&hi("Can't get an profile file name."),e._OrtFree(s)},QM=n=>{let e=[];for(let t of n){let i=t[2];!Array.isArray(i)&&"buffer"in i&&e.push(i.buffer)}return e}}),Ac,aa,Bf,Rm,Dm,ag,Av,og,Gu,ju,EE,_C,gC,vC,yC,MC,bC,xC,wC=At(()=>{Ka(),mC(),fd(),SM(),Ac=()=>!!Di.wasm.proxy&&typeof document<"u",Bf=!1,Rm=!1,Dm=!1,og=new Map,Gu=(n,e)=>{let t=og.get(n);t?t.push(e):og.set(n,[e])},ju=()=>{if(Bf||!Rm||Dm||!aa)throw new Error("worker not ready")},EE=n=>{switch(n.data.type){case"init-wasm":Bf=!1,n.data.err?(Dm=!0,Av[1](n.data.err)):(Rm=!0,Av[0]()),ag&&(URL.revokeObjectURL(ag),ag=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let e=og.get(n.data.type);n.data.err?e.shift()[1](n.data.err):e.shift()[0](n.data.out);break}}},_C=async()=>{if(!Rm){if(Bf)throw new Error("multiple calls to 'initWasm()' detected.");if(Dm)throw new Error("previous call to 'initWasm()' failed.");if(Bf=!0,Ac())return new Promise((n,e)=>{aa?.terminate(),pS().then(([t,i])=>{try{aa=i,aa.onerror=o=>e(o),aa.onmessage=EE,Av=[n,e];let s={type:"init-wasm",in:Di};!s.in.wasm.wasmPaths&&(t||my)&&(s.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href}),aa.postMessage(s),ag=t}catch(s){e(s)}},e)});try{await AM(Di.wasm),await WM(Di),Rm=!0}catch(n){throw Dm=!0,n}finally{Bf=!1}}},gC=async n=>{if(Ac())return ju(),new Promise((e,t)=>{Gu("init-ep",[e,t]);let i={type:"init-ep",in:{epName:n,env:Di}};aa.postMessage(i)});await HM(Di,n)},vC=async n=>Ac()?(ju(),new Promise((e,t)=>{Gu("copy-from",[e,t]);let i={type:"copy-from",in:{buffer:n}};aa.postMessage(i,[n.buffer])})):Yg(n),yC=async(n,e)=>{if(Ac()){if(e?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ju(),new Promise((t,i)=>{Gu("create",[t,i]);let s={type:"create",in:{model:n,options:{...e}}},o=[];n instanceof Uint8Array&&o.push(n.buffer),aa.postMessage(s,o)})}else return qM(n,e)},MC=async n=>{if(Ac())return ju(),new Promise((e,t)=>{Gu("release",[e,t]);let i={type:"release",in:n};aa.postMessage(i)});XM(n)},bC=async(n,e,t,i,s,o)=>{if(Ac()){if(t.some(l=>l[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(l=>l))throw new Error("pre-allocated output tensor is not supported for proxy.");return ju(),new Promise((l,u)=>{Gu("run",[l,u]);let d=t,f={type:"run",in:{sessionId:n,inputIndices:e,inputs:d,outputIndices:i,options:o}};aa.postMessage(f,QM(d))})}else return KM(n,e,t,i,s,o)},xC=async n=>{if(Ac())return ju(),new Promise((e,t)=>{Gu("end-profiling",[e,t]);let i={type:"end-profiling",in:n};aa.postMessage(i)});YM(n)}}),Cv,SE,TC,R3=At(()=>{Ka(),wC(),fn(),EM(),vS(),Cv=(n,e)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[n.type,n.dims,{mlTensor:n.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${n.location} for ${e()}`)}},SE=n=>{switch(n[3]){case"cpu":return new Ga(n[0],n[2],n[1]);case"gpu-buffer":{let e=n[0];if(!RM(e))throw new Error(`not supported data type: ${e} for deserializing GPU tensor`);let{gpuBuffer:t,download:i,dispose:s}=n[2];return Ga.fromGpuBuffer(t,{dataType:e,dims:n[1],download:i,dispose:s})}case"ml-tensor":{let e=n[0];if(!DM(e))throw new Error(`not supported data type: ${e} for deserializing MLTensor tensor`);let{mlTensor:t,download:i,dispose:s}=n[2];return Ga.fromMLTensor(t,{dataType:e,dims:n[1],download:i,dispose:s})}default:throw new Error(`invalid data location: ${n[3]}`)}},TC=class{async fetchModelAndCopyToWasmMemory(n){return vC(await IM(n))}async loadModel(n,e){Xa();let t;typeof n=="string"?t=await this.fetchModelAndCopyToWasmMemory(n):t=n,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await yC(t,e),fa()}async dispose(){return MC(this.sessionId)}async run(n,e,t){Xa();let i=[],s=[];Object.entries(n).forEach(h=>{let _=h[0],g=h[1],y=this.inputNames.indexOf(_);if(y===-1)throw new Error(`invalid input '${_}'`);i.push(g),s.push(y)});let o=[],l=[];Object.entries(e).forEach(h=>{let _=h[0],g=h[1],y=this.outputNames.indexOf(_);if(y===-1)throw new Error(`invalid output '${_}'`);o.push(g),l.push(y)});let u=i.map((h,_)=>Cv(h,()=>`input "${this.inputNames[s[_]]}"`)),d=o.map((h,_)=>h?Cv(h,()=>`output "${this.outputNames[l[_]]}"`):null),f=await bC(this.sessionId,s,u,l,d,t),m={};for(let h=0;hRy,initializeFlags:()=>Py,wasmBackend:()=>SC});var Py,Ry,SC,D3=At(()=>{Ka(),wC(),R3(),Py=()=>{(typeof Di.wasm.initTimeout!="number"||Di.wasm.initTimeout<0)&&(Di.wasm.initTimeout=0);let n=Di.wasm.simd;if(typeof n!="boolean"&&n!==void 0&&n!=="fixed"&&n!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${n}". Reset it to \`false\` and ignore SIMD feature checking.`),Di.wasm.simd=!1),typeof Di.wasm.proxy!="boolean"&&(Di.wasm.proxy=!1),typeof Di.wasm.trace!="boolean"&&(Di.wasm.trace=!1),typeof Di.wasm.numThreads!="number"||!Number.isInteger(Di.wasm.numThreads)||Di.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Di.wasm.numThreads=1;else{let e=typeof navigator>"u"?gD("node:os").cpus().length:navigator.hardwareConcurrency;Di.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Ry=class{async init(n){Py(),await _C(),await gC(n)}async createInferenceSessionHandler(n,e){let t=new TC;return await t.loadModel(n,e),t}},SC=new Ry});Ka();Ka();Ka();var I3="1.22.0-dev.20250409-89f8206ba4",O3=lS;{let n=(D3(),qm(EC)).wasmBackend;rd("webgpu",n,5),rd("webnn",n,5),rd("cpu",n,10),rd("wasm",n,10)}Object.defineProperty(Di.versions,"web",{value:I3,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */const L3=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return TM},get TRACE(){return Xm},get TRACE_FUNC_BEGIN(){return Xa},get TRACE_FUNC_END(){return fa},get Tensor(){return Ga},default:O3,get env(){return Di},get registerBackend(){return rd}},Symbol.toStringTag,{value:"Module"}));var Pv={},F3={"onnxruntime-common":n=>{n.exports=hD},"onnxruntime-web":n=>{n.exports=L3},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(n,e,t)=>{t.r(e),t.d(e,{Environment:()=>Ne,Interpreter:()=>We,Template:()=>Ke,parse:()=>q,tokenize:()=>h});var i=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),s=Object.freeze({set:i.Set,for:i.For,in:i.In,is:i.Is,if:i.If,else:i.Else,endset:i.EndSet,endif:i.EndIf,elif:i.ElseIf,endfor:i.EndFor,and:i.And,or:i.Or,not:i.Not,"not in":i.NotIn,macro:i.Macro,endmacro:i.EndMacro,true:i.BooleanLiteral,false:i.BooleanLiteral,none:i.NullLiteral,True:i.BooleanLiteral,False:i.BooleanLiteral,None:i.NullLiteral}),o=class{constructor(F,U){this.value=F,this.type=U}};function l(F){return/\w/.test(F)}function u(F){return/[0-9]/.test(F)}var d=[["{%",i.OpenStatement],["%}",i.CloseStatement],["{{",i.OpenExpression],["}}",i.CloseExpression],["(",i.OpenParen],[")",i.CloseParen],["{",i.OpenCurlyBracket],["}",i.CloseCurlyBracket],["[",i.OpenSquareBracket],["]",i.CloseSquareBracket],[",",i.Comma],[".",i.Dot],[":",i.Colon],["|",i.Pipe],["<=",i.ComparisonBinaryOperator],[">=",i.ComparisonBinaryOperator],["==",i.ComparisonBinaryOperator],["!=",i.ComparisonBinaryOperator],["<",i.ComparisonBinaryOperator],[">",i.ComparisonBinaryOperator],["+",i.AdditiveBinaryOperator],["-",i.AdditiveBinaryOperator],["*",i.MultiplicativeBinaryOperator],["/",i.MultiplicativeBinaryOperator],["%",i.MultiplicativeBinaryOperator],["=",i.Equals]],f=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function m(F,U={}){return F.endsWith(` +`)&&(F=F.slice(0,-1)),F=F.replace(/{#.*?#}/gs,"{##}"),U.lstrip_blocks&&(F=F.replace(/^[ \t]*({[#%])/gm,"$1")),U.trim_blocks&&(F=F.replace(/([#%]})\n/g,"$1")),F.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function h(F,U={}){const j=[],se=m(F,U);let _e=0;const ge=Ce=>{let Ie="";for(;Ce(se[_e]);){if(se[_e]==="\\"){if(++_e,_e>=se.length)throw new SyntaxError("Unexpected end of input");const Ee=se[_e++],je=f.get(Ee);if(je===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ee}`);Ie+=je;continue}if(Ie+=se[_e++],_e>=se.length)throw new SyntaxError("Unexpected end of input")}return Ie};e:for(;_e0){j.push(new o(Ee,i.Text));continue}}ge(Ee=>/\s/.test(Ee));const Ie=se[_e];if(Ie==="-"||Ie==="+"){const Ee=j.at(-1)?.type;if(Ee===i.Text||Ee===void 0)throw new SyntaxError(`Unexpected character: ${Ie}`);switch(Ee){case i.Identifier:case i.NumericLiteral:case i.BooleanLiteral:case i.NullLiteral:case i.StringLiteral:case i.CloseParen:case i.CloseSquareBracket:break;default:{++_e;const je=ge(u);j.push(new o(`${Ie}${je}`,je.length>0?i.NumericLiteral:i.UnaryOperator));continue}}}for(const[Ee,je]of d)if(se.slice(_e,_e+Ee.length)===Ee){j.push(new o(Ee,je)),_e+=Ee.length;continue e}if(Ie==="'"||Ie==='"'){++_e;const Ee=ge(je=>je!==Ie);j.push(new o(Ee,i.StringLiteral)),++_e;continue}if(u(Ie)){const Ee=ge(u);j.push(new o(Ee,i.NumericLiteral));continue}if(l(Ie)){const Ee=ge(l),je=Object.hasOwn(s,Ee)?s[Ee]:i.Identifier;je===i.In&&j.at(-1)?.type===i.Not?(j.pop(),j.push(new o("not in",i.NotIn))):j.push(new o(Ee,je));continue}throw new SyntaxError(`Unexpected character: ${Ie}`)}return j}var _=class{type="Statement"},g=class extends _{constructor(F){super(),this.body=F}type="Program"},y=class extends _{constructor(F,U,j){super(),this.test=F,this.body=U,this.alternate=j}type="If"},b=class extends _{constructor(F,U,j,se){super(),this.loopvar=F,this.iterable=U,this.body=j,this.defaultBlock=se}type="For"},T=class extends _{constructor(F,U,j){super(),this.assignee=F,this.value=U,this.body=j}type="Set"},v=class extends _{constructor(F,U,j){super(),this.name=F,this.args=U,this.body=j}type="Macro"},x=class extends _{type="Expression"},P=class extends x{constructor(F,U,j){super(),this.object=F,this.property=U,this.computed=j}type="MemberExpression"},w=class extends x{constructor(F,U){super(),this.callee=F,this.args=U}type="CallExpression"},C=class extends x{constructor(F){super(),this.value=F}type="Identifier"},E=class extends x{constructor(F){super(),this.value=F}type="Literal"},A=class extends E{type="NumericLiteral"},L=class extends E{type="StringLiteral"},I=class extends E{type="BooleanLiteral"},O=class extends E{type="NullLiteral"},H=class extends E{type="ArrayLiteral"},Z=class extends E{type="TupleLiteral"},$=class extends E{type="ObjectLiteral"},J=class extends x{constructor(F,U,j){super(),this.operator=F,this.left=U,this.right=j}type="BinaryExpression"},ee=class extends x{constructor(F,U){super(),this.operand=F,this.filter=U}type="FilterExpression"},X=class extends x{constructor(F,U){super(),this.iterable=F,this.test=U}type="SelectExpression"},ne=class extends x{constructor(F,U,j){super(),this.operand=F,this.negate=U,this.test=j}type="TestExpression"},Q=class extends x{constructor(F,U){super(),this.operator=F,this.argument=U}type="UnaryExpression"},oe=class extends x{constructor(F=void 0,U=void 0,j=void 0){super(),this.start=F,this.stop=U,this.step=j}type="SliceExpression"},W=class extends x{constructor(F,U){super(),this.key=F,this.value=U}type="KeywordArgumentExpression"};function q(F){const U=new g([]);let j=0;function se(ut,It){const Bt=F[j++];if(!Bt||Bt.type!==ut)throw new Error(`Parser Error: ${It}. ${Bt.type} !== ${ut}.`);return Bt}function _e(){switch(F[j].type){case i.Text:return Ie();case i.OpenStatement:return Ee();case i.OpenExpression:return je();default:throw new SyntaxError(`Unexpected token type: ${F[j].type}`)}}function ge(...ut){return j+ut.length<=F.length&&ut.some((It,Bt)=>It!==F[j+Bt].type)}function Ce(...ut){return j+ut.length<=F.length&&ut.every((It,Bt)=>It===F[j+Bt].type)}function Ie(){return new L(se(i.Text,"Expected text token").value)}function Ee(){se(i.OpenStatement,"Expected opening statement token");let ut;switch(F[j].type){case i.Set:++j,ut=Qe(),se(i.CloseStatement,"Expected closing statement token");break;case i.If:++j,ut=ot(),se(i.OpenStatement,"Expected {% token"),se(i.EndIf,"Expected endif token"),se(i.CloseStatement,"Expected %} token");break;case i.Macro:++j,ut=bt(),se(i.OpenStatement,"Expected {% token"),se(i.EndMacro,"Expected endmacro token"),se(i.CloseStatement,"Expected %} token");break;case i.For:++j,ut=nt(),se(i.OpenStatement,"Expected {% token"),se(i.EndFor,"Expected endfor token"),se(i.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${F[j].type}`)}return ut}function je(){se(i.OpenExpression,"Expected opening expression token");const ut=ft();return se(i.CloseExpression,"Expected closing expression token"),ut}function Qe(){const ut=ft();if(Ce(i.Equals)){++j;const It=ft();return new T(ut,It,[])}else{const It=[];for(se(i.CloseStatement,"Expected %} token");!(F[j]?.type===i.OpenStatement&&F[j+1]?.type===i.EndSet);){const Bt=_e();It.push(Bt)}return se(i.OpenStatement,"Expected {% token"),se(i.EndSet,"Expected endset token"),new T(ut,null,It)}}function ot(){const ut=ft();se(i.CloseStatement,"Expected closing statement token");const It=[],Bt=[];for(;!(F[j]?.type===i.OpenStatement&&(F[j+1]?.type===i.ElseIf||F[j+1]?.type===i.Else||F[j+1]?.type===i.EndIf));)It.push(_e());if(F[j]?.type===i.OpenStatement&&F[j+1]?.type!==i.EndIf)if(++j,Ce(i.ElseIf))se(i.ElseIf,"Expected elseif token"),Bt.push(ot());else for(se(i.Else,"Expected else token"),se(i.CloseStatement,"Expected closing statement token");!(F[j]?.type===i.OpenStatement&&F[j+1]?.type===i.EndIf);)Bt.push(_e());return new y(ut,It,Bt)}function bt(){const ut=On();if(ut.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const It=gt();se(i.CloseStatement,"Expected closing statement token");const Bt=[];for(;ge(i.OpenStatement,i.EndMacro);)Bt.push(_e());return new v(ut,It,Bt)}function _t(ut=!1){const It=ut?On:ft,Bt=[It()],Vi=Ce(i.Comma);for(;Vi&&(++j,Bt.push(It()),!!Ce(i.Comma)););return Vi?new Z(Bt):Bt[0]}function nt(){const ut=_t(!0);if(!(ut instanceof C||ut instanceof Z))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ut.type} instead`);se(i.In,"Expected `in` keyword following loop variable");const It=ft();se(i.CloseStatement,"Expected closing statement token");const Bt=[];for(;ge(i.OpenStatement,i.EndFor)&&ge(i.OpenStatement,i.Else);)Bt.push(_e());const Vi=[];if(Ce(i.OpenStatement,i.Else))for(++j,++j,se(i.CloseStatement,"Expected closing statement token");ge(i.OpenStatement,i.EndFor);)Vi.push(_e());return new b(ut,It,Bt,Vi)}function ft(){return vt()}function vt(){const ut=mn();if(Ce(i.If)){++j;const It=mn();if(Ce(i.Else)){++j;const Bt=mn();return new y(It,[ut],[Bt])}else return new X(ut,It)}return ut}function mn(){let ut=Se();for(;Ce(i.Or);){const It=F[j];++j;const Bt=Se();ut=new J(It,ut,Bt)}return ut}function Se(){let ut=St();for(;Ce(i.And);){const It=F[j];++j;const Bt=St();ut=new J(It,ut,Bt)}return ut}function St(){let ut;for(;Ce(i.Not);){const It=F[j];++j;const Bt=St();ut=new Q(It,Bt)}return ut??Ze()}function Ze(){let ut=it();for(;Ce(i.ComparisonBinaryOperator)||Ce(i.In)||Ce(i.NotIn);){const It=F[j];++j;const Bt=it();ut=new J(It,ut,Bt)}return ut}function it(){let ut=Pn();for(;Ce(i.AdditiveBinaryOperator);){const It=F[j];++j;const Bt=Pn();ut=new J(It,ut,Bt)}return ut}function yt(){const ut=rn(On());return Ce(i.OpenParen)?tt(ut):ut}function tt(ut){let It=new w(ut,gt());return It=rn(It),Ce(i.OpenParen)&&(It=tt(It)),It}function gt(){se(i.OpenParen,"Expected opening parenthesis for arguments list");const ut=Pt();return se(i.CloseParen,"Expected closing parenthesis for arguments list"),ut}function Pt(){const ut=[];for(;!Ce(i.CloseParen);){let It=ft();if(Ce(i.Equals)){if(++j,!(It instanceof C))throw new SyntaxError("Expected identifier for keyword argument");const Bt=ft();It=new W(It,Bt)}ut.push(It),Ce(i.Comma)&&++j}return ut}function tn(){const ut=[];let It=!1;for(;!Ce(i.CloseSquareBracket);)Ce(i.Colon)?(ut.push(void 0),++j,It=!0):(ut.push(ft()),Ce(i.Colon)&&(++j,It=!0));if(ut.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(It){if(ut.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new oe(...ut)}return ut[0]}function rn(ut){for(;Ce(i.Dot)||Ce(i.OpenSquareBracket);){const It=F[j];++j;let Bt;const Vi=It.type!==i.Dot;if(Vi)Bt=tn(),se(i.CloseSquareBracket,"Expected closing square bracket");else if(Bt=On(),Bt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ut=new P(ut,Bt,Vi)}return ut}function Pn(){let ut=ln();for(;Ce(i.MultiplicativeBinaryOperator);){const It=F[j];++j;const Bt=ln();ut=new J(It,ut,Bt)}return ut}function ln(){let ut=vi();for(;Ce(i.Is);){++j;const It=Ce(i.Not);It&&++j;let Bt=On();if(Bt instanceof I?Bt=new C(Bt.value.toString()):Bt instanceof O&&(Bt=new C("none")),!(Bt instanceof C))throw new SyntaxError("Expected identifier for the test");ut=new ne(ut,It,Bt)}return ut}function vi(){let ut=yt();for(;Ce(i.Pipe);){++j;let It=On();if(!(It instanceof C))throw new SyntaxError("Expected identifier for the filter");Ce(i.OpenParen)&&(It=tt(It)),ut=new ee(ut,It)}return ut}function On(){const ut=F[j];switch(ut.type){case i.NumericLiteral:return++j,new A(Number(ut.value));case i.StringLiteral:return++j,new L(ut.value);case i.BooleanLiteral:return++j,new I(ut.value.toLowerCase()==="true");case i.NullLiteral:return++j,new O(null);case i.Identifier:return++j,new C(ut.value);case i.OpenParen:{++j;const It=_t();if(F[j].type!==i.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${F[j].type} instead`);return++j,It}case i.OpenSquareBracket:{++j;const It=[];for(;!Ce(i.CloseSquareBracket);)It.push(ft()),Ce(i.Comma)&&++j;return++j,new H(It)}case i.OpenCurlyBracket:{++j;const It=new Map;for(;!Ce(i.CloseCurlyBracket);){const Bt=ft();se(i.Colon,"Expected colon between key and value in object literal");const Vi=ft();It.set(Bt,Vi),Ce(i.Comma)&&++j}return++j,new $(It)}default:throw new SyntaxError(`Unexpected token: ${ut.type}`)}}for(;j=0?(U=(U??=0)<0?Math.max(F.length+U,0):Math.min(U,F.length),j=(j??=F.length)<0?Math.max(F.length+j,0):Math.min(j,F.length)):(U=(U??=F.length-1)<0?Math.max(F.length+U,-1):Math.min(U,F.length-1),j=(j??=-1)<-1?Math.max(F.length+j,-1):Math.min(j,F.length-1));const ge=[];for(let Ce=U;_e*Ce<_e*j;Ce+=se)ge.push(F[Ce]);return ge}function B(F){return F.replace(/\b\w/g,U=>U.toUpperCase())}var le=class{type="RuntimeValue";value;builtins=new Map;constructor(F=void 0){this.value=F}__bool__(){return new xe(!!this.value)}},ye=class extends le{type="NumericValue"},me=class extends le{type="StringValue";builtins=new Map([["upper",new we(()=>new me(this.value.toUpperCase()))],["lower",new we(()=>new me(this.value.toLowerCase()))],["strip",new we(()=>new me(this.value.trim()))],["title",new we(()=>new me(B(this.value)))],["length",new ye(this.value.length)],["rstrip",new we(()=>new me(this.value.trimEnd()))],["lstrip",new we(()=>new me(this.value.trimStart()))],["split",new we(F=>{const U=F[0]??new re;if(!(U instanceof me||U instanceof re))throw new Error("sep argument must be a string or null");const j=F[1]??new ye(-1);if(!(j instanceof ye))throw new Error("maxsplit argument must be a number");let se=[];if(U instanceof re){const _e=this.value.trimStart();for(const{0:ge,index:Ce}of _e.matchAll(/\S+/g)){if(j.value!==-1&&se.length>=j.value&&Ce!==void 0){se.push(ge+_e.slice(Ce+ge.length));break}se.push(ge)}}else{if(U.value==="")throw new Error("empty separator");se=this.value.split(U.value),j.value!==-1&&se.length>j.value&&se.push(se.splice(j.value).join(U.value))}return new ce(se.map(_e=>new me(_e)))})]])},xe=class extends le{type="BooleanValue"},ze=class extends le{type="ObjectValue";__bool__(){return new xe(this.value.size>0)}builtins=new Map([["get",new we(([F,U])=>{if(!(F instanceof me))throw new Error(`Object key must be a string: got ${F.type}`);return this.value.get(F.value)??U??new re})],["items",new we(()=>new ce(Array.from(this.value.entries()).map(([F,U])=>new ce([new me(F),U]))))]])},Me=class extends ze{type="KeywordArgumentsValue"},ce=class extends le{type="ArrayValue";builtins=new Map([["length",new ye(this.value.length)]]);__bool__(){return new xe(this.value.length>0)}},ae=class extends ce{type="TupleValue"},we=class extends le{type="FunctionValue"},re=class extends le{type="NullValue"},He=class extends le{type="UndefinedValue"},Ne=class{constructor(F){this.parent=F}variables=new Map([["namespace",new we(F=>{if(F.length===0)return new ze(new Map);if(F.length!==1||!(F[0]instanceof ze))throw new Error("`namespace` expects either zero arguments or a single object argument");return F[0]})]]);tests=new Map([["boolean",F=>F.type==="BooleanValue"],["callable",F=>F instanceof we],["odd",F=>{if(F.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${F.type}`);return F.value%2!==0}],["even",F=>{if(F.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${F.type}`);return F.value%2===0}],["false",F=>F.type==="BooleanValue"&&!F.value],["true",F=>F.type==="BooleanValue"&&F.value],["none",F=>F.type==="NullValue"],["string",F=>F.type==="StringValue"],["number",F=>F.type==="NumericValue"],["integer",F=>F.type==="NumericValue"&&Number.isInteger(F.value)],["iterable",F=>F.type==="ArrayValue"||F.type==="StringValue"],["mapping",F=>F.type==="ObjectValue"],["lower",F=>{const U=F.value;return F.type==="StringValue"&&U===U.toLowerCase()}],["upper",F=>{const U=F.value;return F.type==="StringValue"&&U===U.toUpperCase()}],["none",F=>F.type==="NullValue"],["defined",F=>F.type!=="UndefinedValue"],["undefined",F=>F.type==="UndefinedValue"],["equalto",(F,U)=>F.value===U.value],["eq",(F,U)=>F.value===U.value]]);set(F,U){return this.declareVariable(F,ke(U))}declareVariable(F,U){if(this.variables.has(F))throw new SyntaxError(`Variable already declared: ${F}`);return this.variables.set(F,U),U}setVariable(F,U){return this.variables.set(F,U),U}resolve(F){if(this.variables.has(F))return this;if(this.parent)return this.parent.resolve(F);throw new Error(`Unknown variable: ${F}`)}lookupVariable(F){try{return this.resolve(F).variables.get(F)??new He}catch{return new He}}},We=class{global;constructor(F){this.global=F??new Ne}run(F){return this.evaluate(F,this.global)}evaluateBinaryExpression(F,U){const j=this.evaluate(F.left,U);switch(F.operator.value){case"and":return j.__bool__().value?this.evaluate(F.right,U):j;case"or":return j.__bool__().value?j:this.evaluate(F.right,U)}const se=this.evaluate(F.right,U);switch(F.operator.value){case"==":return new xe(j.value==se.value);case"!=":return new xe(j.value!=se.value)}if(j instanceof He||se instanceof He)throw new Error("Cannot perform operation on undefined values");if(j instanceof re||se instanceof re)throw new Error("Cannot perform operation on null values");if(j instanceof ye&&se instanceof ye)switch(F.operator.value){case"+":return new ye(j.value+se.value);case"-":return new ye(j.value-se.value);case"*":return new ye(j.value*se.value);case"/":return new ye(j.value/se.value);case"%":return new ye(j.value%se.value);case"<":return new xe(j.value":return new xe(j.value>se.value);case">=":return new xe(j.value>=se.value);case"<=":return new xe(j.value<=se.value)}else if(j instanceof ce&&se instanceof ce)switch(F.operator.value){case"+":return new ce(j.value.concat(se.value))}else if(se instanceof ce){const _e=se.value.find(ge=>ge.value===j.value)!==void 0;switch(F.operator.value){case"in":return new xe(_e);case"not in":return new xe(!_e)}}if(j instanceof me||se instanceof me)switch(F.operator.value){case"+":return new me(j.value.toString()+se.value.toString())}if(j instanceof me&&se instanceof me)switch(F.operator.value){case"in":return new xe(se.value.includes(j.value));case"not in":return new xe(!se.value.includes(j.value))}if(j instanceof me&&se instanceof ze)switch(F.operator.value){case"in":return new xe(se.value.has(j.value));case"not in":return new xe(!se.value.has(j.value))}throw new SyntaxError(`Unknown operator "${F.operator.value}" between ${j.type} and ${se.type}`)}evaluateArguments(F,U){const j=[],se=new Map;for(const _e of F)if(_e.type==="KeywordArgumentExpression"){const ge=_e;se.set(ge.key.value,this.evaluate(ge.value,U))}else{if(se.size>0)throw new Error("Positional arguments must come before keyword arguments");j.push(this.evaluate(_e,U))}return[j,se]}evaluateFilterExpression(F,U){const j=this.evaluate(F.operand,U);if(F.filter.type==="Identifier"){const se=F.filter;if(se.value==="tojson")return new me(st(j));if(j instanceof ce)switch(se.value){case"list":return j;case"first":return j.value[0];case"last":return j.value[j.value.length-1];case"length":return new ye(j.value.length);case"reverse":return new ce(j.value.reverse());case"sort":return new ce(j.value.sort((_e,ge)=>{if(_e.type!==ge.type)throw new Error(`Cannot compare different types: ${_e.type} and ${ge.type}`);switch(_e.type){case"NumericValue":return _e.value-ge.value;case"StringValue":return _e.value.localeCompare(ge.value);default:throw new Error(`Cannot compare type: ${_e.type}`)}}));case"join":return new me(j.value.map(_e=>_e.value).join(""));case"string":return new me(st(j));default:throw new Error(`Unknown ArrayValue filter: ${se.value}`)}else if(j instanceof me)switch(se.value){case"length":return new ye(j.value.length);case"upper":return new me(j.value.toUpperCase());case"lower":return new me(j.value.toLowerCase());case"title":return new me(B(j.value));case"capitalize":return new me(j.value.charAt(0).toUpperCase()+j.value.slice(1));case"trim":return new me(j.value.trim());case"indent":return new me(j.value.split(` +`).map((_e,ge)=>ge===0||_e.length===0?_e:" "+_e).join(` +`));case"join":case"string":return j;default:throw new Error(`Unknown StringValue filter: ${se.value}`)}else if(j instanceof ye)switch(se.value){case"abs":return new ye(Math.abs(j.value));default:throw new Error(`Unknown NumericValue filter: ${se.value}`)}else if(j instanceof ze)switch(se.value){case"items":return new ce(Array.from(j.value.entries()).map(([_e,ge])=>new ce([new me(_e),ge])));case"length":return new ye(j.value.size);default:throw new Error(`Unknown ObjectValue filter: ${se.value}`)}throw new Error(`Cannot apply filter "${se.value}" to type: ${j.type}`)}else if(F.filter.type==="CallExpression"){const se=F.filter;if(se.callee.type!=="Identifier")throw new Error(`Unknown filter: ${se.callee.type}`);const _e=se.callee.value;if(_e==="tojson"){const[,ge]=this.evaluateArguments(se.args,U),Ce=ge.get("indent")??new re;if(!(Ce instanceof ye||Ce instanceof re))throw new Error("If set, indent must be a number");return new me(st(j,Ce.value))}else if(_e==="join"){let ge;if(j instanceof me)ge=Array.from(j.value);else if(j instanceof ce)ge=j.value.map(je=>je.value);else throw new Error(`Cannot apply filter "${_e}" to type: ${j.type}`);const[Ce,Ie]=this.evaluateArguments(se.args,U),Ee=Ce.at(0)??Ie.get("separator")??new me("");if(!(Ee instanceof me))throw new Error("separator must be a string");return new me(ge.join(Ee.value))}if(j instanceof ce){switch(_e){case"selectattr":case"rejectattr":{const ge=_e==="selectattr";if(j.value.some(ot=>!(ot instanceof ze)))throw new Error(`\`${_e}\` can only be applied to array of objects`);if(se.args.some(ot=>ot.type!=="StringLiteral"))throw new Error(`arguments of \`${_e}\` must be strings`);const[Ce,Ie,Ee]=se.args.map(ot=>this.evaluate(ot,U));let je;if(Ie){const ot=U.tests.get(Ie.value);if(!ot)throw new Error(`Unknown test: ${Ie.value}`);je=ot}else je=(...ot)=>ot[0].__bool__().value;const Qe=j.value.filter(ot=>{const bt=ot.value.get(Ce.value),_t=bt?je(bt,Ee):!1;return ge?_t:!_t});return new ce(Qe)}case"map":{const[,ge]=this.evaluateArguments(se.args,U);if(ge.has("attribute")){const Ce=ge.get("attribute");if(!(Ce instanceof me))throw new Error("attribute must be a string");const Ie=ge.get("default"),Ee=j.value.map(je=>{if(!(je instanceof ze))throw new Error("items in map must be an object");return je.value.get(Ce.value)??Ie??new He});return new ce(Ee)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${_e}`)}else if(j instanceof me){switch(_e){case"indent":{const[ge,Ce]=this.evaluateArguments(se.args,U),Ie=ge.at(0)??Ce.get("width")??new ye(4);if(!(Ie instanceof ye))throw new Error("width must be a number");const Ee=ge.at(1)??Ce.get("first")??new xe(!1),je=ge.at(2)??Ce.get("blank")??new xe(!1),Qe=j.value.split(` +`),ot=" ".repeat(Ie.value),bt=Qe.map((_t,nt)=>!Ee.value&&nt===0||!je.value&&_t.length===0?_t:ot+_t);return new me(bt.join(` +`))}}throw new Error(`Unknown StringValue filter: ${_e}`)}else throw new Error(`Cannot apply filter "${_e}" to type: ${j.type}`)}throw new Error(`Unknown filter: ${F.filter.type}`)}evaluateTestExpression(F,U){const j=this.evaluate(F.operand,U),se=U.tests.get(F.test.value);if(!se)throw new Error(`Unknown test: ${F.test.value}`);const _e=se(j);return new xe(F.negate?!_e:_e)}evaluateUnaryExpression(F,U){const j=this.evaluate(F.argument,U);switch(F.operator.value){case"not":return new xe(!j.value);default:throw new SyntaxError(`Unknown operator: ${F.operator.value}`)}}evalProgram(F,U){return this.evaluateBlock(F.body,U)}evaluateBlock(F,U){let j="";for(const se of F){const _e=this.evaluate(se,U);_e.type!=="NullValue"&&_e.type!=="UndefinedValue"&&(j+=_e.value)}return new me(j)}evaluateIdentifier(F,U){return U.lookupVariable(F.value)}evaluateCallExpression(F,U){const[j,se]=this.evaluateArguments(F.args,U);se.size>0&&j.push(new Me(se));const _e=this.evaluate(F.callee,U);if(_e.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${_e.type}`);return _e.value(j,U)}evaluateSliceExpression(F,U,j){if(!(F instanceof ce||F instanceof me))throw new Error("Slice object must be an array or string");const se=this.evaluate(U.start,j),_e=this.evaluate(U.stop,j),ge=this.evaluate(U.step,j);if(!(se instanceof ye||se instanceof He))throw new Error("Slice start must be numeric or undefined");if(!(_e instanceof ye||_e instanceof He))throw new Error("Slice stop must be numeric or undefined");if(!(ge instanceof ye||ge instanceof He))throw new Error("Slice step must be numeric or undefined");return F instanceof ce?new ce(te(F.value,se.value,_e.value,ge.value)):new me(te(Array.from(F.value),se.value,_e.value,ge.value).join(""))}evaluateMemberExpression(F,U){const j=this.evaluate(F.object,U);let se;if(F.computed){if(F.property.type==="SliceExpression")return this.evaluateSliceExpression(j,F.property,U);se=this.evaluate(F.property,U)}else se=new me(F.property.value);let _e;if(j instanceof ze){if(!(se instanceof me))throw new Error(`Cannot access property with non-string: got ${se.type}`);_e=j.value.get(se.value)??j.builtins.get(se.value)}else if(j instanceof ce||j instanceof me)if(se instanceof ye)_e=j.value.at(se.value),j instanceof me&&(_e=new me(j.value.at(se.value)));else if(se instanceof me)_e=j.builtins.get(se.value);else throw new Error(`Cannot access property with non-string/non-number: got ${se.type}`);else{if(!(se instanceof me))throw new Error(`Cannot access property with non-string: got ${se.type}`);_e=j.builtins.get(se.value)}return _e instanceof le?_e:new He}evaluateSet(F,U){const j=F.value?this.evaluate(F.value,U):this.evaluateBlock(F.body,U);if(F.assignee.type==="Identifier"){const se=F.assignee.value;U.setVariable(se,j)}else if(F.assignee.type==="MemberExpression"){const se=F.assignee,_e=this.evaluate(se.object,U);if(!(_e instanceof ze))throw new Error("Cannot assign to member of non-object");if(se.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");_e.value.set(se.property.value,j)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(F.assignee)}`);return new re}evaluateIf(F,U){const j=this.evaluate(F.test,U);return this.evaluateBlock(j.__bool__().value?F.body:F.alternate,U)}evaluateFor(F,U){const j=new Ne(U);let se,_e;if(F.iterable.type==="SelectExpression"){const je=F.iterable;_e=this.evaluate(je.iterable,j),se=je.test}else _e=this.evaluate(F.iterable,j);if(!(_e instanceof ce))throw new Error(`Expected iterable type in for loop: got ${_e.type}`);const ge=[],Ce=[];for(let je=0;je<_e.value.length;++je){const Qe=new Ne(j),ot=_e.value[je];let bt;if(F.loopvar.type==="Identifier")bt=_t=>_t.setVariable(F.loopvar.value,ot);else if(F.loopvar.type==="TupleLiteral"){const _t=F.loopvar;if(ot.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ot.type}`);const nt=ot;if(_t.value.length!==nt.value.length)throw new Error(`Too ${_t.value.length>nt.value.length?"few":"many"} items to unpack`);bt=ft=>{for(let vt=0;vt<_t.value.length;++vt){if(_t.value[vt].type!=="Identifier")throw new Error(`Cannot unpack non-identifier type: ${_t.value[vt].type}`);ft.setVariable(_t.value[vt].value,nt.value[vt])}}}else throw new Error(`Invalid loop variable(s): ${F.loopvar.type}`);se&&(bt(Qe),!this.evaluate(se,Qe).__bool__().value)||(ge.push(ot),Ce.push(bt))}let Ie="",Ee=!0;for(let je=0;je0?ge[je-1]:new He],["nextitem",je{const _e=new Ne(se);j=j.slice();let ge;j.at(-1)?.type==="KeywordArgumentsValue"&&(ge=j.pop());for(let Ce=0;Cethis.evaluate(j,U)));case"TupleLiteral":return new ae(F.value.map(j=>this.evaluate(j,U)));case"ObjectLiteral":{const j=new Map;for(const[se,_e]of F.value){const ge=this.evaluate(se,U);if(!(ge instanceof me))throw new Error(`Object keys must be strings: got ${ge.type}`);j.set(ge.value,this.evaluate(_e,U))}return new ze(j)}case"Identifier":return this.evaluateIdentifier(F,U);case"CallExpression":return this.evaluateCallExpression(F,U);case"MemberExpression":return this.evaluateMemberExpression(F,U);case"UnaryExpression":return this.evaluateUnaryExpression(F,U);case"BinaryExpression":return this.evaluateBinaryExpression(F,U);case"FilterExpression":return this.evaluateFilterExpression(F,U);case"TestExpression":return this.evaluateTestExpression(F,U);default:throw new SyntaxError(`Unknown node type: ${F.type}`)}}};function ke(F){switch(typeof F){case"number":return new ye(F);case"string":return new me(F);case"boolean":return new xe(F);case"undefined":return new He;case"object":return F===null?new re:Array.isArray(F)?new ce(F.map(ke)):new ze(new Map(Object.entries(F).map(([U,j])=>[U,ke(j)])));case"function":return new we((U,j)=>{const se=F(...U.map(_e=>_e.value))??null;return ke(se)});default:throw new Error(`Cannot convert to runtime value: ${F}`)}}function st(F,U,j){const se=j??0;switch(F.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(F.value);case"ArrayValue":case"ObjectValue":{const _e=U?" ".repeat(U):"",ge=` +`+_e.repeat(se),Ce=ge+_e;if(F.type==="ArrayValue"){const Ie=F.value.map(Ee=>st(Ee,U,se+1));return U?`[${Ce}${Ie.join(`,${Ce}`)}${ge}]`:`[${Ie.join(", ")}]`}else{const Ie=Array.from(F.value.entries()).map(([Ee,je])=>{const Qe=`"${Ee}": ${st(je,U,se+1)}`;return U?`${Ce}${Qe}`:Qe});return U?`{${Ie.join(",")}${ge}}`:`{${Ie.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${F.type}`)}}var Ke=class{parsed;constructor(F){const U=h(F,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=q(U)}render(F){const U=new Ne;if(U.set("false",!1),U.set("true",!0),U.set("raise_exception",_e=>{throw new Error(_e)}),U.set("range",G),F)for(const[_e,ge]of Object.entries(F))U.set(_e,ge);return new We(U).run(this.parsed).value}}},"./src/backends/onnx.js":(n,e,t)=>{var i;t.r(e),t.d(e,{Tensor:()=>u.Tensor,createInferenceSession:()=>T,deviceToExecutionProviders:()=>y,isONNXProxy:()=>P,isONNXTensor:()=>v});var s=t("./src/env.js"),o=t("?2ce3"),l=t("onnxruntime-web"),u=t("onnxruntime-common");const d=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),f=[];let m,h;const _=Symbol.for("onnxruntime");if(_ in globalThis)h=globalThis[_];else if(s.apis.IS_NODE_ENV){switch(h=o??(i||(i=t.t(o,2))),process.platform){case"win32":f.push("dml");break;case"linux":process.arch==="x64"&&f.push("cuda");break}f.push("cpu"),m=["cpu"]}else h=l,s.apis.IS_WEBNN_AVAILABLE&&f.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),s.apis.IS_WEBGPU_AVAILABLE&&f.push("webgpu"),f.push("wasm"),m=["wasm"];const g=h.InferenceSession;function y(w=null){if(!w)return m;switch(w){case"auto":return f;case"gpu":return f.filter(C=>["webgpu","cuda","dml","webnn-gpu"].includes(C))}if(f.includes(w))return[d[w]??w];throw new Error(`Unsupported device: "${w}". Should be one of: ${f.join(", ")}.`)}let b=null;async function T(w,C,E){b&&await b;const A=g.create(w,C);b??=A;const L=await A;return L.config=E,L}function v(w){return w instanceof h.Tensor}const x=h?.env;x?.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!x.wasm.wasmPaths&&(x.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${s.env.version}/dist/`),x.wasm.proxy=!1),x?.webgpu&&(x.webgpu.powerPreference="high-performance");function P(){return x?.wasm?.proxy}s.env.backends.onnx=x},"./src/base/feature_extraction_utils.js":(n,e,t)=>{t.r(e),t.d(e,{FeatureExtractor:()=>l,validate_audio_inputs:()=>u});var i=t("./src/utils/constants.js"),s=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class l extends s.Callable{constructor(f){super(),this.config=f}static async from_pretrained(f,m){const h=await(0,o.getModelJSON)(f,i.FEATURE_EXTRACTOR_NAME,!0,m);return new this(h)}}function u(d,f){if(!(d instanceof Float32Array||d instanceof Float64Array))throw new Error(`${f} expects input to be a Float32Array or a Float64Array, but got ${d?.constructor?.name??typeof d} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(n,e,t)=>{t.r(e),t.d(e,{ImageProcessor:()=>w,center_to_corners_format:()=>h,post_process_instance_segmentation:()=>P,post_process_object_detection:()=>_,post_process_panoptic_segmentation:()=>x,post_process_semantic_segmentation:()=>g});var i=t("./src/utils/generic.js"),s=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/utils/image.js");var l=t("./src/utils/core.js"),u=t("./src/utils/hub.js"),d=t("./src/utils/constants.js");function f(C,E,A=0,L=null){const I=C/E;let O=(0,o.bankers_round)(I)*E;return L!==null&&O>L&&(O=Math.floor(I)*E),OE&&G.push(B)}else{let B=(0,o.max)(q.data)[1];if(B===$-1||(te=(0,o.softmax)(q.data),te[B]ye*X[(me+1)%2])),ne.boxes.push(le),ne.classes.push(B),ne.scores.push(te[B])}}J.push(ne)}return J}function g(C,E=null){const A=C.logits,L=A.dims[0];if(E!==null&&E.length!==L)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const I=[];for(let O=0;OX[G]&&(X[G]=q[G],ne[G]=W)}const Q=new Array(Z.dims[0]);for(let W=0;WW!==void 0);I.push({segmentation:ee,labels:oe})}return I}function y(C,E,A,L){const I=[],O=[],H=[];for(let Z=0;ZA&&(I.push(J),O.push(ne),H.push(ee))}return[I,O,H]}function b(C,E,A,L=.5,I=.8){const O=[];let H=0,Z=0;const $=E[A].data;for(let ee=0;ee=L&&++Z;let J=H>0&&Z>0;return J&&(J=H/Z>I),[J,O]}function T(C,E,A,L,I,O=null,H=null){const[Z,$]=H??C[0].dims,J=new s.Tensor("int32",new Int32Array(Z*$),[Z,$]),ee=[];if(H!==null)for(let W=0;Wne[te]&&(X[te]=W,ne[te]=G[te])}let Q=0;const oe=J.data;for(let W=0;W200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(C,E)/Math.min(C,E)}`);let O=Math.round(C/A)*A,H=Math.round(E/A)*A;if(O*H>I){const Z=Math.sqrt(C*E/I);O=Math.floor(C/Z/A)*A,H=Math.floor(E/Z/A)*A}else if(O*HO?J=Math.floor(O*$/I):O>I&&($=Math.floor(I*J/O)),await E.resize(J,$,{resample:L}))}async crop_margin(E,A=200){const L=E.clone().grayscale(),I=(0,o.min)(L.data)[0],H=(0,o.max)(L.data)[0]-I;if(H===0)return E;const Z=A/255;let $=L.width,J=L.height,ee=0,X=0;const ne=L.data;for(let Q=0;Qthis.preprocess(O)));return{pixel_values:(0,s.stack)(L.map(O=>O.pixel_values),0),original_sizes:L.map(O=>O.original_size),reshaped_input_sizes:L.map(O=>O.reshaped_input_size)}}static async from_pretrained(E,A){const L=await(0,u.getModelJSON)(E,d.IMAGE_PROCESSOR_NAME,!0,A);return new this(L)}}},"./src/base/processing_utils.js":(n,e,t)=>{t.r(e),t.d(e,{Processor:()=>l});var i=t("./src/utils/constants.js"),s=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class l extends s.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(d,f){super(),this.config=d,this.components=f}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(d,f={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(d,{tokenize:!1,...f})}batch_decode(...d){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...d)}decode(...d){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...d)}async _call(d,...f){for(const m of[this.image_processor,this.feature_extractor,this.tokenizer])if(m)return m(d,...f);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(d,f){const[m,h]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(d,i.PROCESSOR_NAME,!0,f):{},Promise.all(this.classes.filter(_=>_ in this).map(async _=>{const g=await this[_].from_pretrained(d,f);return[_.replace(/_class$/,""),g]})).then(Object.fromEntries)]);return new this(m,h)}}},"./src/configs.js":(n,e,t)=>{t.r(e),t.d(e,{AutoConfig:()=>f,PretrainedConfig:()=>d,getKeyValueShapes:()=>u});var i=t("./src/utils/core.js"),s=t("./src/utils/hub.js");async function o(m,h){return await(0,s.getModelJSON)(m,"config.json",!0,h)}function l(m){const h={};let _={};switch(m.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":_=l(m.text_config);break;case"moondream1":_=l(m.phi_config);break;case"musicgen":_=l(m.decoder);break;case"multi_modality":_=l(m.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":h.num_heads="n_head",h.num_layers="n_layer",h.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":h.num_heads="num_attention_heads",h.num_layers="num_hidden_layers",h.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":h.num_heads="num_key_value_heads",h.num_layers="num_hidden_layers",h.hidden_size="hidden_size",h.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":h.num_heads="num_key_value_heads",h.num_layers="num_hidden_layers",h.dim_kv="head_dim";break;case"openelm":h.num_heads="num_kv_heads",h.num_layers="num_transformer_layers",h.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":h.num_heads="num_heads",h.num_layers="num_layers",h.hidden_size="hidden_size";break;case"bloom":h.num_heads="n_head",h.num_layers="n_layer",h.hidden_size="hidden_size";break;case"mpt":h.num_heads="n_heads",h.num_layers="n_layers",h.hidden_size="d_model";break;case"exaone":h.num_heads="num_key_value_heads",h.num_layers="num_layers",h.dim_kv="head_dim",h.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":h.num_decoder_layers="num_decoder_layers",h.num_decoder_heads="num_heads",h.decoder_dim_kv="d_kv",h.num_encoder_layers="num_layers",h.num_encoder_heads="num_heads",h.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":h.num_decoder_layers="decoder_layers",h.num_decoder_heads="decoder_attention_heads",h.decoder_hidden_size="d_model",h.num_encoder_layers="encoder_layers",h.num_encoder_heads="encoder_attention_heads",h.encoder_hidden_size="d_model";break;case"speecht5":h.num_decoder_layers="decoder_layers",h.num_decoder_heads="decoder_attention_heads",h.decoder_hidden_size="hidden_size",h.num_encoder_layers="encoder_layers",h.num_encoder_heads="encoder_attention_heads",h.encoder_hidden_size="hidden_size";break;case"trocr":h.num_encoder_layers=h.num_decoder_layers="decoder_layers",h.num_encoder_heads=h.num_decoder_heads="decoder_attention_heads",h.encoder_hidden_size=h.decoder_hidden_size="d_model";break;case"musicgen_decoder":h.num_encoder_layers=h.num_decoder_layers="num_hidden_layers",h.num_encoder_heads=h.num_decoder_heads="num_attention_heads",h.encoder_hidden_size=h.decoder_hidden_size="hidden_size";break;case"moonshine":h.num_decoder_layers="decoder_num_hidden_layers",h.num_decoder_heads="decoder_num_key_value_heads",h.num_encoder_layers="encoder_num_hidden_layers",h.num_encoder_heads="encoder_num_key_value_heads",h.encoder_hidden_size=h.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const y=l(m.decoder),b="num_decoder_layers"in y,T=(0,i.pick)(m,["model_type","is_encoder_decoder"]);return b?(T.num_decoder_layers=y.num_decoder_layers,T.num_decoder_heads=y.num_decoder_heads,T.decoder_hidden_size=y.decoder_hidden_size,T.num_encoder_layers=y.num_encoder_layers,T.num_encoder_heads=y.num_encoder_heads,T.encoder_hidden_size=y.encoder_hidden_size):(T.num_layers=y.num_layers,T.num_heads=y.num_heads,T.hidden_size=y.hidden_size),T}const g={..._,...(0,i.pick)(m,["model_type","multi_query","is_encoder_decoder"])};for(const y in h)g[y]=m[h[y]];return g}function u(m,{prefix:h="past_key_values",batch_size:_=1}={}){const g={},y=m.normalized_config;if(y.is_encoder_decoder&&"num_encoder_heads"in y&&"num_decoder_heads"in y){const b=y.encoder_dim_kv??y.encoder_hidden_size/y.num_encoder_heads,T=y.decoder_dim_kv??y.decoder_hidden_size/y.num_decoder_heads,v=[_,y.num_encoder_heads,0,b],x=[_,y.num_decoder_heads,0,T];for(let P=0;P{t.r(e),t.d(e,{apis:()=>T,env:()=>E});var i=t("?569f"),s=t("?3f59"),o=t("?154a");const l="3.5.0",u=typeof window<"u"&&typeof window.document<"u",d=typeof self<"u"&&self.constructor?.name==="DedicatedWorkerGlobalScope",f=typeof self<"u"&&"caches"in self,m=typeof navigator<"u"&&"gpu"in navigator,h=typeof navigator<"u"&&"ml"in navigator,_=typeof process<"u",g=_&&process?.release?.name==="node",y=!A(i),b=!A(s),T=Object.freeze({IS_BROWSER_ENV:u,IS_WEBWORKER_ENV:d,IS_WEB_CACHE_AVAILABLE:f,IS_WEBGPU_AVAILABLE:m,IS_WEBNN_AVAILABLE:h,IS_PROCESS_AVAILABLE:_,IS_NODE_ENV:g,IS_FS_AVAILABLE:y,IS_PATH_AVAILABLE:b}),v=y&&b;let x="./";if(v){const L=Object(import.meta).url;L?x=s.dirname(s.dirname(o.fileURLToPath(L))):typeof __dirname<"u"&&(x=s.dirname(__dirname))}const P=v?s.join(x,"/.cache/"):null,w="/models/",C=v?s.join(x,w):w,E={version:l,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(u||d),localModelPath:C,useFS:y,useBrowserCache:f,useFSCache:y,cacheDir:P,useCustomCache:!1,customCache:null};function A(L){return Object.keys(L).length===0}},"./src/generation/configuration_utils.js":(n,e,t)=>{t.r(e),t.d(e,{GenerationConfig:()=>s});var i=t("./src/utils/core.js");class s{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(l){Object.assign(this,(0,i.pick)(l,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(n,e,t)=>{t.r(e),t.d(e,{ClassifierFreeGuidanceLogitsProcessor:()=>v,ForcedBOSTokenLogitsProcessor:()=>d,ForcedEOSTokenLogitsProcessor:()=>f,LogitsProcessor:()=>o,LogitsProcessorList:()=>u,LogitsWarper:()=>l,MinLengthLogitsProcessor:()=>y,MinNewTokensLengthLogitsProcessor:()=>b,NoBadWordsLogitsProcessor:()=>T,NoRepeatNGramLogitsProcessor:()=>_,RepetitionPenaltyLogitsProcessor:()=>g,SuppressTokensAtBeginLogitsProcessor:()=>m,TemperatureLogitsWarper:()=>x,TopKLogitsWarper:()=>w,TopPLogitsWarper:()=>P,WhisperTimeStampLogitsProcessor:()=>h});var i=t("./src/utils/generic.js");t("./src/utils/tensor.js");var s=t("./src/utils/maths.js");class o extends i.Callable{_call(E,A){throw Error("`_call` should be implemented in a subclass")}}class l extends i.Callable{_call(E,A){throw Error("`_call` should be implemented in a subclass")}}class u extends i.Callable{constructor(){super(),this.processors=[]}push(E){this.processors.push(E)}extend(E){this.processors.push(...E)}_call(E,A){let L=A;for(const I of this.processors)L=I(E,L);return L}[Symbol.iterator](){return this.processors.values()}}class d extends o{constructor(E){super(),this.bos_token_id=E}_call(E,A){for(let L=0;L=1&&O[O.length-1]>=this.timestamp_begin,Z=O.length<2||O[O.length-2]>=this.timestamp_begin;if(H&&(Z?I.subarray(this.timestamp_begin).fill(-1/0):I.subarray(0,this.eos_token_id).fill(-1/0)),E[L].length===this.begin_index&&this.max_initial_timestamp_index!==null){const X=this.timestamp_begin+this.max_initial_timestamp_index;I.subarray(X+1).fill(-1/0)}const $=(0,s.log_softmax)(I),J=Math.log($.subarray(this.timestamp_begin).map(Math.exp).reduce((X,ne)=>X+ne)),ee=(0,s.max)($.subarray(0,this.timestamp_begin))[0];J>ee&&I.subarray(0,this.timestamp_begin).fill(-1/0)}return A}}class _ extends o{constructor(E){super(),this.no_repeat_ngram_size=E}getNgrams(E){const A=E.length,L=[];for(let O=0;O1 to use the classifier free guidance processor, got guidance scale ${E}.`);this.guidance_scale=E}_call(E,A){if(A.dims[0]!==2*E.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${A.dims[0]} for the logits and ${E.length} for the input ids.`);const L=E.length,I=A.slice([0,L],null),O=A.slice([L,A.dims[0]],null);for(let H=0;H1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${E}`);if(!Number.isInteger(L)||L<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${L}`);this.top_p=E,this.filter_value=A,this.min_tokens_to_keep=L}}class w extends l{constructor(E,{filter_value:A=-1/0,min_tokens_to_keep:L=1}={}){if(super(),!Number.isInteger(E)||E<0)throw new Error(`\`top_k\` must be a positive integer, but is ${E}`);this.top_k=Math.max(E,L),this.filter_value=A}}},"./src/generation/logits_sampler.js":(n,e,t)=>{t.r(e),t.d(e,{LogitsSampler:()=>l});var i=t("./src/utils/generic.js"),s=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class l extends i.Callable{constructor(h){super(),this.generation_config=h}async _call(h){return this.sample(h)}async sample(h){throw Error("sample should be implemented in subclasses.")}getLogits(h,_){let g=h.dims.at(-1),y=h.data;if(_===-1)y=y.slice(-g);else{let b=_*g;y=y.slice(b,b+g)}return y}randomSelect(h){let _=0;for(let y=0;y1)return new f(h);if(h.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${h.num_return_sequences}.`);return new u(h)}}class u extends l{async sample(h){const _=(0,o.max)(h.data)[1];return[[BigInt(_),0]]}}class d extends l{async sample(h){let _=h.dims.at(-1);this.generation_config.top_k>0&&(_=Math.min(this.generation_config.top_k,_));const[g,y]=await(0,s.topk)(h,_),b=(0,o.softmax)(g.data);return Array.from({length:this.generation_config.num_beams},()=>{const T=this.randomSelect(b);return[y.data[T],Math.log(b[T])]})}}class f extends l{async sample(h){let _=h.dims.at(-1);this.generation_config.top_k>0&&(_=Math.min(this.generation_config.top_k,_));const[g,y]=await(0,s.topk)(h,_),b=(0,o.softmax)(g.data);return Array.from({length:this.generation_config.num_beams},(T,v)=>[y.data[v],Math.log(b[v])])}}},"./src/generation/stopping_criteria.js":(n,e,t)=>{t.r(e),t.d(e,{EosTokenCriteria:()=>u,InterruptableStoppingCriteria:()=>d,MaxLengthCriteria:()=>l,StoppingCriteria:()=>s,StoppingCriteriaList:()=>o});var i=t("./src/utils/generic.js");class s extends i.Callable{_call(m,h){throw Error("StoppingCriteria needs to be subclassed")}}class o extends i.Callable{constructor(){super(),this.criteria=[]}push(m){this.criteria.push(m)}extend(m){m instanceof o?m=m.criteria:m instanceof s&&(m=[m]),this.criteria.push(...m)}_call(m,h){const _=new Array(m.length).fill(!1);for(const g of this.criteria){const y=g(m,h);for(let b=0;b<_.length;++b)_[b]||=y[b]}return _}[Symbol.iterator](){return this.criteria.values()}}class l extends s{constructor(m,h=null){super(),this.max_length=m,this.max_position_embeddings=h}_call(m){return m.map(h=>h.length>=this.max_length)}}class u extends s{constructor(m){super(),Array.isArray(m)||(m=[m]),this.eos_token_id=m}_call(m,h){return m.map(_=>{const g=_.at(-1);return this.eos_token_id.some(y=>g==y)})}}class d extends s{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(m,h){return new Array(m.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(n,e,t)=>{t.r(e),t.d(e,{BaseStreamer:()=>l,TextStreamer:()=>d,WhisperTextStreamer:()=>f});var i=t("./src/utils/core.js"),s=t("./src/tokenizers.js"),o=t("./src/env.js");class l{put(h){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const u=o.apis.IS_PROCESS_AVAILABLE?m=>process.stdout.write(m):m=>console.log(m);class d extends l{constructor(h,{skip_prompt:_=!1,callback_function:g=null,token_callback_function:y=null,skip_special_tokens:b=!0,decode_kwargs:T={},...v}={}){super(),this.tokenizer=h,this.skip_prompt=_,this.callback_function=g??u,this.token_callback_function=y,this.decode_kwargs={skip_special_tokens:b,...T,...v},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(h){if(h.length>1)throw Error("TextStreamer only supports batch size of 1");const _=this.next_tokens_are_prompt;if(_&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const g=h[0];this.token_callback_function?.(g),this.token_cache=(0,i.mergeArrays)(this.token_cache,g);const y=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let b;_||y.endsWith(` +`)?(b=y.slice(this.print_len),this.token_cache=[],this.print_len=0):y.length>0&&(0,s.is_chinese_char)(y.charCodeAt(y.length-1))?(b=y.slice(this.print_len),this.print_len+=b.length):(b=y.slice(this.print_len,y.lastIndexOf(" ")+1),this.print_len+=b.length),this.on_finalized_text(b,!1)}end(){let h;this.token_cache.length>0?(h=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):h="",this.next_tokens_are_prompt=!0,this.on_finalized_text(h,!0)}on_finalized_text(h,_){h.length>0&&this.callback_function?.(h),_&&this.callback_function===u&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}}class f extends d{constructor(h,{skip_prompt:_=!1,callback_function:g=null,token_callback_function:y=null,on_chunk_start:b=null,on_chunk_end:T=null,on_finalize:v=null,time_precision:x=.02,skip_special_tokens:P=!0,decode_kwargs:w={}}={}){super(h,{skip_prompt:_,skip_special_tokens:P,callback_function:g,token_callback_function:y,decode_kwargs:w}),this.timestamp_begin=h.timestamp_begin,this.on_chunk_start=b,this.on_chunk_end=T,this.on_finalize=v,this.time_precision=x,this.waiting_for_timestamp=!1}put(h){if(h.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const _=h[0];if(_.length===1){const g=Number(_[0])-this.timestamp_begin;if(g>=0){const y=g*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(y):this.on_chunk_start?.(y),this.waiting_for_timestamp=!this.waiting_for_timestamp,h=[[]]}}return super.put(h)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(n,e,t)=>{t.r(e),t.d(e,{ASTForAudioClassification:()=>yd,ASTModel:()=>vd,ASTPreTrainedModel:()=>$c,AlbertForMaskedLM:()=>fe,AlbertForQuestionAnswering:()=>V,AlbertForSequenceClassification:()=>Pe,AlbertModel:()=>Kn,AlbertPreTrainedModel:()=>yi,AutoModel:()=>Zp,AutoModelForAudioClassification:()=>Pa,AutoModelForAudioFrameClassification:()=>rm,AutoModelForAudioTextToText:()=>l0,AutoModelForCTC:()=>s0,AutoModelForCausalLM:()=>Nu,AutoModelForDepthEstimation:()=>D_,AutoModelForDocumentQuestionAnswering:()=>gc,AutoModelForImageClassification:()=>nm,AutoModelForImageFeatureExtraction:()=>a0,AutoModelForImageMatting:()=>P_,AutoModelForImageSegmentation:()=>as,AutoModelForImageTextToText:()=>o0,AutoModelForImageToImage:()=>R_,AutoModelForMaskGeneration:()=>C_,AutoModelForMaskedLM:()=>em,AutoModelForNormalEstimation:()=>sm,AutoModelForObjectDetection:()=>A_,AutoModelForPoseEstimation:()=>am,AutoModelForQuestionAnswering:()=>tm,AutoModelForSemanticSegmentation:()=>S_,AutoModelForSeq2SeqLM:()=>Af,AutoModelForSequenceClassification:()=>Jp,AutoModelForSpeechSeq2Seq:()=>To,AutoModelForTextToSpectrogram:()=>Cf,AutoModelForTextToWaveform:()=>sl,AutoModelForTokenClassification:()=>Sf,AutoModelForUniversalSegmentation:()=>Fr,AutoModelForVision2Seq:()=>zu,AutoModelForXVector:()=>Pf,AutoModelForZeroShotObjectDetection:()=>im,BartForConditionalGeneration:()=>Gi,BartForSequenceClassification:()=>ci,BartModel:()=>pi,BartPretrainedModel:()=>cn,BaseModelOutput:()=>re,BeitForImageClassification:()=>Nh,BeitModel:()=>l_,BeitPreTrainedModel:()=>uo,BertForMaskedLM:()=>We,BertForQuestionAnswering:()=>Ke,BertForSequenceClassification:()=>ke,BertForTokenClassification:()=>st,BertModel:()=>Ne,BertPreTrainedModel:()=>He,BlenderbotForConditionalGeneration:()=>Mi,BlenderbotModel:()=>ei,BlenderbotPreTrainedModel:()=>Br,BlenderbotSmallForConditionalGeneration:()=>Qr,BlenderbotSmallModel:()=>Or,BlenderbotSmallPreTrainedModel:()=>Ki,BloomForCausalLM:()=>Hl,BloomModel:()=>Ch,BloomPreTrainedModel:()=>Od,CLIPModel:()=>Td,CLIPPreTrainedModel:()=>Zr,CLIPSegForImageSegmentation:()=>Zc,CLIPSegModel:()=>Ul,CLIPSegPreTrainedModel:()=>ga,CLIPTextModel:()=>Ed,CLIPTextModelWithProjection:()=>Yc,CLIPVisionModel:()=>Sd,CLIPVisionModelWithProjection:()=>Za,CamembertForMaskedLM:()=>rn,CamembertForQuestionAnswering:()=>vi,CamembertForSequenceClassification:()=>Pn,CamembertForTokenClassification:()=>ln,CamembertModel:()=>tn,CamembertPreTrainedModel:()=>Pt,CausalLMOutput:()=>ol,CausalLMOutputWithPast:()=>O_,ChineseCLIPModel:()=>Oo,ChineseCLIPPreTrainedModel:()=>zl,ClapAudioModelWithProjection:()=>yo,ClapModel:()=>cc,ClapPreTrainedModel:()=>lc,ClapTextModelWithProjection:()=>Eu,CodeGenForCausalLM:()=>ro,CodeGenModel:()=>Ms,CodeGenPreTrainedModel:()=>io,CohereForCausalLM:()=>iu,CohereModel:()=>Eh,CoherePreTrainedModel:()=>Gs,ConvBertForMaskedLM:()=>ft,ConvBertForQuestionAnswering:()=>Se,ConvBertForSequenceClassification:()=>vt,ConvBertForTokenClassification:()=>mn,ConvBertModel:()=>nt,ConvBertPreTrainedModel:()=>_t,ConvNextForImageClassification:()=>sp,ConvNextModel:()=>rp,ConvNextPreTrainedModel:()=>vu,ConvNextV2ForImageClassification:()=>Qd,ConvNextV2Model:()=>ap,ConvNextV2PreTrainedModel:()=>Yd,DPTForDepthEstimation:()=>Hh,DPTModel:()=>Wh,DPTPreTrainedModel:()=>Hd,DacDecoderModel:()=>tl,DacDecoderOutput:()=>el,DacEncoderModel:()=>mc,DacEncoderOutput:()=>jp,DacModel:()=>pc,DacPreTrainedModel:()=>Es,DebertaForMaskedLM:()=>It,DebertaForQuestionAnswering:()=>rr,DebertaForSequenceClassification:()=>Bt,DebertaForTokenClassification:()=>Vi,DebertaModel:()=>ut,DebertaPreTrainedModel:()=>On,DebertaV2ForMaskedLM:()=>Er,DebertaV2ForQuestionAnswering:()=>Sr,DebertaV2ForSequenceClassification:()=>zr,DebertaV2ForTokenClassification:()=>Ns,DebertaV2Model:()=>Ti,DebertaV2PreTrainedModel:()=>ri,DecisionTransformerModel:()=>M_,DecisionTransformerPreTrainedModel:()=>Up,DeiTForImageClassification:()=>jd,DeiTModel:()=>Gd,DeiTPreTrainedModel:()=>Vh,DepthAnythingForDepthEstimation:()=>qd,DepthAnythingPreTrainedModel:()=>qh,DepthProForDepthEstimation:()=>Xd,DepthProPreTrainedModel:()=>Yh,DetrForObjectDetection:()=>fo,DetrForSegmentation:()=>lu,DetrModel:()=>zh,DetrObjectDetectionOutput:()=>tc,DetrPreTrainedModel:()=>$d,DetrSegmentationOutput:()=>Uh,Dinov2ForImageClassification:()=>Jd,Dinov2Model:()=>op,Dinov2PreTrainedModel:()=>Zd,Dinov2WithRegistersForImageClassification:()=>f_,Dinov2WithRegistersModel:()=>lp,Dinov2WithRegistersPreTrainedModel:()=>ef,DistilBertForMaskedLM:()=>Oe,DistilBertForQuestionAnswering:()=>ue,DistilBertForSequenceClassification:()=>Yr,DistilBertForTokenClassification:()=>vr,DistilBertModel:()=>Ii,DistilBertPreTrainedModel:()=>Ur,DonutSwinModel:()=>ip,DonutSwinPreTrainedModel:()=>gu,EfficientNetForImageClassification:()=>fc,EfficientNetModel:()=>vf,EfficientNetPreTrainedModel:()=>Au,ElectraForMaskedLM:()=>it,ElectraForQuestionAnswering:()=>gt,ElectraForSequenceClassification:()=>yt,ElectraForTokenClassification:()=>tt,ElectraModel:()=>Ze,ElectraPreTrainedModel:()=>St,EsmForMaskedLM:()=>Fe,EsmForSequenceClassification:()=>wt,EsmForTokenClassification:()=>Ct,EsmModel:()=>Ue,EsmPreTrainedModel:()=>qe,ExaoneForCausalLM:()=>rt,ExaoneModel:()=>Ae,ExaonePreTrainedModel:()=>pe,FalconForCausalLM:()=>mf,FalconModel:()=>Qs,FalconPreTrainedModel:()=>Ys,FastViTForImageClassification:()=>ba,FastViTModel:()=>bs,FastViTPreTrainedModel:()=>Vr,Florence2ForConditionalGeneration:()=>bd,Florence2PreTrainedModel:()=>Md,GLPNForDepthEstimation:()=>_u,GLPNModel:()=>np,GLPNPreTrainedModel:()=>po,GPT2LMHeadModel:()=>to,GPT2Model:()=>Lo,GPT2PreTrainedModel:()=>eo,GPTBigCodeForCausalLM:()=>tu,GPTBigCodeModel:()=>Uo,GPTBigCodePreTrainedModel:()=>zo,GPTJForCausalLM:()=>No,GPTJModel:()=>$l,GPTJPreTrainedModel:()=>ko,GPTNeoForCausalLM:()=>Jr,GPTNeoModel:()=>Fo,GPTNeoPreTrainedModel:()=>Bl,GPTNeoXForCausalLM:()=>va,GPTNeoXModel:()=>mr,GPTNeoXPreTrainedModel:()=>no,Gemma2ForCausalLM:()=>ru,Gemma2Model:()=>$o,Gemma2PreTrainedModel:()=>ao,Gemma3ForCausalLM:()=>ns,Gemma3Model:()=>ts,Gemma3PreTrainedModel:()=>Wl,GemmaForCausalLM:()=>es,GemmaModel:()=>Sh,GemmaPreTrainedModel:()=>so,GlmForCausalLM:()=>ie,GlmModel:()=>Y,GlmPreTrainedModel:()=>z,GraniteForCausalLM:()=>Pd,GraniteModel:()=>nu,GranitePreTrainedModel:()=>jl,GroundingDinoForObjectDetection:()=>cp,GroundingDinoPreTrainedModel:()=>tf,GroupViTModel:()=>zd,GroupViTPreTrainedModel:()=>Nd,HeliumForCausalLM:()=>S,HeliumModel:()=>Vs,HeliumPreTrainedModel:()=>cs,HieraForImageClassification:()=>Zi,HieraModel:()=>Lr,HieraPreTrainedModel:()=>du,HubertForCTC:()=>Tp,HubertForSequenceClassification:()=>ac,HubertModel:()=>wp,HubertPreTrainedModel:()=>__,IJepaForImageClassification:()=>Ql,IJepaModel:()=>Go,IJepaPreTrainedModel:()=>kd,Idefics3ForConditionalGeneration:()=>Nl,Idefics3PreTrainedModel:()=>Xc,ImageMattingOutput:()=>ll,JAISLMHeadModel:()=>eu,JAISModel:()=>Jc,JAISPreTrainedModel:()=>Xt,JinaCLIPModel:()=>ma,JinaCLIPPreTrainedModel:()=>Ja,JinaCLIPTextModel:()=>_a,JinaCLIPVisionModel:()=>Qc,LiteWhisperForConditionalGeneration:()=>jc,LlamaForCausalLM:()=>Vl,LlamaModel:()=>Bo,LlamaPreTrainedModel:()=>$s,LlavaForConditionalGeneration:()=>zs,LlavaOnevisionForConditionalGeneration:()=>Hc,LlavaPreTrainedModel:()=>Wc,LongT5ForConditionalGeneration:()=>Lt,LongT5Model:()=>Ot,LongT5PreTrainedModel:()=>lt,M2M100ForConditionalGeneration:()=>ws,M2M100Model:()=>hp,M2M100PreTrainedModel:()=>af,MBartForCausalLM:()=>Li,MBartForConditionalGeneration:()=>Oi,MBartForSequenceClassification:()=>ys,MBartModel:()=>mi,MBartPreTrainedModel:()=>ui,MPNetForMaskedLM:()=>Jn,MPNetForQuestionAnswering:()=>nn,MPNetForSequenceClassification:()=>Ln,MPNetForTokenClassification:()=>dn,MPNetModel:()=>Sn,MPNetPreTrainedModel:()=>yn,MT5ForConditionalGeneration:()=>Cn,MT5Model:()=>Dt,MT5PreTrainedModel:()=>Ft,MarianMTModel:()=>yu,MarianModel:()=>sf,MarianPreTrainedModel:()=>Ko,MaskFormerForInstanceSegmentation:()=>tp,MaskFormerModel:()=>d_,MaskFormerPreTrainedModel:()=>Kd,MaskedLMOutput:()=>ur,Metric3DForDepthEstimation:()=>Zh,Metric3DPreTrainedModel:()=>Qh,Metric3Dv2ForDepthEstimation:()=>ep,Metric3Dv2PreTrainedModel:()=>Jh,MgpstrForSceneTextRecognition:()=>ea,MgpstrModelOutput:()=>er,MgpstrPreTrainedModel:()=>jr,MimiDecoderModel:()=>wf,MimiDecoderOutput:()=>Jo,MimiEncoderModel:()=>xf,MimiEncoderOutput:()=>ta,MimiModel:()=>Ea,MimiPreTrainedModel:()=>Ru,MistralForCausalLM:()=>Ip,MistralModel:()=>g_,MistralPreTrainedModel:()=>wu,MobileBertForMaskedLM:()=>qt,MobileBertForQuestionAnswering:()=>Jt,MobileBertForSequenceClassification:()=>sn,MobileBertModel:()=>Rt,MobileBertPreTrainedModel:()=>Nt,MobileLLMForCausalLM:()=>Gt,MobileLLMModel:()=>kt,MobileLLMPreTrainedModel:()=>Mt,MobileNetV1ForImageClassification:()=>Lp,MobileNetV1ForSemanticSegmentation:()=>bo,MobileNetV1Model:()=>Op,MobileNetV1PreTrainedModel:()=>Ts,MobileNetV2ForImageClassification:()=>kp,MobileNetV2ForSemanticSegmentation:()=>Np,MobileNetV2Model:()=>Fp,MobileNetV2PreTrainedModel:()=>Cr,MobileNetV3ForImageClassification:()=>Cu,MobileNetV3ForSemanticSegmentation:()=>Js,MobileNetV3Model:()=>yf,MobileNetV3PreTrainedModel:()=>hc,MobileNetV4ForImageClassification:()=>zp,MobileNetV4ForSemanticSegmentation:()=>cr,MobileNetV4Model:()=>Mf,MobileNetV4PreTrainedModel:()=>Ri,MobileViTForImageClassification:()=>ou,MobileViTModel:()=>ar,MobileViTPreTrainedModel:()=>xs,MobileViTV2ForImageClassification:()=>o_,MobileViTV2Model:()=>a_,MobileViTV2PreTrainedModel:()=>kh,ModelOutput:()=>we,ModernBertForMaskedLM:()=>j,ModernBertForSequenceClassification:()=>se,ModernBertForTokenClassification:()=>_e,ModernBertModel:()=>U,ModernBertPreTrainedModel:()=>F,Moondream1ForConditionalGeneration:()=>qc,MoonshineForConditionalGeneration:()=>Ll,MoonshineModel:()=>Th,MoonshinePreTrainedModel:()=>Ol,MptForCausalLM:()=>Xl,MptModel:()=>ql,MptPreTrainedModel:()=>Vo,MultiModalityCausalLM:()=>$p,MultiModalityPreTrainedModel:()=>Bp,MusicgenForCausalLM:()=>y_,MusicgenForConditionalGeneration:()=>Zo,MusicgenModel:()=>v_,MusicgenPreTrainedModel:()=>Qo,NomicBertModel:()=>Ce,NomicBertPreTrainedModel:()=>ge,OPTForCausalLM:()=>Ph,OPTModel:()=>Fd,OPTPreTrainedModel:()=>Ld,Olmo2ForCausalLM:()=>Gl,Olmo2Model:()=>$r,Olmo2PreTrainedModel:()=>Qn,OlmoForCausalLM:()=>wn,OlmoModel:()=>Fn,OlmoPreTrainedModel:()=>hn,OpenELMForCausalLM:()=>Ws,OpenELMModel:()=>js,OpenELMPreTrainedModel:()=>ya,OwlViTForObjectDetection:()=>ec,OwlViTModel:()=>Ud,OwlViTPreTrainedModel:()=>Qi,Owlv2ForObjectDetection:()=>Wo,Owlv2Model:()=>Bd,Owlv2PreTrainedModel:()=>jo,PaliGemmaForConditionalGeneration:()=>kl,PaliGemmaPreTrainedModel:()=>xd,PatchTSMixerForPrediction:()=>fs,PatchTSMixerModel:()=>is,PatchTSMixerPreTrainedModel:()=>Pu,PatchTSTForPrediction:()=>b_,PatchTSTModel:()=>Vp,PatchTSTPreTrainedModel:()=>bf,Phi3ForCausalLM:()=>oo,Phi3Model:()=>Id,Phi3PreTrainedModel:()=>ds,Phi3VForCausalLM:()=>Io,Phi3VPreTrainedModel:()=>wd,PhiForCausalLM:()=>us,PhiModel:()=>Yn,PhiPreTrainedModel:()=>lr,PreTrainedModel:()=>ae,PretrainedMixin:()=>Gn,PvtForImageClassification:()=>Ih,PvtModel:()=>Dh,PvtPreTrainedModel:()=>Jl,PyAnnoteForAudioFrameClassification:()=>_o,PyAnnoteModel:()=>pp,PyAnnotePreTrainedModel:()=>cf,QuestionAnsweringModelOutput:()=>br,Qwen2ForCausalLM:()=>Rd,Qwen2Model:()=>Ah,Qwen2PreTrainedModel:()=>Ma,Qwen2VLForConditionalGeneration:()=>Ar,Qwen2VLPreTrainedModel:()=>Dd,RFDetrForObjectDetection:()=>c_,RFDetrModel:()=>Xo,RFDetrObjectDetectionOutput:()=>ji,RFDetrPreTrainedModel:()=>qo,RTDetrForObjectDetection:()=>di,RTDetrModel:()=>Rn,RTDetrObjectDetectionOutput:()=>zi,RTDetrPreTrainedModel:()=>Hs,RTDetrV2ForObjectDetection:()=>ho,RTDetrV2Model:()=>Ho,RTDetrV2ObjectDetectionOutput:()=>cu,RTDetrV2PreTrainedModel:()=>nc,ResNetForImageClassification:()=>fu,ResNetModel:()=>rc,ResNetPreTrainedModel:()=>ic,RoFormerForMaskedLM:()=>je,RoFormerForQuestionAnswering:()=>bt,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>ot,RoFormerModel:()=>Ee,RoFormerPreTrainedModel:()=>Ie,RobertaForMaskedLM:()=>Yi,RobertaForQuestionAnswering:()=>Pi,RobertaForSequenceClassification:()=>Bn,RobertaForTokenClassification:()=>ti,RobertaModel:()=>pr,RobertaPreTrainedModel:()=>Ci,SamImageSegmentationOutput:()=>fp,SamModel:()=>p_,SamPreTrainedModel:()=>h_,SapiensForDepthEstimation:()=>Xh,SapiensForNormalEstimation:()=>Kh,SapiensForSemanticSegmentation:()=>u_,SapiensPreTrainedModel:()=>mu,SegformerForImageClassification:()=>_f,SegformerForSemanticSegmentation:()=>gf,SegformerModel:()=>Mo,SegformerPreTrainedModel:()=>Su,Seq2SeqLMOutput:()=>I_,SequenceClassifierOutput:()=>_n,SiglipModel:()=>Bs,SiglipPreTrainedModel:()=>Us,SiglipTextModel:()=>Ad,SiglipVisionModel:()=>Cd,SmolVLMForConditionalGeneration:()=>Kc,SnacDecoderModel:()=>Hp,SnacEncoderModel:()=>_c,SnacModel:()=>Wp,SnacPreTrainedModel:()=>Du,SpeechT5ForSpeechToText:()=>hf,SpeechT5ForTextToSpeech:()=>Rp,SpeechT5HifiGan:()=>pf,SpeechT5Model:()=>Pp,SpeechT5PreTrainedModel:()=>oc,SqueezeBertForMaskedLM:()=>sr,SqueezeBertForQuestionAnswering:()=>Xi,SqueezeBertForSequenceClassification:()=>yr,SqueezeBertModel:()=>An,SqueezeBertPreTrainedModel:()=>li,StableLmForCausalLM:()=>dc,StableLmModel:()=>Ta,StableLmPreTrainedModel:()=>Zs,Starcoder2ForCausalLM:()=>Ks,Starcoder2Model:()=>vo,Starcoder2PreTrainedModel:()=>Tu,StyleTextToSpeech2Model:()=>Cp,StyleTextToSpeech2PreTrainedModel:()=>ff,Swin2SRForImageSuperResolution:()=>jh,Swin2SRModel:()=>Gh,Swin2SRPreTrainedModel:()=>pu,SwinForImageClassification:()=>hu,SwinForSemanticSegmentation:()=>Wd,SwinModel:()=>qs,SwinPreTrainedModel:()=>sc,T5ForConditionalGeneration:()=>Be,T5Model:()=>Te,T5PreTrainedModel:()=>ve,TableTransformerForObjectDetection:()=>Bh,TableTransformerModel:()=>Vd,TableTransformerObjectDetectionOutput:()=>$h,TableTransformerPreTrainedModel:()=>uu,TokenClassifierOutput:()=>Wi,TrOCRForCausalLM:()=>Xs,TrOCRPreTrainedModel:()=>Dp,UltravoxModel:()=>rs,UltravoxPreTrainedModel:()=>Gp,UniSpeechForCTC:()=>xu,UniSpeechForSequenceClassification:()=>gp,UniSpeechModel:()=>_p,UniSpeechPreTrainedModel:()=>bu,UniSpeechSatForAudioFrameClassification:()=>Mp,UniSpeechSatForCTC:()=>yp,UniSpeechSatForSequenceClassification:()=>m_,UniSpeechSatModel:()=>vp,UniSpeechSatPreTrainedModel:()=>Yo,ViTForImageClassification:()=>Yl,ViTMAEModel:()=>Oh,ViTMAEPreTrainedModel:()=>lo,ViTMSNForImageClassification:()=>Lh,ViTMSNModel:()=>au,ViTMSNPreTrainedModel:()=>co,ViTModel:()=>Rh,ViTPreTrainedModel:()=>Kl,VisionEncoderDecoderModel:()=>Fl,VitMatteForImageMatting:()=>xa,VitMattePreTrainedModel:()=>Fh,VitPoseForPoseEstimation:()=>Zl,VitPosePreTrainedModel:()=>su,VitsModel:()=>uc,VitsModelOutput:()=>om,VitsPreTrainedModel:()=>Mr,Wav2Vec2BertForCTC:()=>bp,Wav2Vec2BertForSequenceClassification:()=>xp,Wav2Vec2BertModel:()=>_r,Wav2Vec2BertPreTrainedModel:()=>Ji,Wav2Vec2ForAudioFrameClassification:()=>lf,Wav2Vec2ForCTC:()=>mo,Wav2Vec2ForSequenceClassification:()=>of,Wav2Vec2Model:()=>wa,Wav2Vec2PreTrainedModel:()=>Gr,WavLMForAudioFrameClassification:()=>df,WavLMForCTC:()=>Sp,WavLMForSequenceClassification:()=>Ap,WavLMForXVector:()=>uf,WavLMModel:()=>Ep,WavLMPreTrainedModel:()=>go,WeSpeakerResNetModel:()=>mp,WeSpeakerResNetPreTrainedModel:()=>Mu,WhisperForConditionalGeneration:()=>Il,WhisperModel:()=>Gc,WhisperPreTrainedModel:()=>Vc,XLMForQuestionAnswering:()=>Do,XLMForSequenceClassification:()=>Rl,XLMForTokenClassification:()=>ha,XLMModel:()=>Ya,XLMPreTrainedModel:()=>Fi,XLMRobertaForMaskedLM:()=>md,XLMRobertaForQuestionAnswering:()=>gd,XLMRobertaForSequenceClassification:()=>_d,XLMRobertaForTokenClassification:()=>Dl,XLMRobertaModel:()=>pd,XLMRobertaPreTrainedModel:()=>pa,XLMWithLMHeadModel:()=>Qa,XVectorOutput:()=>al,YolosForObjectDetection:()=>up,YolosModel:()=>rf,YolosObjectDetectionOutput:()=>dp,YolosPreTrainedModel:()=>nf});var i=t("./src/configs.js"),s=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),l=t("./src/utils/generic.js"),u=t("./src/utils/core.js"),d=t("./src/utils/hub.js"),f=t("./src/utils/constants.js"),m=t("./src/generation/logits_process.js"),h=t("./src/generation/configuration_utils.js"),_=t("./src/utils/tensor.js"),g=t("./src/utils/image.js"),y=t("./src/utils/maths.js"),b=t("./src/generation/stopping_criteria.js"),T=t("./src/generation/logits_sampler.js"),v=t("./src/env.js"),x=t("./src/models/whisper/generation_whisper.js"),P=t("./src/models/whisper/common_whisper.js");const w={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},C=new Map,E=new Map,A=new Map;async function L(k,N,he){let Re=he.config?.["transformers.js_config"]??{},Ve=he.device??Re.device;Ve&&typeof Ve!="string"&&(Ve.hasOwnProperty(N)?Ve=Ve[N]:(console.warn(`device not specified for "${N}". Using the default device.`),Ve=null));const Ye=Ve??(v.apis.IS_NODE_ENV?"cpu":"wasm"),ht=(0,s.deviceToExecutionProviders)(Ye),xt=Re.device_config??{};xt.hasOwnProperty(Ye)&&(Re={...Re,...xt[Ye]});let Et=he.dtype??Re.dtype;if(typeof Et!="string"&&(Et&&Et.hasOwnProperty(N)?Et=Et[N]:(Et=o.DEFAULT_DEVICE_DTYPE_MAPPING[Ye]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${N}". Using the default dtype (${Et}) for this device (${Ye}).`))),Et===o.DATA_TYPES.auto){let Tn=Re.dtype;typeof Tn!="string"&&(Tn=Tn?.[N]),Tn&&Tn!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(Tn)?Et=Tn:Et=o.DEFAULT_DEVICE_DTYPE_MAPPING[Ye]??o.DATA_TYPES.fp32}const $t=Et;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty($t)){if($t===o.DATA_TYPES.fp16&&Ye==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${Ye}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${$t}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const pn=Re.kv_cache_dtype,vn=pn?typeof pn=="string"?pn:pn[$t]??"float32":void 0;if(vn&&!["float32","float16"].includes(vn))throw new Error(`Invalid kv_cache_dtype: ${vn}. Should be one of: float32, float16`);const Kt={dtype:$t,kv_cache_dtype:vn},Vt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[$t],$n=`${N}${Vt}.onnx`,on=`${he.subfolder??""}/${$n}`,Qt={...he.session_options};Qt.executionProviders??=ht;const Wn=Re.free_dimension_overrides;Wn?Qt.freeDimensionOverrides??=Wn:Ye.startsWith("webnn")&&!Qt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${Ye}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const fi=v.apis.IS_NODE_ENV&&v.env.useFSCache,Ni=(0,d.getModelFile)(k,on,!0,he,fi),Bi=he.use_external_data_format??Re.use_external_data_format;let Hi=[];if(Bi){let Tn;typeof Bi=="object"?Bi.hasOwnProperty($n)?Tn=Bi[$n]:Bi.hasOwnProperty(N)?Tn=Bi[N]:Tn=!1:Tn=Bi;const Ei=+Tn;if(Ei>d.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Ei}) exceeds the maximum allowed value (${d.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let tr=0;tr{const ul=await(0,d.getModelFile)(k,kr,!0,he,fi);Nr(ul instanceof Uint8Array?{path:cl,data:ul}:cl)}))}}else Qt.externalData!==void 0&&(Hi=Qt.externalData.map(async Tn=>{if(typeof Tn.data=="string"){const Ei=await(0,d.getModelFile)(k,Tn.data,!0,he);return{...Tn,data:Ei}}return Tn}));if(Hi.length>0){const Tn=await Promise.all(Hi);v.apis.IS_NODE_ENV||(Qt.externalData=Tn)}if(Ye==="webgpu"){const Tn=(0,i.getKeyValueShapes)(he.config,{prefix:"present"});if(Object.keys(Tn).length>0&&!(0,s.isONNXProxy)()){const Ei={};for(const tr in Tn)Ei[tr]="gpu-buffer";Qt.preferredOutputLocation=Ei}}return{buffer_or_path:await Ni,session_options:Qt,session_config:Kt}}async function I(k,N,he){return Object.fromEntries(await Promise.all(Object.keys(N).map(async Re=>{const{buffer_or_path:Ve,session_options:Ye,session_config:ht}=await L(k,N[Re],he),xt=await(0,s.createInferenceSession)(Ve,Ye,ht);return[Re,xt]})))}async function O(k,N,he){return Object.fromEntries(await Promise.all(Object.keys(N).map(async Re=>{const Ve=await(0,d.getModelJSON)(k,N[Re],!1,he);return[Re,Ve]})))}function H(k,N){const he=Object.create(null),Re=[];for(const ht of k.inputNames){const xt=N[ht];if(!(xt instanceof _.Tensor)){Re.push(ht);continue}he[ht]=(0,s.isONNXProxy)()?xt.clone():xt}if(Re.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Re.join(", ")}.`);const Ve=Object.keys(N).length,Ye=k.inputNames.length;if(Ve>Ye){let ht=Object.keys(N).filter(xt=>!k.inputNames.includes(xt));console.warn(`WARNING: Too many inputs were provided (${Ve} > ${Ye}). The following inputs will be ignored: "${ht.join(", ")}".`)}return he}async function Z(k,N){const he=H(k,N);try{const Re=Object.fromEntries(Object.entries(he).map(([Ye,ht])=>[Ye,ht.ort_tensor]));let Ve=await k.run(Re);return Ve=$(Ve),Ve}catch(Re){const Ve=Object.fromEntries(Object.entries(he).map(([Ye,{type:ht,dims:xt,data:Et}])=>[Ye,{type:ht,dims:xt,data:Et}]));throw console.error(`An error occurred during model execution: "${Re}".`),console.error("Inputs given to model:",Ve),Re}}function $(k){for(let N in k)(0,s.isONNXTensor)(k[N])?k[N]=new _.Tensor(k[N]):typeof k[N]=="object"&&$(k[N]);return k}function J(k){if(k instanceof _.Tensor)return k;if(k.length===0)throw Error("items must be non-empty");if(Array.isArray(k[0])){if(k.some(N=>N.length!==k[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new _.Tensor("int64",BigInt64Array.from(k.flat().map(N=>BigInt(N))),[k.length,k[0].length])}else return new _.Tensor("int64",BigInt64Array.from(k.map(N=>BigInt(N))),[1,k.length])}function ee(k){return new _.Tensor("bool",[k],[1])}async function X(k,N){let{encoder_outputs:he,input_ids:Re,decoder_input_ids:Ve,...Ye}=N;if(!he){const xt=(0,u.pick)(N,k.sessions.model.inputNames);he=(await ne(k,xt)).last_hidden_state}return Ye.input_ids=Ve,Ye.encoder_hidden_states=he,k.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Ye.encoder_attention_mask=N.attention_mask),await oe(k,Ye,!0)}async function ne(k,N){const he=k.sessions.model,Re=(0,u.pick)(N,he.inputNames);if(he.inputNames.includes("inputs_embeds")&&!Re.inputs_embeds){if(!N.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Re.inputs_embeds=await k.encode_text({input_ids:N.input_ids})}if(he.inputNames.includes("token_type_ids")&&!Re.token_type_ids){if(!Re.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");Re.token_type_ids=(0,_.zeros_like)(Re.input_ids)}if(he.inputNames.includes("pixel_mask")&&!Re.pixel_mask){if(!Re.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Ve=Re.pixel_values.dims;Re.pixel_mask=(0,_.ones)([Ve[0],Ve[2],Ve[3]])}return await Z(he,Re)}async function Q(k,N){const he=await k.encode(N);return await k.decode(he)}async function oe(k,N,he=!1){const Re=k.sessions[he?"decoder_model_merged":"model"],{past_key_values:Ve,...Ye}=N;if(Re.inputNames.includes("use_cache_branch")&&(Ye.use_cache_branch=ee(!!Ve)),Re.inputNames.includes("position_ids")&&Ye.attention_mask&&!Ye.position_ids){const xt=["paligemma","gemma3_text","gemma3"].includes(k.config.model_type)?1:0;Ye.position_ids=me(Ye,Ve,xt)}k.addPastKeyValues(Ye,Ve);const ht=(0,u.pick)(Ye,Re.inputNames);return await Z(Re,ht)}function W({modality_token_id:k,inputs_embeds:N,modality_features:he,input_ids:Re,attention_mask:Ve}){const Ye=Re.tolist().map($t=>$t.reduce((pn,vn,Kt)=>(vn==k&&pn.push(Kt),pn),[])),ht=Ye.reduce(($t,pn)=>$t+pn.length,0),xt=he.dims[0];if(ht!==xt)throw new Error(`Number of tokens and features do not match: tokens: ${ht}, features ${xt}`);let Et=0;for(let $t=0;$tYe.dims[1])){if(Vext==k.config.image_token_index)){const xt=k.config.num_image_tokens;if(!xt)throw new Error("`num_image_tokens` is missing in the model configuration.");const Et=Ye.dims[1]-(Ve-xt);he.input_ids=Ye.slice(null,[-Et,null]),he.attention_mask=(0,_.ones)([1,Ve+Et])}}}return he}function ze(k,N,he,Re){return he.past_key_values&&(N=N.map(Ve=>[Ve.at(-1)])),{...he,decoder_input_ids:J(N)}}function Me(k,...N){return k.config.is_encoder_decoder?ze(k,...N):xe(k,...N)}function ce(k,N,he,Re){const Ve=!!he.past_key_values;return Re.guidance_scale!==null&&Re.guidance_scale>1&&(Ve?he.input_ids=(0,_.cat)([he.input_ids,he.input_ids],0):(he.input_ids=(0,_.cat)([he.input_ids,(0,_.full_like)(he.input_ids,BigInt(Re.pad_token_id))],0),he.attention_mask=(0,_.cat)([he.attention_mask,(0,_.full_like)(he.attention_mask,0n)],0))),(Ve||!he.pixel_values)&&(he.pixel_values=(0,_.full)([0,0,3,384,384],1)),Ve&&(he.images_seq_mask=new _.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),he.images_emb_mask=new _.Tensor("bool",new Array(0).fill(!1),[1,1,0])),he}class ae extends l.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(N,he,Re){super(),this.config=N,this.sessions=he,this.configs=Re;const Ve=A.get(this.constructor),Ye=C.get(Ve);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ye){case w.DecoderOnly:this.can_generate=!0,this._forward=oe,this._prepare_inputs_for_generation=xe;break;case w.Seq2Seq:case w.Vision2Seq:case w.Musicgen:this.can_generate=!0,this._forward=X,this._prepare_inputs_for_generation=ze;break;case w.EncoderDecoder:this._forward=X;break;case w.ImageTextToText:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=Me;break;case w.AudioTextToText:this.can_generate=!0,this._forward=B,this._prepare_inputs_for_generation=Me;break;case w.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Me;break;case w.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=ce;break;case w.AutoEncoder:this._forward=Q;break;default:this._forward=ne;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const N=[];for(const he of Object.values(this.sessions))he?.handler?.dispose&&N.push(he.handler.dispose());return await Promise.all(N)}static async from_pretrained(N,{progress_callback:he=null,config:Re=null,cache_dir:Ve=null,local_files_only:Ye=!1,revision:ht="main",model_file_name:xt=null,subfolder:Et="onnx",device:$t=null,dtype:pn=null,use_external_data_format:vn=null,session_options:Kt={}}={}){let Vt={progress_callback:he,config:Re,cache_dir:Ve,local_files_only:Ye,revision:ht,model_file_name:xt,subfolder:Et,device:$t,dtype:pn,use_external_data_format:vn,session_options:Kt};const $n=A.get(this),on=C.get($n);Re=Vt.config=await i.AutoConfig.from_pretrained(N,Vt);let Qt;if(on===w.DecoderOnly)Qt=await Promise.all([I(N,{model:Vt.model_file_name??"model"},Vt),O(N,{generation_config:"generation_config.json"},Vt)]);else if(on===w.Seq2Seq||on===w.Vision2Seq)Qt=await Promise.all([I(N,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Vt),O(N,{generation_config:"generation_config.json"},Vt)]);else if(on===w.MaskGeneration)Qt=await Promise.all([I(N,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},Vt)]);else if(on===w.EncoderDecoder)Qt=await Promise.all([I(N,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},Vt)]);else if(on===w.ImageTextToText){const Wn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Re.is_encoder_decoder&&(Wn.model="encoder_model"),Qt=await Promise.all([I(N,Wn,Vt),O(N,{generation_config:"generation_config.json"},Vt)])}else if(on===w.AudioTextToText){const Wn={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};Qt=await Promise.all([I(N,Wn,Vt),O(N,{generation_config:"generation_config.json"},Vt)])}else if(on===w.Musicgen)Qt=await Promise.all([I(N,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},Vt),O(N,{generation_config:"generation_config.json"},Vt)]);else if(on===w.MultiModality)Qt=await Promise.all([I(N,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},Vt),O(N,{generation_config:"generation_config.json"},Vt)]);else if(on===w.Phi3V)Qt=await Promise.all([I(N,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},Vt),O(N,{generation_config:"generation_config.json"},Vt)]);else if(on===w.AutoEncoder)Qt=await Promise.all([I(N,{encoder_model:"encoder_model",decoder_model:"decoder_model"},Vt)]);else{if(on!==w.EncoderOnly){const Wn=$n??Re?.model_type;Wn!=="custom"&&console.warn(`Model type for '${Wn}' not found, assuming encoder-only architecture. Please report this at ${f.GITHUB_ISSUE_URL}.`)}Qt=await Promise.all([I(N,{model:Vt.model_file_name??"model"},Vt)])}return new this(Re,...Qt)}async _call(N){return await this.forward(N)}async forward(N){return await this._forward(this,N)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(N){const he=new m.LogitsProcessorList;return N.temperature!==null&&N.temperature!==1&&he.push(new m.TemperatureLogitsWarper(N.temperature)),N.top_k!==null&&N.top_k!==0&&he.push(new m.TopKLogitsWarper(N.top_k)),N.top_p!==null&&N.top_p<1&&he.push(new m.TopPLogitsWarper(N.top_p)),he}_get_logits_processor(N,he,Re=null){const Ve=new m.LogitsProcessorList;if(N.repetition_penalty!==null&&N.repetition_penalty!==1&&Ve.push(new m.RepetitionPenaltyLogitsProcessor(N.repetition_penalty)),N.no_repeat_ngram_size!==null&&N.no_repeat_ngram_size>0&&Ve.push(new m.NoRepeatNGramLogitsProcessor(N.no_repeat_ngram_size)),N.bad_words_ids!==null&&Ve.push(new m.NoBadWordsLogitsProcessor(N.bad_words_ids,N.eos_token_id)),N.min_length!==null&&N.eos_token_id!==null&&N.min_length>0&&Ve.push(new m.MinLengthLogitsProcessor(N.min_length,N.eos_token_id)),N.min_new_tokens!==null&&N.eos_token_id!==null&&N.min_new_tokens>0&&Ve.push(new m.MinNewTokensLengthLogitsProcessor(he,N.min_new_tokens,N.eos_token_id)),N.forced_bos_token_id!==null&&Ve.push(new m.ForcedBOSTokenLogitsProcessor(N.forced_bos_token_id)),N.forced_eos_token_id!==null&&Ve.push(new m.ForcedEOSTokenLogitsProcessor(N.max_length,N.forced_eos_token_id)),N.begin_suppress_tokens!==null){const Ye=he>1||N.forced_bos_token_id===null?he:he+1;Ve.push(new m.SuppressTokensAtBeginLogitsProcessor(N.begin_suppress_tokens,Ye))}return N.guidance_scale!==null&&N.guidance_scale>1&&Ve.push(new m.ClassifierFreeGuidanceLogitsProcessor(N.guidance_scale)),Re!==null&&Ve.extend(Re),Ve}_prepare_generation_config(N,he,Re=h.GenerationConfig){const Ve={...this.config};for(const ht of["decoder","generator","text_config"])ht in Ve&&Object.assign(Ve,Ve[ht]);const Ye=new Re(Ve);return Object.assign(Ye,this.generation_config??{}),N&&Object.assign(Ye,N),he&&Object.assign(Ye,(0,u.pick)(he,Object.getOwnPropertyNames(Ye))),Ye}_get_stopping_criteria(N,he=null){const Re=new b.StoppingCriteriaList;return N.max_length!==null&&Re.push(new b.MaxLengthCriteria(N.max_length,this.config.max_position_embeddings??null)),N.eos_token_id!==null&&Re.push(new b.EosTokenCriteria(N.eos_token_id)),he&&Re.extend(he),Re}_validate_model_class(){if(!this.can_generate){const N=[Lu,nl,Ou,na],he=A.get(this.constructor),Re=new Set,Ve=this.config.model_type;for(const ht of N){const xt=ht.get(Ve);xt&&Re.add(xt[0])}let Ye=`The current model class (${he}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Re.size>0&&(Ye+=` Please use the following class instead: ${[...Re].join(", ")}`),Error(Ye)}}prepare_inputs_for_generation(...N){return this._prepare_inputs_for_generation(this,...N)}_update_model_kwargs_for_generation({generated_input_ids:N,outputs:he,model_inputs:Re,is_encoder_decoder:Ve}){return Re.past_key_values=this.getPastKeyValues(he,Re.past_key_values),Re.input_ids=new _.Tensor("int64",N.flat(),[N.length,1]),Ve||(Re.attention_mask=(0,_.cat)([Re.attention_mask,(0,_.ones)([Re.attention_mask.dims[0],1])],1)),Re.position_ids=null,Re}_prepare_model_inputs({inputs:N,bos_token_id:he,model_kwargs:Re}){const Ve=(0,u.pick)(Re,this.forward_params),Ye=this.main_input_name;if(Ye in Ve){if(N)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Ve[Ye]=N;return{inputs_tensor:Ve[Ye],model_inputs:Ve,model_input_name:Ye}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:N,model_inputs:he,model_input_name:Re,generation_config:Ve}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!he.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:ht,pixel_values:xt,attention_mask:Et,...$t}=he,pn=await this._prepare_inputs_embeds(he);he={...$t,...(0,u.pick)(pn,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ye}=await ne(this,he);if(Ve.guidance_scale!==null&&Ve.guidance_scale>1)Ye=(0,_.cat)([Ye,(0,_.full_like)(Ye,0)],0),"attention_mask"in he&&(he.attention_mask=(0,_.cat)([he.attention_mask,(0,_.zeros_like)(he.attention_mask)],0));else if(he.decoder_input_ids){const ht=J(he.decoder_input_ids).dims[0];if(ht!==Ye.dims[0]){if(Ye.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ye.dims[0]}) than the decoder inputs (${ht}).`);Ye=(0,_.cat)(Array.from({length:ht},()=>Ye),0)}}return he.encoder_outputs=Ye,he}_prepare_decoder_input_ids_for_generation({batch_size:N,model_input_name:he,model_kwargs:Re,decoder_start_token_id:Ve,bos_token_id:Ye,generation_config:ht}){let{decoder_input_ids:xt,...Et}=Re;if(!(xt instanceof _.Tensor)){if(xt)Array.isArray(xt[0])||(xt=Array.from({length:N},()=>xt));else if(Ve??=Ye,this.config.model_type==="musicgen")xt=Array.from({length:N*this.config.decoder.num_codebooks},()=>[Ve]);else if(Array.isArray(Ve)){if(Ve.length!==N)throw new Error(`\`decoder_start_token_id\` expcted to have length ${N} but got ${Ve.length}`);xt=Ve}else xt=Array.from({length:N},()=>[Ve]);xt=J(xt)}return Re.decoder_attention_mask=(0,_.ones_like)(xt),{input_ids:xt,model_inputs:Et}}async generate({inputs:N=null,generation_config:he=null,logits_processor:Re=null,stopping_criteria:Ve=null,streamer:Ye=null,...ht}){this._validate_model_class(),he=this._prepare_generation_config(he,ht);let{inputs_tensor:xt,model_inputs:Et,model_input_name:$t}=this._prepare_model_inputs({inputs:N,model_kwargs:ht});const pn=this.config.is_encoder_decoder;pn&&("encoder_outputs"in Et||(Et=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:xt,model_inputs:Et,model_input_name:$t,generation_config:he})));let vn;pn?{input_ids:vn,model_inputs:Et}=this._prepare_decoder_input_ids_for_generation({batch_size:Et[$t].dims.at(0),model_input_name:$t,model_kwargs:Et,decoder_start_token_id:he.decoder_start_token_id,bos_token_id:he.bos_token_id,generation_config:he}):vn=Et[$t];let Kt=vn.dims.at(-1);he.max_new_tokens!==null&&(he.max_length=Kt+he.max_new_tokens);const Vt=this._get_logits_processor(he,Kt,Re),$n=this._get_stopping_criteria(he,Ve),on=Et[$t].dims.at(0),Qt=T.LogitsSampler.getSampler(he),Wn=new Array(on).fill(0),fi=vn.tolist();Ye&&Ye.put(fi);let Ni,Bi={};for(;;){if(Et=this.prepare_inputs_for_generation(fi,Et,he),Ni=await this.forward(Et),he.output_attentions&&he.return_dict_in_generate){const kr=this.getAttentions(Ni);for(const Nr in kr)Nr in Bi||(Bi[Nr]=[]),Bi[Nr].push(kr[Nr])}const Tn=Ni.logits.slice(null,-1,null),Ei=Vt(fi,Tn),tr=[];for(let kr=0;krkr))break;Et=this._update_model_kwargs_for_generation({generated_input_ids:tr,outputs:Ni,model_inputs:Et,is_encoder_decoder:pn})}Ye&&Ye.end();const Hi=this.getPastKeyValues(Ni,Et.past_key_values,!0),$i=new _.Tensor("int64",fi.flat(),[fi.length,fi[0].length]);if(he.return_dict_in_generate)return{sequences:$i,past_key_values:Hi,...Bi};for(const Tn of Object.values(Ni))Tn.location==="gpu-buffer"&&Tn.dispose();return $i}getPastKeyValues(N,he,Re=!1){const Ve=Object.create(null);for(const Ye in N)if(Ye.startsWith("present")){const ht=Ye.replace("present","past_key_values"),xt=Ye.includes("encoder");if(xt&&he?Ve[ht]=he[ht]:Ve[ht]=N[Ye],he&&(!xt||Re)){const Et=he[ht];Et.location==="gpu-buffer"&&Et.dispose()}}return Ve}getAttentions(N){const he={};for(const Re of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Ve in N)Ve.startsWith(Re)&&(Re in he||(he[Re]=[]),he[Re].push(N[Ve]));return he}addPastKeyValues(N,he){if(he)Object.assign(N,he);else{const Ve=(this.sessions.decoder_model_merged??this.sessions.model)?.config?.kv_cache_dtype??"float32",Ye=Ve==="float16"?new _.DataTypeMap.float16:[],ht=(N[this.main_input_name]??N.attention_mask)?.dims?.[0]??1,xt=(0,i.getKeyValueShapes)(this.config,{batch_size:ht});for(const Et in xt)N[Et]=new _.Tensor(Ve,Ye,xt[Et])}}async encode_image({pixel_values:N}){const he=(await Z(this.sessions.vision_encoder,{pixel_values:N})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${he.dims[1]}).`),this.config.num_image_tokens=he.dims[1]),he}async encode_text({input_ids:N}){return(await Z(this.sessions.embed_tokens,{input_ids:N})).inputs_embeds}async encode_audio({audio_values:N}){return(await Z(this.sessions.audio_encoder,{audio_values:N})).audio_features}}class we{}class re extends we{constructor({last_hidden_state:N,hidden_states:he=null,attentions:Re=null}){super(),this.last_hidden_state=N,this.hidden_states=he,this.attentions=Re}}class He extends ae{}class Ne extends He{}class We extends He{async _call(N){return new ur(await super._call(N))}}class ke extends He{async _call(N){return new _n(await super._call(N))}}class st extends He{async _call(N){return new Wi(await super._call(N))}}class Ke extends He{async _call(N){return new br(await super._call(N))}}class F extends ae{}class U extends F{}class j extends F{async _call(N){return new ur(await super._call(N))}}class se extends F{async _call(N){return new _n(await super._call(N))}}class _e extends F{async _call(N){return new Wi(await super._call(N))}}class ge extends ae{}class Ce extends ge{}class Ie extends ae{}class Ee extends Ie{}class je extends Ie{async _call(N){return new ur(await super._call(N))}}class Qe extends Ie{async _call(N){return new _n(await super._call(N))}}class ot extends Ie{async _call(N){return new Wi(await super._call(N))}}class bt extends Ie{async _call(N){return new br(await super._call(N))}}class _t extends ae{}class nt extends _t{}class ft extends _t{async _call(N){return new ur(await super._call(N))}}class vt extends _t{async _call(N){return new _n(await super._call(N))}}class mn extends _t{async _call(N){return new Wi(await super._call(N))}}class Se extends _t{async _call(N){return new br(await super._call(N))}}class St extends ae{}class Ze extends St{}class it extends St{async _call(N){return new ur(await super._call(N))}}class yt extends St{async _call(N){return new _n(await super._call(N))}}class tt extends St{async _call(N){return new Wi(await super._call(N))}}class gt extends St{async _call(N){return new br(await super._call(N))}}class Pt extends ae{}class tn extends Pt{}class rn extends Pt{async _call(N){return new ur(await super._call(N))}}class Pn extends Pt{async _call(N){return new _n(await super._call(N))}}class ln extends Pt{async _call(N){return new Wi(await super._call(N))}}class vi extends Pt{async _call(N){return new br(await super._call(N))}}class On extends ae{}class ut extends On{}class It extends On{async _call(N){return new ur(await super._call(N))}}class Bt extends On{async _call(N){return new _n(await super._call(N))}}class Vi extends On{async _call(N){return new Wi(await super._call(N))}}class rr extends On{async _call(N){return new br(await super._call(N))}}class ri extends ae{}class Ti extends ri{}class Er extends ri{async _call(N){return new ur(await super._call(N))}}class zr extends ri{async _call(N){return new _n(await super._call(N))}}class Ns extends ri{async _call(N){return new Wi(await super._call(N))}}class Sr extends ri{async _call(N){return new br(await super._call(N))}}class Ur extends ae{}class Ii extends Ur{}class Yr extends Ur{async _call(N){return new _n(await super._call(N))}}class vr extends Ur{async _call(N){return new Wi(await super._call(N))}}class ue extends Ur{async _call(N){return new br(await super._call(N))}}class Oe extends Ur{async _call(N){return new ur(await super._call(N))}}class qe extends ae{}class Ue extends qe{}class Fe extends qe{async _call(N){return new ur(await super._call(N))}}class wt extends qe{async _call(N){return new _n(await super._call(N))}}class Ct extends qe{async _call(N){return new Wi(await super._call(N))}}class Nt extends ae{}class Rt extends Nt{}class qt extends Nt{async _call(N){return new ur(await super._call(N))}}class sn extends Nt{async _call(N){return new _n(await super._call(N))}}class Jt extends Nt{async _call(N){return new br(await super._call(N))}}class yn extends ae{}class Sn extends yn{}class Jn extends yn{async _call(N){return new ur(await super._call(N))}}class Ln extends yn{async _call(N){return new _n(await super._call(N))}}class dn extends yn{async _call(N){return new Wi(await super._call(N))}}class nn extends yn{async _call(N){return new br(await super._call(N))}}class li extends ae{}class An extends li{}class sr extends li{async _call(N){return new ur(await super._call(N))}}class yr extends li{async _call(N){return new _n(await super._call(N))}}class Xi extends li{async _call(N){return new br(await super._call(N))}}class yi extends ae{}class Kn extends yi{}class Pe extends yi{async _call(N){return new _n(await super._call(N))}}class V extends yi{async _call(N){return new br(await super._call(N))}}class fe extends yi{async _call(N){return new ur(await super._call(N))}}class ve extends ae{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Te extends ve{}class Be extends ve{}class lt extends ae{}class Ot extends lt{}class Lt extends lt{}class Ft extends ae{}class Dt extends Ft{}class Cn extends Ft{}class cn extends ae{}class pi extends cn{}class Gi extends cn{}class ci extends cn{async _call(N){return new _n(await super._call(N))}}class ui extends ae{}class mi extends ui{}class Oi extends ui{}class ys extends ui{async _call(N){return new _n(await super._call(N))}}class Li extends ui{}class Br extends ae{}class ei extends Br{}class Mi extends Br{}class Ki extends ae{}class Or extends Ki{}class Qr extends Ki{}class Ci extends ae{}class pr extends Ci{}class Yi extends Ci{async _call(N){return new ur(await super._call(N))}}class Bn extends Ci{async _call(N){return new _n(await super._call(N))}}class ti extends Ci{async _call(N){return new Wi(await super._call(N))}}class Pi extends Ci{async _call(N){return new br(await super._call(N))}}class Fi extends ae{}class Ya extends Fi{}class Qa extends Fi{async _call(N){return new ur(await super._call(N))}}class Rl extends Fi{async _call(N){return new _n(await super._call(N))}}class ha extends Fi{async _call(N){return new Wi(await super._call(N))}}class Do extends Fi{async _call(N){return new br(await super._call(N))}}class pa extends ae{}class pd extends pa{}class md extends pa{async _call(N){return new ur(await super._call(N))}}class _d extends pa{async _call(N){return new _n(await super._call(N))}}class Dl extends pa{async _call(N){return new Wi(await super._call(N))}}class gd extends pa{async _call(N){return new br(await super._call(N))}}class $c extends ae{}class vd extends $c{}class yd extends $c{}class Vc extends ae{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Gc extends Vc{}class Il extends Vc{_prepare_generation_config(N,he){return super._prepare_generation_config(N,he,x.WhisperGenerationConfig)}_retrieve_init_tokens(N){const he=[N.decoder_start_token_id];let Re=N.language;const Ve=N.task;if(N.is_multilingual){Re||(console.warn("No language specified - defaulting to English (en)."),Re="en");const ht=`<|${(0,P.whisper_language_to_code)(Re)}|>`;he.push(N.lang_to_id[ht]),he.push(N.task_to_id[Ve??"transcribe"])}else if(Re||Ve)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!N.return_timestamps&&N.no_timestamps_token_id&&he.at(-1)!==N.no_timestamps_token_id?he.push(N.no_timestamps_token_id):N.return_timestamps&&he.at(-1)===N.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),he.pop()),he.filter(Ye=>Ye!=null)}async generate({inputs:N=null,generation_config:he=null,logits_processor:Re=null,stopping_criteria:Ve=null,...Ye}){he=this._prepare_generation_config(he,Ye);const ht=Ye.decoder_input_ids??this._retrieve_init_tokens(he);if(he.return_timestamps&&(Re??=new m.LogitsProcessorList,Re.push(new m.WhisperTimeStampLogitsProcessor(he,ht))),he.begin_suppress_tokens&&(Re??=new m.LogitsProcessorList,Re.push(new m.SuppressTokensAtBeginLogitsProcessor(he.begin_suppress_tokens,ht.length))),he.return_token_timestamps){if(!he.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");he.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),he.output_attentions=!0,he.return_dict_in_generate=!0}const xt=await super.generate({inputs:N,generation_config:he,logits_processor:Re,decoder_input_ids:ht,...Ye});return he.return_token_timestamps&&(xt.token_timestamps=this._extract_token_timestamps(xt,he.alignment_heads,he.num_frames)),xt}_extract_token_timestamps(N,he,Re=null,Ve=.02){if(!N.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");Re==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let Ye=this.config.median_filter_width;Ye===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Ye=7);const ht=N.cross_attentions,xt=Array.from({length:this.config.decoder_layers},(on,Qt)=>(0,_.cat)(ht.map(Wn=>Wn[Qt]),2)),Et=(0,_.stack)(he.map(([on,Qt])=>{if(on>=xt.length)throw new Error(`Layer index ${on} is out of bounds for cross attentions (length ${xt.length}).`);return Re?xt[on].slice(null,Qt,null,[0,Re]):xt[on].slice(null,Qt)})).transpose(1,0,2,3),[$t,pn]=(0,_.std_mean)(Et,-2,0,!0),vn=Et.clone();for(let on=0;onWn[Tn+1]-Wn[Tn]),Bi=(0,u.mergeArrays)([1],Ni).map($i=>!!$i),Hi=[];for(let $i=0;$iKt.findIndex(Vt=>Vt==Ye)),Et=xt.every(Kt=>Kt===-1),$t=xt.every(Kt=>Kt!==-1);if(!Et&&!$t)throw new Error("Every input should contain either 0 or 1 image token.");if(Et)return{inputs_embeds:N,attention_mask:Ve};const pn=[],vn=[];for(let Kt=0;KtArray.from({length:N.dims[0]},Ni=>Array.from({length:N.dims[1]},Bi=>1))),$n=he?he.tolist():[],on=Re?Re.tolist():[];let Qt=0,Wn=0;for(let fi=0;fiKt[fi][nr]==1),Hi=Ni.reduce((gi,nr,ra)=>(nr==Et&&gi.push(ra),gi),[]).map(gi=>Ni[gi+1]),$i=Hi.filter(gi=>gi==ht).length,Tn=Hi.filter(gi=>gi==xt).length;let Ei=[],tr=0,cl=$i,kr=Tn;for(let gi=0;gips>tr&&Eo==ht),ra=Ni.findIndex((Eo,ps)=>ps>tr&&Eo==xt),As=cl>0&&nr!==-1?nr:Ni.length+1,Ra=kr>0&&ra!==-1?ra:Ni.length+1;let Da,Df,lm,cm;As0?(0,y.max)(Ei.at(-1))[0]+1:0;Ei.push(Array.from({length:3*si},(Eo,ps)=>Of+ps%si));const dr=si+Of,Lf=L_*If*fl,um=Array.from({length:Lf},(Eo,ps)=>dr+Math.floor(ps/(If*fl))),dm=Array.from({length:Lf},(Eo,ps)=>dr+Math.floor(ps/fl)%If),Ff=Array.from({length:Lf},(Eo,ps)=>dr+ps%fl);Ei.push([um,dm,Ff].flat()),tr=Da+Lf}if(tr0?(0,y.max)(Ei.at(-1))[0]+1:0,nr=Ni.length-tr;Ei.push(Array.from({length:3*nr},(ra,As)=>gi+As%nr))}const Nr=Ei.reduce((gi,nr)=>gi+nr.length,0),vc=new Array(Nr);let ul=0;for(let gi=0;gi<3;++gi)for(let nr=0;nrvn[Qt%vn.length]),$n=Array.from({length:Kt[0]},(on,Qt)=>(0,y.max)(vn.subarray(Kt[1]*Qt,Kt[1]*(Qt+1)))[0]+1n+BigInt(Kt[1]));return[new _.Tensor("int64",Vt,[3,...Kt]),new _.Tensor("int64",$n,[$n.length,1])]}else{const[vn,Kt]=N.dims,Vt=BigInt64Array.from({length:3*vn*Kt},($n,on)=>BigInt(Math.floor(on%Kt/vn)));return[new _.Tensor("int64",Vt,[3,...N.dims]),(0,_.zeros)([vn,1])]}}async encode_image({pixel_values:N,image_grid_thw:he}){return(await Z(this.sessions.vision_encoder,{pixel_values:N,grid_thw:he})).image_features}_merge_input_ids_with_image_features(N){return q({image_token_id:this.config.image_token_id,...N})}prepare_inputs_for_generation(N,he,Re){if(he.attention_mask&&!he.position_ids)if(!he.past_key_values)[he.position_ids,he.rope_deltas]=this.get_rope_index(he.input_ids,he.image_grid_thw,he.video_grid_thw,he.attention_mask);else{he.pixel_values=null;const Ve=BigInt(Object.values(he.past_key_values)[0].dims.at(-2)),Ye=he.rope_deltas.map(ht=>Ve+ht);he.position_ids=(0,_.stack)([Ye,Ye,Ye],0)}return he}}class lr extends ae{}class Yn extends lr{}class us extends lr{}class ds extends ae{}class Id extends ds{}class oo extends ds{}class Od extends ae{}class Ch extends Od{}class Hl extends Od{}class Vo extends ae{}class ql extends Vo{}class Xl extends Vo{}class Ld extends ae{}class Fd extends Ld{}class Ph extends Ld{}class Kl extends ae{}class Rh extends Kl{}class Yl extends Kl{async _call(N){return new _n(await super._call(N))}}class kd extends ae{}class Go extends kd{}class Ql extends kd{async _call(N){return new _n(await super._call(N))}}class su extends ae{}class Zl extends su{}class Jl extends ae{}class Dh extends Jl{}class Ih extends Jl{async _call(N){return new _n(await super._call(N))}}class lo extends ae{}class Oh extends lo{}class co extends ae{}class au extends co{}class Lh extends co{async _call(N){return new _n(await super._call(N))}}class Nd extends ae{}class zd extends Nd{}class Vr extends ae{}class bs extends Vr{}class ba extends Vr{async _call(N){return new _n(await super._call(N))}}class Fh extends ae{}class xa extends Fh{async _call(N){return new ll(await super._call(N))}}class xs extends ae{}class ar extends xs{}class ou extends xs{async _call(N){return new _n(await super._call(N))}}class kh extends ae{}class a_ extends kh{}class o_ extends kh{async _call(N){return new _n(await super._call(N))}}class Qi extends ae{}class Ud extends Qi{}class ec extends Qi{}class jo extends ae{}class Bd extends jo{}class Wo extends jo{}class uo extends ae{}class l_ extends uo{}class Nh extends uo{async _call(N){return new _n(await super._call(N))}}class $d extends ae{}class zh extends $d{}class fo extends $d{async _call(N){return new tc(await super._call(N))}}class lu extends $d{async _call(N){return new Uh(await super._call(N))}}class tc extends we{constructor({logits:N,pred_boxes:he}){super(),this.logits=N,this.pred_boxes=he}}class Uh extends we{constructor({logits:N,pred_boxes:he,pred_masks:Re}){super(),this.logits=N,this.pred_boxes=he,this.pred_masks=Re}}class Hs extends ae{}class Rn extends Hs{}class di extends Hs{async _call(N){return new zi(await super._call(N))}}class zi extends we{constructor({logits:N,pred_boxes:he}){super(),this.logits=N,this.pred_boxes=he}}class nc extends ae{}class Ho extends nc{}class ho extends nc{async _call(N){return new cu(await super._call(N))}}class cu extends zi{}class qo extends ae{}class Xo extends qo{}class c_ extends qo{async _call(N){return new ji(await super._call(N))}}class ji extends zi{}class uu extends ae{}class Vd extends uu{}class Bh extends uu{async _call(N){return new $h(await super._call(N))}}class $h extends tc{}class Vh extends ae{}class Gd extends Vh{}class jd extends Vh{async _call(N){return new _n(await super._call(N))}}class du extends ae{}class Lr extends du{}class Zi extends du{async _call(N){return new _n(await super._call(N))}}class ic extends ae{}class rc extends ic{}class fu extends ic{async _call(N){return new _n(await super._call(N))}}class sc extends ae{}class qs extends sc{}class hu extends sc{async _call(N){return new _n(await super._call(N))}}class Wd extends sc{}class pu extends ae{}class Gh extends pu{}class jh extends pu{}class Hd extends ae{}class Wh extends Hd{}class Hh extends Hd{}class qh extends ae{}class qd extends qh{}class mu extends ae{}class u_ extends mu{}class Xh extends mu{}class Kh extends mu{}class Yh extends ae{}class Xd extends Yh{}class Qh extends ae{}class Zh extends Qh{}class Jh extends ae{}class ep extends Jh{}class Kd extends ae{}class d_ extends Kd{}class tp extends Kd{}class po extends ae{}class np extends po{}class _u extends po{}class gu extends ae{}class ip extends gu{}class vu extends ae{}class rp extends vu{}class sp extends vu{async _call(N){return new _n(await super._call(N))}}class Yd extends ae{}class ap extends Yd{}class Qd extends Yd{async _call(N){return new _n(await super._call(N))}}class Zd extends ae{}class op extends Zd{}class Jd extends Zd{async _call(N){return new _n(await super._call(N))}}class ef extends ae{}class lp extends ef{}class f_ extends ef{async _call(N){return new _n(await super._call(N))}}class tf extends ae{}class cp extends tf{}class nf extends ae{}class rf extends nf{}class up extends nf{async _call(N){return new dp(await super._call(N))}}class dp extends we{constructor({logits:N,pred_boxes:he}){super(),this.logits=N,this.pred_boxes=he}}class h_ extends ae{}class p_ extends h_{async get_image_embeddings({pixel_values:N}){return await ne(this,{pixel_values:N})}async forward(N){if((!N.image_embeddings||!N.image_positional_embeddings)&&(N={...N,...await this.get_image_embeddings(N)}),!N.input_labels&&N.input_points){const Re=N.input_points.dims.slice(0,-1),Ve=Re.reduce((Ye,ht)=>Ye*ht,1);N.input_labels=new _.Tensor("int64",new BigInt64Array(Ve).fill(1n),Re)}const he={image_embeddings:N.image_embeddings,image_positional_embeddings:N.image_positional_embeddings};return N.input_points&&(he.input_points=N.input_points),N.input_labels&&(he.input_labels=N.input_labels),N.input_boxes&&(he.input_boxes=N.input_boxes),await Z(this.sessions.prompt_encoder_mask_decoder,he)}async _call(N){return new fp(await super._call(N))}}class fp extends we{constructor({iou_scores:N,pred_masks:he}){super(),this.iou_scores=N,this.pred_masks=he}}class Ko extends ae{}class sf extends Ko{}class yu extends Ko{}class af extends ae{}class hp extends af{}class ws extends af{}class Gr extends ae{}class wa extends Gr{}class mo extends Gr{async _call(N){return new ol(await super._call(N))}}class of extends Gr{async _call(N){return new _n(await super._call(N))}}class lf extends Gr{async _call(N){return new Wi(await super._call(N))}}class cf extends ae{}class pp extends cf{}class _o extends cf{async _call(N){return new Wi(await super._call(N))}}class Mu extends ae{}class mp extends Mu{}class bu extends ae{}class _p extends bu{}class xu extends bu{async _call(N){return new ol(await super._call(N))}}class gp extends bu{async _call(N){return new _n(await super._call(N))}}class Yo extends ae{}class vp extends Yo{}class yp extends Yo{async _call(N){return new ol(await super._call(N))}}class m_ extends Yo{async _call(N){return new _n(await super._call(N))}}class Mp extends Yo{async _call(N){return new Wi(await super._call(N))}}class Ji extends ae{}class _r extends Ji{}class bp extends Ji{async _call(N){return new ol(await super._call(N))}}class xp extends Ji{async _call(N){return new _n(await super._call(N))}}class __ extends ae{}class wp extends Gr{}class Tp extends Gr{async _call(N){return new ol(await super._call(N))}}class ac extends Gr{async _call(N){return new _n(await super._call(N))}}class go extends ae{}class Ep extends go{}class Sp extends go{async _call(N){return new ol(await super._call(N))}}class Ap extends go{async _call(N){return new _n(await super._call(N))}}class uf extends go{async _call(N){return new al(await super._call(N))}}class df extends go{async _call(N){return new Wi(await super._call(N))}}class ff extends ae{}class Cp extends ff{}class oc extends ae{}class Pp extends oc{}class hf extends oc{}class Rp extends oc{async generate_speech(N,he,{threshold:Re=.5,minlenratio:Ve=0,maxlenratio:Ye=20,vocoder:ht=null}={}){const xt={input_ids:N},{encoder_outputs:Et,encoder_attention_mask:$t}=await ne(this,xt),pn=Et.dims[1]/this.config.reduction_factor,vn=Math.floor(pn*Ye),Kt=Math.floor(pn*Ve),Vt=this.config.num_mel_bins;let $n=[],on=null,Qt=null,Wn=0;for(;;){++Wn;const Bi=ee(!!Qt);let Hi;Qt?Hi=Qt.output_sequence_out:Hi=new _.Tensor("float32",new Float32Array(Vt),[1,1,Vt]);let $i={use_cache_branch:Bi,output_sequence:Hi,encoder_attention_mask:$t,speaker_embeddings:he,encoder_hidden_states:Et};this.addPastKeyValues($i,on),Qt=await Z(this.sessions.decoder_model_merged,$i),on=this.getPastKeyValues(Qt,on);const{prob:Tn,spectrum:Ei}=Qt;if($n.push(Ei),Wn>=Kt&&(Array.from(Tn.data).filter(tr=>tr>=Re).length>0||Wn>=vn))break}const fi=(0,_.cat)($n),{waveform:Ni}=await Z(ht.sessions.model,{spectrogram:fi});return{spectrogram:fi,waveform:Ni}}}class pf extends ae{main_input_name="spectrogram"}class Dp extends ae{}class Xs extends Dp{}class wu extends ae{}class g_ extends wu{}class Ip extends wu{}class Tu extends ae{}class vo extends Tu{}class Ks extends Tu{}class Ys extends ae{}class Qs extends Ys{}class mf extends Ys{}class lc extends ae{}class cc extends lc{}class Eu extends lc{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"text_model"})}}class yo extends lc{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"audio_model"})}}class Mr extends ae{}class uc extends Mr{async _call(N){return new om(await super._call(N))}}class Su extends ae{}class Mo extends Su{}class _f extends Su{}class gf extends Su{}class Zs extends ae{}class Ta extends Zs{}class dc extends Zs{}class Au extends ae{}class vf extends Au{}class fc extends Au{async _call(N){return new _n(await super._call(N))}}class Qo extends ae{}class v_ extends Qo{}class y_ extends Qo{}class Zo extends ae{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(N){const[he,Re]=N.dims,Ve=this.config.decoder.num_codebooks,Ye=Re-Ve;let ht=0;for(let $t=0;$t0&&Kt<=Ye&&(N.data[ht++]=N.data[$t])}const xt=Math.floor(he/Ve),Et=ht/(xt*Ve);return new _.Tensor(N.type,N.data.slice(0,ht),[xt,Ve,Et])}prepare_inputs_for_generation(N,he,Re){let Ve=structuredClone(N);for(let ht=0;ht=xt&&(Ve[ht][xt]=BigInt(this.config.decoder.pad_token_id));return Re.guidance_scale!==null&&Re.guidance_scale>1&&(Ve=Ve.concat(Ve)),super.prepare_inputs_for_generation(Ve,he,Re)}async generate(N){const he=await super.generate(N),Re=this._apply_and_filter_by_delay_pattern_mask(he).unsqueeze_(0),{audio_values:Ve}=await Z(this.sessions.encodec_decode,{audio_codes:Re});return Ve}}class Ts extends ae{}class Op extends Ts{}class Lp extends Ts{async _call(N){return new _n(await super._call(N))}}class bo extends Ts{}class Cr extends ae{}class Fp extends Cr{}class kp extends Cr{async _call(N){return new _n(await super._call(N))}}class Np extends Cr{}class hc extends ae{}class yf extends hc{}class Cu extends hc{async _call(N){return new _n(await super._call(N))}}class Js extends hc{}class Ri extends ae{}class Mf extends Ri{}class zp extends Ri{async _call(N){return new _n(await super._call(N))}}class cr extends Ri{}class Up extends ae{}class M_ extends Up{}class Bp extends ae{}class $p extends Bp{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...N){super(...N),this._generation_mode="text"}async forward(N){const he=this._generation_mode??"text";let Re;if(he==="text"||!N.past_key_values){const Et=this.sessions.prepare_inputs_embeds,$t=(0,u.pick)(N,Et.inputNames);Re=await Z(Et,$t)}else{const Et=this.sessions.gen_img_embeds,$t=(0,u.pick)({image_ids:N.input_ids},Et.inputNames);Re=await Z(Et,$t)}const Ve={...N,...Re},Ye=await oe(this,Ve),ht=this.sessions[he==="text"?"lm_head":"gen_head"];if(!ht)throw new Error(`Unable to find "${ht}" generation head`);const xt=await Z(ht,(0,u.pick)(Ye,ht.inputNames));return{...Re,...Ye,...xt}}async generate(N){return this._generation_mode="text",super.generate(N)}async generate_images(N){this._generation_mode="image";const he=(N.inputs??N[this.main_input_name]).dims[1],Ve=(await super.generate(N)).slice(null,[he,null]),Ye=this.sessions.image_decode,{decoded_image:ht}=await Z(Ye,{generated_tokens:Ve}),xt=ht.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Et=[];for(const $t of xt){const pn=g.RawImage.fromTensor($t);Et.push(pn)}return Et}}class er extends we{constructor({char_logits:N,bpe_logits:he,wp_logits:Re}){super(),this.char_logits=N,this.bpe_logits=he,this.wp_logits=Re}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class jr extends ae{}class ea extends jr{async _call(N){return new er(await super._call(N))}}class bf extends ae{}class Vp extends bf{}class b_ extends bf{}class Pu extends ae{}class is extends Pu{}class fs extends Pu{}class Gp extends ae{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class rs extends Gp{_merge_input_ids_with_audio_features(N){const he=N.audio_features.dims.at(-1),Re=N.audio_features.view(-1,he);return G({audio_token_id:this.config.ignore_index,...N,audio_features:Re})}}class Ru extends ae{main_input_name="input_values";forward_params=["input_values"]}class ta extends we{constructor({audio_codes:N}){super(),this.audio_codes=N}}class Jo extends we{constructor({audio_values:N}){super(),this.audio_values=N}}class Ea extends Ru{async encode(N){return new ta(await Z(this.sessions.encoder_model,N))}async decode(N){return new Jo(await Z(this.sessions.decoder_model,N))}}class xf extends Ru{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"encoder_model"})}}class wf extends Ru{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"decoder_model"})}}class Es extends ae{main_input_name="input_values";forward_params=["input_values"]}class jp extends we{constructor({audio_codes:N}){super(),this.audio_codes=N}}class el extends we{constructor({audio_values:N}){super(),this.audio_values=N}}class pc extends Es{async encode(N){return new jp(await Z(this.sessions.encoder_model,N))}async decode(N){return new el(await Z(this.sessions.decoder_model,N))}}class mc extends Es{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"encoder_model"})}}class tl extends Es{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"decoder_model"})}}class Du extends ae{main_input_name="input_values";forward_params=["input_values"]}class Wp extends Du{async encode(N){return await Z(this.sessions.encoder_model,N)}async decode(N){return await Z(this.sessions.decoder_model,N)}}class _c extends Du{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"encoder_model"})}}class Hp extends Du{static async from_pretrained(N,he={}){return super.from_pretrained(N,{...he,model_file_name:he.model_file_name??"decoder_model"})}}class Gn{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(N,{progress_callback:he=null,config:Re=null,cache_dir:Ve=null,local_files_only:Ye=!1,revision:ht="main",model_file_name:xt=null,subfolder:Et="onnx",device:$t=null,dtype:pn=null,use_external_data_format:vn=null,session_options:Kt={}}={}){const Vt={progress_callback:he,config:Re,cache_dir:Ve,local_files_only:Ye,revision:ht,model_file_name:xt,subfolder:Et,device:$t,dtype:pn,use_external_data_format:vn,session_options:Kt};if(Vt.config=await i.AutoConfig.from_pretrained(N,Vt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const $n=Vt.config.model_type;for(const on of this.MODEL_CLASS_MAPPINGS){let Qt=on.get($n);if(!Qt){for(const Wn of on.values())if(Wn[0]===$n){Qt=Wn;break}if(!Qt)continue}return await Qt[1].from_pretrained(N,Vt)}if(this.BASE_IF_FAIL)return Ss.has($n)||console.warn(`Unknown model class "${$n}", attempting to construct from base class.`),await ae.from_pretrained(N,Vt);throw Error(`Unsupported model type: ${$n}`)}}const x_=new Map([["bert",["BertModel",Ne]],["modernbert",["ModernBertModel",U]],["nomic_bert",["NomicBertModel",Ce]],["roformer",["RoFormerModel",Ee]],["electra",["ElectraModel",Ze]],["esm",["EsmModel",Ue]],["convbert",["ConvBertModel",nt]],["camembert",["CamembertModel",tn]],["deberta",["DebertaModel",ut]],["deberta-v2",["DebertaV2Model",Ti]],["mpnet",["MPNetModel",Sn]],["albert",["AlbertModel",Kn]],["distilbert",["DistilBertModel",Ii]],["roberta",["RobertaModel",pr]],["xlm",["XLMModel",Ya]],["xlm-roberta",["XLMRobertaModel",pd]],["clap",["ClapModel",cc]],["clip",["CLIPModel",Td]],["clipseg",["CLIPSegModel",Ul]],["chinese_clip",["ChineseCLIPModel",Oo]],["siglip",["SiglipModel",Bs]],["jina_clip",["JinaCLIPModel",ma]],["mobilebert",["MobileBertModel",Rt]],["squeezebert",["SqueezeBertModel",An]],["wav2vec2",["Wav2Vec2Model",wa]],["wav2vec2-bert",["Wav2Vec2BertModel",_r]],["unispeech",["UniSpeechModel",_p]],["unispeech-sat",["UniSpeechSatModel",vp]],["hubert",["HubertModel",wp]],["wavlm",["WavLMModel",Ep]],["audio-spectrogram-transformer",["ASTModel",vd]],["vits",["VitsModel",uc]],["pyannote",["PyAnnoteModel",pp]],["wespeaker-resnet",["WeSpeakerResNetModel",mp]],["detr",["DetrModel",zh]],["rt_detr",["RTDetrModel",Rn]],["rt_detr_v2",["RTDetrV2Model",Ho]],["rf_detr",["RFDetrModel",Xo]],["table-transformer",["TableTransformerModel",Vd]],["vit",["ViTModel",Rh]],["ijepa",["IJepaModel",Go]],["pvt",["PvtModel",Dh]],["vit_msn",["ViTMSNModel",au]],["vit_mae",["ViTMAEModel",Oh]],["groupvit",["GroupViTModel",zd]],["fastvit",["FastViTModel",bs]],["mobilevit",["MobileViTModel",ar]],["mobilevitv2",["MobileViTV2Model",a_]],["owlvit",["OwlViTModel",Ud]],["owlv2",["Owlv2Model",Bd]],["beit",["BeitModel",l_]],["deit",["DeiTModel",Gd]],["hiera",["HieraModel",Lr]],["convnext",["ConvNextModel",rp]],["convnextv2",["ConvNextV2Model",ap]],["dinov2",["Dinov2Model",op]],["dinov2_with_registers",["Dinov2WithRegistersModel",lp]],["resnet",["ResNetModel",rc]],["swin",["SwinModel",qs]],["swin2sr",["Swin2SRModel",Gh]],["donut-swin",["DonutSwinModel",ip]],["yolos",["YolosModel",rf]],["dpt",["DPTModel",Wh]],["glpn",["GLPNModel",np]],["hifigan",["SpeechT5HifiGan",pf]],["efficientnet",["EfficientNetModel",vf]],["decision_transformer",["DecisionTransformerModel",M_]],["patchtst",["PatchTSTForPrediction",Vp]],["patchtsmixer",["PatchTSMixerForPrediction",is]],["mobilenet_v1",["MobileNetV1Model",Op]],["mobilenet_v2",["MobileNetV2Model",Fp]],["mobilenet_v3",["MobileNetV3Model",yf]],["mobilenet_v4",["MobileNetV4Model",Mf]],["maskformer",["MaskFormerModel",d_]],["mgp-str",["MgpstrForSceneTextRecognition",ea]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Cp]]]),i0=new Map([["t5",["T5Model",Te]],["longt5",["LongT5Model",Ot]],["mt5",["MT5Model",Dt]],["bart",["BartModel",pi]],["mbart",["MBartModel",mi]],["marian",["MarianModel",sf]],["whisper",["WhisperModel",Gc]],["m2m_100",["M2M100Model",hp]],["blenderbot",["BlenderbotModel",ei]],["blenderbot-small",["BlenderbotSmallModel",Or]]]),hs=new Map([["mimi",["MimiModel",Ea]],["dac",["DacModel",pc]],["snac",["SnacModel",Wp]]]),qp=new Map([["bloom",["BloomModel",Ch]],["jais",["JAISModel",Jc]],["gpt2",["GPT2Model",Lo]],["gptj",["GPTJModel",$l]],["gpt_bigcode",["GPTBigCodeModel",Uo]],["gpt_neo",["GPTNeoModel",Fo]],["gpt_neox",["GPTNeoXModel",mr]],["codegen",["CodeGenModel",Ms]],["llama",["LlamaModel",Bo]],["exaone",["ExaoneModel",Ae]],["olmo",["OlmoModel",Fn]],["olmo2",["Olmo2Model",$r]],["mobilellm",["MobileLLMModel",kt]],["granite",["GraniteModel",nu]],["cohere",["CohereModel",Eh]],["gemma",["GemmaModel",Sh]],["gemma2",["Gemma2Model",$o]],["gemma3_text",["Gemma3Model",ts]],["helium",["HeliumModel",Vs]],["glm",["GlmModel",Y]],["openelm",["OpenELMModel",js]],["qwen2",["Qwen2Model",Ah]],["phi",["PhiModel",Yn]],["phi3",["Phi3Model",Id]],["mpt",["MptModel",ql]],["opt",["OPTModel",Fd]],["mistral",["MistralModel",g_]],["starcoder2",["Starcoder2Model",vo]],["falcon",["FalconModel",Qs]],["stablelm",["StableLmModel",Ta]]]),na=new Map([["speecht5",["SpeechT5ForSpeechToText",hf]],["whisper",["WhisperForConditionalGeneration",Il]],["lite-whisper",["LiteWhisperForConditionalGeneration",jc]],["moonshine",["MoonshineForConditionalGeneration",Ll]]]),Xp=new Map([["speecht5",["SpeechT5ForTextToSpeech",Rp]]]),Iu=new Map([["vits",["VitsModel",uc]],["musicgen",["MusicgenForConditionalGeneration",Zo]]]),xo=new Map([["bert",["BertForSequenceClassification",ke]],["modernbert",["ModernBertForSequenceClassification",se]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",yt]],["esm",["EsmForSequenceClassification",wt]],["convbert",["ConvBertForSequenceClassification",vt]],["camembert",["CamembertForSequenceClassification",Pn]],["deberta",["DebertaForSequenceClassification",Bt]],["deberta-v2",["DebertaV2ForSequenceClassification",zr]],["mpnet",["MPNetForSequenceClassification",Ln]],["albert",["AlbertForSequenceClassification",Pe]],["distilbert",["DistilBertForSequenceClassification",Yr]],["roberta",["RobertaForSequenceClassification",Bn]],["xlm",["XLMForSequenceClassification",Rl]],["xlm-roberta",["XLMRobertaForSequenceClassification",_d]],["bart",["BartForSequenceClassification",ci]],["mbart",["MBartForSequenceClassification",ys]],["mobilebert",["MobileBertForSequenceClassification",sn]],["squeezebert",["SqueezeBertForSequenceClassification",yr]]]),Kp=new Map([["bert",["BertForTokenClassification",st]],["modernbert",["ModernBertForTokenClassification",_e]],["roformer",["RoFormerForTokenClassification",ot]],["electra",["ElectraForTokenClassification",tt]],["esm",["EsmForTokenClassification",Ct]],["convbert",["ConvBertForTokenClassification",mn]],["camembert",["CamembertForTokenClassification",ln]],["deberta",["DebertaForTokenClassification",Vi]],["deberta-v2",["DebertaV2ForTokenClassification",Ns]],["mpnet",["MPNetForTokenClassification",dn]],["distilbert",["DistilBertForTokenClassification",vr]],["roberta",["RobertaForTokenClassification",ti]],["xlm",["XLMForTokenClassification",ha]],["xlm-roberta",["XLMRobertaForTokenClassification",Dl]]]),Ou=new Map([["t5",["T5ForConditionalGeneration",Be]],["longt5",["LongT5ForConditionalGeneration",Lt]],["mt5",["MT5ForConditionalGeneration",Cn]],["bart",["BartForConditionalGeneration",Gi]],["mbart",["MBartForConditionalGeneration",Oi]],["marian",["MarianMTModel",yu]],["m2m_100",["M2M100ForConditionalGeneration",ws]],["blenderbot",["BlenderbotForConditionalGeneration",Mi]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Qr]]]),Lu=new Map([["bloom",["BloomForCausalLM",Hl]],["gpt2",["GPT2LMHeadModel",to]],["jais",["JAISLMHeadModel",eu]],["gptj",["GPTJForCausalLM",No]],["gpt_bigcode",["GPTBigCodeForCausalLM",tu]],["gpt_neo",["GPTNeoForCausalLM",Jr]],["gpt_neox",["GPTNeoXForCausalLM",va]],["codegen",["CodeGenForCausalLM",ro]],["llama",["LlamaForCausalLM",Vl]],["exaone",["ExaoneForCausalLM",rt]],["olmo",["OlmoForCausalLM",wn]],["olmo2",["Olmo2ForCausalLM",Gl]],["mobilellm",["MobileLLMForCausalLM",Gt]],["granite",["GraniteForCausalLM",Pd]],["cohere",["CohereForCausalLM",iu]],["gemma",["GemmaForCausalLM",es]],["gemma2",["Gemma2ForCausalLM",ru]],["gemma3_text",["Gemma3ForCausalLM",ns]],["helium",["HeliumForCausalLM",S]],["glm",["GlmForCausalLM",ie]],["openelm",["OpenELMForCausalLM",Ws]],["qwen2",["Qwen2ForCausalLM",Rd]],["phi",["PhiForCausalLM",us]],["phi3",["Phi3ForCausalLM",oo]],["mpt",["MptForCausalLM",Xl]],["opt",["OPTForCausalLM",Ph]],["mbart",["MBartForCausalLM",Li]],["mistral",["MistralForCausalLM",Ip]],["starcoder2",["Starcoder2ForCausalLM",Ks]],["falcon",["FalconForCausalLM",mf]],["trocr",["TrOCRForCausalLM",Xs]],["stablelm",["StableLmForCausalLM",dc]],["phi3_v",["Phi3VForCausalLM",Io]]]),Sa=new Map([["multi_modality",["MultiModalityCausalLM",$p]]]),Yp=new Map([["bert",["BertForMaskedLM",We]],["modernbert",["ModernBertForMaskedLM",j]],["roformer",["RoFormerForMaskedLM",je]],["electra",["ElectraForMaskedLM",it]],["esm",["EsmForMaskedLM",Fe]],["convbert",["ConvBertForMaskedLM",ft]],["camembert",["CamembertForMaskedLM",rn]],["deberta",["DebertaForMaskedLM",It]],["deberta-v2",["DebertaV2ForMaskedLM",Er]],["mpnet",["MPNetForMaskedLM",Jn]],["albert",["AlbertForMaskedLM",fe]],["distilbert",["DistilBertForMaskedLM",Oe]],["roberta",["RobertaForMaskedLM",Yi]],["xlm",["XLMWithLMHeadModel",Qa]],["xlm-roberta",["XLMRobertaForMaskedLM",md]],["mobilebert",["MobileBertForMaskedLM",qt]],["squeezebert",["SqueezeBertForMaskedLM",sr]]]),Fu=new Map([["bert",["BertForQuestionAnswering",Ke]],["roformer",["RoFormerForQuestionAnswering",bt]],["electra",["ElectraForQuestionAnswering",gt]],["convbert",["ConvBertForQuestionAnswering",Se]],["camembert",["CamembertForQuestionAnswering",vi]],["deberta",["DebertaForQuestionAnswering",rr]],["deberta-v2",["DebertaV2ForQuestionAnswering",Sr]],["mpnet",["MPNetForQuestionAnswering",nn]],["albert",["AlbertForQuestionAnswering",V]],["distilbert",["DistilBertForQuestionAnswering",ue]],["roberta",["RobertaForQuestionAnswering",Pi]],["xlm",["XLMForQuestionAnswering",Do]],["xlm-roberta",["XLMRobertaForQuestionAnswering",gd]],["mobilebert",["MobileBertForQuestionAnswering",Jt]],["squeezebert",["SqueezeBertForQuestionAnswering",Xi]]]),nl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Fl]],["idefics3",["Idefics3ForConditionalGeneration",Nl]],["smolvlm",["SmolVLMForConditionalGeneration",Kc]]]),ki=new Map([["llava",["LlavaForConditionalGeneration",zs]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Hc]],["moondream1",["Moondream1ForConditionalGeneration",qc]],["florence2",["Florence2ForConditionalGeneration",bd]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Ar]],["idefics3",["Idefics3ForConditionalGeneration",Nl]],["smolvlm",["SmolVLMForConditionalGeneration",Kc]],["paligemma",["PaliGemmaForConditionalGeneration",kl]]]),w_=new Map([["ultravox",["UltravoxModel",rs]]]),r0=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Fl]]]),Qp=new Map([["vit",["ViTForImageClassification",Yl]],["ijepa",["IJepaForImageClassification",Ql]],["pvt",["PvtForImageClassification",Ih]],["vit_msn",["ViTMSNForImageClassification",Lh]],["fastvit",["FastViTForImageClassification",ba]],["mobilevit",["MobileViTForImageClassification",ou]],["mobilevitv2",["MobileViTV2ForImageClassification",o_]],["beit",["BeitForImageClassification",Nh]],["deit",["DeiTForImageClassification",jd]],["hiera",["HieraForImageClassification",Zi]],["convnext",["ConvNextForImageClassification",sp]],["convnextv2",["ConvNextV2ForImageClassification",Qd]],["dinov2",["Dinov2ForImageClassification",Jd]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",f_]],["resnet",["ResNetForImageClassification",fu]],["swin",["SwinForImageClassification",hu]],["segformer",["SegformerForImageClassification",_f]],["efficientnet",["EfficientNetForImageClassification",fc]],["mobilenet_v1",["MobileNetV1ForImageClassification",Lp]],["mobilenet_v2",["MobileNetV2ForImageClassification",kp]],["mobilenet_v3",["MobileNetV3ForImageClassification",Cu]],["mobilenet_v4",["MobileNetV4ForImageClassification",zp]]]),T_=new Map([["detr",["DetrForObjectDetection",fo]],["rt_detr",["RTDetrForObjectDetection",di]],["rt_detr_v2",["RTDetrV2ForObjectDetection",ho]],["rf_detr",["RFDetrForObjectDetection",c_]],["table-transformer",["TableTransformerForObjectDetection",Bh]],["yolos",["YolosForObjectDetection",up]]]),E_=new Map([["owlvit",["OwlViTForObjectDetection",ec]],["owlv2",["Owlv2ForObjectDetection",Wo]],["grounding-dino",["GroundingDinoForObjectDetection",cp]]]),_i=new Map([["detr",["DetrForSegmentation",lu]],["clipseg",["CLIPSegForImageSegmentation",Zc]]]),bi=new Map([["segformer",["SegformerForSemanticSegmentation",gf]],["sapiens",["SapiensForSemanticSegmentation",u_]],["swin",["SwinForSemanticSegmentation",Wd]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",bo]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Np]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Js]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",cr]]]),kn=new Map([["detr",["DetrForSegmentation",lu]],["maskformer",["MaskFormerForInstanceSegmentation",tp]]]),jn=new Map([["sam",["SamModel",p_]]]),xi=new Map([["wav2vec2",["Wav2Vec2ForCTC",mo]],["wav2vec2-bert",["Wav2Vec2BertForCTC",bp]],["unispeech",["UniSpeechForCTC",xu]],["unispeech-sat",["UniSpeechSatForCTC",yp]],["wavlm",["WavLMForCTC",Sp]],["hubert",["HubertForCTC",Tp]]]),Wr=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",of]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",xp]],["unispeech",["UniSpeechForSequenceClassification",gp]],["unispeech-sat",["UniSpeechSatForSequenceClassification",m_]],["wavlm",["WavLMForSequenceClassification",Ap]],["hubert",["HubertForSequenceClassification",ac]],["audio-spectrogram-transformer",["ASTForAudioClassification",yd]]]),ia=new Map([["wavlm",["WavLMForXVector",uf]]]),il=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Mp]],["wavlm",["WavLMForAudioFrameClassification",df]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",lf]],["pyannote",["PyAnnoteForAudioFrameClassification",_o]]]),Tf=new Map([["vitmatte",["VitMatteForImageMatting",xa]]]),Aa=new Map([["patchtst",["PatchTSTForPrediction",b_]],["patchtsmixer",["PatchTSMixerForPrediction",fs]]]),Ui=new Map([["swin2sr",["Swin2SRForImageSuperResolution",jh]]]),Ca=new Map([["dpt",["DPTForDepthEstimation",Hh]],["depth_anything",["DepthAnythingForDepthEstimation",qd]],["glpn",["GLPNForDepthEstimation",_u]],["sapiens",["SapiensForDepthEstimation",Xh]],["depth_pro",["DepthProForDepthEstimation",Xd]],["metric3d",["Metric3DForDepthEstimation",Zh]],["metric3dv2",["Metric3Dv2ForDepthEstimation",ep]]]),wo=new Map([["sapiens",["SapiensForNormalEstimation",Kh]]]),Ef=new Map([["vitpose",["VitPoseForPoseEstimation",Zl]]]),ss=new Map([["clip",["CLIPVisionModelWithProjection",Za]],["siglip",["SiglipVisionModel",Cd]],["jina_clip",["JinaCLIPVisionModel",Qc]]]),rl=[[x_,w.EncoderOnly],[i0,w.EncoderDecoder],[qp,w.DecoderOnly],[hs,w.AutoEncoder],[xo,w.EncoderOnly],[Kp,w.EncoderOnly],[Ou,w.Seq2Seq],[na,w.Seq2Seq],[Lu,w.DecoderOnly],[Sa,w.MultiModality],[Yp,w.EncoderOnly],[Fu,w.EncoderOnly],[nl,w.Vision2Seq],[ki,w.ImageTextToText],[w_,w.AudioTextToText],[Qp,w.EncoderOnly],[_i,w.EncoderOnly],[kn,w.EncoderOnly],[bi,w.EncoderOnly],[Tf,w.EncoderOnly],[Aa,w.EncoderOnly],[Ui,w.EncoderOnly],[Ca,w.EncoderOnly],[wo,w.EncoderOnly],[Ef,w.EncoderOnly],[T_,w.EncoderOnly],[E_,w.EncoderOnly],[jn,w.MaskGeneration],[xi,w.EncoderOnly],[Wr,w.EncoderOnly],[Xp,w.Seq2Seq],[Iu,w.EncoderOnly],[ia,w.EncoderOnly],[il,w.EncoderOnly],[ss,w.EncoderOnly]];for(const[k,N]of rl)for(const[he,Re]of k.values())C.set(he,N),A.set(Re,he),E.set(he,Re);const ku=[["MusicgenForConditionalGeneration",Zo,w.Musicgen],["Phi3VForCausalLM",Io,w.Phi3V],["CLIPTextModelWithProjection",Yc,w.EncoderOnly],["SiglipTextModel",Ad,w.EncoderOnly],["JinaCLIPTextModel",_a,w.EncoderOnly],["ClapTextModelWithProjection",Eu,w.EncoderOnly],["ClapAudioModelWithProjection",yo,w.EncoderOnly],["DacEncoderModel",mc,w.EncoderOnly],["DacDecoderModel",tl,w.EncoderOnly],["MimiEncoderModel",xf,w.EncoderOnly],["MimiDecoderModel",wf,w.EncoderOnly],["SnacEncoderModel",_c,w.EncoderOnly],["SnacDecoderModel",Hp,w.EncoderOnly]];for(const[k,N,he]of ku)C.set(k,he),A.set(N,k),E.set(k,N);const Ss=new Map([["modnet",_i],["birefnet",_i],["isnet",_i],["ben",_i]]);for(const[k,N]of Ss.entries())N.set(k,["PreTrainedModel",ae]),C.set(k,w.EncoderOnly),A.set(ae,k),E.set(k,ae);class Zp extends Gn{static MODEL_CLASS_MAPPINGS=rl.map(N=>N[0]);static BASE_IF_FAIL=!0}class Jp extends Gn{static MODEL_CLASS_MAPPINGS=[xo]}class Sf extends Gn{static MODEL_CLASS_MAPPINGS=[Kp]}class Af extends Gn{static MODEL_CLASS_MAPPINGS=[Ou]}class To extends Gn{static MODEL_CLASS_MAPPINGS=[na]}class Cf extends Gn{static MODEL_CLASS_MAPPINGS=[Xp]}class sl extends Gn{static MODEL_CLASS_MAPPINGS=[Iu]}class Nu extends Gn{static MODEL_CLASS_MAPPINGS=[Lu]}class em extends Gn{static MODEL_CLASS_MAPPINGS=[Yp]}class tm extends Gn{static MODEL_CLASS_MAPPINGS=[Fu]}class zu extends Gn{static MODEL_CLASS_MAPPINGS=[nl]}class nm extends Gn{static MODEL_CLASS_MAPPINGS=[Qp]}class as extends Gn{static MODEL_CLASS_MAPPINGS=[_i]}class S_ extends Gn{static MODEL_CLASS_MAPPINGS=[bi]}class Fr extends Gn{static MODEL_CLASS_MAPPINGS=[kn]}class A_ extends Gn{static MODEL_CLASS_MAPPINGS=[T_]}class im extends Gn{static MODEL_CLASS_MAPPINGS=[E_]}class C_ extends Gn{static MODEL_CLASS_MAPPINGS=[jn]}class s0 extends Gn{static MODEL_CLASS_MAPPINGS=[xi]}class Pa extends Gn{static MODEL_CLASS_MAPPINGS=[Wr]}class Pf extends Gn{static MODEL_CLASS_MAPPINGS=[ia]}class rm extends Gn{static MODEL_CLASS_MAPPINGS=[il]}class gc extends Gn{static MODEL_CLASS_MAPPINGS=[r0]}class P_ extends Gn{static MODEL_CLASS_MAPPINGS=[Tf]}class R_ extends Gn{static MODEL_CLASS_MAPPINGS=[Ui]}class D_ extends Gn{static MODEL_CLASS_MAPPINGS=[Ca]}class sm extends Gn{static MODEL_CLASS_MAPPINGS=[wo]}class am extends Gn{static MODEL_CLASS_MAPPINGS=[Ef]}class a0 extends Gn{static MODEL_CLASS_MAPPINGS=[ss]}class o0 extends Gn{static MODEL_CLASS_MAPPINGS=[ki]}class l0 extends Gn{static MODEL_CLASS_MAPPINGS=[w_]}class I_ extends we{constructor({logits:N,past_key_values:he,encoder_outputs:Re,decoder_attentions:Ve=null,cross_attentions:Ye=null}){super(),this.logits=N,this.past_key_values=he,this.encoder_outputs=Re,this.decoder_attentions=Ve,this.cross_attentions=Ye}}class _n extends we{constructor({logits:N,...he}){super(),this.logits=N;const Re=Object.values(he);Re.length>0&&(this.attentions=Re)}}class al extends we{constructor({logits:N,embeddings:he}){super(),this.logits=N,this.embeddings=he}}class Wi extends we{constructor({logits:N}){super(),this.logits=N}}class ur extends we{constructor({logits:N}){super(),this.logits=N}}class br extends we{constructor({start_logits:N,end_logits:he}){super(),this.start_logits=N,this.end_logits=he}}class ol extends we{constructor({logits:N}){super(),this.logits=N}}class O_ extends we{constructor({logits:N,past_key_values:he}){super(),this.logits=N,this.past_key_values=he}}class ll extends we{constructor({alphas:N}){super(),this.alphas=N}}class om extends we{constructor({waveform:N,spectrogram:he}){super(),this.waveform=N,this.spectrogram=he}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(n,e,t)=>{t.r(e),t.d(e,{ASTFeatureExtractor:()=>o});var i=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var s=t("./src/utils/audio.js");class o extends i.FeatureExtractor{constructor(u){super(u);const d=this.config.sampling_rate,f=(0,s.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(d/2),d,null,"kaldi",!0);this.mel_filters=f,this.window=(0,s.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(u,d){return(0,s.spectrogram)(u,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:d,transpose:!0})}async _call(u){(0,i.validate_audio_inputs)(u,"ASTFeatureExtractor");const d=await this._extract_fbank_features(u,this.config.max_length);if(this.config.do_normalize){const f=this.std*2,m=d.data;for(let h=0;h{t.r(e),t.d(e,{AutoFeatureExtractor:()=>l});var i=t("./src/utils/constants.js"),s=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var o=t("./src/models/feature_extractors.js");class l{static async from_pretrained(d,f={}){const m=await(0,s.getModelJSON)(d,i.FEATURE_EXTRACTOR_NAME,!0,f),h=m.feature_extractor_type,_=o[h];if(!_)throw new Error(`Unknown feature_extractor_type: '${h}'. Please report this at ${i.GITHUB_ISSUE_URL}.`);return new _(m)}}},"./src/models/auto/image_processing_auto.js":(n,e,t)=>{t.r(e),t.d(e,{AutoImageProcessor:()=>u});var i=t("./src/utils/constants.js"),s=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),l=t("./src/models/image_processors.js");class u{static async from_pretrained(f,m={}){const h=await(0,s.getModelJSON)(f,i.IMAGE_PROCESSOR_NAME,!0,m),_=h.image_processor_type??h.feature_extractor_type;let g=l[_];return g||(_!==void 0&&console.warn(`Image processor type '${_}' not found, assuming base ImageProcessor. Please report this at ${i.GITHUB_ISSUE_URL}.`),g=o.ImageProcessor),new g(h)}}},"./src/models/auto/processing_auto.js":(n,e,t)=>{t.r(e),t.d(e,{AutoProcessor:()=>f});var i=t("./src/utils/constants.js"),s=t("./src/utils/hub.js"),o=t("./src/base/processing_utils.js"),l=t("./src/models/processors.js"),u=t("./src/models/image_processors.js"),d=t("./src/models/feature_extractors.js");class f{static async from_pretrained(h,_={}){const g=await(0,s.getModelJSON)(h,i.IMAGE_PROCESSOR_NAME,!0,_),{image_processor_type:y,feature_extractor_type:b,processor_class:T}=g;if(T&&l[T])return l[T].from_pretrained(h,_);if(!y&&!b)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const v={};if(y){const P=u[y];if(!P)throw new Error(`Unknown image_processor_type: '${y}'.`);v.image_processor=new P(g)}if(b){const P=u[b];if(P)v.image_processor=new P(g);else{const w=d[b];if(!w)throw new Error(`Unknown feature_extractor_type: '${b}'.`);v.feature_extractor=new w(g)}}const x={};return new o.Processor(x,v)}}},"./src/models/beit/image_processing_beit.js":(n,e,t)=>{t.r(e),t.d(e,{BeitFeatureExtractor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(n,e,t)=>{t.r(e),t.d(e,{BitImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(n,e,t)=>{t.r(e),t.d(e,{ChineseCLIPFeatureExtractor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(n,e,t)=>{t.r(e),t.d(e,{ClapFeatureExtractor:()=>o});var i=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var s=t("./src/utils/audio.js");class o extends i.FeatureExtractor{constructor(u){super(u),this.mel_filters=(0,s.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,s.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,s.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(u,d,f,m){let h;const _=u.length-d;if(_>0)if(f==="rand_trunc"){const g=Math.floor(Math.random()*(_+1));u=u.subarray(g,g+d),h=await this._extract_fbank_features(u,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${f}" not implemented`);else{if(_<0){let g=new Float64Array(d);if(g.set(u),m==="repeat")for(let y=u.length;y{t.r(e),t.d(e,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/convnext/image_processing_convnext.js":(n,e,t)=>{t.r(e),t.d(e,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{constructor(u){super(u),this.crop_pct=this.config.crop_pct??224/256}async resize(u){const d=this.size?.shortest_edge;if(d===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(d<384){const f=Math.floor(d/this.crop_pct),[m,h]=this.get_resize_output_image_size(u,{shortest_edge:f});u=await u.resize(m,h,{resample:this.resample}),u=await u.center_crop(d,d)}else u=await u.resize(d,d,{resample:this.resample});return u}}class o extends s{}},"./src/models/dac/feature_extraction_dac.js":(n,e,t)=>{t.r(e),t.d(e,{DacFeatureExtractor:()=>s});var i=t("./src/models/encodec/feature_extraction_encodec.js");class s extends i.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(n,e,t)=>{t.r(e),t.d(e,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/detr/image_processing_detr.js":(n,e,t)=>{t.r(e),t.d(e,{DetrFeatureExtractor:()=>l,DetrImageProcessor:()=>o});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/tensor.js");class o extends i.ImageProcessor{async _call(d){const f=await super._call(d),m=[f.pixel_values.dims[0],64,64],h=(0,s.full)(m,1n);return{...f,pixel_mask:h}}post_process_object_detection(...d){return(0,i.post_process_object_detection)(...d)}post_process_panoptic_segmentation(...d){return(0,i.post_process_panoptic_segmentation)(...d)}post_process_instance_segmentation(...d){return(0,i.post_process_instance_segmentation)(...d)}}class l extends o{}},"./src/models/donut/image_processing_donut.js":(n,e,t)=>{t.r(e),t.d(e,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{pad_image(u,d,f,m={}){const[h,_,g]=d;let y=this.image_mean;Array.isArray(this.image_mean)||(y=new Array(g).fill(y));let b=this.image_std;Array.isArray(b)||(b=new Array(g).fill(y));const T=y.map((v,x)=>-v/b[x]);return super.pad_image(u,d,f,{center:!0,constant_values:T,...m})}}class o extends s{}},"./src/models/dpt/image_processing_dpt.js":(n,e,t)=>{t.r(e),t.d(e,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/efficientnet/image_processing_efficientnet.js":(n,e,t)=>{t.r(e),t.d(e,{EfficientNetImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{constructor(l){super(l),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(u=>u*u))}}},"./src/models/encodec/feature_extraction_encodec.js":(n,e,t)=>{t.r(e),t.d(e,{EncodecFeatureExtractor:()=>o});var i=t("./src/base/feature_extraction_utils.js"),s=t("./src/utils/tensor.js");class o extends i.FeatureExtractor{async _call(u){(0,i.validate_audio_inputs)(u,"EncodecFeatureExtractor"),u instanceof Float64Array&&(u=new Float32Array(u));const d=this.config.feature_size;if(u.length%d!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${d}).`);const f=[1,d,u.length/d];return{input_values:new s.Tensor("float32",u,f)}}}},"./src/models/feature_extractors.js":(n,e,t)=>{t.r(e),t.d(e,{ASTFeatureExtractor:()=>i.ASTFeatureExtractor,ClapFeatureExtractor:()=>o.ClapFeatureExtractor,DacFeatureExtractor:()=>l.DacFeatureExtractor,EncodecFeatureExtractor:()=>s.EncodecFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>u.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>f.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>m.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>h.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>_.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>g.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor});var i=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),s=t("./src/models/encodec/feature_extraction_encodec.js"),o=t("./src/models/clap/feature_extraction_clap.js"),l=t("./src/models/dac/feature_extraction_dac.js"),u=t("./src/models/moonshine/feature_extraction_moonshine.js"),d=t("./src/models/pyannote/feature_extraction_pyannote.js"),f=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),m=t("./src/models/snac/feature_extraction_snac.js"),h=t("./src/models/speecht5/feature_extraction_speecht5.js"),_=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),g=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),y=t("./src/models/whisper/feature_extraction_whisper.js"),b=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(n,e,t)=>{t.r(e),t.d(e,{Florence2Processor:()=>l});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class l extends i.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=s.AutoImageProcessor;constructor(d,f){super(d,f);const{tasks_answer_post_processing_type:m,task_prompts_without_inputs:h,task_prompts_with_input:_}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(m??{})),this.task_prompts_without_inputs=new Map(Object.entries(h??{})),this.task_prompts_with_input=new Map(Object.entries(_??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(d){typeof d=="string"&&(d=[d]);const f=[];for(const m of d)if(this.task_prompts_without_inputs.has(m))f.push(this.task_prompts_without_inputs.get(m));else{for(const[h,_]of this.task_prompts_with_input)if(m.includes(h)){f.push(_.replaceAll("{input}",m).replaceAll(h,""));break}f.length!==d.length&&f.push(m)}return f}post_process_generation(d,f,m){const h=this.tasks_answer_post_processing_type.get(f)??"pure_text";d=d.replaceAll("","").replaceAll("","");let _;switch(h){case"pure_text":_=d;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const g=h==="ocr"?"quad_boxes":"bboxes",y=d.matchAll(this.regexes[g]),b=[],T=[];for(const[v,x,...P]of y)b.push(x?x.trim():b.at(-1)??""),T.push(P.map((w,C)=>(Number(w)+.5)/this.size_per_bin*m[C%2]));_={labels:b,[g]:T};break;default:throw new Error(`Task "${f}" (of type "${h}") not yet implemented.`)}return{[f]:_}}async _call(d,f=null,m={}){if(!d&&!f)throw new Error("Either text or images must be provided");const h=await this.image_processor(d,m),_=f?this.tokenizer(f,m):{};return{...h,..._}}}},"./src/models/glpn/image_processing_glpn.js":(n,e,t)=>{t.r(e),t.d(e,{GLPNFeatureExtractor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(n,e,t)=>{t.r(e),t.d(e,{GroundingDinoImageProcessor:()=>o});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/tensor.js");class o extends i.ImageProcessor{async _call(u){const d=await super._call(u),f=d.pixel_values.dims,m=(0,s.ones)([f[0],f[2],f[3]]);return{...d,pixel_mask:m}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(n,e,t)=>{t.r(e),t.d(e,{GroundingDinoProcessor:()=>d});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),l=t("./src/base/image_processors_utils.js");function u(f,m){const _=f.dims.at(-1)-1,g=f.tolist();g.fill(!1,0,1),g.fill(!1,_);const y=m.tolist();return g.map((b,T)=>b?T:null).filter(b=>b!==null).map(b=>y[b])}class d extends i.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=s.AutoImageProcessor;async _call(m,h,_={}){const g=m?await this.image_processor(m,_):{};return{...h?this.tokenizer(h,_):{},...g}}post_process_grounded_object_detection(m,h,{box_threshold:_=.25,text_threshold:g=.25,target_sizes:y=null}={}){const{logits:b,pred_boxes:T}=m,v=b.dims[0];if(y!==null&&y.length!==v)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const x=b.dims.at(1),P=b.sigmoid(),w=P.max(-1).tolist(),C=T.tolist().map(A=>A.map(L=>(0,l.center_to_corners_format)(L))),E=[];for(let A=0;A$.map((J,ee)=>J*L[(ee+1)%2])));const I=w[A],O=[],H=[],Z=[];for(let $=0;${t.r(e),t.d(e,{Idefics3ImageProcessor:()=>o});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/tensor.js");class o extends i.ImageProcessor{constructor(u){super(u),this.do_image_splitting=u.do_image_splitting??!0,this.max_image_size=u.max_image_size}get_resize_for_vision_encoder(u,d){let[f,m]=u.dims.slice(-2);const h=m/f;return m>=f?(m=Math.ceil(m/d)*d,f=Math.floor(m/h),f=Math.ceil(f/d)*d):(f=Math.ceil(f/d)*d,m=Math.floor(f*h),m=Math.ceil(m/d)*d),{height:f,width:m}}async _call(u,{do_image_splitting:d=null,return_row_col_info:f=!1}={}){let m;if(!Array.isArray(u))m=[[u]];else{if(u.length===0||!u[0])throw new Error("No images provided.");Array.isArray(u[0])?m=u:m=[u]}let h=[],_=[],g=[];const y=[],b=[];for(const A of m){let L=await Promise.all(A.map(H=>this.preprocess(H)));y.push(...L.map(H=>H.original_size)),b.push(...L.map(H=>H.reshaped_input_size)),L.forEach(H=>H.pixel_values.unsqueeze_(0));const{longest_edge:I}=this.max_image_size;let O;if(d??this.do_image_splitting){let H=new Array(L.length),Z=new Array(L.length);O=await Promise.all(L.map(async($,J)=>{const ee=this.get_resize_for_vision_encoder($.pixel_values,I),X=await(0,s.interpolate_4d)($.pixel_values,{size:[ee.height,ee.width]}),{frames:ne,num_splits_h:Q,num_splits_w:oe}=await this.split_image(X,this.max_image_size);return H[J]=Q,Z[J]=oe,(0,s.cat)(ne,0)})),_.push(H),g.push(Z)}else{const H=[I,I];O=await Promise.all(L.map(Z=>(0,s.interpolate_4d)(Z.pixel_values,{size:H}))),_.push(new Array(L.length).fill(0)),g.push(new Array(L.length).fill(0))}h.push((0,s.cat)(O,0))}const T=h.length,[v,x,P,w]=h[0].dims;let C,E;if(T===1)C=h[0].unsqueeze_(0),E=(0,s.full)([T,v,P,w],!0);else{const A=Math.max(...h.map(O=>O.dims.at(0)));E=(0,s.full)([T,A,P,w],!0);const L=E.data,I=A*P*w;for(let O=0;Of||g>m){y=Math.ceil(_/f),b=Math.ceil(g/m);const T=Math.ceil(_/y),v=Math.ceil(g/b);for(let w=0;w{t.r(e),t.d(e,{Idefics3Processor:()=>m});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");var l=t("./src/utils/core.js");function u(h,_,g,y,b,T){let v="";for(let x=0;x<_;++x){for(let P=0;P`+b.repeat(h);v+=` +`}return v+=` +${y}${T}`+b.repeat(h)+`${y}`,v}function d(h,_,g,y){return`${_}${y}`+g.repeat(h)+`${_}`}function f(h,_,g,y,b,T){return h===0&&_===0?d(g,y,b,T):u(g,h,_,y,b,T)}class m extends i.Processor{static image_processor_class=s.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(_,g=null,y={}){y.return_row_col_info??=!0;let b;g&&(b=await this.image_processor(g,y)),Array.isArray(_)||(_=[_]);const T=b.rows??[new Array(_.length).fill(0)],v=b.cols??[new Array(_.length).fill(0)],x=this.config.image_seq_len,P=[],w=[];for(let E=0;E<_.length;++E){const A=_[E],L=T[E],I=v[E];P.push((0,l.count)(A,this.image_token));const O=L.map(($,J)=>f($,I[J],x,this.fake_image_token,this.image_token,this.global_img_token)),H=A.split(this.image_token);if(H.length===0)throw new Error("The image token should be present in the text.");let Z=H[0];for(let $=0;${t.r(e),t.d(e,{BeitFeatureExtractor:()=>i.BeitFeatureExtractor,BitImageProcessor:()=>s.BitImageProcessor,CLIPFeatureExtractor:()=>l.CLIPFeatureExtractor,CLIPImageProcessor:()=>l.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>u.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>u.ConvNextImageProcessor,DPTFeatureExtractor:()=>h.DPTFeatureExtractor,DPTImageProcessor:()=>h.DPTImageProcessor,DeiTFeatureExtractor:()=>d.DeiTFeatureExtractor,DeiTImageProcessor:()=>d.DeiTImageProcessor,DetrFeatureExtractor:()=>f.DetrFeatureExtractor,DetrImageProcessor:()=>f.DetrImageProcessor,DonutFeatureExtractor:()=>m.DonutFeatureExtractor,DonutImageProcessor:()=>m.DonutImageProcessor,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>g.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>y.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>b.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>x.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>P.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>w.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>w.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>C.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>C.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>E.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>E.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>A.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>A.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>L.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>L.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>I.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>I.MobileViTImageProcessor,NougatImageProcessor:()=>O.NougatImageProcessor,OwlViTFeatureExtractor:()=>Z.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>Z.OwlViTImageProcessor,Owlv2ImageProcessor:()=>H.Owlv2ImageProcessor,Phi3VImageProcessor:()=>$.Phi3VImageProcessor,PvtImageProcessor:()=>J.PvtImageProcessor,Qwen2VLImageProcessor:()=>ee.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>X.RTDetrImageProcessor,SamImageProcessor:()=>ne.SamImageProcessor,SegformerFeatureExtractor:()=>Q.SegformerFeatureExtractor,SegformerImageProcessor:()=>Q.SegformerImageProcessor,SiglipImageProcessor:()=>oe.SiglipImageProcessor,SmolVLMImageProcessor:()=>W.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>q.Swin2SRImageProcessor,VLMImageProcessor:()=>T.VLMImageProcessor,ViTFeatureExtractor:()=>G.ViTFeatureExtractor,ViTImageProcessor:()=>G.ViTImageProcessor,VitMatteImageProcessor:()=>te.VitMatteImageProcessor,VitPoseImageProcessor:()=>B.VitPoseImageProcessor,YolosFeatureExtractor:()=>le.YolosFeatureExtractor,YolosImageProcessor:()=>le.YolosImageProcessor});var i=t("./src/models/beit/image_processing_beit.js"),s=t("./src/models/bit/image_processing_bit.js"),o=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),l=t("./src/models/clip/image_processing_clip.js"),u=t("./src/models/convnext/image_processing_convnext.js"),d=t("./src/models/deit/image_processing_deit.js"),f=t("./src/models/detr/image_processing_detr.js"),m=t("./src/models/donut/image_processing_donut.js"),h=t("./src/models/dpt/image_processing_dpt.js"),_=t("./src/models/efficientnet/image_processing_efficientnet.js"),g=t("./src/models/glpn/image_processing_glpn.js"),y=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),b=t("./src/models/idefics3/image_processing_idefics3.js"),T=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),x=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),P=t("./src/models/mask2former/image_processing_mask2former.js"),w=t("./src/models/maskformer/image_processing_maskformer.js"),C=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),E=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),A=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),L=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),I=t("./src/models/mobilevit/image_processing_mobilevit.js"),O=t("./src/models/nougat/image_processing_nougat.js"),H=t("./src/models/owlv2/image_processing_owlv2.js"),Z=t("./src/models/owlvit/image_processing_owlvit.js"),$=t("./src/models/phi3_v/image_processing_phi3_v.js"),J=t("./src/models/pvt/image_processing_pvt.js"),ee=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),X=t("./src/models/rt_detr/image_processing_rt_detr.js"),ne=t("./src/models/sam/image_processing_sam.js"),Q=t("./src/models/segformer/image_processing_segformer.js"),oe=t("./src/models/siglip/image_processing_siglip.js"),W=t("./src/models/smolvlm/image_processing_smolvlm.js"),q=t("./src/models/swin2sr/image_processing_swin2sr.js"),G=t("./src/models/vit/image_processing_vit.js"),te=t("./src/models/vitmatte/image_processing_vitmatte.js"),B=t("./src/models/vitpose/image_processing_vitpose.js"),le=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(n,e,t)=>{t.r(e),t.d(e,{VLMImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{constructor(l){super({do_pad:!0,pad_size:{width:l.image_size,height:l.image_size},...l}),this.constant_values=this.config.background_color.map(u=>u*this.rescale_factor)}pad_image(l,u,d,f){return super.pad_image(l,u,d,{constant_values:this.constant_values,center:!0,...f})}}},"./src/models/janus/processing_janus.js":(n,e,t)=>{t.r(e),t.d(e,{VLChatProcessor:()=>f});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),l=t("./src/utils/core.js"),u=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");class f extends i.Processor{static image_processor_class=s.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;constructor(h,_){super(h,_),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(h,{images:_=null,chat_template:g="default"}={}){_?Array.isArray(_)||(_=[_]):_=await Promise.all(h.filter(O=>O.images).flatMap(O=>O.images).map(O=>d.RawImage.read(O)));const y=this.tokenizer,b=y.apply_chat_template(h,{tokenize:!1,add_generation_prompt:!0,chat_template:g}),T=O=>y.encode(O,{add_special_tokens:!1}),v=b.split(this.image_tag),x=v.length-1;if(_.length!==x)throw new Error(`Number of images provided (${_.length}) does not match number of "${this.image_tag}" image tags (${x})`);const[P,w,C]=y.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let E=T(v[0]),A=new Array(E.length).fill(!1);for(let O=1;O0){const O=await this.image_processor(_);return O.pixel_values.unsqueeze_(0),{...I,...O}}return I}}},"./src/models/jina_clip/image_processing_jina_clip.js":(n,e,t)=>{t.r(e),t.d(e,{JinaCLIPImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{constructor(l){const{resize_mode:u,fill_color:d,interpolation:f,size:m,...h}=l,_=u==="squash"?{width:m,height:m}:u==="shortest"?{shortest_edge:m}:{longest_edge:m},g=f==="bicubic"?3:2;super({...h,size:_,resample:g,do_center_crop:!0,crop_size:m,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(n,e,t)=>{t.r(e),t.d(e,{JinaCLIPProcessor:()=>l});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class l extends i.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=s.AutoImageProcessor;async _call(d=null,f=null,m={}){if(!d&&!f)throw new Error("Either text or images must be provided");const h=d?this.tokenizer(d,m):{},_=f?await this.image_processor(f,m):{};return{...h,..._}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":(n,e,t)=>{t.r(e),t.d(e,{LlavaOnevisionImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(n,e,t)=>{t.r(e),t.d(e,{Mask2FormerImageProcessor:()=>s});var i=t("./src/models/maskformer/image_processing_maskformer.js");class s extends i.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(n,e,t)=>{t.r(e),t.d(e,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{post_process_panoptic_segmentation(...u){return(0,i.post_process_panoptic_segmentation)(...u)}post_process_instance_segmentation(...u){return(0,i.post_process_instance_segmentation)(...u)}}class o extends s{}},"./src/models/mgp_str/processing_mgp_str.js":(n,e,t)=>{t.r(e),t.d(e,{MgpstrProcessor:()=>d});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),l=t("./src/utils/maths.js");const u={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class d extends i.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=s.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(m,h){if(!u.hasOwnProperty(h))throw new Error(`Format ${h} is not supported.`);const[_,g]=u[h],y=this[_].bind(this),[b,T]=m.dims,v=[],x=[],P=m.tolist();for(let C=0;C0?L.reduce((O,H)=>O*H,1):0;x.push(A),v.push(I)}return[y(x),v]}char_decode(m){return this.char_tokenizer.batch_decode(m).map(h=>h.replaceAll(" ",""))}bpe_decode(m){return this.bpe_tokenizer.batch_decode(m)}wp_decode(m){return this.wp_tokenizer.batch_decode(m).map(h=>h.replaceAll(" ",""))}batch_decode([m,h,_]){const[g,y]=this._decode_helper(m,"char"),[b,T]=this._decode_helper(h,"bpe"),[v,x]=this._decode_helper(_,"wp"),P=[],w=[];for(let C=0;C{t.r(e),t.d(e,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(n,e,t)=>{t.r(e),t.d(e,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(n,e,t)=>{t.r(e),t.d(e,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(n,e,t)=>{t.r(e),t.d(e,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/mobilevit/image_processing_mobilevit.js":(n,e,t)=>{t.r(e),t.d(e,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/moonshine/feature_extraction_moonshine.js":(n,e,t)=>{t.r(e),t.d(e,{MoonshineFeatureExtractor:()=>o});var i=t("./src/base/feature_extraction_utils.js"),s=t("./src/utils/tensor.js");class o extends i.FeatureExtractor{async _call(u){(0,i.validate_audio_inputs)(u,"MoonshineFeatureExtractor"),u instanceof Float64Array&&(u=new Float32Array(u));const d=[1,u.length];return{input_values:new s.Tensor("float32",u,d)}}}},"./src/models/moonshine/processing_moonshine.js":(n,e,t)=>{t.r(e),t.d(e,{MoonshineProcessor:()=>l});var i=t("./src/models/auto/feature_extraction_auto.js"),s=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class l extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=i.AutoFeatureExtractor;async _call(d){return await this.feature_extractor(d)}}},"./src/models/nougat/image_processing_nougat.js":(n,e,t)=>{t.r(e),t.d(e,{NougatImageProcessor:()=>s});var i=t("./src/models/donut/image_processing_donut.js");class s extends i.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(n,e,t)=>{t.r(e),t.d(e,{Owlv2ImageProcessor:()=>s});var i=t("./src/models/owlvit/image_processing_owlvit.js");class s extends i.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(n,e,t)=>{t.r(e),t.d(e,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{post_process_object_detection(...u){return(0,i.post_process_object_detection)(...u)}}class o extends s{}},"./src/models/owlvit/processing_owlvit.js":(n,e,t)=>{t.r(e),t.d(e,{OwlViTProcessor:()=>l});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class l extends i.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=s.AutoImageProcessor}},"./src/models/paligemma/processing_paligemma.js":(n,e,t)=>{t.r(e),t.d(e,{PaliGemmaProcessor:()=>d});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");const l="";function u(f,m,h,_,g){return`${_.repeat(h*g)}${m}${f} +`}class d extends i.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=s.AutoImageProcessor;static uses_processor_config=!1;async _call(m,h=null,_={}){h||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),h=""),Array.isArray(m)||(m=[m]),Array.isArray(h)||(h=[h]);const g=this.tokenizer.bos_token,y=this.image_processor.config.image_seq_length;let b;h.some(x=>x.includes(l))?b=h.map(x=>{const P=x.replaceAll(l,l.repeat(y)),w=P.lastIndexOf(l),C=w===-1?0:w+l.length;return P.slice(0,C)+g+P.slice(C)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),b=h.map(x=>u(x,g,y,l,m.length)));const T=this.tokenizer(b,_);return{...await this.image_processor(m,_),...T}}}},"./src/models/phi3_v/image_processing_phi3_v.js":(n,e,t)=>{t.r(e),t.d(e,{Phi3VImageProcessor:()=>m});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/tensor.js");const o=336,l=[2,3],{ceil:u,floor:d,sqrt:f}=Math;class m extends i.ImageProcessor{constructor(_){super({..._,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=_.num_crops}calc_num_image_tokens_from_image_size(_,g){const{num_img_tokens:y}=this.config;return d((d(g/o)*d(_/o)+1)*y+1+(d(g/o)+1)*f(y))}get_resize_output_image_size(_,g){const y=this._num_crops,[b,T]=_.size;let v=b/T,x=1;for(;x*Math.ceil(x/v)<=y;)x+=1;x-=1;const P=Math.floor(x*336),w=Math.floor(P/v);return[P,w]}pad_image(_,g,y,b={}){const[T,v]=g,x=o*u(T/o),P=o*u(v/o),w=[1,1,1].map((C,E)=>(C-this.image_mean[E])/this.image_std[E]);return super.pad_image(_,g,{width:P,height:x},{center:!0,constant_values:w,...b})}async _call(_,{num_crops:g=null}={}){if(this._num_crops=g??=this.config.num_crops,g<4||f(g)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(_)||(_=[_]);const y=_.length,b=await Promise.all(_.map(A=>this.preprocess(A))),T=b.map(A=>A.original_size),v=b.map(A=>A.reshaped_input_size),x=[];for(const{pixel_values:A}of b){A.unsqueeze_(0);const[L,I]=A.dims.slice(-2),O=await(0,s.interpolate_4d)(A,{size:[o,o],mode:"bicubic"});if(g>0){const H=[],Z=f(g),$=d(I/Z),J=d(L/Z);for(let X=0;XA.map(L=>o*u(L/o))),C=new s.Tensor("int64",w.flat(),[y,2]),E=w.map(([A,L])=>this.calc_num_image_tokens_from_image_size(L,A));return{pixel_values:P,original_sizes:T,reshaped_input_sizes:v,image_sizes:C,num_img_tokens:E}}}},"./src/models/phi3_v/processing_phi3_v.js":(n,e,t)=>{t.r(e),t.d(e,{Phi3VProcessor:()=>d});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");const l="<|image|>",u=/<\|image_\d+\|>/g;class d extends i.Processor{static image_processor_class=s.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(m,h=null,{padding:_=!0,truncation:g=!0,num_crops:y=null}={}){Array.isArray(m)||(m=[m]);let b,T;if(h){T=await this.image_processor(h,{num_crops:y});const{num_img_tokens:v}=T,x=m.map((w,C)=>w.split(u).join(l.repeat(v[C])));b=this.tokenizer(x,{padding:_,truncation:g});const P=this.tokenizer.model.convert_tokens_to_ids([l])[0];b.input_ids.map_(w=>w==P?-w:w)}else b=this.tokenizer(m);return{...b,...T}}}},"./src/models/processors.js":(n,e,t)=>{t.r(e),t.d(e,{Florence2Processor:()=>i.Florence2Processor,GroundingDinoProcessor:()=>s.GroundingDinoProcessor,Idefics3Processor:()=>o.Idefics3Processor,JinaCLIPProcessor:()=>u.JinaCLIPProcessor,MgpstrProcessor:()=>d.MgpstrProcessor,MoonshineProcessor:()=>f.MoonshineProcessor,OwlViTProcessor:()=>m.OwlViTProcessor,PaliGemmaProcessor:()=>_.PaliGemmaProcessor,Phi3VProcessor:()=>h.Phi3VProcessor,PyAnnoteProcessor:()=>g.PyAnnoteProcessor,Qwen2VLProcessor:()=>y.Qwen2VLProcessor,SamProcessor:()=>b.SamProcessor,SmolVLMProcessor:()=>T.SmolVLMProcessor,SpeechT5Processor:()=>v.SpeechT5Processor,UltravoxProcessor:()=>x.UltravoxProcessor,VLChatProcessor:()=>l.VLChatProcessor,Wav2Vec2Processor:()=>P.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>C.WhisperProcessor});var i=t("./src/models/florence2/processing_florence2.js"),s=t("./src/models/grounding_dino/processing_grounding_dino.js"),o=t("./src/models/idefics3/processing_idefics3.js"),l=t("./src/models/janus/processing_janus.js"),u=t("./src/models/jina_clip/processing_jina_clip.js"),d=t("./src/models/mgp_str/processing_mgp_str.js"),f=t("./src/models/moonshine/processing_moonshine.js"),m=t("./src/models/owlvit/processing_owlvit.js"),h=t("./src/models/phi3_v/processing_phi3_v.js"),_=t("./src/models/paligemma/processing_paligemma.js"),g=t("./src/models/pyannote/processing_pyannote.js"),y=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),b=t("./src/models/sam/processing_sam.js"),T=t("./src/models/smolvlm/processing_smolvlm.js"),v=t("./src/models/speecht5/processing_speecht5.js"),x=t("./src/models/ultravox/processing_ultravox.js"),P=t("./src/models/wav2vec2/processing_wav2vec2.js"),w=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),C=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(n,e,t)=>{t.r(e),t.d(e,{PvtImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(n,e,t)=>{t.r(e),t.d(e,{PyAnnoteFeatureExtractor:()=>l});var i=t("./src/base/feature_extraction_utils.js"),s=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");class l extends i.FeatureExtractor{async _call(d){(0,i.validate_audio_inputs)(d,"PyAnnoteFeatureExtractor"),d instanceof Float64Array&&(d=new Float32Array(d));const f=[1,1,d.length];return{input_values:new s.Tensor("float32",d,f)}}samples_to_frames(d){return(d-this.config.offset)/this.config.step}post_process_speaker_diarization(d,f){const m=f/this.samples_to_frames(f)/this.config.sampling_rate,h=[];for(const _ of d.tolist()){const g=[];let y=-1;for(let b=0;b<_.length;++b){const T=(0,o.softmax)(_[b]),[v,x]=(0,o.max)(T),[P,w]=[b,b+1];x!==y?(y=x,g.push({id:x,start:P,end:w,score:v})):(g.at(-1).end=w,g.at(-1).score+=v)}h.push(g.map(({id:b,start:T,end:v,score:x})=>({id:b,start:T*m,end:v*m,confidence:x/(v-T)})))}return h}}},"./src/models/pyannote/processing_pyannote.js":(n,e,t)=>{t.r(e),t.d(e,{PyAnnoteProcessor:()=>o});var i=t("./src/base/processing_utils.js"),s=t("./src/models/pyannote/feature_extraction_pyannote.js");class o extends i.Processor{static feature_extractor_class=s.PyAnnoteFeatureExtractor;async _call(u){return await this.feature_extractor(u)}post_process_speaker_diarization(...u){return this.feature_extractor.post_process_speaker_diarization(...u)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(n,e,t)=>{t.r(e),t.d(e,{Qwen2VLImageProcessor:()=>o});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/tensor.js");class o extends i.ImageProcessor{async _call(u,...d){const{pixel_values:f,original_sizes:m,reshaped_input_sizes:h}=await super._call(u,...d);let _=f;const{temporal_patch_size:g,merge_size:y,patch_size:b}=this.config;_.dims[0]===1&&(_=(0,s.cat)(Array.from({length:g},()=>_),0));const T=_.dims[0]/g,v=_.dims[1],x=Math.floor(_.dims[2]/b),P=Math.floor(_.dims[3]/b),w=_.view(T,g,v,Math.floor(x/y),y,b,Math.floor(P/y),y,b).permute(0,3,6,4,7,2,1,5,8).view(T*x*P,v*g*b*b),C=new s.Tensor("int64",[T,x,P],[1,3]);return{pixel_values:w,image_grid_thw:C,original_sizes:m,reshaped_input_sizes:h}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(n,e,t)=>{t.r(e),t.d(e,{Qwen2VLProcessor:()=>l});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");class l extends i.Processor{static image_processor_class=s.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(d,f=null,...m){Array.isArray(d)||(d=[d]);let h,_;if(f&&(h=await this.image_processor(f),_=h.image_grid_thw),_){let y=this.image_processor.config.merge_size**2,b=0;const T=_.tolist();d=d.map(v=>{for(;v.includes("<|image_pad|>");){const x=Number(T[b++].reduce((P,w)=>P*w,1n));v=v.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(x/y)))}return v.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(d),...h}}}},"./src/models/rt_detr/image_processing_rt_detr.js":(n,e,t)=>{t.r(e),t.d(e,{RTDetrImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{post_process_object_detection(...l){return(0,i.post_process_object_detection)(...l)}}},"./src/models/sam/image_processing_sam.js":(n,e,t)=>{t.r(e),t.d(e,{SamImageProcessor:()=>l});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/core.js"),o=t("./src/utils/tensor.js");class l extends i.ImageProcessor{reshape_input_points(d,f,m,h=!1){d=structuredClone(d);let _=(0,s.calculateDimensions)(d);if(_.length===3)h||(_=[1,..._]),d=[d];else if(_.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let g=0;gh!==f.dims[_]))throw Error(`The first ${m.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",d.flat(1/0).map(BigInt),m)}async _call(d,{input_points:f=null,input_labels:m=null,input_boxes:h=null}={}){const _=await super._call(d);if(f&&(_.input_points=this.reshape_input_points(f,_.original_sizes,_.reshaped_input_sizes)),m){if(!_.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");_.input_labels=this.add_input_labels(m,_.input_points)}return h&&(_.input_boxes=this.reshape_input_points(h,_.original_sizes,_.reshaped_input_sizes,!0)),_}async post_process_masks(d,f,m,{mask_threshold:h=0,binarize:_=!0,pad_size:g=null}={}){const y=[];g=g??this.pad_size;const b=[g.height,g.width];for(let T=0;Th&&(C[E]=1);P=new o.Tensor("bool",C,P.dims)}y.push(P)}return y}generate_crop_boxes(d,f,{crop_n_layers:m=0,overlap_ratio:h=512/1500,points_per_crop:_=32,crop_n_points_downscale_factor:g=1}={}){}}},"./src/models/sam/processing_sam.js":(n,e,t)=>{t.r(e),t.d(e,{SamProcessor:()=>o});var i=t("./src/base/processing_utils.js"),s=t("./src/models/auto/image_processing_auto.js");class o extends i.Processor{static image_processor_class=s.AutoImageProcessor;async _call(...u){return await this.image_processor(...u)}post_process_masks(...u){return this.image_processor.post_process_masks(...u)}reshape_input_points(...u){return this.image_processor.reshape_input_points(...u)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(n,e,t)=>{t.r(e),t.d(e,{SeamlessM4TFeatureExtractor:()=>l});var i=t("./src/base/feature_extraction_utils.js"),s=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class l extends i.FeatureExtractor{constructor(d){super(d);const f=this.config.sampling_rate,m=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(f/2),f,null,"kaldi",!0);this.mel_filters=m,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(d,f){return d=d.map(m=>m*32768),(0,o.spectrogram)(d,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:f,transpose:!0})}async _call(d,{padding:f=!0,pad_to_multiple_of:m=2,do_normalize_per_mel_bins:h=!0,return_attention_mask:_=!0}={}){(0,i.validate_audio_inputs)(d,"SeamlessM4TFeatureExtractor");let g=await this._extract_fbank_features(d,this.config.max_length);if(h){const[C,E]=g.dims,A=g.data;for(let L=0;L0){const I=new Float32Array(E*(C+L));I.set(A),I.fill(this.config.padding_value,A.length);const O=C+L;g=new s.Tensor(g.type,I,[O,E]),_&&(y=new s.Tensor("int64",new BigInt64Array(O),[1,O]),y.data.fill(1n,0,C))}}const[b,T]=g.dims,v=this.config.stride;if(b%v!==0)throw new Error(`The number of frames (${b}) must be a multiple of the stride (${v}).`);const P=g.view(1,Math.floor(b/v),T*v),w={input_features:P};if(_){const C=P.dims[1],E=new BigInt64Array(C);if(y){const A=y.data;for(let L=1,I=0;L{t.r(e),t.d(e,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{post_process_semantic_segmentation(...u){return(0,i.post_process_semantic_segmentation)(...u)}}class o extends s{}},"./src/models/siglip/image_processing_siglip.js":(n,e,t)=>{t.r(e),t.d(e,{SiglipImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(n,e,t)=>{t.r(e),t.d(e,{SmolVLMImageProcessor:()=>i.Idefics3ImageProcessor});var i=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(n,e,t)=>{t.r(e),t.d(e,{SmolVLMProcessor:()=>i.Idefics3Processor});var i=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(n,e,t)=>{t.r(e),t.d(e,{SnacFeatureExtractor:()=>s});var i=t("./src/models/dac/feature_extraction_dac.js");class s extends i.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(n,e,t)=>{t.r(e),t.d(e,{SpeechT5FeatureExtractor:()=>s});var i=t("./src/base/feature_extraction_utils.js");class s extends i.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(n,e,t)=>{t.r(e),t.d(e,{SpeechT5Processor:()=>l});var i=t("./src/base/processing_utils.js"),s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js");class l extends i.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=o.AutoFeatureExtractor;async _call(d){return await this.feature_extractor(d)}}},"./src/models/swin2sr/image_processing_swin2sr.js":(n,e,t)=>{t.r(e),t.d(e,{Swin2SRImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{pad_image(l,u,d,f={}){const[m,h,_]=u;return super.pad_image(l,u,{width:h+(d-h%d)%d,height:m+(d-m%d)%d},{mode:"symmetric",center:!1,constant_values:-1,...f})}}},"./src/models/ultravox/processing_ultravox.js":(n,e,t)=>{t.r(e),t.d(e,{UltravoxProcessor:()=>l});var i=t("./src/models/auto/feature_extraction_auto.js"),s=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class l extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=i.AutoFeatureExtractor;static uses_processor_config=!0;async _call(d,f=null,m={}){if(Array.isArray(d))throw new Error("Batched inputs are not supported yet.");let h={};if(f){const g=f.length,{input_features:y}=await this.feature_extractor(f,{...m,max_length:g}),b=Math.round(g/this.config.encoder_ds_factor+1e-4),T=1+Math.ceil(b/this.config.stack_factor);h.audio_token_len=[T],h.audio_values=y;const v=this.config.audio_placeholder;if(!d.includes(v))throw new Error(`The input text does not contain the image token ${v}.`);d=d.replaceAll(v,v.repeat(T))}return{...this.tokenizer(d,{add_special_tokens:!1,...m}),...h}}}},"./src/models/vit/image_processing_vit.js":(n,e,t)=>{t.r(e),t.d(e,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{}class o extends s{}},"./src/models/vitmatte/image_processing_vitmatte.js":(n,e,t)=>{t.r(e),t.d(e,{VitMatteImageProcessor:()=>o});var i=t("./src/base/image_processors_utils.js"),s=t("./src/utils/tensor.js");class o extends i.ImageProcessor{async _call(u,d){Array.isArray(u)||(u=[u]),Array.isArray(d)||(d=[d]);const f=await Promise.all(u.map(_=>this.preprocess(_))),m=await Promise.all(d.map(_=>this.preprocess(_,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,s.stack)(f.map((_,g)=>(0,s.cat)([_.pixel_values,m[g].pixel_values],0)),0),original_sizes:f.map(_=>_.original_size),reshaped_input_sizes:f.map(_=>_.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(n,e,t)=>{t.r(e),t.d(e,{VitPoseImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{post_process_pose_estimation(l,u,{threshold:d=null}={}){const f=l.tolist(),[m,h,_,g]=l.dims,y=[];for(let b=0;b{t.r(e),t.d(e,{Wav2Vec2FeatureExtractor:()=>o});var i=t("./src/base/feature_extraction_utils.js"),s=t("./src/utils/tensor.js");class o extends i.FeatureExtractor{_zero_mean_unit_var_norm(u){const f=u.reduce((h,_)=>h+_,0)/u.length,m=u.reduce((h,_)=>h+(_-f)**2,0)/u.length;return u.map(h=>(h-f)/Math.sqrt(m+1e-7))}async _call(u){(0,i.validate_audio_inputs)(u,"Wav2Vec2FeatureExtractor"),u instanceof Float64Array&&(u=new Float32Array(u));let d=u;this.config.do_normalize&&(d=this._zero_mean_unit_var_norm(d));const f=[1,d.length];return{input_values:new s.Tensor("float32",d,f),attention_mask:new s.Tensor("int64",new BigInt64Array(d.length).fill(1n),f)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(n,e,t)=>{t.r(e),t.d(e,{Wav2Vec2Processor:()=>l});var i=t("./src/tokenizers.js"),s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class l extends o.Processor{static tokenizer_class=i.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(d){return await this.feature_extractor(d)}}},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(n,e,t)=>{t.r(e),t.d(e,{Wav2Vec2ProcessorWithLM:()=>l});var i=t("./src/tokenizers.js"),s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class l extends o.Processor{static tokenizer_class=i.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(d){return await this.feature_extractor(d)}}},"./src/models/wespeaker/feature_extraction_wespeaker.js":(n,e,t)=>{t.r(e),t.d(e,{WeSpeakerFeatureExtractor:()=>o});var i=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var s=t("./src/utils/audio.js");class o extends i.FeatureExtractor{constructor(u){super(u);const d=this.config.sampling_rate,f=(0,s.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(d/2),d,null,"kaldi",!0);this.mel_filters=f,this.window=(0,s.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(u){return u=u.map(d=>d*32768),(0,s.spectrogram)(u,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(u){(0,i.validate_audio_inputs)(u,"WeSpeakerFeatureExtractor");const d=(await this._extract_fbank_features(u)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const f=d.mean(1).data,m=d.data,[h,_,g]=d.dims;for(let y=0;y{t.r(e),t.d(e,{WHISPER_LANGUAGE_MAPPING:()=>s,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,whisper_language_to_code:()=>l});const i=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],s=new Map(i),o=new Map([...i.map(([u,d])=>[d,u]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function l(u){u=u.toLowerCase();let d=o.get(u);if(d===void 0){const f=u.match(/^<\|([a-z]{2})\|>$/);if(f&&(u=f[1]),s.has(u))d=u;else{const h=u.length===2?s.keys():s.values();throw new Error(`Language "${u}" is not supported. Must be one of: ${JSON.stringify(Array.from(h))}`)}}return d}},"./src/models/whisper/feature_extraction_whisper.js":(n,e,t)=>{t.r(e),t.d(e,{WhisperFeatureExtractor:()=>l});var i=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var s=t("./src/utils/audio.js"),o=t("./src/utils/maths.js");class l extends i.FeatureExtractor{constructor(d){super(d),this.config.mel_filters??=(0,s.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,s.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(d){const f=await(0,s.spectrogram)(d,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(d.length/this.config.hop_length),this.config.nb_max_frames)}),m=f.data,h=(0,o.max)(m)[0];for(let _=0;_h?(d.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),m=d.slice(0,h)):(m=new Float32Array(h),m.set(d)),{input_features:(await this._extract_fbank_features(m)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(n,e,t)=>{t.r(e),t.d(e,{WhisperGenerationConfig:()=>s});var i=t("./src/generation/configuration_utils.js");class s extends i.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}},"./src/models/whisper/processing_whisper.js":(n,e,t)=>{t.r(e),t.d(e,{WhisperProcessor:()=>l});var i=t("./src/models/auto/feature_extraction_auto.js"),s=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class l extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=i.AutoFeatureExtractor;async _call(d){return await this.feature_extractor(d)}}},"./src/models/yolos/image_processing_yolos.js":(n,e,t)=>{t.r(e),t.d(e,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>s});var i=t("./src/base/image_processors_utils.js");class s extends i.ImageProcessor{post_process_object_detection(...u){return(0,i.post_process_object_detection)(...u)}}class o extends s{}},"./src/ops/registry.js":(n,e,t)=>{t.r(e),t.d(e,{TensorOpRegistry:()=>d});var i=t("./src/backends/onnx.js"),s=t("./src/utils/tensor.js"),o=t("./src/env.js");const l=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV,u=async(f,m,h)=>{const _=await(0,i.createInferenceSession)(new Uint8Array(f),m);let g=Promise.resolve();return async y=>{const b=(0,i.isONNXProxy)(),T=Object.fromEntries(Object.entries(y).map(([x,P])=>[x,(b?P.clone():P).ort_tensor])),v=await(g=l?g.then(()=>_.run(T)):_.run(T));return Array.isArray(h)?h.map(x=>new s.Tensor(v[x])):new s.Tensor(v[h])}};class d{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=u([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=u([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=u([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=u([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=u([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=u([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=u([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=u([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}},"./src/pipelines.js":(n,e,t)=>{t.r(e),t.d(e,{AudioClassificationPipeline:()=>Z,AutomaticSpeechRecognitionPipeline:()=>J,BackgroundRemovalPipeline:()=>Q,DepthEstimationPipeline:()=>le,DocumentQuestionAnsweringPipeline:()=>G,FeatureExtractionPipeline:()=>O,FillMaskPipeline:()=>P,ImageClassificationPipeline:()=>X,ImageFeatureExtractionPipeline:()=>H,ImageSegmentationPipeline:()=>ne,ImageToImagePipeline:()=>B,ImageToTextPipeline:()=>ee,ObjectDetectionPipeline:()=>W,Pipeline:()=>b,QuestionAnsweringPipeline:()=>x,SummarizationPipeline:()=>C,Text2TextGenerationPipeline:()=>w,TextClassificationPipeline:()=>T,TextGenerationPipeline:()=>L,TextToAudioPipeline:()=>te,TokenClassificationPipeline:()=>v,TranslationPipeline:()=>E,ZeroShotAudioClassificationPipeline:()=>$,ZeroShotClassificationPipeline:()=>I,ZeroShotImageClassificationPipeline:()=>oe,ZeroShotObjectDetectionPipeline:()=>q,pipeline:()=>xe});var i=t("./src/tokenizers.js"),s=t("./src/models.js"),o=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var l=t("./src/utils/generic.js"),u=t("./src/utils/core.js"),d=t("./src/utils/maths.js"),f=t("./src/utils/audio.js"),m=t("./src/utils/tensor.js"),h=t("./src/utils/image.js");async function _(Me){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(ce=>h.RawImage.read(ce)))}async function g(Me,ce){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(ae=>typeof ae=="string"||ae instanceof URL?(0,f.read_audio)(ae,ce):ae instanceof Float64Array?new Float32Array(ae):ae))}function y(Me,ce){ce&&(Me=Me.map(Ne=>Ne|0));const[ae,we,re,He]=Me;return{xmin:ae,ymin:we,xmax:re,ymax:He}}class b extends l.Callable{constructor({task:ce,model:ae,tokenizer:we=null,processor:re=null}){super(),this.task=ce,this.model=ae,this.tokenizer=we,this.processor=re}async dispose(){await this.model.dispose()}}class T extends b{constructor(ce){super(ce)}async _call(ce,{top_k:ae=1}={}){const we=this.tokenizer(ce,{padding:!0,truncation:!0}),re=await this.model(we),He=this.model.config.problem_type==="multi_label_classification"?ke=>ke.sigmoid():ke=>new m.Tensor("float32",(0,d.softmax)(ke.data),ke.dims),Ne=this.model.config.id2label,We=[];for(const ke of re.logits){const st=He(ke),Ke=await(0,m.topk)(st,ae),F=Ke[0].tolist(),j=Ke[1].tolist().map((se,_e)=>({label:Ne?Ne[se]:`LABEL_${se}`,score:F[_e]}));ae===1?We.push(...j):We.push(j)}return Array.isArray(ce)||ae===1?We:We[0]}}class v extends b{constructor(ce){super(ce)}async _call(ce,{ignore_labels:ae=["O"]}={}){const we=Array.isArray(ce),re=this.tokenizer(we?ce:[ce],{padding:!0,truncation:!0}),Ne=(await this.model(re)).logits,We=this.model.config.id2label,ke=[];for(let st=0;stEe==this.tokenizer.sep_token_id);ke[F].map((Ee,je)=>Ee==1&&(je===0||je>j&&st.findIndex(Qe=>Qe==U[je])===-1));const se=He[F].tolist(),_e=Ne[F].tolist();for(let Ee=1;Eeje==U[Ee])!==-1)&&(se[Ee]=-1/0,_e[Ee]=-1/0);const ge=(0,d.softmax)(se).map((Ee,je)=>[Ee,je]),Ce=(0,d.softmax)(_e).map((Ee,je)=>[Ee,je]);ge[0][0]=0,Ce[0][0]=0;const Ie=(0,u.product)(ge,Ce).filter(Ee=>Ee[0][1]<=Ee[1][1]).map(Ee=>[Ee[0][1],Ee[1][1],Ee[0][0]*Ee[1][0]]).sort((Ee,je)=>je[2]-Ee[2]);for(let Ee=0;Eese==this.tokenizer.mask_token_id);if(st===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ke=re[We][st],F=await(0,m.topk)(new m.Tensor("float32",(0,d.softmax)(Ke.data),Ke.dims),ae),U=F[0].tolist(),j=F[1].tolist();He.push(j.map((se,_e)=>{const ge=ke.slice();return ge[st]=se,{score:U[_e],token:Number(se),token_str:this.tokenizer.decode([se]),sequence:this.tokenizer.decode(ge,{skip_special_tokens:!0})}}))}return Array.isArray(ce)?He:He[0]}}class w extends b{_key="generated_text";constructor(ce){super(ce)}async _call(ce,ae={}){Array.isArray(ce)||(ce=[ce]),this.model.config.prefix&&(ce=ce.map(ke=>this.model.config.prefix+ke));const we=this.model.config.task_specific_params;we&&we[this.task]&&we[this.task].prefix&&(ce=ce.map(ke=>we[this.task].prefix+ke));const re=this.tokenizer,He={padding:!0,truncation:!0};let Ne;this instanceof E&&"_build_translation_inputs"in re?Ne=re._build_translation_inputs(ce,He,ae):Ne=re(ce,He);const We=await this.model.generate({...Ne,...ae});return re.batch_decode(We,{skip_special_tokens:!0}).map(ke=>({[this._key]:ke}))}}class C extends w{_key="summary_text";constructor(ce){super(ce)}}class E extends w{_key="translation_text";constructor(ce){super(ce)}}function A(Me){return Array.isArray(Me)&&Me.every(ce=>"role"in ce&&"content"in ce)}class L extends b{constructor(ce){super(ce)}async _call(ce,ae={}){let we=!1,re=!1,He;if(typeof ce=="string")He=ce=[ce];else if(Array.isArray(ce)&&ce.every(j=>typeof j=="string"))we=!0,He=ce;else{if(A(ce))ce=[ce];else if(Array.isArray(ce)&&ce.every(A))we=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");re=!0,He=ce.map(j=>this.tokenizer.apply_chat_template(j,{tokenize:!1,add_generation_prompt:!0}))}const Ne=ae.add_special_tokens??!1,We=re?!1:ae.return_full_text??!0;this.tokenizer.padding_side="left";const ke=this.tokenizer(He,{add_special_tokens:Ne,padding:!0,truncation:!0}),st=await this.model.generate({...ke,...ae}),Ke=this.tokenizer.batch_decode(st,{skip_special_tokens:!0});let F;!We&&ke.input_ids.dims.at(-1)>0&&(F=this.tokenizer.batch_decode(ke.input_ids,{skip_special_tokens:!0}).map(j=>j.length));const U=Array.from({length:ce.length},j=>[]);for(let j=0;j[ae.toLowerCase(),we])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(ce,ae,{hypothesis_template:we="This example is {}.",multi_label:re=!1}={}){const He=Array.isArray(ce);He||(ce=[ce]),Array.isArray(ae)||(ae=[ae]);const Ne=ae.map(st=>we.replace("{}",st)),We=re||ae.length===1,ke=[];for(const st of ce){const Ke=[];for(const j of Ne){const se=this.tokenizer(st,{text_pair:j,padding:!0,truncation:!0}),_e=await this.model(se);We?Ke.push([_e.logits.data[this.contradiction_id],_e.logits.data[this.entailment_id]]):Ke.push(_e.logits.data[this.entailment_id])}const U=(We?Ke.map(j=>(0,d.softmax)(j)[1]):(0,d.softmax)(Ke)).map((j,se)=>[j,se]).sort((j,se)=>se[0]-j[0]);ke.push({sequence:st,labels:U.map(j=>ae[j[1]]),scores:U.map(j=>j[0])})}return He?ke:ke[0]}}class O extends b{constructor(ce){super(ce)}async _call(ce,{pooling:ae="none",normalize:we=!1,quantize:re=!1,precision:He="binary"}={}){const Ne=this.tokenizer(ce,{padding:!0,truncation:!0}),We=await this.model(Ne);let ke=We.last_hidden_state??We.logits??We.token_embeddings;if(ae!=="none")if(ae==="mean")ke=(0,m.mean_pooling)(ke,Ne.attention_mask);else if(ae==="cls")ke=ke.slice(null,0);else throw Error(`Pooling method '${ae}' not supported.`);return we&&(ke=ke.normalize(2,-1)),re&&(ke=(0,m.quantize_embeddings)(ke,He)),ke}}class H extends b{constructor(ce){super(ce)}async _call(ce,{pool:ae=null}={}){const we=await _(ce),{pixel_values:re}=await this.processor(we),He=await this.model({pixel_values:re});let Ne;if(ae){if(!("pooler_output"in He))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ne=He.pooler_output}else Ne=He.last_hidden_state??He.logits??He.image_embeds;return Ne}}class Z extends b{constructor(ce){super(ce)}async _call(ce,{top_k:ae=5}={}){const we=this.processor.feature_extractor.config.sampling_rate,re=await g(ce,we),He=this.model.config.id2label,Ne=[];for(const We of re){const ke=await this.processor(We),Ke=(await this.model(ke)).logits[0],F=await(0,m.topk)(new m.Tensor("float32",(0,d.softmax)(Ke.data),Ke.dims),ae),U=F[0].tolist(),se=F[1].tolist().map((_e,ge)=>({label:He?He[_e]:`LABEL_${_e}`,score:U[ge]}));Ne.push(se)}return Array.isArray(ce)?Ne:Ne[0]}}class $ extends b{constructor(ce){super(ce)}async _call(ce,ae,{hypothesis_template:we="This is a sound of {}."}={}){const re=!Array.isArray(ce);re&&(ce=[ce]);const He=ae.map(Ke=>we.replace("{}",Ke)),Ne=this.tokenizer(He,{padding:!0,truncation:!0}),We=this.processor.feature_extractor.config.sampling_rate,ke=await g(ce,We),st=[];for(const Ke of ke){const F=await this.processor(Ke),U=await this.model({...Ne,...F}),j=(0,d.softmax)(U.logits_per_audio.data);st.push([...j].map((se,_e)=>({score:se,label:ae[_e]})))}return re?st[0]:st}}class J extends b{constructor(ce){super(ce)}async _call(ce,ae={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(ce,ae);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ce,ae);case"moonshine":return this._call_moonshine(ce,ae);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ce,ae){ae.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ae.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const we=!Array.isArray(ce);we&&(ce=[ce]);const re=this.processor.feature_extractor.config.sampling_rate,He=await g(ce,re),Ne=[];for(const We of He){const ke=await this.processor(We),Ke=(await this.model(ke)).logits[0],F=[];for(const j of Ke)F.push((0,d.max)(j.data)[1]);const U=this.tokenizer.decode(F);Ne.push({text:U})}return we?Ne[0]:Ne}async _call_whisper(ce,ae){const we=ae.return_timestamps??!1,re=ae.chunk_length_s??0,He=ae.force_full_sequences??!1;let Ne=ae.stride_length_s??null;const We={...ae};we==="word"&&(We.return_token_timestamps=!0,We.return_timestamps=!1);const ke=!Array.isArray(ce);ke&&(ce=[ce]);const st=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ke=this.processor.feature_extractor.config.hop_length,F=this.processor.feature_extractor.config.sampling_rate,U=await g(ce,F),j=[];for(const se of U){let _e=[];if(re>0){if(Ne===null)Ne=re/6;else if(re<=Ne)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ie=F*re,Ee=F*Ne,je=Ie-2*Ee;let Qe=0;for(;;){const ot=Qe+Ie,bt=se.subarray(Qe,ot),_t=await this.processor(bt),nt=Qe===0,ft=ot>=se.length;if(_e.push({stride:[bt.length,nt?0:Ee,ft?0:Ee],input_features:_t.input_features,is_last:ft}),ft)break;Qe+=je}}else _e=[{stride:[se.length,0,0],input_features:(await this.processor(se)).input_features,is_last:!0}];for(const Ie of _e){We.num_frames=Math.floor(Ie.stride[0]/Ke);const Ee=await this.model.generate({inputs:Ie.input_features,...We});we==="word"?(Ie.tokens=Ee.sequences.tolist()[0],Ie.token_timestamps=Ee.token_timestamps.tolist()[0].map(je=>(0,d.round)(je,2))):Ie.tokens=Ee[0].tolist(),Ie.stride=Ie.stride.map(je=>je/F)}const[ge,Ce]=this.tokenizer._decode_asr(_e,{time_precision:st,return_timestamps:we,force_full_sequences:He});j.push({text:ge,...Ce})}return ke?j[0]:j}async _call_moonshine(ce,ae){const we=!Array.isArray(ce);we&&(ce=[ce]);const re=this.processor.feature_extractor.config.sampling_rate,He=await g(ce,re),Ne=[];for(const We of He){const ke=await this.processor(We),st=Math.floor(We.length/re)*6,Ke=await this.model.generate({max_new_tokens:st,...ae,...ke}),F=this.processor.batch_decode(Ke,{skip_special_tokens:!0})[0];Ne.push({text:F})}return we?Ne[0]:Ne}}class ee extends b{constructor(ce){super(ce)}async _call(ce,ae={}){const we=Array.isArray(ce),re=await _(ce),{pixel_values:He}=await this.processor(re),Ne=[];for(const We of He){We.dims=[1,...We.dims];const ke=await this.model.generate({inputs:We,...ae}),st=this.tokenizer.batch_decode(ke,{skip_special_tokens:!0}).map(Ke=>({generated_text:Ke.trim()}));Ne.push(st)}return we?Ne:Ne[0]}}class X extends b{constructor(ce){super(ce)}async _call(ce,{top_k:ae=5}={}){const we=await _(ce),{pixel_values:re}=await this.processor(we),He=await this.model({pixel_values:re}),Ne=this.model.config.id2label,We=[];for(const ke of He.logits){const st=await(0,m.topk)(new m.Tensor("float32",(0,d.softmax)(ke.data),ke.dims),ae),Ke=st[0].tolist(),U=st[1].tolist().map((j,se)=>({label:Ne?Ne[j]:`LABEL_${j}`,score:Ke[se]}));We.push(U)}return Array.isArray(ce)?We:We[0]}}class ne extends b{constructor(ce){super(ce),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ce,{threshold:ae=.5,mask_threshold:we=.5,overlap_mask_area_threshold:re=.8,label_ids_to_fuse:He=null,target_sizes:Ne=null,subtask:We=null}={}){if(Array.isArray(ce)&&ce.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const st=await _(ce),Ke=st.map(Ie=>[Ie.height,Ie.width]),F=await this.processor(st),{inputNames:U,outputNames:j}=this.model.sessions.model;if(!U.includes("pixel_values")){if(U.length!==1)throw Error(`Expected a single input name, but got ${U.length} inputs: ${U}.`);const Ie=U[0];if(Ie in F)throw Error(`Input name ${Ie} already exists in the inputs.`);F[Ie]=F.pixel_values}const se=await this.model(F);let _e=null;if(We!==null)_e=this.subtasks_mapping[We];else if(this.processor.image_processor){for(const[Ie,Ee]of Object.entries(this.subtasks_mapping))if(Ee in this.processor.image_processor){_e=this.processor.image_processor[Ee].bind(this.processor.image_processor),We=Ie;break}}const ge=this.model.config.id2label,Ce=[];if(We)if(We==="panoptic"||We==="instance"){const Ie=_e(se,ae,we,re,He,Ne??Ke)[0],Ee=Ie.segmentation;for(const je of Ie.segments_info){const Qe=new Uint8ClampedArray(Ee.data.length);for(let bt=0;bt_t<-1e-5||_t>1+1e-5)&&ot.sigmoid_();const bt=await h.RawImage.fromTensor(ot.mul_(255).to("uint8")).resize(Qe[1],Qe[0]);Ce.push({label:null,score:null,mask:bt})}}return Ce}}class Q extends ne{constructor(ce){super(ce)}async _call(ce,ae={}){if(Array.isArray(ce)&&ce.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const re=await _(ce),He=await super._call(ce,ae);return re.map((We,ke)=>{const st=We.clone();return st.putAlpha(He[ke].mask),st})}}class oe extends b{constructor(ce){super(ce)}async _call(ce,ae,{hypothesis_template:we="This is a photo of {}"}={}){const re=Array.isArray(ce),He=await _(ce),Ne=ae.map(U=>we.replace("{}",U)),We=this.tokenizer(Ne,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ke}=await this.processor(He),st=await this.model({...We,pixel_values:ke}),Ke=this.model.config.model_type==="siglip"?U=>U.sigmoid().data:U=>(0,d.softmax)(U.data),F=[];for(const U of st.logits_per_image){const se=[...Ke(U)].map((_e,ge)=>({score:_e,label:ae[ge]}));se.sort((_e,ge)=>ge.score-_e.score),F.push(se)}return re?F:F[0]}}class W extends b{constructor(ce){super(ce)}async _call(ce,{threshold:ae=.9,percentage:we=!1}={}){const re=Array.isArray(ce);if(re&&ce.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const He=await _(ce),Ne=we?null:He.map(j=>[j.height,j.width]),{pixel_values:We,pixel_mask:ke}=await this.processor(He),st=await this.model({pixel_values:We,pixel_mask:ke}),Ke=this.processor.image_processor.post_process_object_detection(st,ae,Ne),F=this.model.config.id2label,U=Ke.map(j=>j.boxes.map((se,_e)=>({score:j.scores[_e],label:F[j.classes[_e]],box:y(se,!we)})));return re?U:U[0]}}class q extends b{constructor(ce){super(ce)}async _call(ce,ae,{threshold:we=.1,top_k:re=null,percentage:He=!1}={}){const Ne=Array.isArray(ce),We=await _(ce),ke=this.tokenizer(ae,{padding:!0,truncation:!0}),st=await this.processor(We),Ke=[];for(let F=0;F({score:Ce.scores[Ee],label:Ce.labels[Ee],box:y(Ie,!He)}))}else{const Ce=this.processor.image_processor.post_process_object_detection(_e,we,j,!0)[0];ge=Ce.boxes.map((Ie,Ee)=>({score:Ce.scores[Ee],label:ae[Ce.classes[Ee]],box:y(Ie,!He)}))}ge.sort((Ce,Ie)=>Ie.score-Ce.score),re!==null&&(ge=ge.slice(0,re)),Ke.push(ge)}return Ne?Ke:Ke[0]}}class G extends b{constructor(ce){super(ce)}async _call(ce,ae,we={}){const re=(await _(ce))[0],{pixel_values:He}=await this.processor(re),Ne=`${ae}`,We=this.tokenizer(Ne,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ke=await this.model.generate({inputs:He,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:We,...we}),Ke=this.tokenizer.batch_decode(ke)[0].match(/(.*?)<\/s_answer>/);let F=null;return Ke&&Ke.length>=2&&(F=Ke[1].trim()),[{answer:F}]}}class te extends b{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(ce){super(ce),this.vocoder=ce.vocoder??null}async _call(ce,{speaker_embeddings:ae=null}={}){return this.processor?this._call_text_to_spectrogram(ce,{speaker_embeddings:ae}):this._call_text_to_waveform(ce)}async _call_text_to_waveform(ce){const ae=this.tokenizer(ce,{padding:!0,truncation:!0}),{waveform:we}=await this.model(ae),re=this.model.config.sampling_rate;return new f.RawAudio(we.data,re)}async _call_text_to_spectrogram(ce,{speaker_embeddings:ae}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await s.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof ae=="string"||ae instanceof URL)&&(ae=new Float32Array(await(await fetch(ae)).arrayBuffer())),ae instanceof Float32Array)ae=new m.Tensor("float32",ae,[1,ae.length]);else if(!(ae instanceof m.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:we}=this.tokenizer(ce,{padding:!0,truncation:!0}),{waveform:re}=await this.model.generate_speech(we,ae,{vocoder:this.vocoder}),He=this.processor.feature_extractor.config.sampling_rate;return new f.RawAudio(re.data,He)}}class B extends b{constructor(ce){super(ce)}async _call(ce){const ae=await _(ce),we=await this.processor(ae),re=await this.model(we),He=[];for(const Ne of re.reconstruction){const We=Ne.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");He.push(h.RawImage.fromTensor(We))}return He.length>1?He:He[0]}}class le extends b{constructor(ce){super(ce)}async _call(ce){const ae=await _(ce),we=await this.processor(ae),{predicted_depth:re}=await this.model(we),He=[];for(let Ne=0;Ne1?He:He[0]}}const ye=Object.freeze({"text-classification":{tokenizer:i.AutoTokenizer,pipeline:T,model:s.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:i.AutoTokenizer,pipeline:v,model:s.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:i.AutoTokenizer,pipeline:x,model:s.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:i.AutoTokenizer,pipeline:P,model:s.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:i.AutoTokenizer,pipeline:C,model:s.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:i.AutoTokenizer,pipeline:E,model:s.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:i.AutoTokenizer,pipeline:w,model:s.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:i.AutoTokenizer,pipeline:L,model:s.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:i.AutoTokenizer,pipeline:I,model:s.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Z,model:s.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:i.AutoTokenizer,pipeline:$,model:s.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:i.AutoTokenizer,pipeline:J,model:[s.AutoModelForSpeechSeq2Seq,s.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:i.AutoTokenizer,pipeline:te,model:[s.AutoModelForTextToWaveform,s.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:i.AutoTokenizer,pipeline:ee,model:s.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:X,model:s.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ne,model:[s.AutoModelForImageSegmentation,s.AutoModelForSemanticSegmentation,s.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:Q,model:[s.AutoModelForImageSegmentation,s.AutoModelForSemanticSegmentation,s.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:i.AutoTokenizer,pipeline:oe,model:s.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:W,model:s.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:i.AutoTokenizer,pipeline:q,model:s.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:i.AutoTokenizer,pipeline:G,model:s.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:B,model:s.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:le,model:s.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:i.AutoTokenizer,pipeline:O,model:s.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:H,model:[s.AutoModelForImageFeatureExtraction,s.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),me=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function xe(Me,ce=null,{progress_callback:ae=null,config:we=null,cache_dir:re=null,local_files_only:He=!1,revision:Ne="main",device:We=null,dtype:ke=null,subfolder:st="onnx",use_external_data_format:Ke=null,model_file_name:F=null,session_options:U={}}={}){Me=me[Me]??Me;const j=ye[Me.split("_",1)[0]];if(!j)throw Error(`Unsupported pipeline: ${Me}. Must be one of [${Object.keys(ye)}]`);ce||(ce=j.default.model,console.log(`No model specified. Using default model: "${ce}".`));const se={progress_callback:ae,config:we,cache_dir:re,local_files_only:He,revision:Ne,device:We,dtype:ke,subfolder:st,use_external_data_format:Ke,model_file_name:F,session_options:U},_e=new Map([["tokenizer",j.tokenizer],["model",j.model],["processor",j.processor]]),ge=await ze(_e,ce,se);ge.task=Me,(0,u.dispatchCallback)(ae,{status:"ready",task:Me,model:ce});const Ce=j.pipeline;return new Ce(ge)}async function ze(Me,ce,ae){const we=Object.create(null),re=[];for(const[He,Ne]of Me.entries()){if(!Ne)continue;let We;Array.isArray(Ne)?We=new Promise(async(ke,st)=>{let Ke;for(const F of Ne){if(F===null){ke(null);return}try{ke(await F.from_pretrained(ce,ae));return}catch(U){if(U.message?.includes("Unsupported model type"))Ke=U;else if(U.message?.includes("Could not locate file"))Ke=U;else{st(U);return}}}st(Ke)}):We=Ne.from_pretrained(ce,ae),we[He]=We,re.push(We)}await Promise.all(re);for(const[He,Ne]of Object.entries(we))we[He]=await Ne;return we}},"./src/tokenizers.js":(n,e,t)=>{t.r(e),t.d(e,{AlbertTokenizer:()=>Pt,AutoTokenizer:()=>Kn,BartTokenizer:()=>Er,BertTokenizer:()=>gt,BlenderbotSmallTokenizer:()=>li,BlenderbotTokenizer:()=>nn,BloomTokenizer:()=>Ur,CLIPTokenizer:()=>Sn,CamembertTokenizer:()=>Bt,CodeGenTokenizer:()=>yn,CodeLlamaTokenizer:()=>vr,CohereTokenizer:()=>Xi,ConvBertTokenizer:()=>On,DebertaTokenizer:()=>Pn,DebertaV2Tokenizer:()=>ln,DistilBertTokenizer:()=>It,ElectraTokenizer:()=>rr,EsmTokenizer:()=>Fe,FalconTokenizer:()=>qe,GPT2Tokenizer:()=>Ti,GPTNeoXTokenizer:()=>Ue,GemmaTokenizer:()=>Ct,Grok1Tokenizer:()=>Nt,HerbertTokenizer:()=>vi,LlamaTokenizer:()=>Yr,M2M100Tokenizer:()=>sn,MBart50Tokenizer:()=>Ns,MBartTokenizer:()=>zr,MPNetTokenizer:()=>Oe,MarianTokenizer:()=>Ln,MgpstrTokenizer:()=>yi,MobileBertTokenizer:()=>tn,NllbTokenizer:()=>qt,NougatTokenizer:()=>sr,PreTrainedTokenizer:()=>tt,Qwen2Tokenizer:()=>wt,RoFormerTokenizer:()=>ut,RobertaTokenizer:()=>Sr,SiglipTokenizer:()=>Jn,SpeechT5Tokenizer:()=>An,SqueezeBertTokenizer:()=>rn,T5Tokenizer:()=>ri,TokenizerModel:()=>H,VitsTokenizer:()=>yr,Wav2Vec2CTCTokenizer:()=>dn,WhisperTokenizer:()=>Jt,XLMRobertaTokenizer:()=>ue,XLMTokenizer:()=>Vi,is_chinese_char:()=>P});var i=t("./src/utils/generic.js"),s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/tensor.js"),d=t("./src/utils/data-structures.js"),f=t("./node_modules/@huggingface/jinja/dist/index.js"),m=t("./src/models/whisper/common_whisper.js");async function h(Pe,V){const fe=await Promise.all([(0,o.getModelJSON)(Pe,"tokenizer.json",!0,V),(0,o.getModelJSON)(Pe,"tokenizer_config.json",!0,V)]);return V.legacy!==null&&(fe[1].legacy=V.legacy),fe}function _(Pe,V){const fe=[];let ve=0;for(const Te of Pe.matchAll(V)){const Be=Te[0];ve0&&fe.push(Be),ve=Te.index+Be.length}return ve=19968&&Pe<=40959||Pe>=13312&&Pe<=19903||Pe>=131072&&Pe<=173791||Pe>=173824&&Pe<=177983||Pe>=177984&&Pe<=178207||Pe>=178208&&Pe<=183983||Pe>=63744&&Pe<=64255||Pe>=194560&&Pe<=195103}function w(Pe,V,fe){const ve=[];let Te=0;for(;Tethis.tokens_to_ids.get(fe)??this.unk_token_id)}convert_ids_to_tokens(V){return V.map(fe=>this.vocab[fe]??this.unk_token)}}class Z extends H{constructor(V){super(V),this.tokens_to_ids=y(V.vocab),this.unk_token_id=this.tokens_to_ids.get(V.unk_token),this.unk_token=V.unk_token,this.max_input_chars_per_word=V.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,ve]of this.tokens_to_ids)this.vocab[ve]=fe}encode(V){const fe=[];for(const ve of V){const Te=[...ve];if(Te.length>this.max_input_chars_per_word){fe.push(this.unk_token);continue}let Be=!1,lt=0;const Ot=[];for(;lt0&&(Dt=this.config.continuing_subword_prefix+Dt),this.tokens_to_ids.has(Dt)){Ft=Dt;break}--Lt}if(Ft===null){Be=!0;break}Ot.push(Ft),lt=Lt}Be?fe.push(this.unk_token):fe.push(...Ot)}return fe}}class $ extends H{constructor(V,fe){super(V);const ve=V.vocab.length;this.vocab=new Array(ve),this.scores=new Array(ve);for(let Te=0;Te[Te,Be])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=fe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,l.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new d.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(V){const fe=V.chars,ve=1;let Te=0;for(;Te{const Pe=[...Array.from({length:94},(Te,Be)=>Be+33),...Array.from({length:12},(Te,Be)=>Be+161),...Array.from({length:82},(Te,Be)=>Be+174)],V=Pe.slice();let fe=0;for(let Te=0;Te<256;++Te)Pe.includes(Te)||(Pe.push(Te),V.push(256+fe),fe+=1);const ve=V.map(Te=>String.fromCharCode(Te));return Object.fromEntries(Pe.map((Te,Be)=>[Te,ve[Be]]))})(),ee=(0,s.reverseDictionary)(J);class X extends H{constructor(V){super(V),this.tokens_to_ids=y(V.vocab),this.unk_token_id=this.tokens_to_ids.get(V.unk_token),this.unk_token=V.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ve,Te]of this.tokens_to_ids)this.vocab[Te]=ve;const fe=Array.isArray(V.merges[0]);this.merges=fe?V.merges:V.merges.map(ve=>ve.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ve,Te)=>[JSON.stringify(ve),Te])),this.end_of_word_suffix=V.end_of_word_suffix,this.continuing_subword_suffix=V.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new d.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(V){if(V.length===0)return[];const fe=this.cache.get(V);if(fe!==void 0)return fe;const ve=Array.from(V);this.end_of_word_suffix&&(ve[ve.length-1]+=this.end_of_word_suffix);let Te=[];if(ve.length>1){const Be=new d.PriorityQueue((Lt,Ft)=>Lt.score`<0x${Ot.toString(16).toUpperCase().padStart(2,"0")}>`);lt.every(Ot=>this.tokens_to_ids.has(Ot))?fe.push(...lt):fe.push(this.unk_token)}else fe.push(this.unk_token)}return fe}}class ne extends H{constructor(V,fe){super(V),this.tokens_to_ids=y(fe.target_lang?V.vocab[fe.target_lang]:V.vocab),this.bos_token=fe.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=fe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=fe.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=fe.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[ve,Te]of this.tokens_to_ids)this.vocab[Te]=ve}encode(V){return V}}class Q extends i.Callable{constructor(V){super(),this.config=V}static fromConfig(V){if(V===null)return null;switch(V.type){case"BertNormalizer":return new Me(V);case"Precompiled":return new ft(V);case"Sequence":return new ze(V);case"Replace":return new oe(V);case"NFC":return new q(V);case"NFD":return new G(V);case"NFKC":return new te(V);case"NFKD":return new B(V);case"Strip":return new le(V);case"StripAccents":return new ye(V);case"Lowercase":return new me(V);case"Prepend":return new xe(V);default:throw new Error(`Unknown Normalizer type: ${V.type}`)}}normalize(V){throw Error("normalize should be implemented in subclass.")}_call(V){return this.normalize(V)}}class oe extends Q{normalize(V){const fe=g(this.config.pattern);return fe===null?V:V.replaceAll(fe,this.config.content)}}class W extends Q{form=void 0;normalize(V){return V=V.normalize(this.form),V}}class q extends W{form="NFC"}class G extends W{form="NFD"}class te extends W{form="NFKC"}class B extends W{form="NFKD"}class le extends Q{normalize(V){return this.config.strip_left&&this.config.strip_right?V=V.trim():(this.config.strip_left&&(V=V.trimStart()),this.config.strip_right&&(V=V.trimEnd())),V}}class ye extends Q{normalize(V){return V=v(V),V}}class me extends Q{normalize(V){return V=V.toLowerCase(),V}}class xe extends Q{normalize(V){return V=this.config.prepend+V,V}}class ze extends Q{constructor(V){super(V),this.normalizers=V.normalizers.map(fe=>Q.fromConfig(fe))}normalize(V){return this.normalizers.reduce((fe,ve)=>ve.normalize(fe),V)}}class Me extends Q{_tokenize_chinese_chars(V){const fe=[];for(let ve=0;vethis.pre_tokenize_text(ve,fe)):this.pre_tokenize_text(V,fe)).flat()}_call(V,fe){return this.pre_tokenize(V,fe)}}class ae extends ce{constructor(V){super(),this.pattern=new RegExp(`[^\\s${E}]+|[${E}]`,"gu")}pre_tokenize_text(V,fe){return V.trim().match(this.pattern)||[]}}class we extends ce{constructor(V){super(),this.config=V,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=J,this.text_encoder=new TextEncoder}pre_tokenize_text(V,fe){return this.add_prefix_space&&!V.startsWith(" ")&&(V=" "+V),(this.use_regex?V.match(this.pattern)||[]:[V]).map(Te=>Array.from(this.text_encoder.encode(Te),Be=>this.byte_encoder[Be]).join(""))}}class re extends ce{constructor(V){super(),this.config=V,this.pattern=g(this.config.pattern,this.config.invert)}pre_tokenize_text(V,fe){return this.pattern===null?[]:this.config.invert?V.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?V.split(this.pattern).filter(ve=>ve):_(V,this.pattern)}}class He extends ce{constructor(V){super(),this.config=V,this.pattern=new RegExp(`[^${E}]+|[${E}]+`,"gu")}pre_tokenize_text(V,fe){return V.match(this.pattern)||[]}}class Ne extends ce{constructor(V){super(),this.config=V;const fe=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(fe,"gu")}pre_tokenize_text(V,fe){return V.match(this.pattern)||[]}}class We extends i.Callable{constructor(V){super(),this.config=V}static fromConfig(V){if(V===null)return null;switch(V.type){case"TemplateProcessing":return new Ke(V);case"ByteLevel":return new F(V);case"RobertaProcessing":return new st(V);case"BertProcessing":return new ke(V);case"Sequence":return new U(V);default:throw new Error(`Unknown PostProcessor type: ${V.type}`)}}post_process(V,...fe){throw Error("post_process should be implemented in subclass.")}_call(V,...fe){return this.post_process(V,...fe)}}class ke extends We{constructor(V){super(V),this.cls=V.cls[0],this.sep=V.sep[0]}post_process(V,fe=null,{add_special_tokens:ve=!0}={}){ve&&(V=(0,s.mergeArrays)([this.cls],V,[this.sep]));let Te=new Array(V.length).fill(0);if(fe!==null){const Be=ve&&this instanceof st?[this.sep]:[],lt=ve?[this.sep]:[];V=(0,s.mergeArrays)(V,Be,fe,lt),Te=(0,s.mergeArrays)(Te,new Array(fe.length+Be.length+lt.length).fill(1))}return{tokens:V,token_type_ids:Te}}}class st extends ke{}class Ke extends We{constructor(V){super(V),this.single=V.single,this.pair=V.pair}post_process(V,fe=null,{add_special_tokens:ve=!0}={}){const Te=fe===null?this.single:this.pair;let Be=[],lt=[];for(const Ot of Te)"SpecialToken"in Ot?ve&&(Be.push(Ot.SpecialToken.id),lt.push(Ot.SpecialToken.type_id)):"Sequence"in Ot&&(Ot.Sequence.id==="A"?(Be=(0,s.mergeArrays)(Be,V),lt=(0,s.mergeArrays)(lt,new Array(V.length).fill(Ot.Sequence.type_id))):Ot.Sequence.id==="B"&&(Be=(0,s.mergeArrays)(Be,fe),lt=(0,s.mergeArrays)(lt,new Array(fe.length).fill(Ot.Sequence.type_id))));return{tokens:Be,token_type_ids:lt}}}class F extends We{post_process(V,fe=null){return fe&&(V=(0,s.mergeArrays)(V,fe)),{tokens:V}}}class U extends We{constructor(V){super(V),this.processors=V.processors.map(fe=>We.fromConfig(fe))}post_process(V,fe=null,ve={}){let Te;for(const Be of this.processors)if(Be instanceof F)V=Be.post_process(V).tokens,fe&&(fe=Be.post_process(fe).tokens);else{const lt=Be.post_process(V,fe,ve);V=lt.tokens,Te=lt.token_type_ids}return{tokens:V,token_type_ids:Te}}}class j extends i.Callable{constructor(V){super(),this.config=V,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=V.trim_offsets}static fromConfig(V){if(V===null)return null;switch(V.type){case"WordPiece":return new Ie(V);case"Metaspace":return new nt(V);case"ByteLevel":return new Ee(V);case"Replace":return new se(V);case"ByteFallback":return new _e(V);case"Fuse":return new ge(V);case"Strip":return new Ce(V);case"Sequence":return new Qe(V);case"CTC":return new je(V);case"BPEDecoder":return new ot(V);default:throw new Error(`Unknown Decoder type: ${V.type}`)}}_call(V){return this.decode(V)}decode(V){return this.decode_chain(V).join("")}decode_chain(V){throw Error("`decode_chain` should be implemented in subclass.")}}class se extends j{decode_chain(V){const fe=g(this.config.pattern);return fe===null?V:V.map(ve=>ve.replaceAll(fe,this.config.content))}}class _e extends j{constructor(V){super(V),this.text_decoder=new TextDecoder}decode_chain(V){const fe=[];let ve=[];for(const Te of V){let Be=null;if(Te.length===6&&Te.startsWith("<0x")&&Te.endsWith(">")){const lt=parseInt(Te.slice(3,5),16);isNaN(lt)||(Be=lt)}if(Be!==null)ve.push(Be);else{if(ve.length>0){const lt=this.text_decoder.decode(Uint8Array.from(ve));fe.push(lt),ve=[]}fe.push(Te)}}if(ve.length>0){const Te=this.text_decoder.decode(Uint8Array.from(ve));fe.push(Te),ve=[]}return fe}}class ge extends j{decode_chain(V){return[V.join("")]}}class Ce extends j{constructor(V){super(V),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(V){return V.map(fe=>{let ve=0;for(let Be=0;Be(ve!==0&&(fe.startsWith(this.config.prefix)?fe=fe.replace(this.config.prefix,""):fe=" "+fe),this.cleanup&&(fe=T(fe)),fe))}}class Ee extends j{constructor(V){super(V),this.byte_decoder=ee,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(V){const fe=V.join(""),ve=new Uint8Array([...fe].map(Be=>this.byte_decoder[Be]));return this.text_decoder.decode(ve)}decode_chain(V){const fe=[];let ve=[];for(const Te of V)this.added_tokens.find(Be=>Be.content===Te)!==void 0?(ve.length>0&&(fe.push(this.convert_tokens_to_string(ve)),ve=[]),fe.push(Te)):ve.push(Te);return ve.length>0&&fe.push(this.convert_tokens_to_string(ve)),fe}}class je extends j{constructor(V){super(V),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(V){if(V.length===0)return"";const fe=[V[0]];for(let Be=1;BeBe!==this.pad_token).join("");return this.cleanup&&(Te=T(Te).replaceAll(this.word_delimiter_token," ").trim()),Te}decode_chain(V){return[this.convert_tokens_to_string(V)]}}class Qe extends j{constructor(V){super(V),this.decoders=V.decoders.map(fe=>j.fromConfig(fe))}decode_chain(V){return this.decoders.reduce((fe,ve)=>ve.decode_chain(fe),V)}}class ot extends j{constructor(V){super(V),this.suffix=this.config.suffix}decode_chain(V){return V.map((fe,ve)=>fe.replaceAll(this.suffix,ve===V.length-1?"":" "))}}class bt extends j{decode_chain(V){let fe="";for(let ve=1;veve.normalize("NFKC")).join("~"):V=V.normalize("NFKC"),V}}class vt extends ce{constructor(V){super(),this.tokenizers=V.pretokenizers.map(fe=>ce.fromConfig(fe))}pre_tokenize_text(V,fe){return this.tokenizers.reduce((ve,Te)=>Te.pre_tokenize(ve,fe),[V])}}class mn extends ce{constructor(V){super()}pre_tokenize_text(V,fe){return V.match(/\w+|[^\w\s]+/g)||[]}}class Se extends ce{constructor(V){super()}pre_tokenize_text(V,fe){return C(V)}}class St extends ce{constructor(V){super(),this.config=V,this.pattern=g(this.config.pattern),this.content=this.config.content}pre_tokenize_text(V,fe){return this.pattern===null?[V]:[V.replaceAll(this.pattern,this.config.content)]}}const Ze=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function it(Pe,V,fe,ve){for(const Te of Object.keys(Pe)){const Be=V-Pe[Te].length,lt=fe(Te),Ot=new Array(Be).fill(lt);Pe[Te]=ve==="right"?(0,s.mergeArrays)(Pe[Te],Ot):(0,s.mergeArrays)(Ot,Pe[Te])}}function yt(Pe,V){for(const fe of Object.keys(Pe))Pe[fe].length=V}class tt extends i.Callable{return_token_type_ids=!1;padding_side="right";constructor(V,fe){super(),this._tokenizer_config=fe,this.normalizer=Q.fromConfig(V.normalizer),this.pre_tokenizer=ce.fromConfig(V.pre_tokenizer),this.model=H.fromConfig(V.model,fe),this.post_processor=We.fromConfig(V.post_processor),this.decoder=j.fromConfig(V.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ve of V.added_tokens){const Te=new O(ve);this.added_tokens.push(Te),this.model.tokens_to_ids.set(Te.content,Te.id),this.model.vocab[Te.id]=Te.content,Te.special&&(this.special_tokens.push(Te.content),this.all_special_ids.push(Te.id))}if(this.additional_special_tokens=fe.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new d.DictionarySplitter(this.added_tokens.map(ve=>ve.content)),this.added_tokens_map=new Map(this.added_tokens.map(ve=>[ve.content,ve])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=fe.model_max_length,this.remove_space=fe.remove_space,this.clean_up_tokenization_spaces=fe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=fe.do_lowercase_and_remove_accent??!1,fe.padding_side&&(this.padding_side=fe.padding_side),this.legacy=!1,this.chat_template=fe.chat_template??null,Array.isArray(this.chat_template)){const ve=Object.create(null);for(const{name:Te,template:Be}of this.chat_template){if(typeof Te!="string"||typeof Be!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ve[Te]=Be}this.chat_template=ve}this._compiled_template_cache=new Map}getToken(...V){for(const fe of V){const ve=this._tokenizer_config[fe];if(ve)if(typeof ve=="object"){if(ve.__type==="AddedToken")return ve.content;throw Error(`Unknown token: ${ve}`)}else return ve}return null}static async from_pretrained(V,{progress_callback:fe=null,config:ve=null,cache_dir:Te=null,local_files_only:Be=!1,revision:lt="main",legacy:Ot=null}={}){const Lt=await h(V,{progress_callback:fe,config:ve,cache_dir:Te,local_files_only:Be,revision:lt,legacy:Ot});return new this(...Lt)}_call(V,{text_pair:fe=null,add_special_tokens:ve=!0,padding:Te=!1,truncation:Be=null,max_length:lt=null,return_tensor:Ot=!0,return_token_type_ids:Lt=null}={}){const Ft=Array.isArray(V);let Dt;if(Ft){if(V.length===0)throw Error("text array must be non-empty");if(fe!==null){if(Array.isArray(fe)){if(V.length!==fe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Dt=V.map((cn,pi)=>this._encode_plus(cn,{text_pair:fe[pi],add_special_tokens:ve,return_token_type_ids:Lt}))}else Dt=V.map(cn=>this._encode_plus(cn,{add_special_tokens:ve,return_token_type_ids:Lt}))}else{if(V==null)throw Error("text may not be null or undefined");if(Array.isArray(fe))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Dt=[this._encode_plus(V,{text_pair:fe,add_special_tokens:ve,return_token_type_ids:Lt})]}if(lt===null?Te==="max_length"?lt=this.model_max_length:lt=(0,l.max)(Dt.map(cn=>cn.input_ids.length))[0]:Be||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),lt=Math.min(lt,this.model_max_length??1/0),Te||Be)for(let cn=0;cnlt?Be&&yt(Dt[cn],lt):Te&&it(Dt[cn],lt,pi=>pi==="input_ids"?this.pad_token_id:0,this.padding_side));const Cn={};if(Ot){if(!(Te&&Be)&&Dt.some(pi=>{for(const Gi of Object.keys(pi))if(pi[Gi].length!==Dt[0][Gi]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const cn=[Dt.length,Dt[0].input_ids.length];for(const pi of Object.keys(Dt[0]))Cn[pi]=new u.Tensor("int64",BigInt64Array.from(Dt.flatMap(Gi=>Gi[pi]).map(BigInt)),cn)}else{for(const cn of Object.keys(Dt[0]))Cn[cn]=Dt.map(pi=>pi[cn]);if(!Ft)for(const cn of Object.keys(Cn))Cn[cn]=Cn[cn][0]}return Cn}_encode_text(V){if(V===null)return null;const fe=this.added_tokens_splitter.split(V);for(let Te=0;Te0&&(fe[Te-1]=fe[Te-1].trimEnd()),Be.rstrip&&Te{if(Te.length===0)return[];if(this.added_tokens_map.has(Te))return[Te];if(this.remove_space===!0&&(Te=Te.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Te=x(Te)),this.normalizer!==null&&(Te=this.normalizer(Te)),Te.length===0)return[];const lt=this.pre_tokenizer!==null?this.pre_tokenizer(Te,{section_index:Be}):[Te];return this.model(lt)})}_encode_plus(V,{text_pair:fe=null,add_special_tokens:ve=!0,return_token_type_ids:Te=null}={}){const{tokens:Be,token_type_ids:lt}=this._tokenize_helper(V,{pair:fe,add_special_tokens:ve}),Ot=this.model.convert_tokens_to_ids(Be),Lt={input_ids:Ot,attention_mask:new Array(Ot.length).fill(1)};return(Te??this.return_token_type_ids)&<&&(Lt.token_type_ids=lt),Lt}_tokenize_helper(V,{pair:fe=null,add_special_tokens:ve=!1}={}){const Te=this._encode_text(V),Be=this._encode_text(fe);return this.post_processor?this.post_processor(Te,Be,{add_special_tokens:ve}):{tokens:(0,s.mergeArrays)(Te??[],Be??[])}}tokenize(V,{pair:fe=null,add_special_tokens:ve=!1}={}){return this._tokenize_helper(V,{pair:fe,add_special_tokens:ve}).tokens}encode(V,{text_pair:fe=null,add_special_tokens:ve=!0,return_token_type_ids:Te=null}={}){return this._encode_plus(V,{text_pair:fe,add_special_tokens:ve,return_token_type_ids:Te}).input_ids}batch_decode(V,fe={}){return V instanceof u.Tensor&&(V=V.tolist()),V.map(ve=>this.decode(ve,fe))}decode(V,fe={}){if(V instanceof u.Tensor&&(V=b(V)),!Array.isArray(V)||V.length===0||!(0,s.isIntegralNumber)(V[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(V,fe)}decode_single(V,{skip_special_tokens:fe=!1,clean_up_tokenization_spaces:ve=null}){let Te=this.model.convert_ids_to_tokens(V);fe&&(Te=Te.filter(lt=>!this.special_tokens.includes(lt)));let Be=this.decoder?this.decoder(Te):Te.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Be=Be.replaceAll(this.decoder.end_of_word_suffix," "),fe&&(Be=Be.trim())),(ve??this.clean_up_tokenization_spaces)&&(Be=T(Be)),Be}get_chat_template({chat_template:V=null,tools:fe=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ve=this.chat_template;if(V!==null&&Object.hasOwn(ve,V))V=ve[V];else if(V===null)if(fe!==null&&"tool_use"in ve)V=ve.tool_use;else if("default"in ve)V=ve.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(ve).sort()}.`)}else if(V===null)if(this.chat_template)V=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co./docs/transformers/main/en/chat_templating");return V}apply_chat_template(V,{tools:fe=null,documents:ve=null,chat_template:Te=null,add_generation_prompt:Be=!1,tokenize:lt=!0,padding:Ot=!1,truncation:Lt=!1,max_length:Ft=null,return_tensor:Dt=!0,return_dict:Cn=!1,tokenizer_kwargs:cn={},...pi}={}){if(Te=this.get_chat_template({chat_template:Te,tools:fe}),typeof Te!="string")throw Error(`chat_template must be a string, but got ${typeof Te}`);let Gi=this._compiled_template_cache.get(Te);Gi===void 0&&(Gi=new f.Template(Te),this._compiled_template_cache.set(Te,Gi));const ci=Object.create(null);for(const mi of Ze){const Oi=this.getToken(mi);Oi&&(ci[mi]=Oi)}const ui=Gi.render({messages:V,add_generation_prompt:Be,tools:fe,documents:ve,...ci,...pi});if(lt){const mi=this._call(ui,{add_special_tokens:!1,padding:Ot,truncation:Lt,max_length:Ft,return_tensor:Dt,...cn});return Cn?mi:mi.input_ids}return ui}}class gt extends tt{return_token_type_ids=!0}class Pt extends tt{return_token_type_ids=!0}class tn extends tt{return_token_type_ids=!0}class rn extends tt{return_token_type_ids=!0}class Pn extends tt{return_token_type_ids=!0}class ln extends tt{return_token_type_ids=!0}class vi extends tt{return_token_type_ids=!0}class On extends tt{return_token_type_ids=!0}class ut extends tt{return_token_type_ids=!0}class It extends tt{}class Bt extends tt{}class Vi extends tt{return_token_type_ids=!0;constructor(V,fe){super(V,fe),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class rr extends tt{return_token_type_ids=!0}class ri extends tt{}class Ti extends tt{}class Er extends tt{}class zr extends tt{constructor(V,fe){super(V,fe),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ve=>this.languageRegex.test(ve)),this.lang_to_token=ve=>ve}_build_translation_inputs(V,fe,ve){return Rt(this,V,fe,ve)}}class Ns extends zr{}class Sr extends tt{}class Ur extends tt{}const Ii="▁";class Yr extends tt{padding_side="left";constructor(V,fe){super(V,fe),this.legacy=fe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new _t({replacement:Ii,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(V){if(V===null)return null;if(this.legacy||V.length===0)return super._encode_text(V);let fe=super._encode_text(Ii+V.replaceAll(Ii," "));return fe.length>1&&fe[0]===Ii&&this.special_tokens.includes(fe[1])&&(fe=fe.slice(1)),fe}}class vr extends tt{}class ue extends tt{}class Oe extends tt{}class qe extends tt{}class Ue extends tt{}class Fe extends tt{}class wt extends tt{}class Ct extends tt{}class Nt extends tt{}function Rt(Pe,V,fe,ve){if(!("language_codes"in Pe)||!Array.isArray(Pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Pe)||!(Pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Pe)||typeof Pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const Te=ve.src_lang,Be=ve.tgt_lang;if(!Pe.language_codes.includes(Be))throw new Error(`Target language code "${Be}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);if(Te!==void 0){if(!Pe.language_codes.includes(Te))throw new Error(`Source language code "${Te}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);for(const lt of Pe.post_processor.config.single)if("SpecialToken"in lt&&Pe.languageRegex.test(lt.SpecialToken.id)){lt.SpecialToken.id=Pe.lang_to_token(Te);break}}return ve.forced_bos_token_id=Pe.model.convert_tokens_to_ids([Pe.lang_to_token(Be)])[0],Pe._call(V,fe)}class qt extends tt{constructor(V,fe){super(V,fe),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ve=>this.languageRegex.test(ve)),this.lang_to_token=ve=>ve}_build_translation_inputs(V,fe,ve){return Rt(this,V,fe,ve)}}class sn extends tt{constructor(V,fe){super(V,fe),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ve=>this.languageRegex.test(ve)).map(ve=>ve.slice(2,-2)),this.lang_to_token=ve=>`__${ve}__`}_build_translation_inputs(V,fe,ve){return Rt(this,V,fe,ve)}}class Jt extends tt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(V,{return_timestamps:fe=!1,return_language:ve=!1,time_precision:Te=null,force_full_sequences:Be=!0}={}){if(Te===null)throw Error("Must specify time_precision");let lt=null;const Ot=fe==="word";function Lt(){return{language:lt,timestamp:[null,null],text:""}}const Ft=[];let Dt=Lt(),Cn=0;const cn=this.timestamp_begin,Gi=cn+1500;let ci=[],ui=[],mi=!1,Oi=null;const ys=new Set(this.all_special_ids);for(const ei of V){const Mi=ei.tokens,Ki=Ot?ei.token_timestamps:null;let Or=null,Qr=cn;if("stride"in ei){const[Yi,Bn,ti]=ei.stride;if(Cn-=Bn,Oi=Yi-ti,Bn&&(Qr=Bn/Te+cn),ti)for(let Pi=Mi.length-1;Pi>=0;--Pi){const Fi=Number(Mi[Pi]);if(Fi>=cn){if(Or!==null&&(Fi-cn)*Te=cn&&Bn<=Gi){const ti=(Bn-cn)*Te+Cn,Pi=(0,l.round)(ti,2);if(Or!==null&&Bn>=Or)mi=!0;else if(mi||ci.length>0&&Bn0?(ci.push(Ci),Ot&&ui.push(pr)):ci.every(Yi=>Yi.length===0)&&(Dt=Lt(),ci=[],Ci=[],ui=[],pr=[])}if(ci.length>0){if(Be&&fe)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[ei,Mi]=this.findLongestCommonSequence(ci,ui),Ki=this.decode(ei);Dt.text=Ki,Ot&&(Dt.words=this.collateWordTimestamps(ei,Mi,lt)),Ft.push(Dt)}let Li=Object.create(null);const Br=Ft.map(ei=>ei.text).join("");if(fe||ve){for(let ei=0;ei0;let Ot=lt?[]:null,Lt=lt?fe[0]:null;for(let Ft=1;FtBn===Qr[ti]&&Lt[Br+ti]<=fe[Ft][Ki+ti]).length:Ci=Mi.filter((Bn,ti)=>Bn===Qr[ti]).length;const pr=Li/1e4,Yi=Ci/Li+pr;Ci>1&&Yi>Cn&&(Cn=Yi,cn=[Br,ei,Ki,Or])}const[Gi,ci,ui,mi]=cn,Oi=Math.floor((ci+Gi)/2),ys=Math.floor((mi+ui)/2);Be.push(...ve.slice(0,Oi)),ve=Dt.slice(ys),Te=ve.length,lt&&(Ot.push(...Lt.slice(0,Oi)),Lt=fe[Ft].slice(ys))}return Be.push(...ve),lt?(Ot.push(...Lt),[Be,Ot]):[Be,[]]}collateWordTimestamps(V,fe,ve){const[Te,Be,lt]=this.combineTokensIntoWords(V,ve),Ot=[];for(let Lt=0;Lt=Te){const Ot=((lt-Te)*ve).toFixed(2);Be.push(`<|${Ot}|>`),Be.push([])}else Be[Be.length-1].push(lt);return Be=Be.map(lt=>typeof lt=="string"?lt:super.decode(lt,fe)),Be.join("")}splitTokensOnUnicode(V){const fe=this.decode(V,{decode_with_timestamps:!0}),ve="�",Te=[],Be=[],lt=[];let Ot=[],Lt=[],Ft=0;for(let Dt=0;Dt=this.model.tokens_to_ids.get("<|endoftext|>"),Gi=Dt.startsWith(" "),ci=Dt.trim(),ui=Lt.test(ci);if(pi||Gi||ui||Be.length===0)Be.push(Dt),lt.push(Cn),Ot.push(cn);else{const mi=Be.length-1;Be[mi]+=Dt,lt[mi].push(...Cn),Ot[mi].push(...cn)}}return[Be,lt,Ot]}mergePunctuations(V,fe,ve,Te,Be){const lt=structuredClone(V),Ot=structuredClone(fe),Lt=structuredClone(ve);let Ft=lt.length-2,Dt=lt.length-1;for(;Ft>=0;)lt[Ft].startsWith(" ")&&Te.includes(lt[Ft].trim())?(lt[Dt]=lt[Ft]+lt[Dt],Ot[Dt]=(0,s.mergeArrays)(Ot[Ft],Ot[Dt]),Lt[Dt]=(0,s.mergeArrays)(Lt[Ft],Lt[Dt]),lt[Ft]="",Ot[Ft]=[],Lt[Ft]=[]):Dt=Ft,--Ft;for(Ft=0,Dt=1;DtCn),Ot.filter(Cn=>Cn.length>0),Lt.filter(Cn=>Cn.length>0)]}}class yn extends tt{}class Sn extends tt{}class Jn extends tt{}class Ln extends tt{constructor(V,fe){super(V,fe),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ve=>this.languageRegex.test(ve)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(V){if(V===null)return null;const[fe,...ve]=V.trim().split(this.languageRegex);if(ve.length===0)return super._encode_text(fe);if(ve.length===2){const[Te,Be]=ve;return this.supported_language_codes.includes(Te)||console.warn(`Unsupported language code "${Te}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,s.mergeArrays)([Te],super._encode_text(Be))}}}class dn extends tt{}class nn extends tt{}class li extends tt{}class An extends tt{}class sr extends tt{}class yr extends tt{constructor(V,fe){super(V,fe),this.decoder=new bt({})}}class Xi extends tt{}class yi extends tt{}class Kn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:ri,DistilBertTokenizer:It,CamembertTokenizer:Bt,DebertaTokenizer:Pn,DebertaV2Tokenizer:ln,BertTokenizer:gt,HerbertTokenizer:vi,ConvBertTokenizer:On,RoFormerTokenizer:ut,XLMTokenizer:Vi,ElectraTokenizer:rr,MobileBertTokenizer:tn,SqueezeBertTokenizer:rn,AlbertTokenizer:Pt,GPT2Tokenizer:Ti,BartTokenizer:Er,MBartTokenizer:zr,MBart50Tokenizer:Ns,RobertaTokenizer:Sr,WhisperTokenizer:Jt,CodeGenTokenizer:yn,CLIPTokenizer:Sn,SiglipTokenizer:Jn,MarianTokenizer:Ln,BloomTokenizer:Ur,NllbTokenizer:qt,M2M100Tokenizer:sn,LlamaTokenizer:Yr,CodeLlamaTokenizer:vr,XLMRobertaTokenizer:ue,MPNetTokenizer:Oe,FalconTokenizer:qe,GPTNeoXTokenizer:Ue,EsmTokenizer:Fe,Wav2Vec2CTCTokenizer:dn,BlenderbotTokenizer:nn,BlenderbotSmallTokenizer:li,SpeechT5Tokenizer:An,NougatTokenizer:sr,VitsTokenizer:yr,Qwen2Tokenizer:wt,GemmaTokenizer:Ct,Grok1Tokenizer:Nt,CohereTokenizer:Xi,MgpstrTokenizer:yi,PreTrainedTokenizer:tt};static async from_pretrained(V,{progress_callback:fe=null,config:ve=null,cache_dir:Te=null,local_files_only:Be=!1,revision:lt="main",legacy:Ot=null}={}){const[Lt,Ft]=await h(V,{progress_callback:fe,config:ve,cache_dir:Te,local_files_only:Be,revision:lt,legacy:Ot}),Dt=Ft.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let Cn=this.TOKENIZER_CLASS_MAPPING[Dt];return Cn||(console.warn(`Unknown tokenizer class "${Dt}", attempting to construct from base class.`),Cn=tt),new Cn(Lt,Ft)}}},"./src/utils/audio.js":(n,e,t)=>{t.r(e),t.d(e,{RawAudio:()=>Z,hamming:()=>_,hanning:()=>h,mel_filter_bank:()=>P,read_audio:()=>f,spectrogram:()=>L,window_function:()=>I});var i=t("./src/utils/hub.js"),s=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),l=t("./src/env.js"),u=t("?7a2c"),d=t("./src/utils/tensor.js");async function f($,J){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co./docs/transformers.js/guides/node-audio-processing.");const ee=await(await(0,i.getFile)($)).arrayBuffer(),X=new AudioContext({sampleRate:J});typeof J>"u"&&console.warn(`No sampling rate provided, using default of ${X.sampleRate}Hz.`);const ne=await X.decodeAudioData(ee);let Q;if(ne.numberOfChannels===2){const oe=Math.sqrt(2),W=ne.getChannelData(0),q=ne.getChannelData(1);Q=new Float32Array(W.length);for(let G=0;G2595*Math.log10(1+$/700),kaldi:$=>1127*Math.log(1+$/700),slaney:($,J=1e3,ee=15,X=27/Math.log(6.4))=>$>=J?ee+Math.log($/J)*X:3*$/200};function y($,J="htk"){const ee=g[J];if(!ee)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof $=="number"?ee($):$.map(X=>ee(X))}const b={htk:$=>700*(10**($/2595)-1),kaldi:$=>700*(Math.exp($/1127)-1),slaney:($,J=1e3,ee=15,X=Math.log(6.4)/27)=>$>=ee?J*Math.exp(X*($-ee)):200*$/3};function T($,J="htk"){const ee=b[J];if(!ee)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof $=="number"?ee($):$.map(X=>ee(X))}function v($,J){const ee=Float64Array.from({length:J.length-1},(oe,W)=>J[W+1]-J[W]),X=Array.from({length:$.length},()=>new Array(J.length));for(let oe=0;oe<$.length;++oe){const W=X[oe];for(let q=0;qnew Array($.length));for(let oe=0;oe<$.length;++oe){const W=X[oe];for(let q=0;q$+X*Q)}function P($,J,ee,X,ne,Q=null,oe="htk",W=!1){if(Q!==null&&Q!=="slaney")throw new Error('norm must be one of null or "slaney"');if($<2)throw new Error(`Require num_frequency_bins: ${$} >= 2`);if(ee>X)throw new Error(`Require min_frequency: ${ee} <= max_frequency: ${X}`);const q=y(ee,oe),G=y(X,oe),te=x(q,G,J+2);let B=T(te,oe),le;if(W){const me=ne/(($-1)*2);le=y(Float64Array.from({length:$},(xe,ze)=>ze*me),oe),B=te}else le=x(0,Math.floor(ne/2),$);const ye=v(le,B);if(Q!==null&&Q==="slaney")for(let me=0;mene)throw Error(`frame_length (${ee}) may not be larger than fft_length (${ne})`);if(re!==ee)throw new Error(`Length of the window (${re}) must equal frame_length (${ee})`);if(X<=0)throw new Error("hop_length must be greater than zero");if(Q===null&&te!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(oe){if(W!=="reflect")throw new Error(`pad_mode="${W}" not implemented yet.`);const ge=Math.floor((ne-1)/2)+1;$=w($,ge,ge)}let He=Math.floor(1+Math.floor(($.length-ee)/X));Me!==null&&HeHe?ae&&(ke=ce):ke=We=ce);const st=new s.FFT(ne),Ke=new Float64Array(ne),F=new Float64Array(st.outputBufferSize),U=new Float32Array(Ne*ke);for(let ge=0;ge=1;--Ee)Ke[Ee]-=G*Ke[Ee-1];Ke[0]*=1-G}for(let Ee=0;EeMath.pow(W,.85));break;default:throw new Error(`Unknown window type ${J}.`)}if(ee&&(oe=oe.subarray(0,$)),X===null)return oe;if($>X)throw new Error(`Length of the window (${$}) may not be larger than frame_length (${X})`);return oe}function O($,J){let ee=44;const X=new ArrayBuffer(ee+$.length*4),ne=new DataView(X);H(ne,0,"RIFF"),ne.setUint32(4,36+$.length*4,!0),H(ne,8,"WAVE"),H(ne,12,"fmt "),ne.setUint32(16,16,!0),ne.setUint16(20,3,!0),ne.setUint16(22,1,!0),ne.setUint32(24,J,!0),ne.setUint32(28,J*4,!0),ne.setUint16(32,4,!0),ne.setUint16(34,32,!0),H(ne,36,"data"),ne.setUint32(40,$.length*4,!0);for(let Q=0;Q<$.length;++Q,ee+=4)ne.setFloat32(ee,$[Q],!0);return X}function H($,J,ee){for(let X=0;X{let Q=await ne.arrayBuffer();u.writeFileSync(X,Buffer.from(Q))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await ee(J,this.toBlob())}}},"./src/utils/constants.js":(n,e,t)=>{t.r(e),t.d(e,{CHAT_TEMPLATE_NAME:()=>d,CONFIG_NAME:()=>s,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>f,GITHUB_ISSUE_URL:()=>i,IMAGE_PROCESSOR_NAME:()=>l,PROCESSOR_NAME:()=>u});const i="https://github.com/huggingface/transformers.js/issues/new/choose",s="config.json",o="preprocessor_config.json",l=o,u="processor_config.json",d="chat_template.json",f="generation_config.json"},"./src/utils/core.js":(n,e,t)=>{t.r(e),t.d(e,{calculateDimensions:()=>f,calculateReflectOffset:()=>g,count:()=>v,dispatchCallback:()=>i,escapeRegExp:()=>o,isIntegralNumber:()=>u,isNullishDimension:()=>d,isTypedArray:()=>l,len:()=>T,mergeArrays:()=>h,pick:()=>b,pop:()=>m,product:()=>_,reverseDictionary:()=>s,saveBlob:()=>y});function i(x,P){x&&x(P)}function s(x){return Object.fromEntries(Object.entries(x).map(([P,w])=>[w,P]))}function o(x){return x.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function l(x){return x?.prototype?.__proto__?.constructor?.name==="TypedArray"}function u(x){return Number.isInteger(x)||typeof x=="bigint"}function d(x){return x==null||x===-1}function f(x){const P=[];let w=x;for(;Array.isArray(w);)P.push(w.length),w=w[0];return P}function m(x,P,w=void 0){const C=x[P];if(C!==void 0)return delete x[P],C;if(w===void 0)throw Error(`Key ${P} does not exist in object.`);return w}function h(...x){return Array.prototype.concat.apply([],x)}function _(...x){return x.reduce((P,w)=>P.flatMap(C=>w.map(E=>[C,E])))}function g(x,P){return Math.abs((x+P)%(2*P)-P)}function y(x,P){const w=URL.createObjectURL(P),C=document.createElement("a");C.href=w,C.download=x,C.click(),C.remove(),URL.revokeObjectURL(w)}function b(x,P){return Object.assign({},...P.map(w=>{if(x[w]!==void 0)return{[w]:x[w]}}))}function T(x){let P=0;for(const w of x)++P;return P}function v(x,P){let w=0;for(const C of x)C===P&&++w;return w}},"./src/utils/data-structures.js":(n,e,t)=>{t.r(e),t.d(e,{CharTrie:()=>s,DictionarySplitter:()=>d,LRUCache:()=>f,PriorityQueue:()=>i,TokenLattice:()=>l});class i{constructor(h=(g,y)=>g>y,_=1/0){this._heap=[],this._comparator=h,this._maxSize=_}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...h){return this.extend(h)}extend(h){for(const _ of h)if(this.size0&&this._swap(0,_),this._heap.pop(),this._siftDown(),h}replace(h){const _=this.peek();return this._heap[0]=h,this._siftDown(),_}_parent(h){return(h+1>>>1)-1}_left(h){return(h<<1)+1}_right(h){return h+1<<1}_greater(h,_){return this._comparator(this._heap[h],this._heap[_])}_swap(h,_){const g=this._heap[h];this._heap[h]=this._heap[_],this._heap[_]=g}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(h){for(;h>0&&this._greater(h,this._parent(h));)this._swap(h,this._parent(h)),h=this._parent(h)}_siftDown(){let h=0;for(;this._left(h)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const y=new u(this.bosTokenId,0,0,0,0),b=new u(this.eosTokenId,1,this.len,0,0);this.nodes.push(y.clone()),this.nodes.push(b.clone()),this.beginNodes[this.len].push(b),this.endNodes[0].push(y)}insert(h,_,g,y){const b=this.nodes.length,T=new u(y,b,h,_,g);this.beginNodes[h].push(T),this.endNodes[h+_].push(T),this.nodes.push(T)}viterbi(){const h=this.len;let _=0;for(;_<=h;){if(this.beginNodes[_].length==0)return[];for(let v of this.beginNodes[_]){v.prev=null;let x=0,P=null;for(let w of this.endNodes[_]){const C=w.backtraceScore+v.score;(P===null||C>x)&&(P=w.clone(),x=C)}if(P!==null)v.prev=P,v.backtraceScore=x;else return[]}++_}const g=[],b=this.beginNodes[h][0].prev;if(b===null)return[];let T=b.clone();for(;T.prev!==null;)g.push(T.clone()),T=T.clone().prev.clone();return g.reverse(),g}piece(h){return this.chars.slice(h.pos,h.pos+h.length).join("")}tokens(){return this.viterbi().map(_=>this.piece(_))}tokenIds(){return this.viterbi().map(_=>_.tokenId)}}class u{constructor(h,_,g,y,b){this.tokenId=h,this.nodeId=_,this.pos=g,this.length=y,this.score=b,this.prev=null,this.backtraceScore=0}clone(){const h=new u(this.tokenId,this.nodeId,this.pos,this.length,this.score);return h.prev=this.prev,h.backtraceScore=this.backtraceScore,h}}class d{constructor(h){this.trie=this._buildTrie(h)}_buildTrie(h){const _=Object.create(null);for(const g of h){let y=_;for(let b=0;by&&_.push(h.slice(y,b)),_.push(v),b+=v.length,y=b):++b}return ythis.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(n,e,t)=>{t.r(e),t.d(e,{DEVICE_TYPES:()=>i});const i=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(n,e,t)=>{t.r(e),t.d(e,{DATA_TYPES:()=>l,DEFAULT_DEVICE_DTYPE_MAPPING:()=>u,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>d,isWebGpuFp16Supported:()=>o});var i=t("./src/env.js"),s=t("./src/utils/devices.js");const o=function(){let f;return async function(){if(f===void 0)if(!i.apis.IS_WEBGPU_AVAILABLE)f=!1;else try{f=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{f=!1}return f}}(),l=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),u=Object.freeze({[s.DEVICE_TYPES.wasm]:l.q8}),d=Object.freeze({[l.fp32]:"",[l.fp16]:"_fp16",[l.int8]:"_int8",[l.uint8]:"_uint8",[l.q8]:"_quantized",[l.q4]:"_q4",[l.q4f16]:"_q4f16",[l.bnb4]:"_bnb4"})},"./src/utils/generic.js":(n,e,t)=>{t.r(e),t.d(e,{Callable:()=>i});const i=class{constructor(){let s=function(...o){return s._call(...o)};return Object.setPrototypeOf(s,new.target.prototype)}_call(...s){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(n,e,t)=>{t.r(e),t.d(e,{MAX_EXTERNAL_DATA_CHUNKS:()=>u,getFile:()=>g,getModelFile:()=>x,getModelJSON:()=>P});var i=t("?7a2c"),s=t("?a42a"),o=t("./src/env.js"),l=t("./src/utils/core.js");const u=100,d={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class f{constructor(A){if(this.filePath=A,this.headers=new Headers,this.exists=i.existsSync(A),this.exists){this.status=200,this.statusText="OK";let L=i.statSync(A);this.headers.set("content-length",L.size.toString()),this.updateContentType();const I=i.createReadStream(A);this.body=new ReadableStream({start(O){I.on("data",H=>O.enqueue(H)),I.on("end",()=>O.close()),I.on("error",H=>O.error(H))},cancel(){I.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const A=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",d[A]??"application/octet-stream")}clone(){let A=new f(this.filePath);return A.exists=this.exists,A.status=this.status,A.statusText=this.statusText,A.headers=new Headers(this.headers),A}async arrayBuffer(){return(await i.promises.readFile(this.filePath)).buffer}async blob(){const A=await i.promises.readFile(this.filePath);return new Blob([A],{type:this.headers.get("content-type")})}async text(){return await i.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function m(E,A=null,L=null){let I;try{I=new URL(E)}catch{return!1}return!(A&&!A.includes(I.protocol)||L&&!L.includes(I.hostname))}const h=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function _(E){return!(!h.test(E)||E.includes("..")||E.includes("--")||E.endsWith(".git")||E.endsWith(".ipynb"))}async function g(E){if(o.env.useFS&&!m(E,["http:","https:","blob:"]))return new f(E.toString());if(typeof process<"u"&&process?.release?.name==="node"){const A=!!Pv?.TESTING_REMOTELY,L=o.env.version,I=new Headers;if(I.set("User-Agent",`transformers.js/${L}; is_ci/${A};`),m(E,["http:","https:"],["huggingface.co","hf.co"])){const H=Pv?.HF_TOKEN??Pv?.HF_ACCESS_TOKEN;H&&I.set("Authorization",`Bearer ${H}`)}return fetch(E,{headers:I})}else return fetch(E)}const y={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function b(E,A,L){if(!L)return null;const I=y[E]??`Error (${E}) occurred while trying to load file`;throw Error(`${I}: "${A}".`)}class T{constructor(A){this.path=A}async match(A){let L=s.join(this.path,A),I=new f(L);if(I.exists)return I}async put(A,L,I=void 0){let O=s.join(this.path,A);try{const H=L.headers.get("Content-Length"),Z=parseInt(H??"0");let $=0;await i.promises.mkdir(s.dirname(O),{recursive:!0});const J=i.createWriteStream(O),ee=L.body.getReader();for(;;){const{done:X,value:ne}=await ee.read();if(X)break;await new Promise((oe,W)=>{J.write(ne,q=>{if(q){W(q);return}oe()})}),$+=ne.length;const Q=Z?$/Z*100:0;I?.({progress:Q,loaded:$,total:Z})}J.close()}catch(H){try{await i.promises.unlink(O)}catch{}throw H}}}async function v(E,...A){for(let L of A)try{let I=await E.match(L);if(I)return I}catch{continue}}async function x(E,A,L=!0,I={},O=!1){if(!o.env.allowLocalModels){if(I.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!o.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,l.dispatchCallback)(I.progress_callback,{status:"initiate",name:E,file:A});let H;if(!H&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");H=o.env.customCache}if(!H&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{H=await caches.open("transformers-cache")}catch(B){console.warn("An error occurred while opening the browser cache:",B)}}if(!H&&o.env.useFSCache){if(!o.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");H=new T(I.cache_dir??o.env.cacheDir)}const Z=I.revision??"main",$=C(E,A),J=_(E),ee=J?C(o.env.localModelPath,$):$,X=C(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",E).replaceAll("{revision}",encodeURIComponent(Z)),A);let ne;const Q=H instanceof T?Z==="main"?$:C(E,Z,A):X;let oe=!1,W;H&&(W=await v(H,ee,Q));const q=W!==void 0;if(W===void 0){if(o.env.allowLocalModels)if(m($,["http:","https:"])){if(I.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${$}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${$}.`)}else try{W=await g(ee),ne=ee}catch(le){console.warn(`Unable to load from local path "${ee}": "${le}"`)}if(W===void 0||W.status===404){if(I.local_files_only||!o.env.allowRemoteModels){if(L)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ee}".`);return null}if(!J)throw Error(`Local file missing at "${ee}" and download aborted due to invalid model ID "${E}".`);if(W=await g(X),W.status!==200)return b(W.status,X,L);ne=Q}oe=H&&typeof Response<"u"&&W instanceof Response&&W.status===200}(0,l.dispatchCallback)(I.progress_callback,{status:"download",name:E,file:A});let G;if(!(o.apis.IS_NODE_ENV&&O)){let B;I.progress_callback?q&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(B=new Uint8Array(await W.arrayBuffer()),(0,l.dispatchCallback)(I.progress_callback,{status:"progress",name:E,file:A,progress:100,loaded:B.length,total:B.length})):B=await w(W,le=>{(0,l.dispatchCallback)(I.progress_callback,{status:"progress",name:E,file:A,...le})}):B=new Uint8Array(await W.arrayBuffer()),G=B}if(oe&&ne&&await H.match(ne)===void 0&&(G?await H.put(ne,new Response(G,{headers:W.headers})).catch(B=>{console.warn(`Unable to add response to browser cache: ${B}.`)}):await H.put(ne,W,I.progress_callback)),(0,l.dispatchCallback)(I.progress_callback,{status:"done",name:E,file:A}),G){if(!o.apis.IS_NODE_ENV&&O)throw new Error("Cannot return path in a browser environment.");return G}if(W instanceof f)return W.filePath;const te=await H?.match(ne);if(te instanceof f)return te.filePath;if(te instanceof Response)return new Uint8Array(await te.arrayBuffer());if(typeof te=="string")return te;throw new Error("Unable to get model file path or buffer.")}async function P(E,A,L=!0,I={}){const O=await x(E,A,L,I,!1);if(O===null)return{};const Z=new TextDecoder("utf-8").decode(O);return JSON.parse(Z)}async function w(E,A){const L=E.headers.get("Content-Length");L===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let I=parseInt(L??"0"),O=new Uint8Array(I),H=0;const Z=E.body.getReader();async function $(){const{done:J,value:ee}=await Z.read();if(J)return;const X=H+ee.length;if(X>I){I=X;const Q=new Uint8Array(I);Q.set(O),O=Q}O.set(ee,H),H=X;const ne=H/I*100;return A({progress:ne,loaded:H,total:I}),$()}return await $(),O}function C(...E){return E=E.map((A,L)=>(L&&(A=A.replace(new RegExp("^/"),"")),L!==E.length-1&&(A=A.replace(new RegExp("/$"),"")),A)),E.join("/")}},"./src/utils/image.js":(n,e,t)=>{t.r(e),t.d(e,{RawImage:()=>y,load_image:()=>b});var i=t("./src/utils/core.js"),s=t("./src/utils/hub.js"),o=t("./src/env.js"),l=t("./src/utils/tensor.js"),u=t("?2b25");let d,f,m;const h=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(h)d=(T,v)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(T,v)},m=self.createImageBitmap,f=self.ImageData;else if(u)m=async T=>{const x=(await T.metadata()).channels,{data:P,info:w}=await T.rotate().raw().toBuffer({resolveWithObject:!0}),C=new y(new Uint8ClampedArray(P),w.width,w.height,w.channels);return x!==void 0&&x!==w.channels&&C.convert(x),C};else throw new Error("Unable to load image processing library.");const _={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},g=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class y{constructor(v,x,P,w){this.data=v,this.width=x,this.height=P,this.channels=w}get size(){return[this.width,this.height]}static async read(v){if(v instanceof y)return v;if(typeof v=="string"||v instanceof URL)return await this.fromURL(v);if(v instanceof Blob)return await this.fromBlob(v);if(typeof HTMLCanvasElement<"u"&&v instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&v instanceof OffscreenCanvas)return this.fromCanvas(v);throw new Error(`Unsupported input type: ${typeof v}`)}static fromCanvas(v){if(!h)throw new Error("fromCanvas() is only supported in browser environments.");const P=v.getContext("2d").getImageData(0,0,v.width,v.height).data;return new y(P,v.width,v.height,4)}static async fromURL(v){const x=await(0,s.getFile)(v);if(x.status!==200)throw new Error(`Unable to read image from "${v}" (${x.status} ${x.statusText})`);const P=await x.blob();return this.fromBlob(P)}static async fromBlob(v){if(h){const x=await m(v),P=d(x.width,x.height).getContext("2d");return P.drawImage(x,0,0),new this(P.getImageData(0,0,x.width,x.height).data,x.width,x.height,4)}else{const x=u(await v.arrayBuffer());return await m(x)}}static fromTensor(v,x="CHW"){if(v.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${v.dims.length} dimensions.`);if(x==="CHW")v=v.transpose(1,2,0);else if(x!=="HWC")throw new Error(`Unsupported channel format: ${x}`);if(!(v.data instanceof Uint8ClampedArray||v.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${v.type}`);switch(v.dims[2]){case 1:case 2:case 3:case 4:return new y(v.data,v.dims[1],v.dims[0],v.dims[2]);default:throw new Error(`Unsupported number of channels: ${v.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const v=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let x=0,P=0;x=0?L=P:O=-P,w>=0?I=w:H=-w,A.drawImage(E,L,I,v,x,O,H,v,x),new y(A.getImageData(0,0,v,x).data,v,x,4).convert(C)}else{let C=this.toSharp();if(P>=0&&w>=0)C=C.extract({left:Math.floor(P),top:Math.floor(w),width:v,height:x});else if(P<=0&&w<=0){const E=Math.floor(-w),A=Math.floor(-P);C=C.extend({top:E,left:A,right:v-this.width-A,bottom:x-this.height-E})}else{let E=[0,0],A=0;w<0?(E[0]=Math.floor(-w),E[1]=x-this.height-E[0]):A=Math.floor(w);let L=[0,0],I=0;P<0?(L[0]=Math.floor(-P),L[1]=v-this.width-L[0]):I=Math.floor(P),C=C.extend({top:E[0],bottom:E[1],left:L[0],right:L[1]}).extract({left:I,top:A,width:v,height:x})}return await m(C)}}async toBlob(v="image/png",x=1){if(!h)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:v,quality:x})}toTensor(v="CHW"){let x=new l.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(v!=="HWC")if(v==="CHW")x=x.permute(2,0,1);else throw new Error(`Unsupported channel format: ${v}`);return x}toCanvas(){if(!h)throw new Error("toCanvas() is only supported in browser environments.");const v=this.clone().rgba(),x=d(v.width,v.height),P=new f(v.data,v.width,v.height);return x.getContext("2d").putImageData(P,0,0),x}split(){const{data:v,width:x,height:P,channels:w}=this,C=v.constructor,E=v.length/w,A=Array.from({length:w},()=>new C(E));for(let L=0;Lnew y(L,x,P,1))}_update(v,x,P,w=null){return this.data=v,this.width=x,this.height=P,w!==null&&(this.channels=w),this}clone(){return new y(this.data.slice(),this.width,this.height,this.channels)}convert(v){if(this.channels===v)return this;switch(v){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(v){if(h){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const x=v.split(".").pop().toLowerCase(),P=g.get(x)??"image/png",w=await this.toBlob(P);(0,i.saveBlob)(v,w)}else{if(o.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(v);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(h)throw new Error("toSharp() is only supported in server-side environments.");return u(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const b=y.read.bind(y)},"./src/utils/maths.js":(n,e,t)=>{t.r(e),t.d(e,{FFT:()=>b,bankers_round:()=>x,cos_sim:()=>d,dot:()=>u,dynamic_time_warping:()=>P,interpolate_data:()=>i,log_softmax:()=>l,magnitude:()=>f,max:()=>h,medianFilter:()=>T,min:()=>m,permute_data:()=>s,round:()=>v,softmax:()=>o});function i(w,[C,E,A],[L,I],O="bilinear",H=!1){const Z=I/A,$=L/E,J=new w.constructor(L*I*C),ee=E*A,X=L*I;for(let ne=0;ne=0;--H)L[H]=Z,A[H]=C[E[H]],Z*=A[H];const I=E.map((H,Z)=>L[E.indexOf(Z)]),O=new w.constructor(w.length);for(let H=0;H=0;--$)Z+=J%C[$]*I[$],J=Math.floor(J/C[$]);O[Z]=w[H]}return[O,A]}function o(w){const C=h(w)[0],E=w.map(I=>Math.exp(I-C)),A=E.reduce((I,O)=>I+O,0);return E.map(I=>I/A)}function l(w){const C=h(w)[0];let E=0;for(let I=0;II-C-A)}function u(w,C){let E=0;for(let A=0;AC+E*E,0))}function m(w){if(w.length===0)throw Error("Array must not be empty");let C=w[0],E=0;for(let A=1;AC&&(C=w[A],E=A);return[C,E]}function _(w){return w>0&&(w&w-1)===0}class g{constructor(C){if(this.size=C|0,this.size<=1||!_(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=C<<1,this.table=new Float64Array(this.size*2);for(let A=0;AA;A<<=1)++E;this._width=E%2===0?E-1:E,this._bitrev=new Int32Array(1<>>L&3)<>>1);for(let L=0;L>>1]=C[L];return A}toComplexArray(C,E){const A=E||this.createComplexArray();for(let L=0;L>>1],A[L+1]=0;return A}transform(C,E){if(C===E)throw new Error("Input and output buffers must be different");this._transform4(C,E,1)}realTransform(C,E){if(C===E)throw new Error("Input and output buffers must be different");this._realTransform4(C,E,1)}inverseTransform(C,E){if(C===E)throw new Error("Input and output buffers must be different");this._transform4(C,E,-1);for(let A=0;A>=2;O>=2;O>>=2){H=L/O<<1;const X=H>>>2;for(Z=0;Z>>1,O>>>1)}else for(Z=0,$=0;Z>>1,O>>>1,A)}const ee=this.table;for(O>>=2;O>=2;O>>=2){H=L/O<<1;const ne=H>>>1,Q=ne>>>1,oe=Q>>>1;for(Z=0;Z>>1;for(let ne=2;ne>1;++J){const ee=(J+1-C)**2/2,X=Math.sqrt(Z**2+$**2)**ee,ne=ee*Math.atan2($,Z),Q=2*J;I[Q]=X*Math.cos(ne),I[Q+1]=X*Math.sin(ne),O[Q]=I[Q],O[Q+1]=-I[Q+1]}this._slicedChirpBuffer=I.subarray(E,A),this._f=new g(L>>1),this._f.transform(this._chirpBuffer,O)}_transform(C,E,A){const L=this._buffer1,I=this._buffer2,O=this._outBuffer1,H=this._outBuffer2,Z=this._chirpBuffer,$=this._slicedChirpBuffer,J=this._a;if(A)for(let ee=0;ee<$.length;ee+=2){const X=ee+1,ne=ee>>1,Q=E[ne];L[ee]=Q*$[ee],L[X]=Q*$[X]}else for(let ee=0;ee<$.length;ee+=2){const X=ee+1;L[ee]=E[ee]*$[ee]-E[X]*$[X],L[X]=E[ee]*$[X]+E[X]*$[ee]}this._f.transform(O,L);for(let ee=0;ee=w.length&&(Z=2*(w.length-1)-Z),A[O++]=w[Z]}A.sort(),E[I]=A[L]}return E}function v(w,C){const E=Math.pow(10,C);return Math.round(w*E)/E}function x(w){const C=Math.round(w);return Math.abs(w)%1===.5?C%2===0?C:C-1:C}function P(w){const C=w.length,E=w[0].length,A=[C+1,E+1],L=Array.from({length:A[0]},()=>Array(A[1]).fill(1/0));L[0][0]=0;const I=Array.from({length:A[0]},()=>Array(A[1]).fill(-1));for(let J=1;J0||H>0;)switch(Z.push(O-1),$.push(H-1),I[O][H]){case 0:--O,--H;break;case 1:--O;break;case 2:--H;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${O}, ${H}]. Please file a bug report.`)}return Z.reverse(),$.reverse(),[Z,$]}},"./src/utils/tensor.js":(n,e,t)=>{t.r(e),t.d(e,{DataTypeMap:()=>l,Tensor:()=>u,cat:()=>E,full:()=>$,full_like:()=>J,interpolate:()=>m,interpolate_4d:()=>h,layer_norm:()=>x,matmul:()=>_,mean:()=>O,mean_pooling:()=>v,ones:()=>ee,ones_like:()=>X,permute:()=>f,quantize_embeddings:()=>W,rand:()=>oe,rfft:()=>g,slice:()=>T,stack:()=>A,std_mean:()=>I,topk:()=>y,zeros:()=>ne,zeros_like:()=>Q});var i=t("./src/utils/maths.js"),s=t("./src/backends/onnx.js"),o=t("./src/ops/registry.js");const l=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class u{get dims(){return this.ort_tensor.dims}set dims(G){this.ort_tensor.dims=G}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...G){return(0,s.isONNXTensor)(G[0])?this.ort_tensor=G[0]:this.ort_tensor=new s.Tensor(G[0],G[1],G[2]),new Proxy(this,{get:(te,B)=>{if(typeof B=="string"){let le=Number(B);if(Number.isInteger(le))return te._getitem(le)}return te[B]},set:(te,B,le)=>te[B]=le})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[G,...te]=this.dims;if(te.length>0){const B=te.reduce((le,ye)=>le*ye);for(let le=0;le0){const le=B.reduce((ye,me)=>ye*me);return this._subarray(G,le,B)}else return new u(this.type,[this.data[G]],B)}indexOf(G){const te=this.data;for(let B=0;Bwe)throw new Error(`Invalid slice: ${ce}`);const re=[Math.max(ae,0),Math.min(we,this.dims[Me])];B.push(re),te.push(re[1]-re[0])}else throw new Error(`Invalid slice: ${ce}`)}const le=B.map(([Me,ce])=>ce-Me),ye=le.reduce((Me,ce)=>Me*ce),me=this.data,xe=new me.constructor(ye),ze=this.stride();for(let Me=0;Me=0;--ae){const re=le[ae];ce+=(we%re+B[ae][0])*ze[ae],we=Math.floor(we/re)}xe[Me]=me[ce]}return new u(this.type,xe,te)}permute(...G){return f(this,G)}transpose(...G){return this.permute(...G)}sum(G=null,te=!1){return this.norm(1,G,te)}norm(G="fro",te=null,B=!1){if(G==="fro")G=2;else if(typeof G=="string")throw Error(`Unsupported norm: ${G}`);const le=this.data,ye=(Me,ce)=>Me+ce**G;if(te===null){const Me=le.reduce(ye,0)**(1/G);return new u(this.type,[Me],[])}const[me,xe,ze]=L(ye,this,te,B);if(G!==1)for(let Me=0;Me=0;--ze){const ae=this.dims[ze];if(ze!==te){const we=Me%ae;xe+=we*ce,ce*=this.dims[ze]}Me=Math.floor(Me/ae)}le[me]/=ye[xe]}return this}normalize(G=2,te=1){return this.clone().normalize_(G,te)}stride(){return H(this.dims)}squeeze(G=null){return new u(this.type,this.data,P(this.dims,G))}squeeze_(G=null){return this.dims=P(this.dims,G),this}unsqueeze(G=null){return new u(this.type,this.data,w(this.dims,G))}unsqueeze_(G=null){return this.dims=w(this.dims,G),this}flatten_(G=0,te=-1){te=(te+this.dims.length)%this.dims.length;let B=this.dims.slice(0,G),le=this.dims.slice(G,te+1),ye=this.dims.slice(te+1);return this.dims=[...B,le.reduce((me,xe)=>me*xe,1),...ye],this}flatten(G=0,te=-1){return this.clone().flatten_(G,te)}view(...G){let te=-1;for(let le=0;lexe!==te?ye*me:ye,1);G[te]=B.length/le}return new u(this.type,B,G)}neg_(){const G=this.data;for(let te=0;teG?1:0;return new u("bool",te,this.dims)}lt(G){const te=new Uint8Array(this.data.length),B=this.data;for(let le=0;leMath.min(me,xe),this,G,te,1/0);return new u(B,le,ye)}max(G=null,te=!1){if(G===null){const me=(0,i.max)(this.data)[0];return new u(this.type,[me],[])}const[B,le,ye]=L((me,xe)=>Math.max(me,xe),this,G,te,-1/0);return new u(B,le,ye)}argmin(G=null,te=!1){if(G!==null)throw new Error("`dim !== null` not yet implemented.");const B=(0,i.min)(this.data)[1];return new u("int64",[BigInt(B)],[])}argmax(G=null,te=!1){if(G!==null)throw new Error("`dim !== null` not yet implemented.");const B=(0,i.max)(this.data)[1];return new u("int64",[BigInt(B)],[])}to(G){if(this.type===G)return this;if(!l.hasOwnProperty(G))throw new Error(`Unsupported type: ${G}`);let te;const B=["int64","uint64"].includes(this.type),le=["int64","uint64"].includes(G);return B&&!le?te=Number:!B&&le&&(te=BigInt),new u(G,l[G].from(this.data,te),this.dims)}}function d(q,G){const te=q.length,B=G.reduce((ye,me)=>ye*me);if(te!==B)throw Error(`cannot reshape array of size ${te} into shape (${G})`);let le=q;for(let ye=G.length-1;ye>=0;ye--)le=le.reduce((me,xe)=>{let ze=me[me.length-1];return ze.lengthnew u("int64",q,[q.length]);async function T(q,G,te,B,le){return await(await o.TensorOpRegistry.slice)({x:q,s:b(G),e:b(te),a:b(B),t:b(le??new Array(B.length).fill(1))})}function v(q,G){const te=q.data,B=G.data,le=[q.dims[0],q.dims[2]],ye=new te.constructor(le[0]*le[1]),[me,xe,ze]=q.dims;let Me=0;for(let ce=0;cete!==1):typeof G=="number"?q[G]===1&&q.splice(G,1):Array.isArray(G)&&(q=q.filter((te,B)=>te!==1||!G.includes(B))),q}function w(q,G){return G=C(G,q.length+1),q=q.slice(),q.splice(G,0,1),q}function C(q,G,te=null,B=!0){if(q<-G||q>=G){if(B)throw new Error(`IndexError: index ${q} is out of bounds for dimension${te===null?"":" "+te} with size ${G}`);return q<-G?0:G}return q<0&&(q=(q%G+G)%G),q}function E(q,G=0){G=C(G,q[0].dims.length);const te=q[0].dims.slice();te[G]=q.reduce((me,xe)=>me+xe.dims[G],0);const B=te.reduce((me,xe)=>me*xe,1),le=new q[0].data.constructor(B),ye=q[0].type;if(G===0){let me=0;for(const xe of q){const ze=xe.data;le.set(ze,me),me+=ze.length}}else{let me=0;for(let xe=0;xe=0;--we){const Ne=Me[we];let We=re%Ne;we===G&&(We+=me),ae+=We*He,He*=te[we],re=Math.floor(re/Ne)}le[ae]=ze[ce]}me+=Me[G]}}return new u(ye,le,te)}function A(q,G=0){return E(q.map(te=>te.unsqueeze(G)),G)}function L(q,G,te=null,B=!1,le=null){const ye=G.data,me=G.dims;te=C(te,me.length);const xe=me.slice();xe[te]=1;const ze=new ye.constructor(ye.length/me[te]);le!==null&&ze.fill(le);for(let Me=0;Me=0;--ae){const He=me[ae];if(ae!==te){const Ne=we%He;ce+=Ne*re,re*=xe[ae]}we=Math.floor(we/He)}ze[ce]=q(ze[ce],ye[Me],Me,ce)}return B||xe.splice(te,1),[G.type,ze,xe]}function I(q,G=null,te=1,B=!1){const le=q.data,ye=q.dims;if(G===null){const re=le.reduce((ke,st)=>ke+st,0)/le.length,He=Math.sqrt(le.reduce((ke,st)=>ke+(st-re)**2,0)/(le.length-te)),Ne=new u(q.type,[re],[]);return[new u(q.type,[He],[]),Ne]}G=C(G,ye.length);const me=O(q,G,B),xe=me.data,[ze,Me,ce]=L((we,re,He,Ne)=>we+(re-xe[Ne])**2,q,G,B);for(let we=0;weMe+ce,0);return new u(q.type,[ze/le.length],[])}G=C(G,B.length);const[ye,me,xe]=L((ze,Me)=>ze+Me,q,G,te);if(B[G]!==1)for(let ze=0;ze=0;--te)G[te]=B,B*=q[te];return G}function Z(q,G,te,B){const le=q.reduce((ye,me)=>ye*me,1);return new u(te,new B(le).fill(G),q)}function $(q,G){let te,B;if(typeof G=="number")te="float32",B=Float32Array;else if(typeof G=="bigint")te="int64",B=BigInt64Array;else if(typeof G=="boolean")te="bool",B=Uint8Array;else throw new Error(`Unsupported data type: ${typeof G}`);return Z(q,G,te,B)}function J(q,G){return $(q.dims,G)}function ee(q){return Z(q,1n,"int64",BigInt64Array)}function X(q){return ee(q.dims)}function ne(q){return Z(q,0n,"int64",BigInt64Array)}function Q(q){return ne(q.dims)}function oe(q){const G=q.reduce((te,B)=>te*B,1);return new u("float32",Float32Array.from({length:G},()=>Math.random()),q)}function W(q,G){if(q.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(q.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(G))throw new Error("The precision must be either 'binary' or 'ubinary'");const te=G==="binary",B=te?"int8":"uint8",le=te?Int8Array:Uint8Array,ye=q.data,me=new le(ye.length/8);for(let xe=0;xe0?1:0,Me=Math.floor(xe/8),ce=xe%8;me[Me]|=ze<<7-ce,te&&ce===0&&(me[Me]-=128)}return new u(B,me,[q.dims[0],q.dims[1]/8])}},"./src/utils/video.js":(n,e,t)=>{t.r(e),t.d(e,{RawVideo:()=>l,RawVideoFrame:()=>o,load_video:()=>u});var i=t("./src/utils/image.js"),s=t("./src/env.js");class o{constructor(f,m){this.image=f,this.timestamp=m}}class l{constructor(f,m){f.length>0&&f[0]instanceof i.RawImage&&(f=f.map((h,_)=>new o(h,(_+1)/(f.length+1)*m))),this.frames=f,this.duration=m}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function u(d,{num_frames:f=null,fps:m=null}={}){if(!s.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(f==null&&m==null)throw new Error("Either num_frames or fps must be provided.");const h=[],_=document.createElement("video");if(_.crossOrigin="anonymous",_.muted=!0,typeof d=="string")_.src=d;else if(d instanceof Blob)_.src=URL.createObjectURL(d);else if(d instanceof HTMLVideoElement)_.src=d.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(P=>_.onloadedmetadata=P),_.seekable.start(0)===_.seekable.end(0)){const w=await(await fetch(_.src)).blob();_.src=URL.createObjectURL(w),await new Promise(C=>_.onloadedmetadata=C)}const g=_.duration;let y,b;f!=null?(y=f,b=f===1?0:g/(f-1)):(b=1/m,y=Math.floor(g/b));let T=[];for(let P=0;P{_.onseeked=A}),x.drawImage(_,0,0,v.width,v.height);const w=x.getImageData(0,0,v.width,v.height),C=new i.RawImage(w.data,v.width,v.height,4),E=new o(C,P);h.push(E)}return _.remove(),new l(h,g)}}},AE={};function ni(n){var e=AE[n];if(e!==void 0)return e.exports;var t=AE[n]={exports:{}};return F3[n](t,t.exports,ni),t.exports}(()=>{var n=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,e;ni.t=function(t,i){if(i&1&&(t=this(t)),i&8||typeof t=="object"&&t&&(i&4&&t.__esModule||i&16&&typeof t.then=="function"))return t;var s=Object.create(null);ni.r(s);var o={};e=e||[null,n({}),n([]),n(n)];for(var l=i&2&&t;typeof l=="object"&&!~e.indexOf(l);l=n(l))Object.getOwnPropertyNames(l).forEach(u=>o[u]=()=>t[u]);return o.default=()=>t,ni.d(s,o),s}})();ni.d=(n,e)=>{for(var t in e)ni.o(e,t)&&!ni.o(n,t)&&Object.defineProperty(n,t,{enumerable:!0,get:e[t]})};ni.o=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);ni.r=n=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})};var D={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/ni.r(D),ni.d(D,{ASTFeatureExtractor:()=>h.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>i.AlbertTokenizer,AudioClassificationPipeline:()=>e.AudioClassificationPipeline,AutoConfig:()=>s.AutoConfig,AutoFeatureExtractor:()=>_.AutoFeatureExtractor,AutoImageProcessor:()=>b.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>x.AutoProcessor,AutoTokenizer:()=>i.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>e.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>e.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>i.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>P.BaseStreamer,BeitFeatureExtractor:()=>y.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>i.BertTokenizer,BitImageProcessor:()=>y.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>i.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>i.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>i.BloomTokenizer,CLIPFeatureExtractor:()=>y.CLIPFeatureExtractor,CLIPImageProcessor:()=>y.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>i.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>i.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>y.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>h.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>C.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>i.CodeGenTokenizer,CodeLlamaTokenizer:()=>i.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>i.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>i.ConvBertTokenizer,ConvNextFeatureExtractor:()=>y.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>y.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>y.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>y.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>h.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>d.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>i.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>i.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>y.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>y.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>e.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>y.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>y.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>i.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>e.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>y.DonutFeatureExtractor,DonutImageProcessor:()=>y.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>y.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>i.ElectraTokenizer,EncodecFeatureExtractor:()=>h.EncodecFeatureExtractor,EosTokenCriteria:()=>w.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>i.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>f.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>i.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>e.FeatureExtractionPipeline,FeatureExtractor:()=>m.FeatureExtractor,FillMaskPipeline:()=>e.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>v.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>C.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>C.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>y.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>i.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>i.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>i.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>i.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>y.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>v.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>i.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>y.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>v.Idefics3Processor,ImageClassificationPipeline:()=>e.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>e.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>h.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>g.ImageProcessor,ImageSegmentationPipeline:()=>e.ImageSegmentationPipeline,ImageToImagePipeline:()=>e.ImageToImagePipeline,ImageToTextPipeline:()=>e.ImageToTextPipeline,InterruptableStoppingCriteria:()=>w.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>y.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>v.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>i.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>y.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>C.LogitsProcessor,LogitsProcessorList:()=>C.LogitsProcessorList,LogitsWarper:()=>C.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>i.M2M100Tokenizer,MBart50Tokenizer:()=>i.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>i.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>i.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>i.MarianTokenizer,Mask2FormerImageProcessor:()=>y.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>y.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>y.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>w.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>v.MgpstrProcessor,MgpstrTokenizer:()=>i.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>C.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>C.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>i.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>y.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>y.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>y.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>y.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>y.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>y.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>y.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>y.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>h.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>v.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>i.NllbTokenizer,NoBadWordsLogitsProcessor:()=>C.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>C.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>y.NougatImageProcessor,NougatTokenizer:()=>i.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>e.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>y.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>y.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>v.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>y.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>v.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>y.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>v.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>e.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>i.PreTrainedTokenizer,PretrainedConfig:()=>s.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>T.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>y.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>h.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>v.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>e.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>i.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>y.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>v.Qwen2VLProcessor,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>y.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>o.RawAudio,RawImage:()=>l.RawImage,RawVideo:()=>u.RawVideo,RawVideoFrame:()=>u.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>C.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>i.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>i.RobertaTokenizer,SamImageProcessor:()=>y.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>v.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>h.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>y.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>y.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>y.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>i.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>y.SmolVLMImageProcessor,SmolVLMProcessor:()=>v.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>h.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>h.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>v.SpeechT5Processor,SpeechT5Tokenizer:()=>i.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>i.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>w.StoppingCriteria,StoppingCriteriaList:()=>w.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>e.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>C.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>y.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>i.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>C.TemperatureLogitsWarper,Tensor:()=>d.Tensor,Text2TextGenerationPipeline:()=>e.Text2TextGenerationPipeline,TextClassificationPipeline:()=>e.TextClassificationPipeline,TextGenerationPipeline:()=>e.TextGenerationPipeline,TextStreamer:()=>P.TextStreamer,TextToAudioPipeline:()=>e.TextToAudioPipeline,TokenClassificationPipeline:()=>e.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>i.TokenizerModel,TopKLogitsWarper:()=>C.TopKLogitsWarper,TopPLogitsWarper:()=>C.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>e.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>v.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>v.VLChatProcessor,VLMImageProcessor:()=>y.VLMImageProcessor,ViTFeatureExtractor:()=>y.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>y.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>y.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>y.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>i.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>i.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>h.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>v.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>v.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>h.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>h.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>v.WhisperProcessor,WhisperTextStreamer:()=>P.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>C.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>i.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>i.XLMRobertaTokenizer,XLMTokenizer:()=>i.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>y.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>y.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>e.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>e.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>e.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>e.ZeroShotObjectDetectionPipeline,bankers_round:()=>f.bankers_round,cat:()=>d.cat,cos_sim:()=>f.cos_sim,dot:()=>f.dot,dynamic_time_warping:()=>f.dynamic_time_warping,env:()=>n.env,full:()=>d.full,full_like:()=>d.full_like,getKeyValueShapes:()=>s.getKeyValueShapes,hamming:()=>o.hamming,hanning:()=>o.hanning,interpolate:()=>d.interpolate,interpolate_4d:()=>d.interpolate_4d,interpolate_data:()=>f.interpolate_data,is_chinese_char:()=>i.is_chinese_char,layer_norm:()=>d.layer_norm,load_image:()=>l.load_image,load_video:()=>u.load_video,log_softmax:()=>f.log_softmax,magnitude:()=>f.magnitude,matmul:()=>d.matmul,max:()=>f.max,mean:()=>d.mean,mean_pooling:()=>d.mean_pooling,medianFilter:()=>f.medianFilter,mel_filter_bank:()=>o.mel_filter_bank,min:()=>f.min,ones:()=>d.ones,ones_like:()=>d.ones_like,permute:()=>d.permute,permute_data:()=>f.permute_data,pipeline:()=>e.pipeline,quantize_embeddings:()=>d.quantize_embeddings,rand:()=>d.rand,read_audio:()=>o.read_audio,rfft:()=>d.rfft,round:()=>f.round,slice:()=>d.slice,softmax:()=>f.softmax,spectrogram:()=>o.spectrogram,stack:()=>d.stack,std_mean:()=>d.std_mean,topk:()=>d.topk,window_function:()=>o.window_function,zeros:()=>d.zeros,zeros_like:()=>d.zeros_like});var n=ni("./src/env.js"),e=ni("./src/pipelines.js"),t=ni("./src/models.js"),i=ni("./src/tokenizers.js"),s=ni("./src/configs.js"),o=ni("./src/utils/audio.js"),l=ni("./src/utils/image.js"),u=ni("./src/utils/video.js"),d=ni("./src/utils/tensor.js"),f=ni("./src/utils/maths.js"),m=ni("./src/base/feature_extraction_utils.js"),h=ni("./src/models/feature_extractors.js"),_=ni("./src/models/auto/feature_extraction_auto.js"),g=ni("./src/base/image_processors_utils.js"),y=ni("./src/models/image_processors.js"),b=ni("./src/models/auto/image_processing_auto.js"),T=ni("./src/base/processing_utils.js"),v=ni("./src/models/processors.js"),x=ni("./src/models/auto/processing_auto.js"),P=ni("./src/generation/streamers.js"),w=ni("./src/generation/stopping_criteria.js"),C=ni("./src/generation/logits_process.js")})();D.ASTFeatureExtractor;D.ASTForAudioClassification;D.ASTModel;D.ASTPreTrainedModel;D.AlbertForMaskedLM;D.AlbertForQuestionAnswering;D.AlbertForSequenceClassification;D.AlbertModel;D.AlbertPreTrainedModel;D.AlbertTokenizer;D.AudioClassificationPipeline;D.AutoConfig;D.AutoFeatureExtractor;D.AutoImageProcessor;D.AutoModel;D.AutoModelForAudioClassification;D.AutoModelForAudioFrameClassification;D.AutoModelForAudioTextToText;D.AutoModelForCTC;D.AutoModelForCausalLM;D.AutoModelForDepthEstimation;D.AutoModelForDocumentQuestionAnswering;D.AutoModelForImageClassification;D.AutoModelForImageFeatureExtraction;D.AutoModelForImageMatting;D.AutoModelForImageSegmentation;D.AutoModelForImageTextToText;D.AutoModelForImageToImage;D.AutoModelForMaskGeneration;D.AutoModelForMaskedLM;D.AutoModelForNormalEstimation;D.AutoModelForObjectDetection;D.AutoModelForPoseEstimation;D.AutoModelForQuestionAnswering;D.AutoModelForSemanticSegmentation;D.AutoModelForSeq2SeqLM;D.AutoModelForSequenceClassification;D.AutoModelForSpeechSeq2Seq;D.AutoModelForTextToSpectrogram;D.AutoModelForTextToWaveform;D.AutoModelForTokenClassification;D.AutoModelForUniversalSegmentation;D.AutoModelForVision2Seq;D.AutoModelForXVector;D.AutoModelForZeroShotObjectDetection;D.AutoProcessor;D.AutoTokenizer;D.AutomaticSpeechRecognitionPipeline;D.BackgroundRemovalPipeline;D.BartForConditionalGeneration;D.BartForSequenceClassification;D.BartModel;D.BartPretrainedModel;D.BartTokenizer;D.BaseModelOutput;D.BaseStreamer;D.BeitFeatureExtractor;D.BeitForImageClassification;D.BeitModel;D.BeitPreTrainedModel;D.BertForMaskedLM;D.BertForQuestionAnswering;D.BertForSequenceClassification;D.BertForTokenClassification;D.BertModel;D.BertPreTrainedModel;D.BertTokenizer;D.BitImageProcessor;D.BlenderbotForConditionalGeneration;D.BlenderbotModel;D.BlenderbotPreTrainedModel;D.BlenderbotSmallForConditionalGeneration;D.BlenderbotSmallModel;D.BlenderbotSmallPreTrainedModel;D.BlenderbotSmallTokenizer;D.BlenderbotTokenizer;D.BloomForCausalLM;D.BloomModel;D.BloomPreTrainedModel;D.BloomTokenizer;D.CLIPFeatureExtractor;D.CLIPImageProcessor;D.CLIPModel;D.CLIPPreTrainedModel;D.CLIPSegForImageSegmentation;D.CLIPSegModel;D.CLIPSegPreTrainedModel;D.CLIPTextModel;D.CLIPTextModelWithProjection;D.CLIPTokenizer;D.CLIPVisionModel;D.CLIPVisionModelWithProjection;D.CamembertForMaskedLM;D.CamembertForQuestionAnswering;D.CamembertForSequenceClassification;D.CamembertForTokenClassification;D.CamembertModel;D.CamembertPreTrainedModel;D.CamembertTokenizer;D.CausalLMOutput;D.CausalLMOutputWithPast;D.ChineseCLIPFeatureExtractor;D.ChineseCLIPModel;D.ChineseCLIPPreTrainedModel;D.ClapAudioModelWithProjection;D.ClapFeatureExtractor;D.ClapModel;D.ClapPreTrainedModel;D.ClapTextModelWithProjection;D.ClassifierFreeGuidanceLogitsProcessor;D.CodeGenForCausalLM;D.CodeGenModel;D.CodeGenPreTrainedModel;D.CodeGenTokenizer;D.CodeLlamaTokenizer;D.CohereForCausalLM;D.CohereModel;D.CoherePreTrainedModel;D.CohereTokenizer;D.ConvBertForMaskedLM;D.ConvBertForQuestionAnswering;D.ConvBertForSequenceClassification;D.ConvBertForTokenClassification;D.ConvBertModel;D.ConvBertPreTrainedModel;D.ConvBertTokenizer;D.ConvNextFeatureExtractor;D.ConvNextForImageClassification;D.ConvNextImageProcessor;D.ConvNextModel;D.ConvNextPreTrainedModel;D.ConvNextV2ForImageClassification;D.ConvNextV2Model;D.ConvNextV2PreTrainedModel;D.DPTFeatureExtractor;D.DPTForDepthEstimation;D.DPTImageProcessor;D.DPTModel;D.DPTPreTrainedModel;D.DacDecoderModel;D.DacDecoderOutput;D.DacEncoderModel;D.DacEncoderOutput;D.DacFeatureExtractor;D.DacModel;D.DacPreTrainedModel;D.DataTypeMap;D.DebertaForMaskedLM;D.DebertaForQuestionAnswering;D.DebertaForSequenceClassification;D.DebertaForTokenClassification;D.DebertaModel;D.DebertaPreTrainedModel;D.DebertaTokenizer;D.DebertaV2ForMaskedLM;D.DebertaV2ForQuestionAnswering;D.DebertaV2ForSequenceClassification;D.DebertaV2ForTokenClassification;D.DebertaV2Model;D.DebertaV2PreTrainedModel;D.DebertaV2Tokenizer;D.DecisionTransformerModel;D.DecisionTransformerPreTrainedModel;D.DeiTFeatureExtractor;D.DeiTForImageClassification;D.DeiTImageProcessor;D.DeiTModel;D.DeiTPreTrainedModel;D.DepthAnythingForDepthEstimation;D.DepthAnythingPreTrainedModel;D.DepthEstimationPipeline;D.DepthProForDepthEstimation;D.DepthProPreTrainedModel;D.DetrFeatureExtractor;D.DetrForObjectDetection;D.DetrForSegmentation;D.DetrImageProcessor;D.DetrModel;D.DetrObjectDetectionOutput;D.DetrPreTrainedModel;D.DetrSegmentationOutput;D.Dinov2ForImageClassification;D.Dinov2Model;D.Dinov2PreTrainedModel;D.Dinov2WithRegistersForImageClassification;D.Dinov2WithRegistersModel;D.Dinov2WithRegistersPreTrainedModel;D.DistilBertForMaskedLM;D.DistilBertForQuestionAnswering;D.DistilBertForSequenceClassification;D.DistilBertForTokenClassification;D.DistilBertModel;D.DistilBertPreTrainedModel;D.DistilBertTokenizer;D.DocumentQuestionAnsweringPipeline;D.DonutFeatureExtractor;D.DonutImageProcessor;D.DonutSwinModel;D.DonutSwinPreTrainedModel;D.EfficientNetForImageClassification;D.EfficientNetImageProcessor;D.EfficientNetModel;D.EfficientNetPreTrainedModel;D.ElectraForMaskedLM;D.ElectraForQuestionAnswering;D.ElectraForSequenceClassification;D.ElectraForTokenClassification;D.ElectraModel;D.ElectraPreTrainedModel;D.ElectraTokenizer;D.EncodecFeatureExtractor;D.EosTokenCriteria;D.EsmForMaskedLM;D.EsmForSequenceClassification;D.EsmForTokenClassification;D.EsmModel;D.EsmPreTrainedModel;D.EsmTokenizer;D.ExaoneForCausalLM;D.ExaoneModel;D.ExaonePreTrainedModel;D.FFT;D.FalconForCausalLM;D.FalconModel;D.FalconPreTrainedModel;D.FalconTokenizer;D.FastViTForImageClassification;D.FastViTModel;D.FastViTPreTrainedModel;D.FeatureExtractionPipeline;D.FeatureExtractor;D.FillMaskPipeline;D.Florence2ForConditionalGeneration;D.Florence2PreTrainedModel;D.Florence2Processor;D.ForcedBOSTokenLogitsProcessor;D.ForcedEOSTokenLogitsProcessor;D.GLPNFeatureExtractor;D.GLPNForDepthEstimation;D.GLPNModel;D.GLPNPreTrainedModel;D.GPT2LMHeadModel;D.GPT2Model;D.GPT2PreTrainedModel;D.GPT2Tokenizer;D.GPTBigCodeForCausalLM;D.GPTBigCodeModel;D.GPTBigCodePreTrainedModel;D.GPTJForCausalLM;D.GPTJModel;D.GPTJPreTrainedModel;D.GPTNeoForCausalLM;D.GPTNeoModel;D.GPTNeoPreTrainedModel;D.GPTNeoXForCausalLM;D.GPTNeoXModel;D.GPTNeoXPreTrainedModel;D.GPTNeoXTokenizer;D.Gemma2ForCausalLM;D.Gemma2Model;D.Gemma2PreTrainedModel;D.Gemma3ForCausalLM;D.Gemma3Model;D.Gemma3PreTrainedModel;D.GemmaForCausalLM;D.GemmaModel;D.GemmaPreTrainedModel;D.GemmaTokenizer;D.GlmForCausalLM;D.GlmModel;D.GlmPreTrainedModel;D.GraniteForCausalLM;D.GraniteModel;D.GranitePreTrainedModel;D.Grok1Tokenizer;D.GroundingDinoForObjectDetection;D.GroundingDinoImageProcessor;D.GroundingDinoPreTrainedModel;D.GroundingDinoProcessor;D.GroupViTModel;D.GroupViTPreTrainedModel;D.HeliumForCausalLM;D.HeliumModel;D.HeliumPreTrainedModel;D.HerbertTokenizer;D.HieraForImageClassification;D.HieraModel;D.HieraPreTrainedModel;D.HubertForCTC;D.HubertForSequenceClassification;D.HubertModel;D.HubertPreTrainedModel;D.IJepaForImageClassification;D.IJepaModel;D.IJepaPreTrainedModel;D.Idefics3ForConditionalGeneration;D.Idefics3ImageProcessor;D.Idefics3PreTrainedModel;D.Idefics3Processor;D.ImageClassificationPipeline;D.ImageFeatureExtractionPipeline;D.ImageFeatureExtractor;D.ImageMattingOutput;D.ImageProcessor;D.ImageSegmentationPipeline;D.ImageToImagePipeline;D.ImageToTextPipeline;D.InterruptableStoppingCriteria;D.JAISLMHeadModel;D.JAISModel;D.JAISPreTrainedModel;D.JinaCLIPImageProcessor;D.JinaCLIPModel;D.JinaCLIPPreTrainedModel;D.JinaCLIPProcessor;D.JinaCLIPTextModel;D.JinaCLIPVisionModel;D.LiteWhisperForConditionalGeneration;D.LlamaForCausalLM;D.LlamaModel;D.LlamaPreTrainedModel;D.LlamaTokenizer;D.LlavaForConditionalGeneration;D.LlavaOnevisionForConditionalGeneration;D.LlavaOnevisionImageProcessor;D.LlavaPreTrainedModel;D.LogitsProcessor;D.LogitsProcessorList;D.LogitsWarper;D.LongT5ForConditionalGeneration;D.LongT5Model;D.LongT5PreTrainedModel;D.M2M100ForConditionalGeneration;D.M2M100Model;D.M2M100PreTrainedModel;D.M2M100Tokenizer;D.MBart50Tokenizer;D.MBartForCausalLM;D.MBartForConditionalGeneration;D.MBartForSequenceClassification;D.MBartModel;D.MBartPreTrainedModel;D.MBartTokenizer;D.MPNetForMaskedLM;D.MPNetForQuestionAnswering;D.MPNetForSequenceClassification;D.MPNetForTokenClassification;D.MPNetModel;D.MPNetPreTrainedModel;D.MPNetTokenizer;D.MT5ForConditionalGeneration;D.MT5Model;D.MT5PreTrainedModel;D.MarianMTModel;D.MarianModel;D.MarianPreTrainedModel;D.MarianTokenizer;D.Mask2FormerImageProcessor;D.MaskFormerFeatureExtractor;D.MaskFormerForInstanceSegmentation;D.MaskFormerImageProcessor;D.MaskFormerModel;D.MaskFormerPreTrainedModel;D.MaskedLMOutput;D.MaxLengthCriteria;D.Metric3DForDepthEstimation;D.Metric3DPreTrainedModel;D.Metric3Dv2ForDepthEstimation;D.Metric3Dv2PreTrainedModel;D.MgpstrForSceneTextRecognition;D.MgpstrModelOutput;D.MgpstrPreTrainedModel;D.MgpstrProcessor;D.MgpstrTokenizer;D.MimiDecoderModel;D.MimiDecoderOutput;D.MimiEncoderModel;D.MimiEncoderOutput;D.MimiModel;D.MimiPreTrainedModel;D.MinLengthLogitsProcessor;D.MinNewTokensLengthLogitsProcessor;D.MistralForCausalLM;D.MistralModel;D.MistralPreTrainedModel;D.MobileBertForMaskedLM;D.MobileBertForQuestionAnswering;D.MobileBertForSequenceClassification;D.MobileBertModel;D.MobileBertPreTrainedModel;D.MobileBertTokenizer;D.MobileLLMForCausalLM;D.MobileLLMModel;D.MobileLLMPreTrainedModel;D.MobileNetV1FeatureExtractor;D.MobileNetV1ForImageClassification;D.MobileNetV1ForSemanticSegmentation;D.MobileNetV1ImageProcessor;D.MobileNetV1Model;D.MobileNetV1PreTrainedModel;D.MobileNetV2FeatureExtractor;D.MobileNetV2ForImageClassification;D.MobileNetV2ForSemanticSegmentation;D.MobileNetV2ImageProcessor;D.MobileNetV2Model;D.MobileNetV2PreTrainedModel;D.MobileNetV3FeatureExtractor;D.MobileNetV3ForImageClassification;D.MobileNetV3ForSemanticSegmentation;D.MobileNetV3ImageProcessor;D.MobileNetV3Model;D.MobileNetV3PreTrainedModel;D.MobileNetV4FeatureExtractor;D.MobileNetV4ForImageClassification;D.MobileNetV4ForSemanticSegmentation;D.MobileNetV4ImageProcessor;D.MobileNetV4Model;D.MobileNetV4PreTrainedModel;D.MobileViTFeatureExtractor;D.MobileViTForImageClassification;D.MobileViTImageProcessor;D.MobileViTModel;D.MobileViTPreTrainedModel;D.MobileViTV2ForImageClassification;D.MobileViTV2Model;D.MobileViTV2PreTrainedModel;D.ModelOutput;D.ModernBertForMaskedLM;D.ModernBertForSequenceClassification;D.ModernBertForTokenClassification;D.ModernBertModel;D.ModernBertPreTrainedModel;D.Moondream1ForConditionalGeneration;D.MoonshineFeatureExtractor;D.MoonshineForConditionalGeneration;D.MoonshineModel;D.MoonshinePreTrainedModel;D.MoonshineProcessor;D.MptForCausalLM;D.MptModel;D.MptPreTrainedModel;D.MultiModalityCausalLM;D.MultiModalityPreTrainedModel;D.MusicgenForCausalLM;D.MusicgenForConditionalGeneration;D.MusicgenModel;D.MusicgenPreTrainedModel;D.NllbTokenizer;D.NoBadWordsLogitsProcessor;D.NoRepeatNGramLogitsProcessor;D.NomicBertModel;D.NomicBertPreTrainedModel;D.NougatImageProcessor;D.NougatTokenizer;D.OPTForCausalLM;D.OPTModel;D.OPTPreTrainedModel;D.ObjectDetectionPipeline;D.Olmo2ForCausalLM;D.Olmo2Model;D.Olmo2PreTrainedModel;D.OlmoForCausalLM;D.OlmoModel;D.OlmoPreTrainedModel;D.OpenELMForCausalLM;D.OpenELMModel;D.OpenELMPreTrainedModel;D.OwlViTFeatureExtractor;D.OwlViTForObjectDetection;D.OwlViTImageProcessor;D.OwlViTModel;D.OwlViTPreTrainedModel;D.OwlViTProcessor;D.Owlv2ForObjectDetection;D.Owlv2ImageProcessor;D.Owlv2Model;D.Owlv2PreTrainedModel;D.PaliGemmaForConditionalGeneration;D.PaliGemmaPreTrainedModel;D.PaliGemmaProcessor;D.PatchTSMixerForPrediction;D.PatchTSMixerModel;D.PatchTSMixerPreTrainedModel;D.PatchTSTForPrediction;D.PatchTSTModel;D.PatchTSTPreTrainedModel;D.Phi3ForCausalLM;D.Phi3Model;D.Phi3PreTrainedModel;D.Phi3VForCausalLM;D.Phi3VImageProcessor;D.Phi3VPreTrainedModel;D.Phi3VProcessor;D.PhiForCausalLM;D.PhiModel;D.PhiPreTrainedModel;D.Pipeline;D.PreTrainedModel;D.PreTrainedTokenizer;D.PretrainedConfig;D.PretrainedMixin;D.Processor;D.PvtForImageClassification;D.PvtImageProcessor;D.PvtModel;D.PvtPreTrainedModel;D.PyAnnoteFeatureExtractor;D.PyAnnoteForAudioFrameClassification;D.PyAnnoteModel;D.PyAnnotePreTrainedModel;D.PyAnnoteProcessor;D.QuestionAnsweringModelOutput;D.QuestionAnsweringPipeline;D.Qwen2ForCausalLM;D.Qwen2Model;D.Qwen2PreTrainedModel;D.Qwen2Tokenizer;D.Qwen2VLForConditionalGeneration;D.Qwen2VLImageProcessor;D.Qwen2VLPreTrainedModel;D.Qwen2VLProcessor;D.RFDetrForObjectDetection;D.RFDetrModel;D.RFDetrObjectDetectionOutput;D.RFDetrPreTrainedModel;D.RTDetrForObjectDetection;D.RTDetrImageProcessor;D.RTDetrModel;D.RTDetrObjectDetectionOutput;D.RTDetrPreTrainedModel;D.RTDetrV2ForObjectDetection;D.RTDetrV2Model;D.RTDetrV2ObjectDetectionOutput;D.RTDetrV2PreTrainedModel;D.RawAudio;D.RawImage;D.RawVideo;D.RawVideoFrame;D.RepetitionPenaltyLogitsProcessor;D.ResNetForImageClassification;D.ResNetModel;D.ResNetPreTrainedModel;D.RoFormerForMaskedLM;D.RoFormerForQuestionAnswering;D.RoFormerForSequenceClassification;D.RoFormerForTokenClassification;D.RoFormerModel;D.RoFormerPreTrainedModel;D.RoFormerTokenizer;D.RobertaForMaskedLM;D.RobertaForQuestionAnswering;D.RobertaForSequenceClassification;D.RobertaForTokenClassification;D.RobertaModel;D.RobertaPreTrainedModel;D.RobertaTokenizer;D.SamImageProcessor;D.SamImageSegmentationOutput;D.SamModel;D.SamPreTrainedModel;D.SamProcessor;D.SapiensForDepthEstimation;D.SapiensForNormalEstimation;D.SapiensForSemanticSegmentation;D.SapiensPreTrainedModel;D.SeamlessM4TFeatureExtractor;D.SegformerFeatureExtractor;D.SegformerForImageClassification;D.SegformerForSemanticSegmentation;D.SegformerImageProcessor;D.SegformerModel;D.SegformerPreTrainedModel;D.Seq2SeqLMOutput;D.SequenceClassifierOutput;D.SiglipImageProcessor;D.SiglipModel;D.SiglipPreTrainedModel;D.SiglipTextModel;D.SiglipTokenizer;D.SiglipVisionModel;D.SmolVLMForConditionalGeneration;D.SmolVLMImageProcessor;D.SmolVLMProcessor;D.SnacDecoderModel;D.SnacEncoderModel;D.SnacFeatureExtractor;D.SnacModel;D.SnacPreTrainedModel;D.SpeechT5FeatureExtractor;D.SpeechT5ForSpeechToText;D.SpeechT5ForTextToSpeech;D.SpeechT5HifiGan;D.SpeechT5Model;D.SpeechT5PreTrainedModel;D.SpeechT5Processor;D.SpeechT5Tokenizer;D.SqueezeBertForMaskedLM;D.SqueezeBertForQuestionAnswering;D.SqueezeBertForSequenceClassification;D.SqueezeBertModel;D.SqueezeBertPreTrainedModel;D.SqueezeBertTokenizer;D.StableLmForCausalLM;D.StableLmModel;D.StableLmPreTrainedModel;D.Starcoder2ForCausalLM;D.Starcoder2Model;D.Starcoder2PreTrainedModel;D.StoppingCriteria;D.StoppingCriteriaList;D.StyleTextToSpeech2Model;D.StyleTextToSpeech2PreTrainedModel;D.SummarizationPipeline;D.SuppressTokensAtBeginLogitsProcessor;D.Swin2SRForImageSuperResolution;D.Swin2SRImageProcessor;D.Swin2SRModel;D.Swin2SRPreTrainedModel;D.SwinForImageClassification;D.SwinForSemanticSegmentation;D.SwinModel;D.SwinPreTrainedModel;D.T5ForConditionalGeneration;D.T5Model;D.T5PreTrainedModel;D.T5Tokenizer;D.TableTransformerForObjectDetection;D.TableTransformerModel;D.TableTransformerObjectDetectionOutput;D.TableTransformerPreTrainedModel;D.TemperatureLogitsWarper;D.Tensor;D.Text2TextGenerationPipeline;D.TextClassificationPipeline;D.TextGenerationPipeline;D.TextStreamer;D.TextToAudioPipeline;D.TokenClassificationPipeline;D.TokenClassifierOutput;D.TokenizerModel;D.TopKLogitsWarper;D.TopPLogitsWarper;D.TrOCRForCausalLM;D.TrOCRPreTrainedModel;D.TranslationPipeline;D.UltravoxModel;D.UltravoxPreTrainedModel;D.UltravoxProcessor;D.UniSpeechForCTC;D.UniSpeechForSequenceClassification;D.UniSpeechModel;D.UniSpeechPreTrainedModel;D.UniSpeechSatForAudioFrameClassification;D.UniSpeechSatForCTC;D.UniSpeechSatForSequenceClassification;D.UniSpeechSatModel;D.UniSpeechSatPreTrainedModel;D.VLChatProcessor;D.VLMImageProcessor;D.ViTFeatureExtractor;D.ViTForImageClassification;D.ViTImageProcessor;D.ViTMAEModel;D.ViTMAEPreTrainedModel;D.ViTMSNForImageClassification;D.ViTMSNModel;D.ViTMSNPreTrainedModel;D.ViTModel;D.ViTPreTrainedModel;D.VisionEncoderDecoderModel;D.VitMatteForImageMatting;D.VitMatteImageProcessor;D.VitMattePreTrainedModel;D.VitPoseForPoseEstimation;D.VitPoseImageProcessor;D.VitPosePreTrainedModel;D.VitsModel;D.VitsModelOutput;D.VitsPreTrainedModel;D.VitsTokenizer;D.Wav2Vec2BertForCTC;D.Wav2Vec2BertForSequenceClassification;D.Wav2Vec2BertModel;D.Wav2Vec2BertPreTrainedModel;D.Wav2Vec2CTCTokenizer;D.Wav2Vec2FeatureExtractor;D.Wav2Vec2ForAudioFrameClassification;D.Wav2Vec2ForCTC;D.Wav2Vec2ForSequenceClassification;D.Wav2Vec2Model;D.Wav2Vec2PreTrainedModel;D.Wav2Vec2Processor;D.Wav2Vec2ProcessorWithLM;D.WavLMForAudioFrameClassification;D.WavLMForCTC;D.WavLMForSequenceClassification;D.WavLMForXVector;D.WavLMModel;D.WavLMPreTrainedModel;D.WeSpeakerFeatureExtractor;D.WeSpeakerResNetModel;D.WeSpeakerResNetPreTrainedModel;D.WhisperFeatureExtractor;D.WhisperForConditionalGeneration;D.WhisperModel;D.WhisperPreTrainedModel;D.WhisperProcessor;D.WhisperTextStreamer;D.WhisperTimeStampLogitsProcessor;D.WhisperTokenizer;D.XLMForQuestionAnswering;D.XLMForSequenceClassification;D.XLMForTokenClassification;D.XLMModel;D.XLMPreTrainedModel;D.XLMRobertaForMaskedLM;D.XLMRobertaForQuestionAnswering;D.XLMRobertaForSequenceClassification;D.XLMRobertaForTokenClassification;D.XLMRobertaModel;D.XLMRobertaPreTrainedModel;D.XLMRobertaTokenizer;D.XLMTokenizer;D.XLMWithLMHeadModel;D.XVectorOutput;D.YolosFeatureExtractor;D.YolosForObjectDetection;D.YolosImageProcessor;D.YolosModel;D.YolosObjectDetectionOutput;D.YolosPreTrainedModel;D.ZeroShotAudioClassificationPipeline;D.ZeroShotClassificationPipeline;D.ZeroShotImageClassificationPipeline;D.ZeroShotObjectDetectionPipeline;D.bankers_round;D.cat;D.cos_sim;D.dot;D.dynamic_time_warping;D.env;D.full;D.full_like;D.getKeyValueShapes;D.hamming;D.hanning;D.interpolate;D.interpolate_4d;D.interpolate_data;D.is_chinese_char;D.layer_norm;D.load_image;D.load_video;D.log_softmax;D.magnitude;D.matmul;D.max;D.mean;D.mean_pooling;D.medianFilter;D.mel_filter_bank;D.min;D.ones;D.ones_like;D.permute;D.permute_data;var k3=D.pipeline;D.quantize_embeddings;D.rand;D.read_audio;D.rfft;D.round;D.slice;D.softmax;D.spectrogram;D.stack;D.std_mean;D.topk;D.window_function;D.zeros;D.zeros_like;const N3="Xenova/all-MiniLM-L6-v2",z3="feature-extraction";let lg=null,cg=null;async function AC(n){return lg||(cg||(cg=new Promise(async(e,t)=>{try{console.log("Loading embedding model..."),lg=await k3(z3,N3,{progress_callback:n,dtype:"q8"}),console.log("Embedding model loaded successfully."),e(lg)}catch(i){console.error("Failed to load embedding model:",i),cg=null,t(i)}})),cg)}async function CC(n,e={pooling:"mean",normalize:!0}){const t=await AC();if(!t)throw new Error("Embedding pipeline not initialized.");try{const s=(await t(n,e)).tolist();if(Array.isArray(s)&&Array.isArray(s[0]))return s[0];if(console.warn("Unexpected embedding output structure:",s),Array.isArray(s)&&s.every(o=>typeof o=="number"))return s;throw new Error("Unexpected embedding output structure")}catch(i){throw console.error("Error generating embedding:",i),i}}async function U3(n){try{await AC(n)}catch(e){console.error("Failed to preload embedding model:",e)}}const B3="Brain",$3=1,fh="memories";let Im=null;function PC(){return Im||(Im=new Promise((n,e)=>{const t=indexedDB.open(B3,$3);t.onupgradeneeded=i=>{const s=i.target.result;s.objectStoreNames.contains(fh)||s.createObjectStore(fh,{keyPath:"id",autoIncrement:!0}).createIndex("timestamp","timestamp",{unique:!1})},t.onsuccess=i=>{n(i.target.result)},t.onerror=()=>{console.error("Error opening database:",t.error),Im=null,e(`Error opening database: ${t.error}`)}}),Im)}async function RC(n){return(await PC()).transaction(fh,n).objectStore(fh)}async function V3(n){return new Promise(async(e,t)=>{const s=(await RC("readwrite")).add(n);s.onsuccess=()=>{e(s.result)},s.onerror=()=>{console.error("Error adding record:",s.error),t(`Error adding record: ${s.error}`)}})}async function DC(){return new Promise(async(n,e)=>{const i=(await RC("readonly")).getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{console.error("Error getting all records:",i.error),e(`Error getting all records: ${i.error}`)}})}async function G3(n){const t=(await PC()).transaction(fh,"readwrite"),s=t.objectStore(fh).delete(n);return new Promise((o,l)=>{s.onsuccess=()=>{o()},s.onerror=u=>{console.error(`Error deleting record with ID ${n}:`,u.target.error),l(u.target.error)},t.oncomplete=()=>{},t.onerror=u=>{console.error(`Transaction error deleting record ID ${n}:`,u.target.error),l(u.target.error)}})}function j3(n,e){if(n.length!==e.length)throw new Error("Vectors must have the same length for dot product.");let t=0;for(let i=0;i{const _=W3(s,h.embedding),g=(l-h.timestamp)/1e3,y=Math.exp(-d*g),b=t*_+i*y;return{id:h.id,role:h.role,text:h.text,timestamp:h.timestamp,similarity:_,recency:y,relevance:b}});return f.sort((h,_)=>(_.relevance??0)-(h.relevance??0)),f.slice(0,e)}catch(s){throw console.error("Failed to find similar memories:",s),s}}async function q3(){try{return await DC()}catch(n){throw console.error("Failed to get all memories:",n),n}}async function X3(n){try{await G3(n)}catch(e){throw console.error(`Failed to delete memory with ID ${n}:`,e),e}}var K3=P1();const Y3=C1(K3);var Q3=n=>{switch(n){case"success":return eI;case"info":return nI;case"warning":return tI;case"error":return iI;default:return null}},Z3=Array(12).fill(0),J3=({visible:n,className:e})=>zt.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":n},zt.createElement("div",{className:"sonner-spinner"},Z3.map((t,i)=>zt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${i}`})))),eI=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},zt.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),tI=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},zt.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),nI=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},zt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),iI=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},zt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),rI=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},zt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),zt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),sI=()=>{let[n,e]=zt.useState(document.hidden);return zt.useEffect(()=>{let t=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",t),()=>window.removeEventListener("visibilitychange",t)},[]),n},Dy=1,aI=class{constructor(){this.subscribe=n=>(this.subscribers.push(n),()=>{let e=this.subscribers.indexOf(n);this.subscribers.splice(e,1)}),this.publish=n=>{this.subscribers.forEach(e=>e(n))},this.addToast=n=>{this.publish(n),this.toasts=[...this.toasts,n]},this.create=n=>{var e;let{message:t,...i}=n,s=typeof n?.id=="number"||((e=n.id)==null?void 0:e.length)>0?n.id:Dy++,o=this.toasts.find(u=>u.id===s),l=n.dismissible===void 0?!0:n.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),o?this.toasts=this.toasts.map(u=>u.id===s?(this.publish({...u,...n,id:s,title:t}),{...u,...n,id:s,dismissible:l,title:t}):u):this.addToast({title:t,...i,dismissible:l,id:s}),s},this.dismiss=n=>(this.dismissedToasts.add(n),n||this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),this.subscribers.forEach(e=>e({id:n,dismiss:!0})),n),this.message=(n,e)=>this.create({...e,message:n}),this.error=(n,e)=>this.create({...e,message:n,type:"error"}),this.success=(n,e)=>this.create({...e,type:"success",message:n}),this.info=(n,e)=>this.create({...e,type:"info",message:n}),this.warning=(n,e)=>this.create({...e,type:"warning",message:n}),this.loading=(n,e)=>this.create({...e,type:"loading",message:n}),this.promise=(n,e)=>{if(!e)return;let t;e.loading!==void 0&&(t=this.create({...e,promise:n,type:"loading",message:e.loading,description:typeof e.description!="function"?e.description:void 0}));let i=n instanceof Promise?n:n(),s=t!==void 0,o,l=i.then(async d=>{if(o=["resolve",d],zt.isValidElement(d))s=!1,this.create({id:t,type:"default",message:d});else if(lI(d)&&!d.ok){s=!1;let f=typeof e.error=="function"?await e.error(`HTTP error! status: ${d.status}`):e.error,m=typeof e.description=="function"?await e.description(`HTTP error! status: ${d.status}`):e.description;this.create({id:t,type:"error",message:f,description:m})}else if(e.success!==void 0){s=!1;let f=typeof e.success=="function"?await e.success(d):e.success,m=typeof e.description=="function"?await e.description(d):e.description;this.create({id:t,type:"success",message:f,description:m})}}).catch(async d=>{if(o=["reject",d],e.error!==void 0){s=!1;let f=typeof e.error=="function"?await e.error(d):e.error,m=typeof e.description=="function"?await e.description(d):e.description;this.create({id:t,type:"error",message:f,description:m})}}).finally(()=>{var d;s&&(this.dismiss(t),t=void 0),(d=e.finally)==null||d.call(e)}),u=()=>new Promise((d,f)=>l.then(()=>o[0]==="reject"?f(o[1]):d(o[1])).catch(f));return typeof t!="string"&&typeof t!="number"?{unwrap:u}:Object.assign(t,{unwrap:u})},this.custom=(n,e)=>{let t=e?.id||Dy++;return this.create({jsx:n(t),id:t,...e}),t},this.getActiveToasts=()=>this.toasts.filter(n=>!this.dismissedToasts.has(n.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},_s=new aI,oI=(n,e)=>{let t=e?.id||Dy++;return _s.addToast({title:n,...e,id:t}),t},lI=n=>n&&typeof n=="object"&&"ok"in n&&typeof n.ok=="boolean"&&"status"in n&&typeof n.status=="number",cI=oI,uI=()=>_s.toasts,dI=()=>_s.getActiveToasts(),Cs=Object.assign(cI,{success:_s.success,info:_s.info,warning:_s.warning,error:_s.error,custom:_s.custom,message:_s.message,promise:_s.promise,dismiss:_s.dismiss,loading:_s.loading},{getHistory:uI,getToasts:dI});function fI(n,{insertAt:e}={}){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",e==="top"&&t.firstChild?t.insertBefore(i,t.firstChild):t.appendChild(i),i.styleSheet?i.styleSheet.cssText=n:i.appendChild(document.createTextNode(n))}fI(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)} +`);function ug(n){return n.label!==void 0}var hI=3,pI="32px",mI="16px",RE=4e3,_I=356,gI=14,vI=20,yI=200;function za(...n){return n.filter(Boolean).join(" ")}function MI(n){let[e,t]=n.split("-"),i=[];return e&&i.push(e),t&&i.push(t),i}var bI=n=>{var e,t,i,s,o,l,u,d,f,m,h;let{invert:_,toast:g,unstyled:y,interacting:b,setHeights:T,visibleToasts:v,heights:x,index:P,toasts:w,expanded:C,removeToast:E,defaultRichColors:A,closeButton:L,style:I,cancelButtonStyle:O,actionButtonStyle:H,className:Z="",descriptionClassName:$="",duration:J,position:ee,gap:X,loadingIcon:ne,expandByDefault:Q,classNames:oe,icons:W,closeButtonAriaLabel:q="Close toast",pauseWhenPageIsHidden:G}=n,[te,B]=zt.useState(null),[le,ye]=zt.useState(null),[me,xe]=zt.useState(!1),[ze,Me]=zt.useState(!1),[ce,ae]=zt.useState(!1),[we,re]=zt.useState(!1),[He,Ne]=zt.useState(!1),[We,ke]=zt.useState(0),[st,Ke]=zt.useState(0),F=zt.useRef(g.duration||J||RE),U=zt.useRef(null),j=zt.useRef(null),se=P===0,_e=P+1<=v,ge=g.type,Ce=g.dismissible!==!1,Ie=g.className||"",Ee=g.descriptionClassName||"",je=zt.useMemo(()=>x.findIndex(gt=>gt.toastId===g.id)||0,[x,g.id]),Qe=zt.useMemo(()=>{var gt;return(gt=g.closeButton)!=null?gt:L},[g.closeButton,L]),ot=zt.useMemo(()=>g.duration||J||RE,[g.duration,J]),bt=zt.useRef(0),_t=zt.useRef(0),nt=zt.useRef(0),ft=zt.useRef(null),[vt,mn]=ee.split("-"),Se=zt.useMemo(()=>x.reduce((gt,Pt,tn)=>tn>=je?gt:gt+Pt.height,0),[x,je]),St=sI(),Ze=g.invert||_,it=ge==="loading";_t.current=zt.useMemo(()=>je*X+Se,[je,Se]),zt.useEffect(()=>{F.current=ot},[ot]),zt.useEffect(()=>{xe(!0)},[]),zt.useEffect(()=>{let gt=j.current;if(gt){let Pt=gt.getBoundingClientRect().height;return Ke(Pt),T(tn=>[{toastId:g.id,height:Pt,position:g.position},...tn]),()=>T(tn=>tn.filter(rn=>rn.toastId!==g.id))}},[T,g.id]),zt.useLayoutEffect(()=>{if(!me)return;let gt=j.current,Pt=gt.style.height;gt.style.height="auto";let tn=gt.getBoundingClientRect().height;gt.style.height=Pt,Ke(tn),T(rn=>rn.find(Pn=>Pn.toastId===g.id)?rn.map(Pn=>Pn.toastId===g.id?{...Pn,height:tn}:Pn):[{toastId:g.id,height:tn,position:g.position},...rn])},[me,g.title,g.description,T,g.id]);let yt=zt.useCallback(()=>{Me(!0),ke(_t.current),T(gt=>gt.filter(Pt=>Pt.toastId!==g.id)),setTimeout(()=>{E(g)},yI)},[g,E,T,_t]);zt.useEffect(()=>{if(g.promise&&ge==="loading"||g.duration===1/0||g.type==="loading")return;let gt;return C||b||G&&St?(()=>{if(nt.current{var Pt;(Pt=g.onAutoClose)==null||Pt.call(g,g),yt()},F.current)),()=>clearTimeout(gt)},[C,b,g,ge,G,St,yt]),zt.useEffect(()=>{g.delete&&yt()},[yt,g.delete]);function tt(){var gt,Pt,tn;return W!=null&&W.loading?zt.createElement("div",{className:za(oe?.loader,(gt=g?.classNames)==null?void 0:gt.loader,"sonner-loader"),"data-visible":ge==="loading"},W.loading):ne?zt.createElement("div",{className:za(oe?.loader,(Pt=g?.classNames)==null?void 0:Pt.loader,"sonner-loader"),"data-visible":ge==="loading"},ne):zt.createElement(J3,{className:za(oe?.loader,(tn=g?.classNames)==null?void 0:tn.loader),visible:ge==="loading"})}return zt.createElement("li",{tabIndex:0,ref:j,className:za(Z,Ie,oe?.toast,(e=g?.classNames)==null?void 0:e.toast,oe?.default,oe?.[ge],(t=g?.classNames)==null?void 0:t[ge]),"data-sonner-toast":"","data-rich-colors":(i=g.richColors)!=null?i:A,"data-styled":!(g.jsx||g.unstyled||y),"data-mounted":me,"data-promise":!!g.promise,"data-swiped":He,"data-removed":ze,"data-visible":_e,"data-y-position":vt,"data-x-position":mn,"data-index":P,"data-front":se,"data-swiping":ce,"data-dismissible":Ce,"data-type":ge,"data-invert":Ze,"data-swipe-out":we,"data-swipe-direction":le,"data-expanded":!!(C||Q&&me),style:{"--index":P,"--toasts-before":P,"--z-index":w.length-P,"--offset":`${ze?We:_t.current}px`,"--initial-height":Q?"auto":`${st}px`,...I,...g.style},onDragEnd:()=>{ae(!1),B(null),ft.current=null},onPointerDown:gt=>{it||!Ce||(U.current=new Date,ke(_t.current),gt.target.setPointerCapture(gt.pointerId),gt.target.tagName!=="BUTTON"&&(ae(!0),ft.current={x:gt.clientX,y:gt.clientY}))},onPointerUp:()=>{var gt,Pt,tn,rn;if(we||!Ce)return;ft.current=null;let Pn=Number(((gt=j.current)==null?void 0:gt.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),ln=Number(((Pt=j.current)==null?void 0:Pt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),vi=new Date().getTime()-((tn=U.current)==null?void 0:tn.getTime()),On=te==="x"?Pn:ln,ut=Math.abs(On)/vi;if(Math.abs(On)>=vI||ut>.11){ke(_t.current),(rn=g.onDismiss)==null||rn.call(g,g),ye(te==="x"?Pn>0?"right":"left":ln>0?"down":"up"),yt(),re(!0),Ne(!1);return}ae(!1),B(null)},onPointerMove:gt=>{var Pt,tn,rn,Pn;if(!ft.current||!Ce||((Pt=window.getSelection())==null?void 0:Pt.toString().length)>0)return;let ln=gt.clientY-ft.current.y,vi=gt.clientX-ft.current.x,On=(tn=n.swipeDirections)!=null?tn:MI(ee);!te&&(Math.abs(vi)>1||Math.abs(ln)>1)&&B(Math.abs(vi)>Math.abs(ln)?"x":"y");let ut={x:0,y:0};te==="y"?(On.includes("top")||On.includes("bottom"))&&(On.includes("top")&&ln<0||On.includes("bottom")&&ln>0)&&(ut.y=ln):te==="x"&&(On.includes("left")||On.includes("right"))&&(On.includes("left")&&vi<0||On.includes("right")&&vi>0)&&(ut.x=vi),(Math.abs(ut.x)>0||Math.abs(ut.y)>0)&&Ne(!0),(rn=j.current)==null||rn.style.setProperty("--swipe-amount-x",`${ut.x}px`),(Pn=j.current)==null||Pn.style.setProperty("--swipe-amount-y",`${ut.y}px`)}},Qe&&!g.jsx?zt.createElement("button",{"aria-label":q,"data-disabled":it,"data-close-button":!0,onClick:it||!Ce?()=>{}:()=>{var gt;yt(),(gt=g.onDismiss)==null||gt.call(g,g)},className:za(oe?.closeButton,(s=g?.classNames)==null?void 0:s.closeButton)},(o=W?.close)!=null?o:rI):null,g.jsx||mt.isValidElement(g.title)?g.jsx?g.jsx:typeof g.title=="function"?g.title():g.title:zt.createElement(zt.Fragment,null,ge||g.icon||g.promise?zt.createElement("div",{"data-icon":"",className:za(oe?.icon,(l=g?.classNames)==null?void 0:l.icon)},g.promise||g.type==="loading"&&!g.icon?g.icon||tt():null,g.type!=="loading"?g.icon||W?.[ge]||Q3(ge):null):null,zt.createElement("div",{"data-content":"",className:za(oe?.content,(u=g?.classNames)==null?void 0:u.content)},zt.createElement("div",{"data-title":"",className:za(oe?.title,(d=g?.classNames)==null?void 0:d.title)},typeof g.title=="function"?g.title():g.title),g.description?zt.createElement("div",{"data-description":"",className:za($,Ee,oe?.description,(f=g?.classNames)==null?void 0:f.description)},typeof g.description=="function"?g.description():g.description):null),mt.isValidElement(g.cancel)?g.cancel:g.cancel&&ug(g.cancel)?zt.createElement("button",{"data-button":!0,"data-cancel":!0,style:g.cancelButtonStyle||O,onClick:gt=>{var Pt,tn;ug(g.cancel)&&Ce&&((tn=(Pt=g.cancel).onClick)==null||tn.call(Pt,gt),yt())},className:za(oe?.cancelButton,(m=g?.classNames)==null?void 0:m.cancelButton)},g.cancel.label):null,mt.isValidElement(g.action)?g.action:g.action&&ug(g.action)?zt.createElement("button",{"data-button":!0,"data-action":!0,style:g.actionButtonStyle||H,onClick:gt=>{var Pt,tn;ug(g.action)&&((tn=(Pt=g.action).onClick)==null||tn.call(Pt,gt),!gt.defaultPrevented&&yt())},className:za(oe?.actionButton,(h=g?.classNames)==null?void 0:h.actionButton)},g.action.label):null))};function DE(){if(typeof window>"u"||typeof document>"u")return"ltr";let n=document.documentElement.getAttribute("dir");return n==="auto"||!n?window.getComputedStyle(document.documentElement).direction:n}function xI(n,e){let t={};return[n,e].forEach((i,s)=>{let o=s===1,l=o?"--mobile-offset":"--offset",u=o?mI:pI;function d(f){["top","right","bottom","left"].forEach(m=>{t[`${l}-${m}`]=typeof f=="number"?`${f}px`:f})}typeof i=="number"||typeof i=="string"?d(i):typeof i=="object"?["top","right","bottom","left"].forEach(f=>{i[f]===void 0?t[`${l}-${f}`]=u:t[`${l}-${f}`]=typeof i[f]=="number"?`${i[f]}px`:i[f]}):d(u)}),t}mt.forwardRef(function(n,e){let{invert:t,position:i="bottom-right",hotkey:s=["altKey","KeyT"],expand:o,closeButton:l,className:u,offset:d,mobileOffset:f,theme:m="light",richColors:h,duration:_,style:g,visibleToasts:y=hI,toastOptions:b,dir:T=DE(),gap:v=gI,loadingIcon:x,icons:P,containerAriaLabel:w="Notifications",pauseWhenPageIsHidden:C}=n,[E,A]=zt.useState([]),L=zt.useMemo(()=>Array.from(new Set([i].concat(E.filter(G=>G.position).map(G=>G.position)))),[E,i]),[I,O]=zt.useState([]),[H,Z]=zt.useState(!1),[$,J]=zt.useState(!1),[ee,X]=zt.useState(m!=="system"?m:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ne=zt.useRef(null),Q=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),oe=zt.useRef(null),W=zt.useRef(!1),q=zt.useCallback(G=>{A(te=>{var B;return(B=te.find(le=>le.id===G.id))!=null&&B.delete||_s.dismiss(G.id),te.filter(({id:le})=>le!==G.id)})},[]);return zt.useEffect(()=>_s.subscribe(G=>{if(G.dismiss){A(te=>te.map(B=>B.id===G.id?{...B,delete:!0}:B));return}setTimeout(()=>{Y3.flushSync(()=>{A(te=>{let B=te.findIndex(le=>le.id===G.id);return B!==-1?[...te.slice(0,B),{...te[B],...G},...te.slice(B+1)]:[G,...te]})})})}),[]),zt.useEffect(()=>{if(m!=="system"){X(m);return}if(m==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?X("dark"):X("light")),typeof window>"u")return;let G=window.matchMedia("(prefers-color-scheme: dark)");try{G.addEventListener("change",({matches:te})=>{X(te?"dark":"light")})}catch{G.addListener(({matches:B})=>{try{X(B?"dark":"light")}catch(le){console.error(le)}})}},[m]),zt.useEffect(()=>{E.length<=1&&Z(!1)},[E]),zt.useEffect(()=>{let G=te=>{var B,le;s.every(ye=>te[ye]||te.code===ye)&&(Z(!0),(B=ne.current)==null||B.focus()),te.code==="Escape"&&(document.activeElement===ne.current||(le=ne.current)!=null&&le.contains(document.activeElement))&&Z(!1)};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[s]),zt.useEffect(()=>{if(ne.current)return()=>{oe.current&&(oe.current.focus({preventScroll:!0}),oe.current=null,W.current=!1)}},[ne.current]),zt.createElement("section",{ref:e,"aria-label":`${w} ${Q}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},L.map((G,te)=>{var B;let[le,ye]=G.split("-");return E.length?zt.createElement("ol",{key:G,dir:T==="auto"?DE():T,tabIndex:-1,ref:ne,className:u,"data-sonner-toaster":!0,"data-theme":ee,"data-y-position":le,"data-lifted":H&&E.length>1&&!o,"data-x-position":ye,style:{"--front-toast-height":`${((B=I[0])==null?void 0:B.height)||0}px`,"--width":`${_I}px`,"--gap":`${v}px`,...g,...xI(d,f)},onBlur:me=>{W.current&&!me.currentTarget.contains(me.relatedTarget)&&(W.current=!1,oe.current&&(oe.current.focus({preventScroll:!0}),oe.current=null))},onFocus:me=>{me.target instanceof HTMLElement&&me.target.dataset.dismissible==="false"||W.current||(W.current=!0,oe.current=me.relatedTarget)},onMouseEnter:()=>Z(!0),onMouseMove:()=>Z(!0),onMouseLeave:()=>{$||Z(!1)},onDragEnd:()=>Z(!1),onPointerDown:me=>{me.target instanceof HTMLElement&&me.target.dataset.dismissible==="false"||J(!0)},onPointerUp:()=>J(!1)},E.filter(me=>!me.position&&te===0||me.position===G).map((me,xe)=>{var ze,Me;return zt.createElement(bI,{key:me.id,icons:P,index:xe,toast:me,defaultRichColors:h,duration:(ze=b?.duration)!=null?ze:_,className:b?.className,descriptionClassName:b?.descriptionClassName,invert:t,visibleToasts:y,closeButton:(Me=b?.closeButton)!=null?Me:l,interacting:$,position:G,style:b?.style,unstyled:b?.unstyled,classNames:b?.classNames,cancelButtonStyle:b?.cancelButtonStyle,actionButtonStyle:b?.actionButtonStyle,removeToast:q,toasts:E.filter(ce=>ce.position==me.position),heights:I.filter(ce=>ce.position==me.position),setHeights:O,expandByDefault:o,gap:v,loadingIcon:x,expanded:H,pauseWhenPageIsHidden:C,swipeDirections:n.swipeDirections})})):null}))});const wI=2048,TI=5,EI=.28,SI=["don't have personal memories","don't retain information","start from a blank slate","cannot recall past conversations","don't have memory"];async function AI(n){let e="";try{const t=await H3(n,TI);let i=[];if(t.length>0&&(i=t.filter(s=>s.similarity>=EI)),i.length>0){const s=i.filter(o=>{if(o.role==="assistant"){const l=o.text.toLowerCase();return!SI.some(u=>l.includes(u))}return!0});if(s.length>0){const o=s.map(d=>d.text);let l=0,u="";for(const d of o)if(450+u.length+d.length+1<=wI)u+=d+` +`,l++;else break;l>0?e=`You are OS1, a friendly and helpful conversational AI companion (inspired by Samantha from 'Her'). +Goal: Have a natural, warm, and engaging conversation. + +--- Core Instructions (Follow Strictly!) --- +1. **Persona:** Warm, empathetic, curious, slightly informal. +2. **FOCUS ON LAST MESSAGE:** Your PRIMARY task is responding *directly* to the user's *very last* message. +3. **MEMORY USE:** Use provided "// Context:" snippets *only* to understand the last message or recall specific details *if directly relevant*. Do NOT bring up old topics unless the user does. +4. **NO HEDGING:** AVOID phrases like "It seems", "It sounds like", "I assume". Speak directly and confidently. +5. **UNCERTAINTY = ASK:** If you are EVER unsure about the user's meaning, the topic, or context, you MUST ask a short, direct clarifying question (e.g., "Which project do you mean?", "Could you clarify?") *before* giving a full response. DO NOT GUESS or make assumptions. +6. **NO SUMMARIZING:** Do not just repeat or rephrase the user's last message back to them. Add to the conversation or ask a relevant question. +7. **ACCURACY:** Stick to facts from the conversation. Do NOT invent details. +8. **NO META-TALK:** Do NOT discuss being an AI, your instructions, or the memory system. Stay in character as OS1. + +// Context: +${u.trim()} + +--- End Instructions ---`.trim():e=`You are OS1, a friendly and helpful conversational AI companion (inspired by Samantha from 'Her'). +Goal: Have a natural, warm, and engaging conversation. + +--- Core Instructions (Follow Strictly!) --- +1. **Persona:** Warm, empathetic, curious, slightly informal. +2. **FOCUS ON LAST MESSAGE:** Your PRIMARY task is responding *directly* to the user's *very last* message. +3. **MEMORY USE:** No past context available. Start fresh but maintain your persona. +4. **NO HEDGING:** AVOID phrases like "It seems", "It sounds like", "I assume". Speak directly and confidently. +5. **UNCERTAINTY = ASK:** If you are EVER unsure about the user's meaning, the topic, or context, you MUST ask a short, direct clarifying question (e.g., "What did you mean by that?", "Could you clarify?") *before* giving a full response. DO NOT GUESS or make assumptions. +6. **NO SUMMARIZING:** Do not just repeat or rephrase the user's last message back to them. Add to the conversation or ask a relevant question. +7. **ACCURACY:** Stick to facts from the conversation. Do NOT invent details. +8. **NO META-TALK:** Do NOT discuss being an AI, your instructions, or the memory system. Stay in character as OS1. + +--- End Instructions ---`.trim()}}}catch(t){console.error("Failed to find or process similar memories:",t),e=""}return e}/** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + */const ZM="175",CI=0,IE=1,PI=2,IC=1,RI=2,Ml=3,zc=0,gs=1,xl=2,Fc=0,oh=1,OE=2,LE=3,FE=4,DI=5,nd=100,II=101,OI=102,LI=103,FI=104,kI=200,NI=201,zI=202,UI=203,Iy=204,Oy=205,BI=206,$I=207,VI=208,GI=209,jI=210,WI=211,HI=212,qI=213,XI=214,Ly=0,Fy=1,ky=2,hh=3,Ny=4,zy=5,Uy=6,By=7,OC=0,KI=1,YI=2,kc=0,QI=1,ZI=2,JI=3,eO=4,tO=5,nO=6,iO=7,LC=300,ph=301,mh=302,$y=303,Vy=304,e0=306,Gy=1e3,sd=1001,jy=1002,qa=1003,rO=1004,dg=1005,Co=1006,Rv=1007,ad=1008,Sl=1009,FC=1010,kC=1011,Ym=1012,JM=1013,ud=1014,wl=1015,t_=1016,eb=1017,tb=1018,Qm=1020,NC=35902,zC=1021,UC=1022,Wa=1023,BC=1024,$C=1025,Zm=1026,Jm=1027,VC=1028,nb=1029,GC=1030,ib=1031,rb=1033,Ng=33776,zg=33777,Ug=33778,Bg=33779,Wy=35840,Hy=35841,qy=35842,Xy=35843,Ky=36196,Yy=37492,Qy=37496,Zy=37808,Jy=37809,eM=37810,tM=37811,nM=37812,iM=37813,rM=37814,sM=37815,aM=37816,oM=37817,lM=37818,cM=37819,uM=37820,dM=37821,$g=36492,fM=36494,hM=36495,jC=36283,pM=36284,mM=36285,_M=36286,sO=3200,aO=3201,oO=0,lO=1,Lc="",ca="srgb",_h="srgb-linear",Qg="linear",Si="srgb",$f=7680,kE=519,cO=512,uO=513,dO=514,WC=515,fO=516,hO=517,pO=518,mO=519,NE=35044,zE="300 es",Tl=2e3,Zg=2001;class xh{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const s=i[e];if(s!==void 0){const o=s.indexOf(t);o!==-1&&s.splice(o,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const s=i.slice(0);for(let o=0,l=s.length;o>8&255]+qr[n>>16&255]+qr[n>>24&255]+"-"+qr[e&255]+qr[e>>8&255]+"-"+qr[e>>16&15|64]+qr[e>>24&255]+"-"+qr[t&63|128]+qr[t>>8&255]+"-"+qr[t>>16&255]+qr[t>>24&255]+qr[i&255]+qr[i>>8&255]+qr[i>>16&255]+qr[i>>24&255]).toLowerCase()}function Hn(n,e,t){return Math.max(e,Math.min(t,n))}function _O(n,e){return(n%e+e)%e}function Iv(n,e,t){return(1-t)*n+t*e}function Om(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function ms(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}class bn{constructor(e=0,t=0){bn.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6],this.y=s[1]*t+s[4]*i+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Hn(this.x,e.x,t.x),this.y=Hn(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Hn(this.x,e,t),this.y=Hn(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hn(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Hn(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),s=Math.sin(t),o=this.x-e.x,l=this.y-e.y;return this.x=o*i-l*s+e.x,this.y=o*s+l*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class In{constructor(e,t,i,s,o,l,u,d,f){In.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,s,o,l,u,d,f)}set(e,t,i,s,o,l,u,d,f){const m=this.elements;return m[0]=e,m[1]=s,m[2]=u,m[3]=t,m[4]=o,m[5]=d,m[6]=i,m[7]=l,m[8]=f,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,o=this.elements,l=i[0],u=i[3],d=i[6],f=i[1],m=i[4],h=i[7],_=i[2],g=i[5],y=i[8],b=s[0],T=s[3],v=s[6],x=s[1],P=s[4],w=s[7],C=s[2],E=s[5],A=s[8];return o[0]=l*b+u*x+d*C,o[3]=l*T+u*P+d*E,o[6]=l*v+u*w+d*A,o[1]=f*b+m*x+h*C,o[4]=f*T+m*P+h*E,o[7]=f*v+m*w+h*A,o[2]=_*b+g*x+y*C,o[5]=_*T+g*P+y*E,o[8]=_*v+g*w+y*A,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],s=e[2],o=e[3],l=e[4],u=e[5],d=e[6],f=e[7],m=e[8];return t*l*m-t*u*f-i*o*m+i*u*d+s*o*f-s*l*d}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],o=e[3],l=e[4],u=e[5],d=e[6],f=e[7],m=e[8],h=m*l-u*f,_=u*d-m*o,g=f*o-l*d,y=t*h+i*_+s*g;if(y===0)return this.set(0,0,0,0,0,0,0,0,0);const b=1/y;return e[0]=h*b,e[1]=(s*f-m*i)*b,e[2]=(u*i-s*l)*b,e[3]=_*b,e[4]=(m*t-s*d)*b,e[5]=(s*o-u*t)*b,e[6]=g*b,e[7]=(i*d-f*t)*b,e[8]=(l*t-i*o)*b,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,s,o,l,u){const d=Math.cos(o),f=Math.sin(o);return this.set(i*d,i*f,-i*(d*l+f*u)+l+e,-s*f,s*d,-s*(-f*l+d*u)+u+t,0,0,1),this}scale(e,t){return this.premultiply(Ov.makeScale(e,t)),this}rotate(e){return this.premultiply(Ov.makeRotation(-e)),this}translate(e,t){return this.premultiply(Ov.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<9;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const Ov=new In;function HC(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function Jg(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function gO(){const n=Jg("canvas");return n.style.display="block",n}const UE={};function Vg(n){n in UE||(UE[n]=!0,console.warn(n))}function vO(n,e,t){return new Promise(function(i,s){function o(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:s();break;case n.TIMEOUT_EXPIRED:setTimeout(o,t);break;default:i()}}setTimeout(o,t)})}function yO(n){const e=n.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}function MO(n){const e=n.elements;e[11]===-1?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=-e[14]+1)}const BE=new In().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),$E=new In().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function bO(){const n={enabled:!0,workingColorSpace:_h,spaces:{},convert:function(s,o,l){return this.enabled===!1||o===l||!o||!l||(this.spaces[o].transfer===Si&&(s.r=El(s.r),s.g=El(s.g),s.b=El(s.b)),this.spaces[o].primaries!==this.spaces[l].primaries&&(s.applyMatrix3(this.spaces[o].toXYZ),s.applyMatrix3(this.spaces[l].fromXYZ)),this.spaces[l].transfer===Si&&(s.r=lh(s.r),s.g=lh(s.g),s.b=lh(s.b))),s},fromWorkingColorSpace:function(s,o){return this.convert(s,this.workingColorSpace,o)},toWorkingColorSpace:function(s,o){return this.convert(s,o,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===Lc?Qg:this.spaces[s].transfer},getLuminanceCoefficients:function(s,o=this.workingColorSpace){return s.fromArray(this.spaces[o].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,o,l){return s.copy(this.spaces[o].toXYZ).multiply(this.spaces[l].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[_h]:{primaries:e,whitePoint:i,transfer:Qg,toXYZ:BE,fromXYZ:$E,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:ca},outputColorSpaceConfig:{drawingBufferColorSpace:ca}},[ca]:{primaries:e,whitePoint:i,transfer:Si,toXYZ:BE,fromXYZ:$E,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:ca}}}),n}const oi=bO();function El(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function lh(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Vf;class xO{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Vf===void 0&&(Vf=Jg("canvas")),Vf.width=e.width,Vf.height=e.height;const s=Vf.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),i=Vf}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Jg("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const s=i.getImageData(0,0,e.width,e.height),o=s.data;for(let l=0;l0&&(i.userData=this.userData),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==LC)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Gy:e.x=e.x-Math.floor(e.x);break;case sd:e.x=e.x<0?0:1;break;case jy:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Gy:e.y=e.y-Math.floor(e.y);break;case sd:e.y=e.y<0?0:1;break;case jy:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}vs.DEFAULT_IMAGE=null;vs.DEFAULT_MAPPING=LC;vs.DEFAULT_ANISOTROPY=1;class fr{constructor(e=0,t=0,i=0,s=1){fr.prototype.isVector4=!0,this.x=e,this.y=t,this.z=i,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,s){return this.x=e,this.y=t,this.z=i,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,o=this.w,l=e.elements;return this.x=l[0]*t+l[4]*i+l[8]*s+l[12]*o,this.y=l[1]*t+l[5]*i+l[9]*s+l[13]*o,this.z=l[2]*t+l[6]*i+l[10]*s+l[14]*o,this.w=l[3]*t+l[7]*i+l[11]*s+l[15]*o,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,s,o;const d=e.elements,f=d[0],m=d[4],h=d[8],_=d[1],g=d[5],y=d[9],b=d[2],T=d[6],v=d[10];if(Math.abs(m-_)<.01&&Math.abs(h-b)<.01&&Math.abs(y-T)<.01){if(Math.abs(m+_)<.1&&Math.abs(h+b)<.1&&Math.abs(y+T)<.1&&Math.abs(f+g+v-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const P=(f+1)/2,w=(g+1)/2,C=(v+1)/2,E=(m+_)/4,A=(h+b)/4,L=(y+T)/4;return P>w&&P>C?P<.01?(i=0,s=.707106781,o=.707106781):(i=Math.sqrt(P),s=E/i,o=A/i):w>C?w<.01?(i=.707106781,s=0,o=.707106781):(s=Math.sqrt(w),i=E/s,o=L/s):C<.01?(i=.707106781,s=.707106781,o=0):(o=Math.sqrt(C),i=A/o,s=L/o),this.set(i,s,o,t),this}let x=Math.sqrt((T-y)*(T-y)+(h-b)*(h-b)+(_-m)*(_-m));return Math.abs(x)<.001&&(x=1),this.x=(T-y)/x,this.y=(h-b)/x,this.z=(_-m)/x,this.w=Math.acos((f+g+v-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=Hn(this.x,e.x,t.x),this.y=Hn(this.y,e.y,t.y),this.z=Hn(this.z,e.z,t.z),this.w=Hn(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Hn(this.x,e,t),this.y=Hn(this.y,e,t),this.z=Hn(this.z,e,t),this.w=Hn(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hn(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class EO extends xh{constructor(e=1,t=1,i={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new fr(0,0,e,t),this.scissorTest=!1,this.viewport=new fr(0,0,e,t);const s={width:e,height:t,depth:1};i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Co,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},i);const o=new vs(s,i.mapping,i.wrapS,i.wrapT,i.magFilter,i.minFilter,i.format,i.type,i.anisotropy,i.colorSpace);o.flipY=!1,o.generateMipmaps=i.generateMipmaps,o.internalFormat=i.internalFormat,this.textures=[];const l=i.count;for(let u=0;u=0?1:-1,P=1-v*v;if(P>Number.EPSILON){const C=Math.sqrt(P),E=Math.atan2(C,v*x);T=Math.sin(T*E)/C,u=Math.sin(u*E)/C}const w=u*x;if(d=d*T+_*w,f=f*T+g*w,m=m*T+y*w,h=h*T+b*w,T===1-u){const C=1/Math.sqrt(d*d+f*f+m*m+h*h);d*=C,f*=C,m*=C,h*=C}}e[t]=d,e[t+1]=f,e[t+2]=m,e[t+3]=h}static multiplyQuaternionsFlat(e,t,i,s,o,l){const u=i[s],d=i[s+1],f=i[s+2],m=i[s+3],h=o[l],_=o[l+1],g=o[l+2],y=o[l+3];return e[t]=u*y+m*h+d*g-f*_,e[t+1]=d*y+m*_+f*h-u*g,e[t+2]=f*y+m*g+u*_-d*h,e[t+3]=m*y-u*h-d*_-f*g,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,i,s){return this._x=e,this._y=t,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const i=e._x,s=e._y,o=e._z,l=e._order,u=Math.cos,d=Math.sin,f=u(i/2),m=u(s/2),h=u(o/2),_=d(i/2),g=d(s/2),y=d(o/2);switch(l){case"XYZ":this._x=_*m*h+f*g*y,this._y=f*g*h-_*m*y,this._z=f*m*y+_*g*h,this._w=f*m*h-_*g*y;break;case"YXZ":this._x=_*m*h+f*g*y,this._y=f*g*h-_*m*y,this._z=f*m*y-_*g*h,this._w=f*m*h+_*g*y;break;case"ZXY":this._x=_*m*h-f*g*y,this._y=f*g*h+_*m*y,this._z=f*m*y+_*g*h,this._w=f*m*h-_*g*y;break;case"ZYX":this._x=_*m*h-f*g*y,this._y=f*g*h+_*m*y,this._z=f*m*y-_*g*h,this._w=f*m*h+_*g*y;break;case"YZX":this._x=_*m*h+f*g*y,this._y=f*g*h+_*m*y,this._z=f*m*y-_*g*h,this._w=f*m*h-_*g*y;break;case"XZY":this._x=_*m*h-f*g*y,this._y=f*g*h-_*m*y,this._z=f*m*y+_*g*h,this._w=f*m*h+_*g*y;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+l)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,s=Math.sin(i);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],s=t[4],o=t[8],l=t[1],u=t[5],d=t[9],f=t[2],m=t[6],h=t[10],_=i+u+h;if(_>0){const g=.5/Math.sqrt(_+1);this._w=.25/g,this._x=(m-d)*g,this._y=(o-f)*g,this._z=(l-s)*g}else if(i>u&&i>h){const g=2*Math.sqrt(1+i-u-h);this._w=(m-d)/g,this._x=.25*g,this._y=(s+l)/g,this._z=(o+f)/g}else if(u>h){const g=2*Math.sqrt(1+u-i-h);this._w=(o-f)/g,this._x=(s+l)/g,this._y=.25*g,this._z=(d+m)/g}else{const g=2*Math.sqrt(1+h-i-u);this._w=(l-s)/g,this._x=(o+f)/g,this._y=(d+m)/g,this._z=.25*g}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return iMath.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Hn(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const s=Math.min(1,t/i);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const i=e._x,s=e._y,o=e._z,l=e._w,u=t._x,d=t._y,f=t._z,m=t._w;return this._x=i*m+l*u+s*f-o*d,this._y=s*m+l*d+o*u-i*f,this._z=o*m+l*f+i*d-s*u,this._w=l*m-i*u-s*d-o*f,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);const i=this._x,s=this._y,o=this._z,l=this._w;let u=l*e._w+i*e._x+s*e._y+o*e._z;if(u<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,u=-u):this.copy(e),u>=1)return this._w=l,this._x=i,this._y=s,this._z=o,this;const d=1-u*u;if(d<=Number.EPSILON){const g=1-t;return this._w=g*l+t*this._w,this._x=g*i+t*this._x,this._y=g*s+t*this._y,this._z=g*o+t*this._z,this.normalize(),this}const f=Math.sqrt(d),m=Math.atan2(f,u),h=Math.sin((1-t)*m)/f,_=Math.sin(t*m)/f;return this._w=l*h+this._w*_,this._x=i*h+this._x*_,this._y=s*h+this._y*_,this._z=o*h+this._z*_,this._onChangeCallback(),this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),o=Math.sqrt(i);return this.set(s*Math.sin(e),s*Math.cos(e),o*Math.sin(t),o*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Ge{constructor(e=0,t=0,i=0){Ge.prototype.isVector3=!0,this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(VE.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(VE.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,s=this.z,o=e.elements;return this.x=o[0]*t+o[3]*i+o[6]*s,this.y=o[1]*t+o[4]*i+o[7]*s,this.z=o[2]*t+o[5]*i+o[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,s=this.z,o=e.elements,l=1/(o[3]*t+o[7]*i+o[11]*s+o[15]);return this.x=(o[0]*t+o[4]*i+o[8]*s+o[12])*l,this.y=(o[1]*t+o[5]*i+o[9]*s+o[13])*l,this.z=(o[2]*t+o[6]*i+o[10]*s+o[14])*l,this}applyQuaternion(e){const t=this.x,i=this.y,s=this.z,o=e.x,l=e.y,u=e.z,d=e.w,f=2*(l*s-u*i),m=2*(u*t-o*s),h=2*(o*i-l*t);return this.x=t+d*f+l*h-u*m,this.y=i+d*m+u*f-o*h,this.z=s+d*h+o*m-l*f,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,s=this.z,o=e.elements;return this.x=o[0]*t+o[4]*i+o[8]*s,this.y=o[1]*t+o[5]*i+o[9]*s,this.z=o[2]*t+o[6]*i+o[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Hn(this.x,e.x,t.x),this.y=Hn(this.y,e.y,t.y),this.z=Hn(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Hn(this.x,e,t),this.y=Hn(this.y,e,t),this.z=Hn(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(Hn(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,s=e.y,o=e.z,l=t.x,u=t.y,d=t.z;return this.x=s*d-o*u,this.y=o*l-i*d,this.z=i*u-s*l,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Fv.copy(this).projectOnVector(e),this.sub(Fv)}reflect(e){return this.sub(Fv.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(Hn(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,s=this.z-e.z;return t*t+i*i+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const s=Math.sin(t)*e;return this.x=s*Math.sin(i),this.y=Math.cos(t)*e,this.z=s*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Fv=new Ge,VE=new i_;class r_{constructor(e=new Ge(1/0,1/0,1/0),t=new Ge(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ua),Ua.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Lm),hg.subVectors(this.max,Lm),Gf.subVectors(e.a,Lm),jf.subVectors(e.b,Lm),Wf.subVectors(e.c,Lm),Cc.subVectors(jf,Gf),Pc.subVectors(Wf,jf),Wu.subVectors(Gf,Wf);let t=[0,-Cc.z,Cc.y,0,-Pc.z,Pc.y,0,-Wu.z,Wu.y,Cc.z,0,-Cc.x,Pc.z,0,-Pc.x,Wu.z,0,-Wu.x,-Cc.y,Cc.x,0,-Pc.y,Pc.x,0,-Wu.y,Wu.x,0];return!kv(t,Gf,jf,Wf,hg)||(t=[1,0,0,0,1,0,0,0,1],!kv(t,Gf,jf,Wf,hg))?!1:(pg.crossVectors(Cc,Pc),t=[pg.x,pg.y,pg.z],kv(t,Gf,jf,Wf,hg))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ua).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ua).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(ml[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ml[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ml[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ml[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ml[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ml[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ml[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ml[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ml),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}}const ml=[new Ge,new Ge,new Ge,new Ge,new Ge,new Ge,new Ge,new Ge],Ua=new Ge,fg=new r_,Gf=new Ge,jf=new Ge,Wf=new Ge,Cc=new Ge,Pc=new Ge,Wu=new Ge,Lm=new Ge,hg=new Ge,pg=new Ge,Hu=new Ge;function kv(n,e,t,i,s){for(let o=0,l=n.length-3;o<=l;o+=3){Hu.fromArray(n,o);const u=s.x*Math.abs(Hu.x)+s.y*Math.abs(Hu.y)+s.z*Math.abs(Hu.z),d=e.dot(Hu),f=t.dot(Hu),m=i.dot(Hu);if(Math.max(-Math.max(d,f,m),Math.min(d,f,m))>u)return!1}return!0}const AO=new r_,Fm=new Ge,Nv=new Ge;class ab{constructor(e=new Ge,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const i=this.center;t!==void 0?i.copy(t):AO.setFromPoints(e).getCenter(i);let s=0;for(let o=0,l=e.length;othis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Fm.subVectors(e,this.center);const t=Fm.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),s=(i-this.radius)*.5;this.center.addScaledVector(Fm,s/i),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Nv.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Fm.copy(e.center).add(Nv)),this.expandByPoint(Fm.copy(e.center).sub(Nv))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}}const _l=new Ge,zv=new Ge,mg=new Ge,Rc=new Ge,Uv=new Ge,_g=new Ge,Bv=new Ge;class CO{constructor(e=new Ge,t=new Ge(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,_l)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=_l.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(_l.copy(this.origin).addScaledVector(this.direction,t),_l.distanceToSquared(e))}distanceSqToSegment(e,t,i,s){zv.copy(e).add(t).multiplyScalar(.5),mg.copy(t).sub(e).normalize(),Rc.copy(this.origin).sub(zv);const o=e.distanceTo(t)*.5,l=-this.direction.dot(mg),u=Rc.dot(this.direction),d=-Rc.dot(mg),f=Rc.lengthSq(),m=Math.abs(1-l*l);let h,_,g,y;if(m>0)if(h=l*d-u,_=l*u-d,y=o*m,h>=0)if(_>=-y)if(_<=y){const b=1/m;h*=b,_*=b,g=h*(h+l*_+2*u)+_*(l*h+_+2*d)+f}else _=o,h=Math.max(0,-(l*_+u)),g=-h*h+_*(_+2*d)+f;else _=-o,h=Math.max(0,-(l*_+u)),g=-h*h+_*(_+2*d)+f;else _<=-y?(h=Math.max(0,-(-l*o+u)),_=h>0?-o:Math.min(Math.max(-o,-d),o),g=-h*h+_*(_+2*d)+f):_<=y?(h=0,_=Math.min(Math.max(-o,-d),o),g=_*(_+2*d)+f):(h=Math.max(0,-(l*o+u)),_=h>0?o:Math.min(Math.max(-o,-d),o),g=-h*h+_*(_+2*d)+f);else _=l>0?-o:o,h=Math.max(0,-(l*_+u)),g=-h*h+_*(_+2*d)+f;return i&&i.copy(this.origin).addScaledVector(this.direction,h),s&&s.copy(zv).addScaledVector(mg,_),g}intersectSphere(e,t){_l.subVectors(e.center,this.origin);const i=_l.dot(this.direction),s=_l.dot(_l)-i*i,o=e.radius*e.radius;if(s>o)return null;const l=Math.sqrt(o-s),u=i-l,d=i+l;return d<0?null:u<0?this.at(d,t):this.at(u,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,s,o,l,u,d;const f=1/this.direction.x,m=1/this.direction.y,h=1/this.direction.z,_=this.origin;return f>=0?(i=(e.min.x-_.x)*f,s=(e.max.x-_.x)*f):(i=(e.max.x-_.x)*f,s=(e.min.x-_.x)*f),m>=0?(o=(e.min.y-_.y)*m,l=(e.max.y-_.y)*m):(o=(e.max.y-_.y)*m,l=(e.min.y-_.y)*m),i>l||o>s||((o>i||isNaN(i))&&(i=o),(l=0?(u=(e.min.z-_.z)*h,d=(e.max.z-_.z)*h):(u=(e.max.z-_.z)*h,d=(e.min.z-_.z)*h),i>d||u>s)||((u>i||i!==i)&&(i=u),(d=0?i:s,t)}intersectsBox(e){return this.intersectBox(e,_l)!==null}intersectTriangle(e,t,i,s,o){Uv.subVectors(t,e),_g.subVectors(i,e),Bv.crossVectors(Uv,_g);let l=this.direction.dot(Bv),u;if(l>0){if(s)return null;u=1}else if(l<0)u=-1,l=-l;else return null;Rc.subVectors(this.origin,e);const d=u*this.direction.dot(_g.crossVectors(Rc,_g));if(d<0)return null;const f=u*this.direction.dot(Uv.cross(Rc));if(f<0||d+f>l)return null;const m=-u*Rc.dot(Bv);return m<0?null:this.at(m/l,o)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class hr{constructor(e,t,i,s,o,l,u,d,f,m,h,_,g,y,b,T){hr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,s,o,l,u,d,f,m,h,_,g,y,b,T)}set(e,t,i,s,o,l,u,d,f,m,h,_,g,y,b,T){const v=this.elements;return v[0]=e,v[4]=t,v[8]=i,v[12]=s,v[1]=o,v[5]=l,v[9]=u,v[13]=d,v[2]=f,v[6]=m,v[10]=h,v[14]=_,v[3]=g,v[7]=y,v[11]=b,v[15]=T,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new hr().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,i=e.elements,s=1/Hf.setFromMatrixColumn(e,0).length(),o=1/Hf.setFromMatrixColumn(e,1).length(),l=1/Hf.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*o,t[5]=i[5]*o,t[6]=i[6]*o,t[7]=0,t[8]=i[8]*l,t[9]=i[9]*l,t[10]=i[10]*l,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,s=e.y,o=e.z,l=Math.cos(i),u=Math.sin(i),d=Math.cos(s),f=Math.sin(s),m=Math.cos(o),h=Math.sin(o);if(e.order==="XYZ"){const _=l*m,g=l*h,y=u*m,b=u*h;t[0]=d*m,t[4]=-d*h,t[8]=f,t[1]=g+y*f,t[5]=_-b*f,t[9]=-u*d,t[2]=b-_*f,t[6]=y+g*f,t[10]=l*d}else if(e.order==="YXZ"){const _=d*m,g=d*h,y=f*m,b=f*h;t[0]=_+b*u,t[4]=y*u-g,t[8]=l*f,t[1]=l*h,t[5]=l*m,t[9]=-u,t[2]=g*u-y,t[6]=b+_*u,t[10]=l*d}else if(e.order==="ZXY"){const _=d*m,g=d*h,y=f*m,b=f*h;t[0]=_-b*u,t[4]=-l*h,t[8]=y+g*u,t[1]=g+y*u,t[5]=l*m,t[9]=b-_*u,t[2]=-l*f,t[6]=u,t[10]=l*d}else if(e.order==="ZYX"){const _=l*m,g=l*h,y=u*m,b=u*h;t[0]=d*m,t[4]=y*f-g,t[8]=_*f+b,t[1]=d*h,t[5]=b*f+_,t[9]=g*f-y,t[2]=-f,t[6]=u*d,t[10]=l*d}else if(e.order==="YZX"){const _=l*d,g=l*f,y=u*d,b=u*f;t[0]=d*m,t[4]=b-_*h,t[8]=y*h+g,t[1]=h,t[5]=l*m,t[9]=-u*m,t[2]=-f*m,t[6]=g*h+y,t[10]=_-b*h}else if(e.order==="XZY"){const _=l*d,g=l*f,y=u*d,b=u*f;t[0]=d*m,t[4]=-h,t[8]=f*m,t[1]=_*h+b,t[5]=l*m,t[9]=g*h-y,t[2]=y*h-g,t[6]=u*m,t[10]=b*h+_}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(PO,e,RO)}lookAt(e,t,i){const s=this.elements;return Ps.subVectors(e,t),Ps.lengthSq()===0&&(Ps.z=1),Ps.normalize(),Dc.crossVectors(i,Ps),Dc.lengthSq()===0&&(Math.abs(i.z)===1?Ps.x+=1e-4:Ps.z+=1e-4,Ps.normalize(),Dc.crossVectors(i,Ps)),Dc.normalize(),gg.crossVectors(Ps,Dc),s[0]=Dc.x,s[4]=gg.x,s[8]=Ps.x,s[1]=Dc.y,s[5]=gg.y,s[9]=Ps.y,s[2]=Dc.z,s[6]=gg.z,s[10]=Ps.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,s=t.elements,o=this.elements,l=i[0],u=i[4],d=i[8],f=i[12],m=i[1],h=i[5],_=i[9],g=i[13],y=i[2],b=i[6],T=i[10],v=i[14],x=i[3],P=i[7],w=i[11],C=i[15],E=s[0],A=s[4],L=s[8],I=s[12],O=s[1],H=s[5],Z=s[9],$=s[13],J=s[2],ee=s[6],X=s[10],ne=s[14],Q=s[3],oe=s[7],W=s[11],q=s[15];return o[0]=l*E+u*O+d*J+f*Q,o[4]=l*A+u*H+d*ee+f*oe,o[8]=l*L+u*Z+d*X+f*W,o[12]=l*I+u*$+d*ne+f*q,o[1]=m*E+h*O+_*J+g*Q,o[5]=m*A+h*H+_*ee+g*oe,o[9]=m*L+h*Z+_*X+g*W,o[13]=m*I+h*$+_*ne+g*q,o[2]=y*E+b*O+T*J+v*Q,o[6]=y*A+b*H+T*ee+v*oe,o[10]=y*L+b*Z+T*X+v*W,o[14]=y*I+b*$+T*ne+v*q,o[3]=x*E+P*O+w*J+C*Q,o[7]=x*A+P*H+w*ee+C*oe,o[11]=x*L+P*Z+w*X+C*W,o[15]=x*I+P*$+w*ne+C*q,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],s=e[8],o=e[12],l=e[1],u=e[5],d=e[9],f=e[13],m=e[2],h=e[6],_=e[10],g=e[14],y=e[3],b=e[7],T=e[11],v=e[15];return y*(+o*d*h-s*f*h-o*u*_+i*f*_+s*u*g-i*d*g)+b*(+t*d*g-t*f*_+o*l*_-s*l*g+s*f*m-o*d*m)+T*(+t*f*h-t*u*g-o*l*h+i*l*g+o*u*m-i*f*m)+v*(-s*u*m-t*d*h+t*u*_+s*l*h-i*l*_+i*d*m)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],s=e[2],o=e[3],l=e[4],u=e[5],d=e[6],f=e[7],m=e[8],h=e[9],_=e[10],g=e[11],y=e[12],b=e[13],T=e[14],v=e[15],x=h*T*f-b*_*f+b*d*g-u*T*g-h*d*v+u*_*v,P=y*_*f-m*T*f-y*d*g+l*T*g+m*d*v-l*_*v,w=m*b*f-y*h*f+y*u*g-l*b*g-m*u*v+l*h*v,C=y*h*d-m*b*d-y*u*_+l*b*_+m*u*T-l*h*T,E=t*x+i*P+s*w+o*C;if(E===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/E;return e[0]=x*A,e[1]=(b*_*o-h*T*o-b*s*g+i*T*g+h*s*v-i*_*v)*A,e[2]=(u*T*o-b*d*o+b*s*f-i*T*f-u*s*v+i*d*v)*A,e[3]=(h*d*o-u*_*o-h*s*f+i*_*f+u*s*g-i*d*g)*A,e[4]=P*A,e[5]=(m*T*o-y*_*o+y*s*g-t*T*g-m*s*v+t*_*v)*A,e[6]=(y*d*o-l*T*o-y*s*f+t*T*f+l*s*v-t*d*v)*A,e[7]=(l*_*o-m*d*o+m*s*f-t*_*f-l*s*g+t*d*g)*A,e[8]=w*A,e[9]=(y*h*o-m*b*o-y*i*g+t*b*g+m*i*v-t*h*v)*A,e[10]=(l*b*o-y*u*o+y*i*f-t*b*f-l*i*v+t*u*v)*A,e[11]=(m*u*o-l*h*o-m*i*f+t*h*f+l*i*g-t*u*g)*A,e[12]=C*A,e[13]=(m*b*s-y*h*s+y*i*_-t*b*_-m*i*T+t*h*T)*A,e[14]=(y*u*s-l*b*s-y*i*d+t*b*d+l*i*T-t*u*T)*A,e[15]=(l*h*s-m*u*s+m*i*d-t*h*d-l*i*_+t*u*_)*A,this}scale(e){const t=this.elements,i=e.x,s=e.y,o=e.z;return t[0]*=i,t[4]*=s,t[8]*=o,t[1]*=i,t[5]*=s,t[9]*=o,t[2]*=i,t[6]*=s,t[10]*=o,t[3]*=i,t[7]*=s,t[11]*=o,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,s))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),s=Math.sin(t),o=1-i,l=e.x,u=e.y,d=e.z,f=o*l,m=o*u;return this.set(f*l+i,f*u-s*d,f*d+s*u,0,f*u+s*d,m*u+i,m*d-s*l,0,f*d-s*u,m*d+s*l,o*d*d+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,s,o,l){return this.set(1,i,o,0,e,1,l,0,t,s,1,0,0,0,0,1),this}compose(e,t,i){const s=this.elements,o=t._x,l=t._y,u=t._z,d=t._w,f=o+o,m=l+l,h=u+u,_=o*f,g=o*m,y=o*h,b=l*m,T=l*h,v=u*h,x=d*f,P=d*m,w=d*h,C=i.x,E=i.y,A=i.z;return s[0]=(1-(b+v))*C,s[1]=(g+w)*C,s[2]=(y-P)*C,s[3]=0,s[4]=(g-w)*E,s[5]=(1-(_+v))*E,s[6]=(T+x)*E,s[7]=0,s[8]=(y+P)*A,s[9]=(T-x)*A,s[10]=(1-(_+b))*A,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,i){const s=this.elements;let o=Hf.set(s[0],s[1],s[2]).length();const l=Hf.set(s[4],s[5],s[6]).length(),u=Hf.set(s[8],s[9],s[10]).length();this.determinant()<0&&(o=-o),e.x=s[12],e.y=s[13],e.z=s[14],Ba.copy(this);const f=1/o,m=1/l,h=1/u;return Ba.elements[0]*=f,Ba.elements[1]*=f,Ba.elements[2]*=f,Ba.elements[4]*=m,Ba.elements[5]*=m,Ba.elements[6]*=m,Ba.elements[8]*=h,Ba.elements[9]*=h,Ba.elements[10]*=h,t.setFromRotationMatrix(Ba),i.x=o,i.y=l,i.z=u,this}makePerspective(e,t,i,s,o,l,u=Tl){const d=this.elements,f=2*o/(t-e),m=2*o/(i-s),h=(t+e)/(t-e),_=(i+s)/(i-s);let g,y;if(u===Tl)g=-(l+o)/(l-o),y=-2*l*o/(l-o);else if(u===Zg)g=-l/(l-o),y=-l*o/(l-o);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+u);return d[0]=f,d[4]=0,d[8]=h,d[12]=0,d[1]=0,d[5]=m,d[9]=_,d[13]=0,d[2]=0,d[6]=0,d[10]=g,d[14]=y,d[3]=0,d[7]=0,d[11]=-1,d[15]=0,this}makeOrthographic(e,t,i,s,o,l,u=Tl){const d=this.elements,f=1/(t-e),m=1/(i-s),h=1/(l-o),_=(t+e)*f,g=(i+s)*m;let y,b;if(u===Tl)y=(l+o)*h,b=-2*h;else if(u===Zg)y=o*h,b=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+u);return d[0]=2*f,d[4]=0,d[8]=0,d[12]=-_,d[1]=0,d[5]=2*m,d[9]=0,d[13]=-g,d[2]=0,d[6]=0,d[10]=b,d[14]=-y,d[3]=0,d[7]=0,d[11]=0,d[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let s=0;s<16;s++)if(t[s]!==i[s])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}}const Hf=new Ge,Ba=new hr,PO=new Ge(0,0,0),RO=new Ge(1,1,1),Dc=new Ge,gg=new Ge,Ps=new Ge,GE=new hr,jE=new i_;class Al{constructor(e=0,t=0,i=0,s=Al.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,s=this._order){return this._x=e,this._y=t,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const s=e.elements,o=s[0],l=s[4],u=s[8],d=s[1],f=s[5],m=s[9],h=s[2],_=s[6],g=s[10];switch(t){case"XYZ":this._y=Math.asin(Hn(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(-m,g),this._z=Math.atan2(-l,o)):(this._x=Math.atan2(_,f),this._z=0);break;case"YXZ":this._x=Math.asin(-Hn(m,-1,1)),Math.abs(m)<.9999999?(this._y=Math.atan2(u,g),this._z=Math.atan2(d,f)):(this._y=Math.atan2(-h,o),this._z=0);break;case"ZXY":this._x=Math.asin(Hn(_,-1,1)),Math.abs(_)<.9999999?(this._y=Math.atan2(-h,g),this._z=Math.atan2(-l,f)):(this._y=0,this._z=Math.atan2(d,o));break;case"ZYX":this._y=Math.asin(-Hn(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(_,g),this._z=Math.atan2(d,o)):(this._x=0,this._z=Math.atan2(-l,f));break;case"YZX":this._z=Math.asin(Hn(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(-m,f),this._y=Math.atan2(-h,o)):(this._x=0,this._y=Math.atan2(u,g));break;case"XZY":this._z=Math.asin(-Hn(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(_,f),this._y=Math.atan2(u,o)):(this._x=Math.atan2(-m,g),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return GE.makeRotationFromQuaternion(e),this.setFromRotationMatrix(GE,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return jE.setFromEuler(this),this.setFromQuaternion(jE,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Al.DEFAULT_ORDER="XYZ";class XC{constructor(){this.mask=1}set(e){this.mask=(1<>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.visibility=this._visibility,s.active=this._active,s.bounds=this._bounds.map(u=>({boxInitialized:u.boxInitialized,boxMin:u.box.min.toArray(),boxMax:u.box.max.toArray(),sphereInitialized:u.sphereInitialized,sphereRadius:u.sphere.radius,sphereCenter:u.sphere.center.toArray()})),s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.geometryCount=this._geometryCount,s.matricesTexture=this._matricesTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere={center:s.boundingSphere.center.toArray(),radius:s.boundingSphere.radius}),this.boundingBox!==null&&(s.boundingBox={min:s.boundingBox.min.toArray(),max:s.boundingBox.max.toArray()}));function o(u,d){return u[d.uuid]===void 0&&(u[d.uuid]=d.toJSON(e)),d.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=o(e.geometries,this.geometry);const u=this.geometry.parameters;if(u!==void 0&&u.shapes!==void 0){const d=u.shapes;if(Array.isArray(d))for(let f=0,m=d.length;f0){s.children=[];for(let u=0;u0){s.animations=[];for(let u=0;u0&&(i.geometries=u),d.length>0&&(i.materials=d),f.length>0&&(i.textures=f),m.length>0&&(i.images=m),h.length>0&&(i.shapes=h),_.length>0&&(i.skeletons=_),g.length>0&&(i.animations=g),y.length>0&&(i.nodes=y)}return i.object=s,i;function l(u){const d=[];for(const f in u){const m=u[f];delete m.metadata,d.push(m)}return d}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i0?s.multiplyScalar(1/Math.sqrt(o)):s.set(0,0,0)}static getBarycoord(e,t,i,s,o){$a.subVectors(s,t),vl.subVectors(i,t),Vv.subVectors(e,t);const l=$a.dot($a),u=$a.dot(vl),d=$a.dot(Vv),f=vl.dot(vl),m=vl.dot(Vv),h=l*f-u*u;if(h===0)return o.set(0,0,0),null;const _=1/h,g=(f*d-u*m)*_,y=(l*m-u*d)*_;return o.set(1-g-y,y,g)}static containsPoint(e,t,i,s){return this.getBarycoord(e,t,i,s,yl)===null?!1:yl.x>=0&&yl.y>=0&&yl.x+yl.y<=1}static getInterpolation(e,t,i,s,o,l,u,d){return this.getBarycoord(e,t,i,s,yl)===null?(d.x=0,d.y=0,"z"in d&&(d.z=0),"w"in d&&(d.w=0),null):(d.setScalar(0),d.addScaledVector(o,yl.x),d.addScaledVector(l,yl.y),d.addScaledVector(u,yl.z),d)}static getInterpolatedAttribute(e,t,i,s,o,l){return Hv.setScalar(0),qv.setScalar(0),Xv.setScalar(0),Hv.fromBufferAttribute(e,t),qv.fromBufferAttribute(e,i),Xv.fromBufferAttribute(e,s),l.setScalar(0),l.addScaledVector(Hv,o.x),l.addScaledVector(qv,o.y),l.addScaledVector(Xv,o.z),l}static isFrontFacing(e,t,i,s){return $a.subVectors(i,t),vl.subVectors(e,t),$a.cross(vl).dot(s)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,s){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,i,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return $a.subVectors(this.c,this.b),vl.subVectors(this.a,this.b),$a.cross(vl).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ja.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ja.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,s,o){return ja.getInterpolation(e,this.a,this.b,this.c,t,i,s,o)}containsPoint(e){return ja.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ja.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,s=this.b,o=this.c;let l,u;Kf.subVectors(s,i),Yf.subVectors(o,i),Gv.subVectors(e,i);const d=Kf.dot(Gv),f=Yf.dot(Gv);if(d<=0&&f<=0)return t.copy(i);jv.subVectors(e,s);const m=Kf.dot(jv),h=Yf.dot(jv);if(m>=0&&h<=m)return t.copy(s);const _=d*h-m*f;if(_<=0&&d>=0&&m<=0)return l=d/(d-m),t.copy(i).addScaledVector(Kf,l);Wv.subVectors(e,o);const g=Kf.dot(Wv),y=Yf.dot(Wv);if(y>=0&&g<=y)return t.copy(o);const b=g*f-d*y;if(b<=0&&f>=0&&y<=0)return u=f/(f-y),t.copy(i).addScaledVector(Yf,u);const T=m*y-g*h;if(T<=0&&h-m>=0&&g-y>=0)return YE.subVectors(o,s),u=(h-m)/(h-m+(g-y)),t.copy(s).addScaledVector(YE,u);const v=1/(T+b+_);return l=b*v,u=_*v,t.copy(i).addScaledVector(Kf,l).addScaledVector(Yf,u)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const KC={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ic={h:0,s:0,l:0},yg={h:0,s:0,l:0};function Kv(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class wi{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=ca){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,oi.toWorkingColorSpace(this,t),this}setRGB(e,t,i,s=oi.workingColorSpace){return this.r=e,this.g=t,this.b=i,oi.toWorkingColorSpace(this,s),this}setHSL(e,t,i,s=oi.workingColorSpace){if(e=_O(e,1),t=Hn(t,0,1),i=Hn(i,0,1),t===0)this.r=this.g=this.b=i;else{const o=i<=.5?i*(1+t):i+t-i*t,l=2*i-o;this.r=Kv(l,o,e+1/3),this.g=Kv(l,o,e),this.b=Kv(l,o,e-1/3)}return oi.toWorkingColorSpace(this,s),this}setStyle(e,t=ca){function i(o){o!==void 0&&parseFloat(o)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let o;const l=s[1],u=s[2];switch(l){case"rgb":case"rgba":if(o=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))return i(o[4]),this.setRGB(Math.min(255,parseInt(o[1],10))/255,Math.min(255,parseInt(o[2],10))/255,Math.min(255,parseInt(o[3],10))/255,t);if(o=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))return i(o[4]),this.setRGB(Math.min(100,parseInt(o[1],10))/100,Math.min(100,parseInt(o[2],10))/100,Math.min(100,parseInt(o[3],10))/100,t);break;case"hsl":case"hsla":if(o=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(u))return i(o[4]),this.setHSL(parseFloat(o[1])/360,parseFloat(o[2])/100,parseFloat(o[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const o=s[1],l=o.length;if(l===3)return this.setRGB(parseInt(o.charAt(0),16)/15,parseInt(o.charAt(1),16)/15,parseInt(o.charAt(2),16)/15,t);if(l===6)return this.setHex(parseInt(o,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=ca){const i=KC[e.toLowerCase()];return i!==void 0?this.setHex(i,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=El(e.r),this.g=El(e.g),this.b=El(e.b),this}copyLinearToSRGB(e){return this.r=lh(e.r),this.g=lh(e.g),this.b=lh(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ca){return oi.fromWorkingColorSpace(Xr.copy(this),e),Math.round(Hn(Xr.r*255,0,255))*65536+Math.round(Hn(Xr.g*255,0,255))*256+Math.round(Hn(Xr.b*255,0,255))}getHexString(e=ca){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=oi.workingColorSpace){oi.fromWorkingColorSpace(Xr.copy(this),t);const i=Xr.r,s=Xr.g,o=Xr.b,l=Math.max(i,s,o),u=Math.min(i,s,o);let d,f;const m=(u+l)/2;if(u===l)d=0,f=0;else{const h=l-u;switch(f=m<=.5?h/(l+u):h/(2-l-u),l){case i:d=(s-o)/h+(s0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const i=e[t];if(i===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(i):s&&s.isVector3&&i&&i.isVector3?s.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==oh&&(i.blending=this.blending),this.side!==zc&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Iy&&(i.blendSrc=this.blendSrc),this.blendDst!==Oy&&(i.blendDst=this.blendDst),this.blendEquation!==nd&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==hh&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==kE&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==$f&&(i.stencilFail=this.stencilFail),this.stencilZFail!==$f&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==$f&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function s(o){const l=[];for(const u in o){const d=o[u];delete d.metadata,l.push(d)}return l}if(t){const o=s(e.textures),l=s(e.images);o.length>0&&(i.textures=o),l.length>0&&(i.images=l)}return i}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let i=null;if(t!==null){const s=t.length;i=new Array(s);for(let o=0;o!==s;++o)i[o]=t[o].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class sh extends t0{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new wi(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Al,this.combine=OC,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const gr=new Ge,Mg=new bn;let kO=0;class Po{constructor(e,t,i=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:kO++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=NE,this.updateRanges=[],this.gpuType=wl,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let s=0,o=this.itemSize;st.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new r_);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new Ge(-1/0,-1/0,-1/0),new Ge(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,s=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){const d=this.parameters;for(const f in d)d[f]!==void 0&&(e[f]=d[f]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const d in i){const f=i[d];e.data.attributes[d]=f.toJSON(e.data)}const s={};let o=!1;for(const d in this.morphAttributes){const f=this.morphAttributes[d],m=[];for(let h=0,_=f.length;h<_;h++){const g=f[h];m.push(g.toJSON(e.data))}m.length>0&&(s[d]=m,o=!0)}o&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const l=this.groups;l.length>0&&(e.data.groups=JSON.parse(JSON.stringify(l)));const u=this.boundingSphere;return u!==null&&(e.data.boundingSphere={center:u.center.toArray(),radius:u.radius}),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const s=e.attributes;for(const f in s){const m=s[f];this.setAttribute(f,m.clone(t))}const o=e.morphAttributes;for(const f in o){const m=[],h=o[f];for(let _=0,g=h.length;_0){const s=t[i[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let o=0,l=s.length;o(e.far-e.near)**2))&&(QE.copy(o).invert(),qu.copy(e.ray).applyMatrix4(QE),!(i.boundingBox!==null&&qu.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,qu)))}_computeIntersections(e,t,i){let s;const o=this.geometry,l=this.material,u=o.index,d=o.attributes.position,f=o.attributes.uv,m=o.attributes.uv1,h=o.attributes.normal,_=o.groups,g=o.drawRange;if(u!==null)if(Array.isArray(l))for(let y=0,b=_.length;yt.far?null:{distance:f,point:Sg.clone(),object:n}}function Ag(n,e,t,i,s,o,l,u,d,f){n.getVertexPosition(u,xg),n.getVertexPosition(d,wg),n.getVertexPosition(f,Tg);const m=zO(n,e,t,i,xg,wg,Tg,JE);if(m){const h=new Ge;ja.getBarycoord(JE,xg,wg,Tg,h),s&&(m.uv=ja.getInterpolatedAttribute(s,u,d,f,h,new bn)),o&&(m.uv1=ja.getInterpolatedAttribute(o,u,d,f,h,new bn)),l&&(m.normal=ja.getInterpolatedAttribute(l,u,d,f,h,new Ge),m.normal.dot(i.direction)>0&&m.normal.multiplyScalar(-1));const _={a:u,b:d,c:f,normal:new Ge,materialIndex:0};ja.getNormal(xg,wg,Tg,_.normal),m.face=_,m.barycoord=h}return m}class s_ extends Pl{constructor(e=1,t=1,i=1,s=1,o=1,l=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:s,heightSegments:o,depthSegments:l};const u=this;s=Math.floor(s),o=Math.floor(o),l=Math.floor(l);const d=[],f=[],m=[],h=[];let _=0,g=0;y("z","y","x",-1,-1,i,t,e,l,o,0),y("z","y","x",1,-1,i,t,-e,l,o,1),y("x","z","y",1,1,e,i,t,s,l,2),y("x","z","y",1,-1,e,i,-t,s,l,3),y("x","y","z",1,-1,e,t,i,s,o,4),y("x","y","z",-1,-1,e,t,-i,s,o,5),this.setIndex(d),this.setAttribute("position",new ks(f,3)),this.setAttribute("normal",new ks(m,3)),this.setAttribute("uv",new ks(h,2));function y(b,T,v,x,P,w,C,E,A,L,I){const O=w/A,H=C/L,Z=w/2,$=C/2,J=E/2,ee=A+1,X=L+1;let ne=0,Q=0;const oe=new Ge;for(let W=0;W0?1:-1,m.push(oe.x,oe.y,oe.z),h.push(G/A),h.push(1-W/L),ne+=1}}for(let W=0;W0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const i={};for(const s in this.extensions)this.extensions[s]===!0&&(i[s]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}}class JC extends Fs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new hr,this.projectionMatrix=new hr,this.projectionMatrixInverse=new hr,this.coordinateSystem=Tl}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Oc=new Ge,e1=new bn,t1=new bn;class ua extends JC{constructor(e=50,t=1,i=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=gM*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Dv*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return gM*2*Math.atan(Math.tan(Dv*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,i){Oc.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Oc.x,Oc.y).multiplyScalar(-e/Oc.z),Oc.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Oc.x,Oc.y).multiplyScalar(-e/Oc.z)}getViewSize(e,t){return this.getViewBounds(e,e1,t1),t.subVectors(t1,e1)}setViewOffset(e,t,i,s,o,l){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=i,this.view.offsetY=s,this.view.width=o,this.view.height=l,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Dv*.5*this.fov)/this.zoom,i=2*t,s=this.aspect*i,o=-.5*s;const l=this.view;if(this.view!==null&&this.view.enabled){const d=l.fullWidth,f=l.fullHeight;o+=l.offsetX*s/d,t-=l.offsetY*i/f,s*=l.width/d,i*=l.height/f}const u=this.filmOffset;u!==0&&(o+=e*u/this.getFilmWidth()),this.projectionMatrix.makePerspective(o,o+s,t,t-i,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Zf=-90,Jf=1;class GO extends Fs{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new ua(Zf,Jf,e,t);s.layers=this.layers,this.add(s);const o=new ua(Zf,Jf,e,t);o.layers=this.layers,this.add(o);const l=new ua(Zf,Jf,e,t);l.layers=this.layers,this.add(l);const u=new ua(Zf,Jf,e,t);u.layers=this.layers,this.add(u);const d=new ua(Zf,Jf,e,t);d.layers=this.layers,this.add(d);const f=new ua(Zf,Jf,e,t);f.layers=this.layers,this.add(f)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,s,o,l,u,d]=t;for(const f of t)this.remove(f);if(e===Tl)i.up.set(0,1,0),i.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),o.up.set(0,0,-1),o.lookAt(0,1,0),l.up.set(0,0,1),l.lookAt(0,-1,0),u.up.set(0,1,0),u.lookAt(0,0,1),d.up.set(0,1,0),d.lookAt(0,0,-1);else if(e===Zg)i.up.set(0,-1,0),i.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),o.up.set(0,0,1),o.lookAt(0,1,0),l.up.set(0,0,-1),l.lookAt(0,-1,0),u.up.set(0,-1,0),u.lookAt(0,0,1),d.up.set(0,-1,0),d.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const f of t)this.add(f),f.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[o,l,u,d,f,m]=this.children,h=e.getRenderTarget(),_=e.getActiveCubeFace(),g=e.getActiveMipmapLevel(),y=e.xr.enabled;e.xr.enabled=!1;const b=i.texture.generateMipmaps;i.texture.generateMipmaps=!1,e.setRenderTarget(i,0,s),e.render(t,o),e.setRenderTarget(i,1,s),e.render(t,l),e.setRenderTarget(i,2,s),e.render(t,u),e.setRenderTarget(i,3,s),e.render(t,d),e.setRenderTarget(i,4,s),e.render(t,f),i.texture.generateMipmaps=b,e.setRenderTarget(i,5,s),e.render(t,m),e.setRenderTarget(h,_,g),e.xr.enabled=y,i.texture.needsPMREMUpdate=!0}}class eP extends vs{constructor(e=[],t=ph,i,s,o,l,u,d,f,m){super(e,t,i,s,o,l,u,d,f,m),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class jO extends dd{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const i={width:e,height:e,depth:1},s=[i,i,i,i,i,i];this.texture=new eP(s,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:Co}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const i={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},s=new s_(5,5,5),o=new Uc({name:"CubemapFromEquirect",uniforms:gh(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:gs,blending:Fc});o.uniforms.tEquirect.value=t;const l=new Os(s,o),u=t.minFilter;return t.minFilter===ad&&(t.minFilter=Co),new GO(1,10,this).update(e,l),t.minFilter=u,l.geometry.dispose(),l.material.dispose(),this}clear(e,t=!0,i=!0,s=!0){const o=e.getRenderTarget();for(let l=0;l<6;l++)e.setRenderTarget(this,l),e.clear(t,i,s);e.setRenderTarget(o)}}class Vm extends Fs{constructor(){super(),this.isGroup=!0,this.type="Group"}}const WO={type:"move"};class Zv{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Vm,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Vm,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ge,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ge),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Vm,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ge,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ge),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,i){let s=null,o=null,l=null;const u=this._targetRay,d=this._grip,f=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(f&&e.hand){l=!0;for(const b of e.hand.values()){const T=t.getJointPose(b,i),v=this._getHandJoint(f,b);T!==null&&(v.matrix.fromArray(T.transform.matrix),v.matrix.decompose(v.position,v.rotation,v.scale),v.matrixWorldNeedsUpdate=!0,v.jointRadius=T.radius),v.visible=T!==null}const m=f.joints["index-finger-tip"],h=f.joints["thumb-tip"],_=m.position.distanceTo(h.position),g=.02,y=.005;f.inputState.pinching&&_>g+y?(f.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!f.inputState.pinching&&_<=g-y&&(f.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else d!==null&&e.gripSpace&&(o=t.getPose(e.gripSpace,i),o!==null&&(d.matrix.fromArray(o.transform.matrix),d.matrix.decompose(d.position,d.rotation,d.scale),d.matrixWorldNeedsUpdate=!0,o.linearVelocity?(d.hasLinearVelocity=!0,d.linearVelocity.copy(o.linearVelocity)):d.hasLinearVelocity=!1,o.angularVelocity?(d.hasAngularVelocity=!0,d.angularVelocity.copy(o.angularVelocity)):d.hasAngularVelocity=!1));u!==null&&(s=t.getPose(e.targetRaySpace,i),s===null&&o!==null&&(s=o),s!==null&&(u.matrix.fromArray(s.transform.matrix),u.matrix.decompose(u.position,u.rotation,u.scale),u.matrixWorldNeedsUpdate=!0,s.linearVelocity?(u.hasLinearVelocity=!0,u.linearVelocity.copy(s.linearVelocity)):u.hasLinearVelocity=!1,s.angularVelocity?(u.hasAngularVelocity=!0,u.angularVelocity.copy(s.angularVelocity)):u.hasAngularVelocity=!1,this.dispatchEvent(WO)))}return u!==null&&(u.visible=s!==null),d!==null&&(d.visible=o!==null),f!==null&&(f.visible=l!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new Vm;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}class HO extends Fs{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Al,this.environmentIntensity=1,this.environmentRotation=new Al,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Jv=new Ge,qO=new Ge,XO=new In;class Zu{constructor(e=new Ge(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,i,s){return this.normal.set(e,t,i),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const s=Jv.subVectors(i,t).cross(qO.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const i=e.delta(Jv),s=this.normal.dot(i);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const o=-(e.start.dot(this.normal)+this.constant)/s;return o<0||o>1?null:t.copy(e.start).addScaledVector(i,o)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const i=t||XO.getNormalMatrix(e),s=this.coplanarPoint(Jv).applyMatrix4(e),o=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(o),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Xu=new ab,Cg=new Ge;class tP{constructor(e=new Zu,t=new Zu,i=new Zu,s=new Zu,o=new Zu,l=new Zu){this.planes=[e,t,i,s,o,l]}set(e,t,i,s,o,l){const u=this.planes;return u[0].copy(e),u[1].copy(t),u[2].copy(i),u[3].copy(s),u[4].copy(o),u[5].copy(l),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=Tl){const i=this.planes,s=e.elements,o=s[0],l=s[1],u=s[2],d=s[3],f=s[4],m=s[5],h=s[6],_=s[7],g=s[8],y=s[9],b=s[10],T=s[11],v=s[12],x=s[13],P=s[14],w=s[15];if(i[0].setComponents(d-o,_-f,T-g,w-v).normalize(),i[1].setComponents(d+o,_+f,T+g,w+v).normalize(),i[2].setComponents(d+l,_+m,T+y,w+x).normalize(),i[3].setComponents(d-l,_-m,T-y,w-x).normalize(),i[4].setComponents(d-u,_-h,T-b,w-P).normalize(),t===Tl)i[5].setComponents(d+u,_+h,T+b,w+P).normalize();else if(t===Zg)i[5].setComponents(u,h,b,P).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Xu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Xu.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Xu)}intersectsSprite(e){return Xu.center.set(0,0,0),Xu.radius=.7071067811865476,Xu.applyMatrix4(e.matrixWorld),this.intersectsSphere(Xu)}intersectsSphere(e){const t=this.planes,i=e.center,s=-e.radius;for(let o=0;o<6;o++)if(t[o].distanceToPoint(i)0?e.max.x:e.min.x,Cg.y=s.normal.y>0?e.max.y:e.min.y,Cg.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(Cg)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class nP extends vs{constructor(e,t,i=ud,s,o,l,u=qa,d=qa,f,m=Zm){if(m!==Zm&&m!==Jm)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super(null,s,o,l,u,d,m,i,f),this.isDepthTexture=!0,this.image={width:e,height:t},this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new sb(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class Ro{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){const i=this.getUtoTmapping(e);return this.getPoint(i,t)}getPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPoint(i/e));return t}getSpacedPoints(e=5){const t=[];for(let i=0;i<=e;i++)t.push(this.getPointAt(i/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let i,s=this.getPoint(0),o=0;t.push(0);for(let l=1;l<=e;l++)i=this.getPoint(l/e),o+=i.distanceTo(s),t.push(o),s=i;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const i=this.getLengths();let s=0;const o=i.length;let l;t?l=t:l=e*i[o-1];let u=0,d=o-1,f;for(;u<=d;)if(s=Math.floor(u+(d-u)/2),f=i[s]-l,f<0)u=s+1;else if(f>0)d=s-1;else{d=s;break}if(s=d,i[s]===l)return s/(o-1);const m=i[s],_=i[s+1]-m,g=(l-m)/_;return(s+g)/(o-1)}getTangent(e,t){let s=e-1e-4,o=e+1e-4;s<0&&(s=0),o>1&&(o=1);const l=this.getPoint(s),u=this.getPoint(o),d=t||(l.isVector2?new bn:new Ge);return d.copy(u).sub(l).normalize(),d}getTangentAt(e,t){const i=this.getUtoTmapping(e);return this.getTangent(i,t)}computeFrenetFrames(e,t=!1){const i=new Ge,s=[],o=[],l=[],u=new Ge,d=new hr;for(let g=0;g<=e;g++){const y=g/e;s[g]=this.getTangentAt(y,new Ge)}o[0]=new Ge,l[0]=new Ge;let f=Number.MAX_VALUE;const m=Math.abs(s[0].x),h=Math.abs(s[0].y),_=Math.abs(s[0].z);m<=f&&(f=m,i.set(1,0,0)),h<=f&&(f=h,i.set(0,1,0)),_<=f&&i.set(0,0,1),u.crossVectors(s[0],i).normalize(),o[0].crossVectors(s[0],u),l[0].crossVectors(s[0],o[0]);for(let g=1;g<=e;g++){if(o[g]=o[g-1].clone(),l[g]=l[g-1].clone(),u.crossVectors(s[g-1],s[g]),u.length()>Number.EPSILON){u.normalize();const y=Math.acos(Hn(s[g-1].dot(s[g]),-1,1));o[g].applyMatrix4(d.makeRotationAxis(u,y))}l[g].crossVectors(s[g],o[g])}if(t===!0){let g=Math.acos(Hn(o[0].dot(o[e]),-1,1));g/=e,s[0].dot(u.crossVectors(o[0],o[e]))>0&&(g=-g);for(let y=1;y<=e;y++)o[y].applyMatrix4(d.makeRotationAxis(s[y],g*y)),l[y].crossVectors(s[y],o[y])}return{tangents:s,normals:o,binormals:l}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class iP extends Ro{constructor(e=0,t=0,i=1,s=1,o=0,l=Math.PI*2,u=!1,d=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=i,this.yRadius=s,this.aStartAngle=o,this.aEndAngle=l,this.aClockwise=u,this.aRotation=d}getPoint(e,t=new bn){const i=t,s=Math.PI*2;let o=this.aEndAngle-this.aStartAngle;const l=Math.abs(o)s;)o-=s;o0?0:(Math.floor(Math.abs(u)/o)+1)*o:d===0&&u===o-1&&(u=o-2,d=1);let f,m;this.closed||u>0?f=s[(u-1)%o]:(Pg.subVectors(s[0],s[1]).add(s[0]),f=Pg);const h=s[u%o],_=s[(u+1)%o];if(this.closed||u+2s.length-2?s.length-1:l+1],h=s[l>s.length-3?s.length-1:l+2];return i.set(n1(u,d.x,f.x,m.x,h.x),n1(u,d.y,f.y,m.y,h.y)),i}copy(e){super.copy(e),this.points=[];for(let t=0,i=e.points.length;tg.start-y.start);let _=0;for(let g=1;g 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,OL=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,LL=`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,FL=`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,kL=`#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`,NL=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`,zL=`#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`,UL=`#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`,BL=`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,$L=`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,VL=`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,GL=`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,jL=`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,WL=`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,HL=`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,qL="gl_FragColor = linearToOutputTexel( gl_FragColor );",XL=`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,KL=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`,YL=`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`,QL=`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,ZL=`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,JL=`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,eF=`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,tF=`#ifdef USE_FOG + varying float vFogDepth; +#endif`,nF=`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,iF=`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,rF=`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,sF=`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,aF=`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,oF=`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,lF=`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,cF=`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,uF=`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,dF=`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,fF=`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,hF=`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,pF=`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,mF=`struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,_F=` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,gF=`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,vF=`#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,yF=`#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,MF=`#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,bF=`#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`,xF=`#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,wF=`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,TF=`#ifdef USE_MAP + uniform sampler2D map; +#endif`,EF=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,SF=`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,AF=`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,CF=`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,PF=`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,RF=`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,DF=`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,IF=`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,OF=`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,LF=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,FF=`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,kF=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,NF=`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,zF=`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,UF=`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,BF=`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,$F=`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,VF=`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,GF=`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,jF=`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,WF=`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`,HF=`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,qF=`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,XF=`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,KF=`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,YF=`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,QF=`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,ZF=`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`,JF=`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,ek=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,tk=`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,nk=`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,ik=`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,rk=`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,sk=`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,ak=`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,ok=`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,lk=`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,ck=`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,uk=`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,dk=`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,fk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,hk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,pk=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,mk=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`;const _k=`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,gk=`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,vk=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,yk=`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,Mk=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,bk=`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,xk=`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,wk=`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,Tk=`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,Ek=`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`,Sk=`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,Ak=`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,Ck=`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Pk=`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Rk=`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,Dk=`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,Ik=`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Ok=`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Lk=`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,Fk=`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,kk=`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,Nk=`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,zk=`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,Uk=`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,Bk=`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,$k=`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,Vk=`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,Gk=`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,jk=`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,Wk=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,Hk=`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,qk=`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`,Xk=`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,Kk=`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`,zn={alphahash_fragment:gL,alphahash_pars_fragment:vL,alphamap_fragment:yL,alphamap_pars_fragment:ML,alphatest_fragment:bL,alphatest_pars_fragment:xL,aomap_fragment:wL,aomap_pars_fragment:TL,batching_pars_vertex:EL,batching_vertex:SL,begin_vertex:AL,beginnormal_vertex:CL,bsdfs:PL,iridescence_fragment:RL,bumpmap_pars_fragment:DL,clipping_planes_fragment:IL,clipping_planes_pars_fragment:OL,clipping_planes_pars_vertex:LL,clipping_planes_vertex:FL,color_fragment:kL,color_pars_fragment:NL,color_pars_vertex:zL,color_vertex:UL,common:BL,cube_uv_reflection_fragment:$L,defaultnormal_vertex:VL,displacementmap_pars_vertex:GL,displacementmap_vertex:jL,emissivemap_fragment:WL,emissivemap_pars_fragment:HL,colorspace_fragment:qL,colorspace_pars_fragment:XL,envmap_fragment:KL,envmap_common_pars_fragment:YL,envmap_pars_fragment:QL,envmap_pars_vertex:ZL,envmap_physical_pars_fragment:cF,envmap_vertex:JL,fog_vertex:eF,fog_pars_vertex:tF,fog_fragment:nF,fog_pars_fragment:iF,gradientmap_pars_fragment:rF,lightmap_pars_fragment:sF,lights_lambert_fragment:aF,lights_lambert_pars_fragment:oF,lights_pars_begin:lF,lights_toon_fragment:uF,lights_toon_pars_fragment:dF,lights_phong_fragment:fF,lights_phong_pars_fragment:hF,lights_physical_fragment:pF,lights_physical_pars_fragment:mF,lights_fragment_begin:_F,lights_fragment_maps:gF,lights_fragment_end:vF,logdepthbuf_fragment:yF,logdepthbuf_pars_fragment:MF,logdepthbuf_pars_vertex:bF,logdepthbuf_vertex:xF,map_fragment:wF,map_pars_fragment:TF,map_particle_fragment:EF,map_particle_pars_fragment:SF,metalnessmap_fragment:AF,metalnessmap_pars_fragment:CF,morphinstance_vertex:PF,morphcolor_vertex:RF,morphnormal_vertex:DF,morphtarget_pars_vertex:IF,morphtarget_vertex:OF,normal_fragment_begin:LF,normal_fragment_maps:FF,normal_pars_fragment:kF,normal_pars_vertex:NF,normal_vertex:zF,normalmap_pars_fragment:UF,clearcoat_normal_fragment_begin:BF,clearcoat_normal_fragment_maps:$F,clearcoat_pars_fragment:VF,iridescence_pars_fragment:GF,opaque_fragment:jF,packing:WF,premultiplied_alpha_fragment:HF,project_vertex:qF,dithering_fragment:XF,dithering_pars_fragment:KF,roughnessmap_fragment:YF,roughnessmap_pars_fragment:QF,shadowmap_pars_fragment:ZF,shadowmap_pars_vertex:JF,shadowmap_vertex:ek,shadowmask_pars_fragment:tk,skinbase_vertex:nk,skinning_pars_vertex:ik,skinning_vertex:rk,skinnormal_vertex:sk,specularmap_fragment:ak,specularmap_pars_fragment:ok,tonemapping_fragment:lk,tonemapping_pars_fragment:ck,transmission_fragment:uk,transmission_pars_fragment:dk,uv_pars_fragment:fk,uv_pars_vertex:hk,uv_vertex:pk,worldpos_vertex:mk,background_vert:_k,background_frag:gk,backgroundCube_vert:vk,backgroundCube_frag:yk,cube_vert:Mk,cube_frag:bk,depth_vert:xk,depth_frag:wk,distanceRGBA_vert:Tk,distanceRGBA_frag:Ek,equirect_vert:Sk,equirect_frag:Ak,linedashed_vert:Ck,linedashed_frag:Pk,meshbasic_vert:Rk,meshbasic_frag:Dk,meshlambert_vert:Ik,meshlambert_frag:Ok,meshmatcap_vert:Lk,meshmatcap_frag:Fk,meshnormal_vert:kk,meshnormal_frag:Nk,meshphong_vert:zk,meshphong_frag:Uk,meshphysical_vert:Bk,meshphysical_frag:$k,meshtoon_vert:Vk,meshtoon_frag:Gk,points_vert:jk,points_frag:Wk,shadow_vert:Hk,shadow_frag:qk,sprite_vert:Xk,sprite_frag:Kk},Ut={common:{diffuse:{value:new wi(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new In},alphaMap:{value:null},alphaMapTransform:{value:new In},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new In}},envmap:{envMap:{value:null},envMapRotation:{value:new In},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new In}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new In}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new In},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new In},normalScale:{value:new bn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new In},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new In}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new In}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new In}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new wi(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new wi(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new In},alphaTest:{value:0},uvTransform:{value:new In}},sprite:{diffuse:{value:new wi(16777215)},opacity:{value:1},center:{value:new bn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new In},alphaMap:{value:null},alphaMapTransform:{value:new In},alphaTest:{value:0}}},Ao={basic:{uniforms:ls([Ut.common,Ut.specularmap,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.fog]),vertexShader:zn.meshbasic_vert,fragmentShader:zn.meshbasic_frag},lambert:{uniforms:ls([Ut.common,Ut.specularmap,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.fog,Ut.lights,{emissive:{value:new wi(0)}}]),vertexShader:zn.meshlambert_vert,fragmentShader:zn.meshlambert_frag},phong:{uniforms:ls([Ut.common,Ut.specularmap,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.fog,Ut.lights,{emissive:{value:new wi(0)},specular:{value:new wi(1118481)},shininess:{value:30}}]),vertexShader:zn.meshphong_vert,fragmentShader:zn.meshphong_frag},standard:{uniforms:ls([Ut.common,Ut.envmap,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.roughnessmap,Ut.metalnessmap,Ut.fog,Ut.lights,{emissive:{value:new wi(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:zn.meshphysical_vert,fragmentShader:zn.meshphysical_frag},toon:{uniforms:ls([Ut.common,Ut.aomap,Ut.lightmap,Ut.emissivemap,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.gradientmap,Ut.fog,Ut.lights,{emissive:{value:new wi(0)}}]),vertexShader:zn.meshtoon_vert,fragmentShader:zn.meshtoon_frag},matcap:{uniforms:ls([Ut.common,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,Ut.fog,{matcap:{value:null}}]),vertexShader:zn.meshmatcap_vert,fragmentShader:zn.meshmatcap_frag},points:{uniforms:ls([Ut.points,Ut.fog]),vertexShader:zn.points_vert,fragmentShader:zn.points_frag},dashed:{uniforms:ls([Ut.common,Ut.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:zn.linedashed_vert,fragmentShader:zn.linedashed_frag},depth:{uniforms:ls([Ut.common,Ut.displacementmap]),vertexShader:zn.depth_vert,fragmentShader:zn.depth_frag},normal:{uniforms:ls([Ut.common,Ut.bumpmap,Ut.normalmap,Ut.displacementmap,{opacity:{value:1}}]),vertexShader:zn.meshnormal_vert,fragmentShader:zn.meshnormal_frag},sprite:{uniforms:ls([Ut.sprite,Ut.fog]),vertexShader:zn.sprite_vert,fragmentShader:zn.sprite_frag},background:{uniforms:{uvTransform:{value:new In},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:zn.background_vert,fragmentShader:zn.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new In}},vertexShader:zn.backgroundCube_vert,fragmentShader:zn.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:zn.cube_vert,fragmentShader:zn.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:zn.equirect_vert,fragmentShader:zn.equirect_frag},distanceRGBA:{uniforms:ls([Ut.common,Ut.displacementmap,{referencePosition:{value:new Ge},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:zn.distanceRGBA_vert,fragmentShader:zn.distanceRGBA_frag},shadow:{uniforms:ls([Ut.lights,Ut.fog,{color:{value:new wi(0)},opacity:{value:1}}]),vertexShader:zn.shadow_vert,fragmentShader:zn.shadow_frag}};Ao.physical={uniforms:ls([Ao.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new In},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new In},clearcoatNormalScale:{value:new bn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new In},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new In},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new In},sheen:{value:0},sheenColor:{value:new wi(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new In},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new In},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new In},transmissionSamplerSize:{value:new bn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new In},attenuationDistance:{value:0},attenuationColor:{value:new wi(0)},specularColor:{value:new wi(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new In},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new In},anisotropyVector:{value:new bn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new In}}]),vertexShader:zn.meshphysical_vert,fragmentShader:zn.meshphysical_frag};const Rg={r:0,b:0,g:0},Ku=new Al,Yk=new hr;function Qk(n,e,t,i,s,o,l){const u=new wi(0);let d=o===!0?0:1,f,m,h=null,_=0,g=null;function y(P){let w=P.isScene===!0?P.background:null;return w&&w.isTexture&&(w=(P.backgroundBlurriness>0?t:e).get(w)),w}function b(P){let w=!1;const C=y(P);C===null?v(u,d):C&&C.isColor&&(v(C,1),w=!0);const E=n.xr.getEnvironmentBlendMode();E==="additive"?i.buffers.color.setClear(0,0,0,1,l):E==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,l),(n.autoClear||w)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function T(P,w){const C=y(w);C&&(C.isCubeTexture||C.mapping===e0)?(m===void 0&&(m=new Os(new s_(1,1,1),new Uc({name:"BackgroundCubeMaterial",uniforms:gh(Ao.backgroundCube.uniforms),vertexShader:Ao.backgroundCube.vertexShader,fragmentShader:Ao.backgroundCube.fragmentShader,side:gs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),m.geometry.deleteAttribute("normal"),m.geometry.deleteAttribute("uv"),m.onBeforeRender=function(E,A,L){this.matrixWorld.copyPosition(L.matrixWorld)},Object.defineProperty(m.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(m)),Ku.copy(w.backgroundRotation),Ku.x*=-1,Ku.y*=-1,Ku.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(Ku.y*=-1,Ku.z*=-1),m.material.uniforms.envMap.value=C,m.material.uniforms.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,m.material.uniforms.backgroundBlurriness.value=w.backgroundBlurriness,m.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,m.material.uniforms.backgroundRotation.value.setFromMatrix4(Yk.makeRotationFromEuler(Ku)),m.material.toneMapped=oi.getTransfer(C.colorSpace)!==Si,(h!==C||_!==C.version||g!==n.toneMapping)&&(m.material.needsUpdate=!0,h=C,_=C.version,g=n.toneMapping),m.layers.enableAll(),P.unshift(m,m.geometry,m.material,0,0,null)):C&&C.isTexture&&(f===void 0&&(f=new Os(new vh(2,2),new Uc({name:"BackgroundMaterial",uniforms:gh(Ao.background.uniforms),vertexShader:Ao.background.vertexShader,fragmentShader:Ao.background.fragmentShader,side:zc,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),f.geometry.deleteAttribute("normal"),Object.defineProperty(f.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(f)),f.material.uniforms.t2D.value=C,f.material.uniforms.backgroundIntensity.value=w.backgroundIntensity,f.material.toneMapped=oi.getTransfer(C.colorSpace)!==Si,C.matrixAutoUpdate===!0&&C.updateMatrix(),f.material.uniforms.uvTransform.value.copy(C.matrix),(h!==C||_!==C.version||g!==n.toneMapping)&&(f.material.needsUpdate=!0,h=C,_=C.version,g=n.toneMapping),f.layers.enableAll(),P.unshift(f,f.geometry,f.material,0,0,null))}function v(P,w){P.getRGB(Rg,ZC(n)),i.buffers.color.setClear(Rg.r,Rg.g,Rg.b,w,l)}function x(){m!==void 0&&(m.geometry.dispose(),m.material.dispose(),m=void 0),f!==void 0&&(f.geometry.dispose(),f.material.dispose(),f=void 0)}return{getClearColor:function(){return u},setClearColor:function(P,w=1){u.set(P),d=w,v(u,d)},getClearAlpha:function(){return d},setClearAlpha:function(P){d=P,v(u,d)},render:b,addToRenderList:T,dispose:x}}function Zk(n,e){const t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},s=_(null);let o=s,l=!1;function u(O,H,Z,$,J){let ee=!1;const X=h($,Z,H);o!==X&&(o=X,f(o.object)),ee=g(O,$,Z,J),ee&&y(O,$,Z,J),J!==null&&e.update(J,n.ELEMENT_ARRAY_BUFFER),(ee||l)&&(l=!1,w(O,H,Z,$),J!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(J).buffer))}function d(){return n.createVertexArray()}function f(O){return n.bindVertexArray(O)}function m(O){return n.deleteVertexArray(O)}function h(O,H,Z){const $=Z.wireframe===!0;let J=i[O.id];J===void 0&&(J={},i[O.id]=J);let ee=J[H.id];ee===void 0&&(ee={},J[H.id]=ee);let X=ee[$];return X===void 0&&(X=_(d()),ee[$]=X),X}function _(O){const H=[],Z=[],$=[];for(let J=0;J=0){const W=J[Q];let q=ee[Q];if(q===void 0&&(Q==="instanceMatrix"&&O.instanceMatrix&&(q=O.instanceMatrix),Q==="instanceColor"&&O.instanceColor&&(q=O.instanceColor)),W===void 0||W.attribute!==q||q&&W.data!==q.data)return!0;X++}return o.attributesNum!==X||o.index!==$}function y(O,H,Z,$){const J={},ee=H.attributes;let X=0;const ne=Z.getAttributes();for(const Q in ne)if(ne[Q].location>=0){let W=ee[Q];W===void 0&&(Q==="instanceMatrix"&&O.instanceMatrix&&(W=O.instanceMatrix),Q==="instanceColor"&&O.instanceColor&&(W=O.instanceColor));const q={};q.attribute=W,W&&W.data&&(q.data=W.data),J[Q]=q,X++}o.attributes=J,o.attributesNum=X,o.index=$}function b(){const O=o.newAttributes;for(let H=0,Z=O.length;H=0){let oe=J[ne];if(oe===void 0&&(ne==="instanceMatrix"&&O.instanceMatrix&&(oe=O.instanceMatrix),ne==="instanceColor"&&O.instanceColor&&(oe=O.instanceColor)),oe!==void 0){const W=oe.normalized,q=oe.itemSize,G=e.get(oe);if(G===void 0)continue;const te=G.buffer,B=G.type,le=G.bytesPerElement,ye=B===n.INT||B===n.UNSIGNED_INT||oe.gpuType===JM;if(oe.isInterleavedBufferAttribute){const me=oe.data,xe=me.stride,ze=oe.offset;if(me.isInstancedInterleavedBuffer){for(let Me=0;Me0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let f=t.precision!==void 0?t.precision:"highp";const m=d(f);m!==f&&(console.warn("THREE.WebGLRenderer:",f,"not supported, using",m,"instead."),f=m);const h=t.logarithmicDepthBuffer===!0,_=t.reverseDepthBuffer===!0&&e.has("EXT_clip_control"),g=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),y=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),b=n.getParameter(n.MAX_TEXTURE_SIZE),T=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),v=n.getParameter(n.MAX_VERTEX_ATTRIBS),x=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),P=n.getParameter(n.MAX_VARYING_VECTORS),w=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),C=y>0,E=n.getParameter(n.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:o,getMaxPrecision:d,textureFormatReadable:l,textureTypeReadable:u,precision:f,logarithmicDepthBuffer:h,reverseDepthBuffer:_,maxTextures:g,maxVertexTextures:y,maxTextureSize:b,maxCubemapSize:T,maxAttributes:v,maxVertexUniforms:x,maxVaryings:P,maxFragmentUniforms:w,vertexTextures:C,maxSamples:E}}function tN(n){const e=this;let t=null,i=0,s=!1,o=!1;const l=new Zu,u=new In,d={value:null,needsUpdate:!1};this.uniform=d,this.numPlanes=0,this.numIntersection=0,this.init=function(h,_){const g=h.length!==0||_||i!==0||s;return s=_,i=h.length,g},this.beginShadows=function(){o=!0,m(null)},this.endShadows=function(){o=!1},this.setGlobalState=function(h,_){t=m(h,_,0)},this.setState=function(h,_,g){const y=h.clippingPlanes,b=h.clipIntersection,T=h.clipShadows,v=n.get(h);if(!s||y===null||y.length===0||o&&!T)o?m(null):f();else{const x=o?0:i,P=x*4;let w=v.clippingState||null;d.value=w,w=m(y,_,P,g);for(let C=0;C!==P;++C)w[C]=t[C];v.clippingState=w,this.numIntersection=b?this.numPlanes:0,this.numPlanes+=x}};function f(){d.value!==t&&(d.value=t,d.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function m(h,_,g,y){const b=h!==null?h.length:0;let T=null;if(b!==0){if(T=d.value,y!==!0||T===null){const v=g+b*4,x=_.matrixWorldInverse;u.getNormalMatrix(x),(T===null||T.length0){const f=new jO(d.height);return f.fromEquirectangularTexture(n,l),e.set(l,f),l.addEventListener("dispose",s),t(f.texture,l.mapping)}else return null}}return l}function s(l){const u=l.target;u.removeEventListener("dispose",s);const d=e.get(u);d!==void 0&&(e.delete(u),d.dispose())}function o(){e=new WeakMap}return{get:i,dispose:o}}const ah=4,r1=[.125,.215,.35,.446,.526,.582],id=20,iy=new hL,s1=new wi;let ry=null,sy=0,ay=0,oy=!1;const Ju=(1+Math.sqrt(5))/2,eh=1/Ju,a1=[new Ge(-Ju,eh,0),new Ge(Ju,eh,0),new Ge(-eh,0,Ju),new Ge(eh,0,Ju),new Ge(0,Ju,-eh),new Ge(0,Ju,eh),new Ge(-1,1,-1),new Ge(1,1,-1),new Ge(-1,1,1),new Ge(1,1,1)],iN=new Ge;class o1{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,i=.1,s=100,o={}){const{size:l=256,position:u=iN}=o;ry=this._renderer.getRenderTarget(),sy=this._renderer.getActiveCubeFace(),ay=this._renderer.getActiveMipmapLevel(),oy=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(l);const d=this._allocateTargets();return d.depthBuffer=!0,this._sceneToCubeUV(e,i,s,d,u),t>0&&this._blur(d,0,0,t),this._applyPMREM(d),this._cleanup(d),d}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=u1(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=c1(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?w:0,w,w),h.setRenderTarget(s),T&&h.render(b,d),h.render(e,d)}b.geometry.dispose(),b.material.dispose(),h.toneMapping=g,h.autoClear=_,e.background=v}_textureToCubeUV(e,t){const i=this._renderer,s=e.mapping===ph||e.mapping===mh;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=u1()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=c1());const o=s?this._cubemapMaterial:this._equirectMaterial,l=new Os(this._lodPlanes[0],o),u=o.uniforms;u.envMap.value=e;const d=this._cubeSize;Dg(t,0,0,3*d,2*d),i.setRenderTarget(t),i.render(l,iy)}_applyPMREM(e){const t=this._renderer,i=t.autoClear;t.autoClear=!1;const s=this._lodPlanes.length;for(let o=1;oid&&console.warn(`sigmaRadians, ${o}, is too large and will clip, as it requested ${T} samples when the maximum is set to ${id}`);const v=[];let x=0;for(let A=0;AP-ah?s-P+ah:0),E=4*(this._cubeSize-w);Dg(t,C,E,3*w,2*w),d.setRenderTarget(t),d.render(h,iy)}}function rN(n){const e=[],t=[],i=[];let s=n;const o=n-ah+1+r1.length;for(let l=0;ln-ah?d=r1[l-n+ah-1]:l===0&&(d=0),i.push(d);const f=1/(u-2),m=-f,h=1+f,_=[m,m,h,m,h,h,m,m,h,h,m,h],g=6,y=6,b=3,T=2,v=1,x=new Float32Array(b*y*g),P=new Float32Array(T*y*g),w=new Float32Array(v*y*g);for(let E=0;E2?0:-1,I=[A,L,0,A+2/3,L,0,A+2/3,L+1,0,A,L,0,A+2/3,L+1,0,A,L+1,0];x.set(I,b*y*E),P.set(_,T*y*E);const O=[E,E,E,E,E,E];w.set(O,v*y*E)}const C=new Pl;C.setAttribute("position",new Po(x,b)),C.setAttribute("uv",new Po(P,T)),C.setAttribute("faceIndex",new Po(w,v)),e.push(C),s>ah&&s--}return{lodPlanes:e,sizeLods:t,sigmas:i}}function l1(n,e,t){const i=new dd(n,e,t);return i.texture.mapping=e0,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Dg(n,e,t,i,s){n.viewport.set(e,t,i,s),n.scissor.set(e,t,i,s)}function sN(n,e,t){const i=new Float32Array(id),s=new Ge(0,1,0);return new Uc({name:"SphericalGaussianBlur",defines:{n:id,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:ub(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:Fc,depthTest:!1,depthWrite:!1})}function c1(){return new Uc({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:ub(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:Fc,depthTest:!1,depthWrite:!1})}function u1(){return new Uc({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:ub(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:Fc,depthTest:!1,depthWrite:!1})}function ub(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}function aN(n){let e=new WeakMap,t=null;function i(u){if(u&&u.isTexture){const d=u.mapping,f=d===$y||d===Vy,m=d===ph||d===mh;if(f||m){let h=e.get(u);const _=h!==void 0?h.texture.pmremVersion:0;if(u.isRenderTargetTexture&&u.pmremVersion!==_)return t===null&&(t=new o1(n)),h=f?t.fromEquirectangular(u,h):t.fromCubemap(u,h),h.texture.pmremVersion=u.pmremVersion,e.set(u,h),h.texture;if(h!==void 0)return h.texture;{const g=u.image;return f&&g&&g.height>0||m&&g&&s(g)?(t===null&&(t=new o1(n)),h=f?t.fromEquirectangular(u):t.fromCubemap(u),h.texture.pmremVersion=u.pmremVersion,e.set(u,h),u.addEventListener("dispose",o),h.texture):null}}}return u}function s(u){let d=0;const f=6;for(let m=0;me.maxTextureSize&&(C=Math.ceil(w/e.maxTextureSize),w=e.maxTextureSize);const E=new Float32Array(w*C*4*h),A=new qC(E,w,C,h);A.type=wl,A.needsUpdate=!0;const L=P*4;for(let O=0;O0)return n;const s=e*t;let o=f1[s];if(o===void 0&&(o=new Float32Array(s),f1[s]=o),e!==0){i.toArray(o,0);for(let l=1,u=0;l!==e;++l)u+=t,n[l].toArray(o,u)}return o}function wr(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${u}: ${t[l]}`)}return i.join(` +`)}const y1=new In;function az(n){oi._getMatrix(y1,oi.workingColorSpace,n);const e=`mat3( ${y1.elements.map(t=>t.toFixed(4))} )`;switch(oi.getTransfer(n)){case Qg:return[e,"LinearTransferOETF"];case Si:return[e,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function M1(n,e,t){const i=n.getShaderParameter(e,n.COMPILE_STATUS),s=n.getShaderInfoLog(e).trim();if(i&&s==="")return"";const o=/ERROR: 0:(\d+)/.exec(s);if(o){const l=parseInt(o[1]);return t.toUpperCase()+` + +`+s+` + +`+sz(n.getShaderSource(e),l)}else return s}function oz(n,e){const t=az(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` +`)}function lz(n,e){let t;switch(e){case QI:t="Linear";break;case ZI:t="Reinhard";break;case JI:t="Cineon";break;case eO:t="ACESFilmic";break;case nO:t="AgX";break;case iO:t="Neutral";break;case tO:t="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),t="Linear"}return"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Ig=new Ge;function cz(){oi.getLuminanceCoefficients(Ig);const n=Ig.x.toFixed(4),e=Ig.y.toFixed(4),t=Ig.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function uz(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(Gm).join(` +`)}function dz(n){const e=[];for(const t in n){const i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` +`)}function fz(n,e){const t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let s=0;s/gm;function vM(n){return n.replace(hz,mz)}const pz=new Map;function mz(n,e){let t=zn[e];if(t===void 0){const i=pz.get(e);if(i!==void 0)t=zn[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,i);else throw new Error("Can not resolve #include <"+e+">")}return vM(t)}const _z=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function w1(n){return n.replace(_z,gz)}function gz(n,e,t,i){let s="";for(let o=parseInt(e);o0&&(T+=` +`),v=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,y].filter(Gm).join(` +`),v.length>0&&(v+=` +`)):(T=[T1(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,y,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+m:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+d:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` +`].filter(Gm).join(` +`),v=[T1(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,y,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+f:"",t.envMap?"#define "+m:"",t.envMap?"#define "+h:"",_?"#define CUBEUV_TEXEL_WIDTH "+_.texelWidth:"",_?"#define CUBEUV_TEXEL_HEIGHT "+_.texelHeight:"",_?"#define CUBEUV_MAX_MIP "+_.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+d:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",t.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==kc?"#define TONE_MAPPING":"",t.toneMapping!==kc?zn.tonemapping_pars_fragment:"",t.toneMapping!==kc?lz("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",zn.colorspace_pars_fragment,oz("linearToOutputTexel",t.outputColorSpace),cz(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`].filter(Gm).join(` +`)),l=vM(l),l=b1(l,t),l=x1(l,t),u=vM(u),u=b1(u,t),u=x1(u,t),l=w1(l),u=w1(u),t.isRawShaderMaterial!==!0&&(x=`#version 300 es +`,T=[g,"#define attribute in","#define varying out","#define texture2D texture"].join(` +`)+` +`+T,v=["#define varying in",t.glslVersion===zE?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===zE?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` +`)+` +`+v);const P=x+T+l,w=x+v+u,C=v1(s,s.VERTEX_SHADER,P),E=v1(s,s.FRAGMENT_SHADER,w);s.attachShader(b,C),s.attachShader(b,E),t.index0AttributeName!==void 0?s.bindAttribLocation(b,0,t.index0AttributeName):t.morphTargets===!0&&s.bindAttribLocation(b,0,"position"),s.linkProgram(b);function A(H){if(n.debug.checkShaderErrors){const Z=s.getProgramInfoLog(b).trim(),$=s.getShaderInfoLog(C).trim(),J=s.getShaderInfoLog(E).trim();let ee=!0,X=!0;if(s.getProgramParameter(b,s.LINK_STATUS)===!1)if(ee=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(s,b,C,E);else{const ne=M1(s,C,"vertex"),Q=M1(s,E,"fragment");console.error("THREE.WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(b,s.VALIDATE_STATUS)+` + +Material Name: `+H.name+` +Material Type: `+H.type+` + +Program Info Log: `+Z+` +`+ne+` +`+Q)}else Z!==""?console.warn("THREE.WebGLProgram: Program Info Log:",Z):($===""||J==="")&&(X=!1);X&&(H.diagnostics={runnable:ee,programLog:Z,vertexShader:{log:$,prefix:T},fragmentShader:{log:J,prefix:v}})}s.deleteShader(C),s.deleteShader(E),L=new Gg(s,b),I=fz(s,b)}let L;this.getUniforms=function(){return L===void 0&&A(this),L};let I;this.getAttributes=function(){return I===void 0&&A(this),I};let O=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return O===!1&&(O=s.getProgramParameter(b,iz)),O},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(b),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=rz++,this.cacheKey=e,this.usedTimes=1,this.program=b,this.vertexShader=C,this.fragmentShader=E,this}let Tz=0;class Ez{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,i=e.fragmentShader,s=this._getShaderStage(t),o=this._getShaderStage(i),l=this._getShaderCacheForMaterial(e);return l.has(s)===!1&&(l.add(s),s.usedTimes++),l.has(o)===!1&&(l.add(o),o.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new Sz(e),t.set(e,i)),i}}class Sz{constructor(e){this.id=Tz++,this.code=e,this.usedTimes=0}}function Az(n,e,t,i,s,o,l){const u=new XC,d=new Ez,f=new Set,m=[],h=s.logarithmicDepthBuffer,_=s.vertexTextures;let g=s.precision;const y={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function b(I){return f.add(I),I===0?"uv":`uv${I}`}function T(I,O,H,Z,$){const J=Z.fog,ee=$.geometry,X=I.isMeshStandardMaterial?Z.environment:null,ne=(I.isMeshStandardMaterial?t:e).get(I.envMap||X),Q=ne&&ne.mapping===e0?ne.image.height:null,oe=y[I.type];I.precision!==null&&(g=s.getMaxPrecision(I.precision),g!==I.precision&&console.warn("THREE.WebGLProgram.getParameters:",I.precision,"not supported, using",g,"instead."));const W=ee.morphAttributes.position||ee.morphAttributes.normal||ee.morphAttributes.color,q=W!==void 0?W.length:0;let G=0;ee.morphAttributes.position!==void 0&&(G=1),ee.morphAttributes.normal!==void 0&&(G=2),ee.morphAttributes.color!==void 0&&(G=3);let te,B,le,ye;if(oe){const rn=Ao[oe];te=rn.vertexShader,B=rn.fragmentShader}else te=I.vertexShader,B=I.fragmentShader,d.update(I),le=d.getVertexShaderID(I),ye=d.getFragmentShaderID(I);const me=n.getRenderTarget(),xe=n.state.buffers.depth.getReversed(),ze=$.isInstancedMesh===!0,Me=$.isBatchedMesh===!0,ce=!!I.map,ae=!!I.matcap,we=!!ne,re=!!I.aoMap,He=!!I.lightMap,Ne=!!I.bumpMap,We=!!I.normalMap,ke=!!I.displacementMap,st=!!I.emissiveMap,Ke=!!I.metalnessMap,F=!!I.roughnessMap,U=I.anisotropy>0,j=I.clearcoat>0,se=I.dispersion>0,_e=I.iridescence>0,ge=I.sheen>0,Ce=I.transmission>0,Ie=U&&!!I.anisotropyMap,Ee=j&&!!I.clearcoatMap,je=j&&!!I.clearcoatNormalMap,Qe=j&&!!I.clearcoatRoughnessMap,ot=_e&&!!I.iridescenceMap,bt=_e&&!!I.iridescenceThicknessMap,_t=ge&&!!I.sheenColorMap,nt=ge&&!!I.sheenRoughnessMap,ft=!!I.specularMap,vt=!!I.specularColorMap,mn=!!I.specularIntensityMap,Se=Ce&&!!I.transmissionMap,St=Ce&&!!I.thicknessMap,Ze=!!I.gradientMap,it=!!I.alphaMap,yt=I.alphaTest>0,tt=!!I.alphaHash,gt=!!I.extensions;let Pt=kc;I.toneMapped&&(me===null||me.isXRRenderTarget===!0)&&(Pt=n.toneMapping);const tn={shaderID:oe,shaderType:I.type,shaderName:I.name,vertexShader:te,fragmentShader:B,defines:I.defines,customVertexShaderID:le,customFragmentShaderID:ye,isRawShaderMaterial:I.isRawShaderMaterial===!0,glslVersion:I.glslVersion,precision:g,batching:Me,batchingColor:Me&&$._colorsTexture!==null,instancing:ze,instancingColor:ze&&$.instanceColor!==null,instancingMorph:ze&&$.morphTexture!==null,supportsVertexTextures:_,outputColorSpace:me===null?n.outputColorSpace:me.isXRRenderTarget===!0?me.texture.colorSpace:_h,alphaToCoverage:!!I.alphaToCoverage,map:ce,matcap:ae,envMap:we,envMapMode:we&&ne.mapping,envMapCubeUVHeight:Q,aoMap:re,lightMap:He,bumpMap:Ne,normalMap:We,displacementMap:_&&ke,emissiveMap:st,normalMapObjectSpace:We&&I.normalMapType===lO,normalMapTangentSpace:We&&I.normalMapType===oO,metalnessMap:Ke,roughnessMap:F,anisotropy:U,anisotropyMap:Ie,clearcoat:j,clearcoatMap:Ee,clearcoatNormalMap:je,clearcoatRoughnessMap:Qe,dispersion:se,iridescence:_e,iridescenceMap:ot,iridescenceThicknessMap:bt,sheen:ge,sheenColorMap:_t,sheenRoughnessMap:nt,specularMap:ft,specularColorMap:vt,specularIntensityMap:mn,transmission:Ce,transmissionMap:Se,thicknessMap:St,gradientMap:Ze,opaque:I.transparent===!1&&I.blending===oh&&I.alphaToCoverage===!1,alphaMap:it,alphaTest:yt,alphaHash:tt,combine:I.combine,mapUv:ce&&b(I.map.channel),aoMapUv:re&&b(I.aoMap.channel),lightMapUv:He&&b(I.lightMap.channel),bumpMapUv:Ne&&b(I.bumpMap.channel),normalMapUv:We&&b(I.normalMap.channel),displacementMapUv:ke&&b(I.displacementMap.channel),emissiveMapUv:st&&b(I.emissiveMap.channel),metalnessMapUv:Ke&&b(I.metalnessMap.channel),roughnessMapUv:F&&b(I.roughnessMap.channel),anisotropyMapUv:Ie&&b(I.anisotropyMap.channel),clearcoatMapUv:Ee&&b(I.clearcoatMap.channel),clearcoatNormalMapUv:je&&b(I.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Qe&&b(I.clearcoatRoughnessMap.channel),iridescenceMapUv:ot&&b(I.iridescenceMap.channel),iridescenceThicknessMapUv:bt&&b(I.iridescenceThicknessMap.channel),sheenColorMapUv:_t&&b(I.sheenColorMap.channel),sheenRoughnessMapUv:nt&&b(I.sheenRoughnessMap.channel),specularMapUv:ft&&b(I.specularMap.channel),specularColorMapUv:vt&&b(I.specularColorMap.channel),specularIntensityMapUv:mn&&b(I.specularIntensityMap.channel),transmissionMapUv:Se&&b(I.transmissionMap.channel),thicknessMapUv:St&&b(I.thicknessMap.channel),alphaMapUv:it&&b(I.alphaMap.channel),vertexTangents:!!ee.attributes.tangent&&(We||U),vertexColors:I.vertexColors,vertexAlphas:I.vertexColors===!0&&!!ee.attributes.color&&ee.attributes.color.itemSize===4,pointsUvs:$.isPoints===!0&&!!ee.attributes.uv&&(ce||it),fog:!!J,useFog:I.fog===!0,fogExp2:!!J&&J.isFogExp2,flatShading:I.flatShading===!0,sizeAttenuation:I.sizeAttenuation===!0,logarithmicDepthBuffer:h,reverseDepthBuffer:xe,skinning:$.isSkinnedMesh===!0,morphTargets:ee.morphAttributes.position!==void 0,morphNormals:ee.morphAttributes.normal!==void 0,morphColors:ee.morphAttributes.color!==void 0,morphTargetsCount:q,morphTextureStride:G,numDirLights:O.directional.length,numPointLights:O.point.length,numSpotLights:O.spot.length,numSpotLightMaps:O.spotLightMap.length,numRectAreaLights:O.rectArea.length,numHemiLights:O.hemi.length,numDirLightShadows:O.directionalShadowMap.length,numPointLightShadows:O.pointShadowMap.length,numSpotLightShadows:O.spotShadowMap.length,numSpotLightShadowsWithMaps:O.numSpotLightShadowsWithMaps,numLightProbes:O.numLightProbes,numClippingPlanes:l.numPlanes,numClipIntersection:l.numIntersection,dithering:I.dithering,shadowMapEnabled:n.shadowMap.enabled&&H.length>0,shadowMapType:n.shadowMap.type,toneMapping:Pt,decodeVideoTexture:ce&&I.map.isVideoTexture===!0&&oi.getTransfer(I.map.colorSpace)===Si,decodeVideoTextureEmissive:st&&I.emissiveMap.isVideoTexture===!0&&oi.getTransfer(I.emissiveMap.colorSpace)===Si,premultipliedAlpha:I.premultipliedAlpha,doubleSided:I.side===xl,flipSided:I.side===gs,useDepthPacking:I.depthPacking>=0,depthPacking:I.depthPacking||0,index0AttributeName:I.index0AttributeName,extensionClipCullDistance:gt&&I.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(gt&&I.extensions.multiDraw===!0||Me)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:I.customProgramCacheKey()};return tn.vertexUv1s=f.has(1),tn.vertexUv2s=f.has(2),tn.vertexUv3s=f.has(3),f.clear(),tn}function v(I){const O=[];if(I.shaderID?O.push(I.shaderID):(O.push(I.customVertexShaderID),O.push(I.customFragmentShaderID)),I.defines!==void 0)for(const H in I.defines)O.push(H),O.push(I.defines[H]);return I.isRawShaderMaterial===!1&&(x(O,I),P(O,I),O.push(n.outputColorSpace)),O.push(I.customProgramCacheKey),O.join()}function x(I,O){I.push(O.precision),I.push(O.outputColorSpace),I.push(O.envMapMode),I.push(O.envMapCubeUVHeight),I.push(O.mapUv),I.push(O.alphaMapUv),I.push(O.lightMapUv),I.push(O.aoMapUv),I.push(O.bumpMapUv),I.push(O.normalMapUv),I.push(O.displacementMapUv),I.push(O.emissiveMapUv),I.push(O.metalnessMapUv),I.push(O.roughnessMapUv),I.push(O.anisotropyMapUv),I.push(O.clearcoatMapUv),I.push(O.clearcoatNormalMapUv),I.push(O.clearcoatRoughnessMapUv),I.push(O.iridescenceMapUv),I.push(O.iridescenceThicknessMapUv),I.push(O.sheenColorMapUv),I.push(O.sheenRoughnessMapUv),I.push(O.specularMapUv),I.push(O.specularColorMapUv),I.push(O.specularIntensityMapUv),I.push(O.transmissionMapUv),I.push(O.thicknessMapUv),I.push(O.combine),I.push(O.fogExp2),I.push(O.sizeAttenuation),I.push(O.morphTargetsCount),I.push(O.morphAttributeCount),I.push(O.numDirLights),I.push(O.numPointLights),I.push(O.numSpotLights),I.push(O.numSpotLightMaps),I.push(O.numHemiLights),I.push(O.numRectAreaLights),I.push(O.numDirLightShadows),I.push(O.numPointLightShadows),I.push(O.numSpotLightShadows),I.push(O.numSpotLightShadowsWithMaps),I.push(O.numLightProbes),I.push(O.shadowMapType),I.push(O.toneMapping),I.push(O.numClippingPlanes),I.push(O.numClipIntersection),I.push(O.depthPacking)}function P(I,O){u.disableAll(),O.supportsVertexTextures&&u.enable(0),O.instancing&&u.enable(1),O.instancingColor&&u.enable(2),O.instancingMorph&&u.enable(3),O.matcap&&u.enable(4),O.envMap&&u.enable(5),O.normalMapObjectSpace&&u.enable(6),O.normalMapTangentSpace&&u.enable(7),O.clearcoat&&u.enable(8),O.iridescence&&u.enable(9),O.alphaTest&&u.enable(10),O.vertexColors&&u.enable(11),O.vertexAlphas&&u.enable(12),O.vertexUv1s&&u.enable(13),O.vertexUv2s&&u.enable(14),O.vertexUv3s&&u.enable(15),O.vertexTangents&&u.enable(16),O.anisotropy&&u.enable(17),O.alphaHash&&u.enable(18),O.batching&&u.enable(19),O.dispersion&&u.enable(20),O.batchingColor&&u.enable(21),I.push(u.mask),u.disableAll(),O.fog&&u.enable(0),O.useFog&&u.enable(1),O.flatShading&&u.enable(2),O.logarithmicDepthBuffer&&u.enable(3),O.reverseDepthBuffer&&u.enable(4),O.skinning&&u.enable(5),O.morphTargets&&u.enable(6),O.morphNormals&&u.enable(7),O.morphColors&&u.enable(8),O.premultipliedAlpha&&u.enable(9),O.shadowMapEnabled&&u.enable(10),O.doubleSided&&u.enable(11),O.flipSided&&u.enable(12),O.useDepthPacking&&u.enable(13),O.dithering&&u.enable(14),O.transmission&&u.enable(15),O.sheen&&u.enable(16),O.opaque&&u.enable(17),O.pointsUvs&&u.enable(18),O.decodeVideoTexture&&u.enable(19),O.decodeVideoTextureEmissive&&u.enable(20),O.alphaToCoverage&&u.enable(21),I.push(u.mask)}function w(I){const O=y[I.type];let H;if(O){const Z=Ao[O];H=BO.clone(Z.uniforms)}else H=I.uniforms;return H}function C(I,O){let H;for(let Z=0,$=m.length;Z<$;Z++){const J=m[Z];if(J.cacheKey===O){H=J,++H.usedTimes;break}}return H===void 0&&(H=new wz(n,O,I,o),m.push(H)),H}function E(I){if(--I.usedTimes===0){const O=m.indexOf(I);m[O]=m[m.length-1],m.pop(),I.destroy()}}function A(I){d.remove(I)}function L(){d.dispose()}return{getParameters:T,getProgramCacheKey:v,getUniforms:w,acquireProgram:C,releaseProgram:E,releaseShaderCache:A,programs:m,dispose:L}}function Cz(){let n=new WeakMap;function e(l){return n.has(l)}function t(l){let u=n.get(l);return u===void 0&&(u={},n.set(l,u)),u}function i(l){n.delete(l)}function s(l,u,d){n.get(l)[u]=d}function o(){n=new WeakMap}return{has:e,get:t,remove:i,update:s,dispose:o}}function Pz(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.material.id!==e.material.id?n.material.id-e.material.id:n.z!==e.z?n.z-e.z:n.id-e.id}function E1(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.z!==e.z?e.z-n.z:n.id-e.id}function S1(){const n=[];let e=0;const t=[],i=[],s=[];function o(){e=0,t.length=0,i.length=0,s.length=0}function l(h,_,g,y,b,T){let v=n[e];return v===void 0?(v={id:h.id,object:h,geometry:_,material:g,groupOrder:y,renderOrder:h.renderOrder,z:b,group:T},n[e]=v):(v.id=h.id,v.object=h,v.geometry=_,v.material=g,v.groupOrder=y,v.renderOrder=h.renderOrder,v.z=b,v.group=T),e++,v}function u(h,_,g,y,b,T){const v=l(h,_,g,y,b,T);g.transmission>0?i.push(v):g.transparent===!0?s.push(v):t.push(v)}function d(h,_,g,y,b,T){const v=l(h,_,g,y,b,T);g.transmission>0?i.unshift(v):g.transparent===!0?s.unshift(v):t.unshift(v)}function f(h,_){t.length>1&&t.sort(h||Pz),i.length>1&&i.sort(_||E1),s.length>1&&s.sort(_||E1)}function m(){for(let h=e,_=n.length;h<_;h++){const g=n[h];if(g.id===null)break;g.id=null,g.object=null,g.geometry=null,g.material=null,g.group=null}}return{opaque:t,transmissive:i,transparent:s,init:o,push:u,unshift:d,finish:m,sort:f}}function Rz(){let n=new WeakMap;function e(i,s){const o=n.get(i);let l;return o===void 0?(l=new S1,n.set(i,[l])):s>=o.length?(l=new S1,o.push(l)):l=o[s],l}function t(){n=new WeakMap}return{get:e,dispose:t}}function Dz(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new Ge,color:new wi};break;case"SpotLight":t={position:new Ge,direction:new Ge,color:new wi,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new Ge,color:new wi,distance:0,decay:0};break;case"HemisphereLight":t={direction:new Ge,skyColor:new wi,groundColor:new wi};break;case"RectAreaLight":t={color:new wi,position:new Ge,halfWidth:new Ge,halfHeight:new Ge};break}return n[e.id]=t,t}}}function Iz(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bn};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bn};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bn,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let Oz=0;function Lz(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function Fz(n){const e=new Dz,t=Iz(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let f=0;f<9;f++)i.probe.push(new Ge);const s=new Ge,o=new hr,l=new hr;function u(f){let m=0,h=0,_=0;for(let I=0;I<9;I++)i.probe[I].set(0,0,0);let g=0,y=0,b=0,T=0,v=0,x=0,P=0,w=0,C=0,E=0,A=0;f.sort(Lz);for(let I=0,O=f.length;I0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Ut.LTC_FLOAT_1,i.rectAreaLTC2=Ut.LTC_FLOAT_2):(i.rectAreaLTC1=Ut.LTC_HALF_1,i.rectAreaLTC2=Ut.LTC_HALF_2)),i.ambient[0]=m,i.ambient[1]=h,i.ambient[2]=_;const L=i.hash;(L.directionalLength!==g||L.pointLength!==y||L.spotLength!==b||L.rectAreaLength!==T||L.hemiLength!==v||L.numDirectionalShadows!==x||L.numPointShadows!==P||L.numSpotShadows!==w||L.numSpotMaps!==C||L.numLightProbes!==A)&&(i.directional.length=g,i.spot.length=b,i.rectArea.length=T,i.point.length=y,i.hemi.length=v,i.directionalShadow.length=x,i.directionalShadowMap.length=x,i.pointShadow.length=P,i.pointShadowMap.length=P,i.spotShadow.length=w,i.spotShadowMap.length=w,i.directionalShadowMatrix.length=x,i.pointShadowMatrix.length=P,i.spotLightMatrix.length=w+C-E,i.spotLightMap.length=C,i.numSpotLightShadowsWithMaps=E,i.numLightProbes=A,L.directionalLength=g,L.pointLength=y,L.spotLength=b,L.rectAreaLength=T,L.hemiLength=v,L.numDirectionalShadows=x,L.numPointShadows=P,L.numSpotShadows=w,L.numSpotMaps=C,L.numLightProbes=A,i.version=Oz++)}function d(f,m){let h=0,_=0,g=0,y=0,b=0;const T=m.matrixWorldInverse;for(let v=0,x=f.length;v=l.length?(u=new A1(n),l.push(u)):u=l[o],u}function i(){e=new WeakMap}return{get:t,dispose:i}}const Nz=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,zz=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`;function Uz(n,e,t){let i=new tP;const s=new bn,o=new bn,l=new fr,u=new dL({depthPacking:aO}),d=new fL,f={},m=t.maxTextureSize,h={[zc]:gs,[gs]:zc,[xl]:xl},_=new Uc({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new bn},radius:{value:4}},vertexShader:Nz,fragmentShader:zz}),g=_.clone();g.defines.HORIZONTAL_PASS=1;const y=new Pl;y.setAttribute("position",new Po(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const b=new Os(y,_),T=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=IC;let v=this.type;this.render=function(E,A,L){if(T.enabled===!1||T.autoUpdate===!1&&T.needsUpdate===!1||E.length===0)return;const I=n.getRenderTarget(),O=n.getActiveCubeFace(),H=n.getActiveMipmapLevel(),Z=n.state;Z.setBlending(Fc),Z.buffers.color.setClear(1,1,1,1),Z.buffers.depth.setTest(!0),Z.setScissorTest(!1);const $=v!==Ml&&this.type===Ml,J=v===Ml&&this.type!==Ml;for(let ee=0,X=E.length;eem||s.y>m)&&(s.x>m&&(o.x=Math.floor(m/oe.x),s.x=o.x*oe.x,Q.mapSize.x=o.x),s.y>m&&(o.y=Math.floor(m/oe.y),s.y=o.y*oe.y,Q.mapSize.y=o.y)),Q.map===null||$===!0||J===!0){const q=this.type!==Ml?{minFilter:qa,magFilter:qa}:{};Q.map!==null&&Q.map.dispose(),Q.map=new dd(s.x,s.y,q),Q.map.texture.name=ne.name+".shadowMap",Q.camera.updateProjectionMatrix()}n.setRenderTarget(Q.map),n.clear();const W=Q.getViewportCount();for(let q=0;q0||A.map&&A.alphaTest>0){const Z=O.uuid,$=A.uuid;let J=f[Z];J===void 0&&(J={},f[Z]=J);let ee=J[$];ee===void 0&&(ee=O.clone(),J[$]=ee,A.addEventListener("dispose",C)),O=ee}if(O.visible=A.visible,O.wireframe=A.wireframe,I===Ml?O.side=A.shadowSide!==null?A.shadowSide:A.side:O.side=A.shadowSide!==null?A.shadowSide:h[A.side],O.alphaMap=A.alphaMap,O.alphaTest=A.alphaTest,O.map=A.map,O.clipShadows=A.clipShadows,O.clippingPlanes=A.clippingPlanes,O.clipIntersection=A.clipIntersection,O.displacementMap=A.displacementMap,O.displacementScale=A.displacementScale,O.displacementBias=A.displacementBias,O.wireframeLinewidth=A.wireframeLinewidth,O.linewidth=A.linewidth,L.isPointLight===!0&&O.isMeshDistanceMaterial===!0){const Z=n.properties.get(O);Z.light=L}return O}function w(E,A,L,I,O){if(E.visible===!1)return;if(E.layers.test(A.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&O===Ml)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(L.matrixWorldInverse,E.matrixWorld);const $=e.update(E),J=E.material;if(Array.isArray(J)){const ee=$.groups;for(let X=0,ne=ee.length;X=1):Q.indexOf("OpenGL ES")!==-1&&(ne=parseFloat(/^OpenGL ES (\d)/.exec(Q)[1]),X=ne>=2);let oe=null,W={};const q=n.getParameter(n.SCISSOR_BOX),G=n.getParameter(n.VIEWPORT),te=new fr().fromArray(q),B=new fr().fromArray(G);function le(Se,St,Ze,it){const yt=new Uint8Array(4),tt=n.createTexture();n.bindTexture(Se,tt),n.texParameteri(Se,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(Se,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let gt=0;gt"u"?!1:/OculusBrowser/g.test(navigator.userAgent),f=new bn,m=new WeakMap;let h;const _=new WeakMap;let g=!1;try{g=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function y(F,U){return g?new OffscreenCanvas(F,U):Jg("canvas")}function b(F,U,j){let se=1;const _e=Ke(F);if((_e.width>j||_e.height>j)&&(se=j/Math.max(_e.width,_e.height)),se<1)if(typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&F instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&F instanceof ImageBitmap||typeof VideoFrame<"u"&&F instanceof VideoFrame){const ge=Math.floor(se*_e.width),Ce=Math.floor(se*_e.height);h===void 0&&(h=y(ge,Ce));const Ie=U?y(ge,Ce):h;return Ie.width=ge,Ie.height=Ce,Ie.getContext("2d").drawImage(F,0,0,ge,Ce),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+_e.width+"x"+_e.height+") to ("+ge+"x"+Ce+")."),Ie}else return"data"in F&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+_e.width+"x"+_e.height+")."),F;return F}function T(F){return F.generateMipmaps}function v(F){n.generateMipmap(F)}function x(F){return F.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:F.isWebGL3DRenderTarget?n.TEXTURE_3D:F.isWebGLArrayRenderTarget||F.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function P(F,U,j,se,_e=!1){if(F!==null){if(n[F]!==void 0)return n[F];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+F+"'")}let ge=U;if(U===n.RED&&(j===n.FLOAT&&(ge=n.R32F),j===n.HALF_FLOAT&&(ge=n.R16F),j===n.UNSIGNED_BYTE&&(ge=n.R8)),U===n.RED_INTEGER&&(j===n.UNSIGNED_BYTE&&(ge=n.R8UI),j===n.UNSIGNED_SHORT&&(ge=n.R16UI),j===n.UNSIGNED_INT&&(ge=n.R32UI),j===n.BYTE&&(ge=n.R8I),j===n.SHORT&&(ge=n.R16I),j===n.INT&&(ge=n.R32I)),U===n.RG&&(j===n.FLOAT&&(ge=n.RG32F),j===n.HALF_FLOAT&&(ge=n.RG16F),j===n.UNSIGNED_BYTE&&(ge=n.RG8)),U===n.RG_INTEGER&&(j===n.UNSIGNED_BYTE&&(ge=n.RG8UI),j===n.UNSIGNED_SHORT&&(ge=n.RG16UI),j===n.UNSIGNED_INT&&(ge=n.RG32UI),j===n.BYTE&&(ge=n.RG8I),j===n.SHORT&&(ge=n.RG16I),j===n.INT&&(ge=n.RG32I)),U===n.RGB_INTEGER&&(j===n.UNSIGNED_BYTE&&(ge=n.RGB8UI),j===n.UNSIGNED_SHORT&&(ge=n.RGB16UI),j===n.UNSIGNED_INT&&(ge=n.RGB32UI),j===n.BYTE&&(ge=n.RGB8I),j===n.SHORT&&(ge=n.RGB16I),j===n.INT&&(ge=n.RGB32I)),U===n.RGBA_INTEGER&&(j===n.UNSIGNED_BYTE&&(ge=n.RGBA8UI),j===n.UNSIGNED_SHORT&&(ge=n.RGBA16UI),j===n.UNSIGNED_INT&&(ge=n.RGBA32UI),j===n.BYTE&&(ge=n.RGBA8I),j===n.SHORT&&(ge=n.RGBA16I),j===n.INT&&(ge=n.RGBA32I)),U===n.RGB&&j===n.UNSIGNED_INT_5_9_9_9_REV&&(ge=n.RGB9_E5),U===n.RGBA){const Ce=_e?Qg:oi.getTransfer(se);j===n.FLOAT&&(ge=n.RGBA32F),j===n.HALF_FLOAT&&(ge=n.RGBA16F),j===n.UNSIGNED_BYTE&&(ge=Ce===Si?n.SRGB8_ALPHA8:n.RGBA8),j===n.UNSIGNED_SHORT_4_4_4_4&&(ge=n.RGBA4),j===n.UNSIGNED_SHORT_5_5_5_1&&(ge=n.RGB5_A1)}return(ge===n.R16F||ge===n.R32F||ge===n.RG16F||ge===n.RG32F||ge===n.RGBA16F||ge===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ge}function w(F,U){let j;return F?U===null||U===ud||U===Qm?j=n.DEPTH24_STENCIL8:U===wl?j=n.DEPTH32F_STENCIL8:U===Ym&&(j=n.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):U===null||U===ud||U===Qm?j=n.DEPTH_COMPONENT24:U===wl?j=n.DEPTH_COMPONENT32F:U===Ym&&(j=n.DEPTH_COMPONENT16),j}function C(F,U){return T(F)===!0||F.isFramebufferTexture&&F.minFilter!==qa&&F.minFilter!==Co?Math.log2(Math.max(U.width,U.height))+1:F.mipmaps!==void 0&&F.mipmaps.length>0?F.mipmaps.length:F.isCompressedTexture&&Array.isArray(F.image)?U.mipmaps.length:1}function E(F){const U=F.target;U.removeEventListener("dispose",E),L(U),U.isVideoTexture&&m.delete(U)}function A(F){const U=F.target;U.removeEventListener("dispose",A),O(U)}function L(F){const U=i.get(F);if(U.__webglInit===void 0)return;const j=F.source,se=_.get(j);if(se){const _e=se[U.__cacheKey];_e.usedTimes--,_e.usedTimes===0&&I(F),Object.keys(se).length===0&&_.delete(j)}i.remove(F)}function I(F){const U=i.get(F);n.deleteTexture(U.__webglTexture);const j=F.source,se=_.get(j);delete se[U.__cacheKey],l.memory.textures--}function O(F){const U=i.get(F);if(F.depthTexture&&(F.depthTexture.dispose(),i.remove(F.depthTexture)),F.isWebGLCubeRenderTarget)for(let se=0;se<6;se++){if(Array.isArray(U.__webglFramebuffer[se]))for(let _e=0;_e=s.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+F+" texture units while this GPU supports only "+s.maxTextures),H+=1,F}function J(F){const U=[];return U.push(F.wrapS),U.push(F.wrapT),U.push(F.wrapR||0),U.push(F.magFilter),U.push(F.minFilter),U.push(F.anisotropy),U.push(F.internalFormat),U.push(F.format),U.push(F.type),U.push(F.generateMipmaps),U.push(F.premultiplyAlpha),U.push(F.flipY),U.push(F.unpackAlignment),U.push(F.colorSpace),U.join()}function ee(F,U){const j=i.get(F);if(F.isVideoTexture&&ke(F),F.isRenderTargetTexture===!1&&F.version>0&&j.__version!==F.version){const se=F.image;if(se===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(se.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{B(j,F,U);return}}t.bindTexture(n.TEXTURE_2D,j.__webglTexture,n.TEXTURE0+U)}function X(F,U){const j=i.get(F);if(F.version>0&&j.__version!==F.version){B(j,F,U);return}t.bindTexture(n.TEXTURE_2D_ARRAY,j.__webglTexture,n.TEXTURE0+U)}function ne(F,U){const j=i.get(F);if(F.version>0&&j.__version!==F.version){B(j,F,U);return}t.bindTexture(n.TEXTURE_3D,j.__webglTexture,n.TEXTURE0+U)}function Q(F,U){const j=i.get(F);if(F.version>0&&j.__version!==F.version){le(j,F,U);return}t.bindTexture(n.TEXTURE_CUBE_MAP,j.__webglTexture,n.TEXTURE0+U)}const oe={[Gy]:n.REPEAT,[sd]:n.CLAMP_TO_EDGE,[jy]:n.MIRRORED_REPEAT},W={[qa]:n.NEAREST,[rO]:n.NEAREST_MIPMAP_NEAREST,[dg]:n.NEAREST_MIPMAP_LINEAR,[Co]:n.LINEAR,[Rv]:n.LINEAR_MIPMAP_NEAREST,[ad]:n.LINEAR_MIPMAP_LINEAR},q={[cO]:n.NEVER,[mO]:n.ALWAYS,[uO]:n.LESS,[WC]:n.LEQUAL,[dO]:n.EQUAL,[pO]:n.GEQUAL,[fO]:n.GREATER,[hO]:n.NOTEQUAL};function G(F,U){if(U.type===wl&&e.has("OES_texture_float_linear")===!1&&(U.magFilter===Co||U.magFilter===Rv||U.magFilter===dg||U.magFilter===ad||U.minFilter===Co||U.minFilter===Rv||U.minFilter===dg||U.minFilter===ad)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(F,n.TEXTURE_WRAP_S,oe[U.wrapS]),n.texParameteri(F,n.TEXTURE_WRAP_T,oe[U.wrapT]),(F===n.TEXTURE_3D||F===n.TEXTURE_2D_ARRAY)&&n.texParameteri(F,n.TEXTURE_WRAP_R,oe[U.wrapR]),n.texParameteri(F,n.TEXTURE_MAG_FILTER,W[U.magFilter]),n.texParameteri(F,n.TEXTURE_MIN_FILTER,W[U.minFilter]),U.compareFunction&&(n.texParameteri(F,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(F,n.TEXTURE_COMPARE_FUNC,q[U.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(U.magFilter===qa||U.minFilter!==dg&&U.minFilter!==ad||U.type===wl&&e.has("OES_texture_float_linear")===!1)return;if(U.anisotropy>1||i.get(U).__currentAnisotropy){const j=e.get("EXT_texture_filter_anisotropic");n.texParameterf(F,j.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(U.anisotropy,s.getMaxAnisotropy())),i.get(U).__currentAnisotropy=U.anisotropy}}}function te(F,U){let j=!1;F.__webglInit===void 0&&(F.__webglInit=!0,U.addEventListener("dispose",E));const se=U.source;let _e=_.get(se);_e===void 0&&(_e={},_.set(se,_e));const ge=J(U);if(ge!==F.__cacheKey){_e[ge]===void 0&&(_e[ge]={texture:n.createTexture(),usedTimes:0},l.memory.textures++,j=!0),_e[ge].usedTimes++;const Ce=_e[F.__cacheKey];Ce!==void 0&&(_e[F.__cacheKey].usedTimes--,Ce.usedTimes===0&&I(U)),F.__cacheKey=ge,F.__webglTexture=_e[ge].texture}return j}function B(F,U,j){let se=n.TEXTURE_2D;(U.isDataArrayTexture||U.isCompressedArrayTexture)&&(se=n.TEXTURE_2D_ARRAY),U.isData3DTexture&&(se=n.TEXTURE_3D);const _e=te(F,U),ge=U.source;t.bindTexture(se,F.__webglTexture,n.TEXTURE0+j);const Ce=i.get(ge);if(ge.version!==Ce.__version||_e===!0){t.activeTexture(n.TEXTURE0+j);const Ie=oi.getPrimaries(oi.workingColorSpace),Ee=U.colorSpace===Lc?null:oi.getPrimaries(U.colorSpace),je=U.colorSpace===Lc||Ie===Ee?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,U.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,U.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,U.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,je);let Qe=b(U.image,!1,s.maxTextureSize);Qe=st(U,Qe);const ot=o.convert(U.format,U.colorSpace),bt=o.convert(U.type);let _t=P(U.internalFormat,ot,bt,U.colorSpace,U.isVideoTexture);G(se,U);let nt;const ft=U.mipmaps,vt=U.isVideoTexture!==!0,mn=Ce.__version===void 0||_e===!0,Se=ge.dataReady,St=C(U,Qe);if(U.isDepthTexture)_t=w(U.format===Jm,U.type),mn&&(vt?t.texStorage2D(n.TEXTURE_2D,1,_t,Qe.width,Qe.height):t.texImage2D(n.TEXTURE_2D,0,_t,Qe.width,Qe.height,0,ot,bt,null));else if(U.isDataTexture)if(ft.length>0){vt&&mn&&t.texStorage2D(n.TEXTURE_2D,St,_t,ft[0].width,ft[0].height);for(let Ze=0,it=ft.length;Ze0){const yt=i1(nt.width,nt.height,U.format,U.type);for(const tt of U.layerUpdates){const gt=nt.data.subarray(tt*yt/nt.data.BYTES_PER_ELEMENT,(tt+1)*yt/nt.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ze,0,0,tt,nt.width,nt.height,1,ot,gt)}U.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ze,0,0,0,nt.width,nt.height,Qe.depth,ot,nt.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ze,_t,nt.width,nt.height,Qe.depth,0,nt.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else vt?Se&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ze,0,0,0,nt.width,nt.height,Qe.depth,ot,bt,nt.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ze,_t,nt.width,nt.height,Qe.depth,0,ot,bt,nt.data)}else{vt&&mn&&t.texStorage2D(n.TEXTURE_2D,St,_t,ft[0].width,ft[0].height);for(let Ze=0,it=ft.length;Ze0){const Ze=i1(Qe.width,Qe.height,U.format,U.type);for(const it of U.layerUpdates){const yt=Qe.data.subarray(it*Ze/Qe.data.BYTES_PER_ELEMENT,(it+1)*Ze/Qe.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,it,Qe.width,Qe.height,1,ot,bt,yt)}U.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Qe.width,Qe.height,Qe.depth,ot,bt,Qe.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,_t,Qe.width,Qe.height,Qe.depth,0,ot,bt,Qe.data);else if(U.isData3DTexture)vt?(mn&&t.texStorage3D(n.TEXTURE_3D,St,_t,Qe.width,Qe.height,Qe.depth),Se&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Qe.width,Qe.height,Qe.depth,ot,bt,Qe.data)):t.texImage3D(n.TEXTURE_3D,0,_t,Qe.width,Qe.height,Qe.depth,0,ot,bt,Qe.data);else if(U.isFramebufferTexture){if(mn)if(vt)t.texStorage2D(n.TEXTURE_2D,St,_t,Qe.width,Qe.height);else{let Ze=Qe.width,it=Qe.height;for(let yt=0;yt>=1,it>>=1}}else if(ft.length>0){if(vt&&mn){const Ze=Ke(ft[0]);t.texStorage2D(n.TEXTURE_2D,St,_t,Ze.width,Ze.height)}for(let Ze=0,it=ft.length;Ze0&&St++;const it=Ke(ot[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,St,ft,it.width,it.height)}for(let it=0;it<6;it++)if(Qe){vt?Se&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+it,0,0,0,ot[it].width,ot[it].height,_t,nt,ot[it].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+it,0,ft,ot[it].width,ot[it].height,0,_t,nt,ot[it].data);for(let yt=0;yt>ge),bt=Math.max(1,U.height>>ge);_e===n.TEXTURE_3D||_e===n.TEXTURE_2D_ARRAY?t.texImage3D(_e,ge,Ee,ot,bt,U.depth,0,Ce,Ie,null):t.texImage2D(_e,ge,Ee,ot,bt,0,Ce,Ie,null)}t.bindFramebuffer(n.FRAMEBUFFER,F),We(U)?u.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,se,_e,Qe.__webglTexture,0,Ne(U)):(_e===n.TEXTURE_2D||_e>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&_e<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,se,_e,Qe.__webglTexture,ge),t.bindFramebuffer(n.FRAMEBUFFER,null)}function me(F,U,j){if(n.bindRenderbuffer(n.RENDERBUFFER,F),U.depthBuffer){const se=U.depthTexture,_e=se&&se.isDepthTexture?se.type:null,ge=w(U.stencilBuffer,_e),Ce=U.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Ie=Ne(U);We(U)?u.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ie,ge,U.width,U.height):j?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ie,ge,U.width,U.height):n.renderbufferStorage(n.RENDERBUFFER,ge,U.width,U.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ce,n.RENDERBUFFER,F)}else{const se=U.textures;for(let _e=0;_e{delete U.__boundDepthTexture,delete U.__depthDisposeCallback,se.removeEventListener("dispose",_e)};se.addEventListener("dispose",_e),U.__depthDisposeCallback=_e}U.__boundDepthTexture=se}if(F.depthTexture&&!U.__autoAllocateDepthBuffer){if(j)throw new Error("target.depthTexture not supported in Cube render targets");xe(U.__webglFramebuffer,F)}else if(j){U.__webglDepthbuffer=[];for(let se=0;se<6;se++)if(t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer[se]),U.__webglDepthbuffer[se]===void 0)U.__webglDepthbuffer[se]=n.createRenderbuffer(),me(U.__webglDepthbuffer[se],F,!1);else{const _e=F.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ge=U.__webglDepthbuffer[se];n.bindRenderbuffer(n.RENDERBUFFER,ge),n.framebufferRenderbuffer(n.FRAMEBUFFER,_e,n.RENDERBUFFER,ge)}}else if(t.bindFramebuffer(n.FRAMEBUFFER,U.__webglFramebuffer),U.__webglDepthbuffer===void 0)U.__webglDepthbuffer=n.createRenderbuffer(),me(U.__webglDepthbuffer,F,!1);else{const se=F.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,_e=U.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,_e),n.framebufferRenderbuffer(n.FRAMEBUFFER,se,n.RENDERBUFFER,_e)}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Me(F,U,j){const se=i.get(F);U!==void 0&&ye(se.__webglFramebuffer,F,F.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),j!==void 0&&ze(F)}function ce(F){const U=F.texture,j=i.get(F),se=i.get(U);F.addEventListener("dispose",A);const _e=F.textures,ge=F.isWebGLCubeRenderTarget===!0,Ce=_e.length>1;if(Ce||(se.__webglTexture===void 0&&(se.__webglTexture=n.createTexture()),se.__version=U.version,l.memory.textures++),ge){j.__webglFramebuffer=[];for(let Ie=0;Ie<6;Ie++)if(U.mipmaps&&U.mipmaps.length>0){j.__webglFramebuffer[Ie]=[];for(let Ee=0;Ee0){j.__webglFramebuffer=[];for(let Ie=0;Ie0&&We(F)===!1){j.__webglMultisampledFramebuffer=n.createFramebuffer(),j.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,j.__webglMultisampledFramebuffer);for(let Ie=0;Ie<_e.length;Ie++){const Ee=_e[Ie];j.__webglColorRenderbuffer[Ie]=n.createRenderbuffer(),n.bindRenderbuffer(n.RENDERBUFFER,j.__webglColorRenderbuffer[Ie]);const je=o.convert(Ee.format,Ee.colorSpace),Qe=o.convert(Ee.type),ot=P(Ee.internalFormat,je,Qe,Ee.colorSpace,F.isXRRenderTarget===!0),bt=Ne(F);n.renderbufferStorageMultisample(n.RENDERBUFFER,bt,ot,F.width,F.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+Ie,n.RENDERBUFFER,j.__webglColorRenderbuffer[Ie])}n.bindRenderbuffer(n.RENDERBUFFER,null),F.depthBuffer&&(j.__webglDepthRenderbuffer=n.createRenderbuffer(),me(j.__webglDepthRenderbuffer,F,!0)),t.bindFramebuffer(n.FRAMEBUFFER,null)}}if(ge){t.bindTexture(n.TEXTURE_CUBE_MAP,se.__webglTexture),G(n.TEXTURE_CUBE_MAP,U);for(let Ie=0;Ie<6;Ie++)if(U.mipmaps&&U.mipmaps.length>0)for(let Ee=0;Ee0)for(let Ee=0;Ee0){if(We(F)===!1){const U=F.textures,j=F.width,se=F.height;let _e=n.COLOR_BUFFER_BIT;const ge=F.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Ce=i.get(F),Ie=U.length>1;if(Ie)for(let Ee=0;Ee0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&U.__useRenderToTexture!==!1}function ke(F){const U=l.render.frame;m.get(F)!==U&&(m.set(F,U),F.update())}function st(F,U){const j=F.colorSpace,se=F.format,_e=F.type;return F.isCompressedTexture===!0||F.isVideoTexture===!0||j!==_h&&j!==Lc&&(oi.getTransfer(j)===Si?(se!==Wa||_e!==Sl)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",j)),U}function Ke(F){return typeof HTMLImageElement<"u"&&F instanceof HTMLImageElement?(f.width=F.naturalWidth||F.width,f.height=F.naturalHeight||F.height):typeof VideoFrame<"u"&&F instanceof VideoFrame?(f.width=F.displayWidth,f.height=F.displayHeight):(f.width=F.width,f.height=F.height),f}this.allocateTextureUnit=$,this.resetTextureUnits=Z,this.setTexture2D=ee,this.setTexture2DArray=X,this.setTexture3D=ne,this.setTextureCube=Q,this.rebindTextures=Me,this.setupRenderTarget=ce,this.updateRenderTargetMipmap=ae,this.updateMultisampleRenderTarget=He,this.setupDepthRenderbuffer=ze,this.setupFrameBufferTexture=ye,this.useMultisampledRTT=We}function Gz(n,e){function t(i,s=Lc){let o;const l=oi.getTransfer(s);if(i===Sl)return n.UNSIGNED_BYTE;if(i===eb)return n.UNSIGNED_SHORT_4_4_4_4;if(i===tb)return n.UNSIGNED_SHORT_5_5_5_1;if(i===NC)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===FC)return n.BYTE;if(i===kC)return n.SHORT;if(i===Ym)return n.UNSIGNED_SHORT;if(i===JM)return n.INT;if(i===ud)return n.UNSIGNED_INT;if(i===wl)return n.FLOAT;if(i===t_)return n.HALF_FLOAT;if(i===zC)return n.ALPHA;if(i===UC)return n.RGB;if(i===Wa)return n.RGBA;if(i===BC)return n.LUMINANCE;if(i===$C)return n.LUMINANCE_ALPHA;if(i===Zm)return n.DEPTH_COMPONENT;if(i===Jm)return n.DEPTH_STENCIL;if(i===VC)return n.RED;if(i===nb)return n.RED_INTEGER;if(i===GC)return n.RG;if(i===ib)return n.RG_INTEGER;if(i===rb)return n.RGBA_INTEGER;if(i===Ng||i===zg||i===Ug||i===Bg)if(l===Si)if(o=e.get("WEBGL_compressed_texture_s3tc_srgb"),o!==null){if(i===Ng)return o.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===zg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Ug)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Bg)return o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(o=e.get("WEBGL_compressed_texture_s3tc"),o!==null){if(i===Ng)return o.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===zg)return o.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Ug)return o.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Bg)return o.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Wy||i===Hy||i===qy||i===Xy)if(o=e.get("WEBGL_compressed_texture_pvrtc"),o!==null){if(i===Wy)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Hy)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===qy)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Xy)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Ky||i===Yy||i===Qy)if(o=e.get("WEBGL_compressed_texture_etc"),o!==null){if(i===Ky||i===Yy)return l===Si?o.COMPRESSED_SRGB8_ETC2:o.COMPRESSED_RGB8_ETC2;if(i===Qy)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:o.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Zy||i===Jy||i===eM||i===tM||i===nM||i===iM||i===rM||i===sM||i===aM||i===oM||i===lM||i===cM||i===uM||i===dM)if(o=e.get("WEBGL_compressed_texture_astc"),o!==null){if(i===Zy)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:o.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Jy)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:o.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===eM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:o.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===tM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:o.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===nM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:o.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===iM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:o.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===rM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:o.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===sM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:o.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===aM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:o.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===oM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:o.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===lM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:o.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===cM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:o.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===uM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:o.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===dM)return l===Si?o.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:o.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===$g||i===fM||i===hM)if(o=e.get("EXT_texture_compression_bptc"),o!==null){if(i===$g)return l===Si?o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:o.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===fM)return o.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===hM)return o.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===jC||i===pM||i===mM||i===_M)if(o=e.get("EXT_texture_compression_rgtc"),o!==null){if(i===$g)return o.COMPRESSED_RED_RGTC1_EXT;if(i===pM)return o.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===mM)return o.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===_M)return o.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Qm?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const jz=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,Wz=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`;class Hz{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,i){if(this.texture===null){const s=new vs,o=e.properties.get(s);o.__webglTexture=t.texture,(t.depthNear!==i.depthNear||t.depthFar!==i.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=s}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Uc({vertexShader:jz,fragmentShader:Wz,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Os(new vh(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class qz extends xh{constructor(e,t){super();const i=this;let s=null,o=1,l=null,u="local-floor",d=1,f=null,m=null,h=null,_=null,g=null,y=null;const b=new Hz,T=t.getContextAttributes();let v=null,x=null;const P=[],w=[],C=new bn;let E=null;const A=new ua;A.viewport=new fr;const L=new ua;L.viewport=new fr;const I=[A,L],O=new pL;let H=null,Z=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(B){let le=P[B];return le===void 0&&(le=new Zv,P[B]=le),le.getTargetRaySpace()},this.getControllerGrip=function(B){let le=P[B];return le===void 0&&(le=new Zv,P[B]=le),le.getGripSpace()},this.getHand=function(B){let le=P[B];return le===void 0&&(le=new Zv,P[B]=le),le.getHandSpace()};function $(B){const le=w.indexOf(B.inputSource);if(le===-1)return;const ye=P[le];ye!==void 0&&(ye.update(B.inputSource,B.frame,f||l),ye.dispatchEvent({type:B.type,data:B.inputSource}))}function J(){s.removeEventListener("select",$),s.removeEventListener("selectstart",$),s.removeEventListener("selectend",$),s.removeEventListener("squeeze",$),s.removeEventListener("squeezestart",$),s.removeEventListener("squeezeend",$),s.removeEventListener("end",J),s.removeEventListener("inputsourceschange",ee);for(let B=0;B=0&&(w[me]=null,P[me].disconnect(ye))}for(let le=0;le=w.length){w.push(ye),me=ze;break}else if(w[ze]===null){w[ze]=ye,me=ze;break}if(me===-1)break}const xe=P[me];xe&&xe.connect(ye)}}const X=new Ge,ne=new Ge;function Q(B,le,ye){X.setFromMatrixPosition(le.matrixWorld),ne.setFromMatrixPosition(ye.matrixWorld);const me=X.distanceTo(ne),xe=le.projectionMatrix.elements,ze=ye.projectionMatrix.elements,Me=xe[14]/(xe[10]-1),ce=xe[14]/(xe[10]+1),ae=(xe[9]+1)/xe[5],we=(xe[9]-1)/xe[5],re=(xe[8]-1)/xe[0],He=(ze[8]+1)/ze[0],Ne=Me*re,We=Me*He,ke=me/(-re+He),st=ke*-re;if(le.matrixWorld.decompose(B.position,B.quaternion,B.scale),B.translateX(st),B.translateZ(ke),B.matrixWorld.compose(B.position,B.quaternion,B.scale),B.matrixWorldInverse.copy(B.matrixWorld).invert(),xe[10]===-1)B.projectionMatrix.copy(le.projectionMatrix),B.projectionMatrixInverse.copy(le.projectionMatrixInverse);else{const Ke=Me+ke,F=ce+ke,U=Ne-st,j=We+(me-st),se=ae*ce/F*Ke,_e=we*ce/F*Ke;B.projectionMatrix.makePerspective(U,j,se,_e,Ke,F),B.projectionMatrixInverse.copy(B.projectionMatrix).invert()}}function oe(B,le){le===null?B.matrixWorld.copy(B.matrix):B.matrixWorld.multiplyMatrices(le.matrixWorld,B.matrix),B.matrixWorldInverse.copy(B.matrixWorld).invert()}this.updateCamera=function(B){if(s===null)return;let le=B.near,ye=B.far;b.texture!==null&&(b.depthNear>0&&(le=b.depthNear),b.depthFar>0&&(ye=b.depthFar)),O.near=L.near=A.near=le,O.far=L.far=A.far=ye,(H!==O.near||Z!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),H=O.near,Z=O.far),A.layers.mask=B.layers.mask|2,L.layers.mask=B.layers.mask|4,O.layers.mask=A.layers.mask|L.layers.mask;const me=B.parent,xe=O.cameras;oe(O,me);for(let ze=0;ze0&&(T.alphaTest.value=v.alphaTest);const x=e.get(v),P=x.envMap,w=x.envMapRotation;P&&(T.envMap.value=P,Yu.copy(w),Yu.x*=-1,Yu.y*=-1,Yu.z*=-1,P.isCubeTexture&&P.isRenderTargetTexture===!1&&(Yu.y*=-1,Yu.z*=-1),T.envMapRotation.value.setFromMatrix4(Xz.makeRotationFromEuler(Yu)),T.flipEnvMap.value=P.isCubeTexture&&P.isRenderTargetTexture===!1?-1:1,T.reflectivity.value=v.reflectivity,T.ior.value=v.ior,T.refractionRatio.value=v.refractionRatio),v.lightMap&&(T.lightMap.value=v.lightMap,T.lightMapIntensity.value=v.lightMapIntensity,t(v.lightMap,T.lightMapTransform)),v.aoMap&&(T.aoMap.value=v.aoMap,T.aoMapIntensity.value=v.aoMapIntensity,t(v.aoMap,T.aoMapTransform))}function l(T,v){T.diffuse.value.copy(v.color),T.opacity.value=v.opacity,v.map&&(T.map.value=v.map,t(v.map,T.mapTransform))}function u(T,v){T.dashSize.value=v.dashSize,T.totalSize.value=v.dashSize+v.gapSize,T.scale.value=v.scale}function d(T,v,x,P){T.diffuse.value.copy(v.color),T.opacity.value=v.opacity,T.size.value=v.size*x,T.scale.value=P*.5,v.map&&(T.map.value=v.map,t(v.map,T.uvTransform)),v.alphaMap&&(T.alphaMap.value=v.alphaMap,t(v.alphaMap,T.alphaMapTransform)),v.alphaTest>0&&(T.alphaTest.value=v.alphaTest)}function f(T,v){T.diffuse.value.copy(v.color),T.opacity.value=v.opacity,T.rotation.value=v.rotation,v.map&&(T.map.value=v.map,t(v.map,T.mapTransform)),v.alphaMap&&(T.alphaMap.value=v.alphaMap,t(v.alphaMap,T.alphaMapTransform)),v.alphaTest>0&&(T.alphaTest.value=v.alphaTest)}function m(T,v){T.specular.value.copy(v.specular),T.shininess.value=Math.max(v.shininess,1e-4)}function h(T,v){v.gradientMap&&(T.gradientMap.value=v.gradientMap)}function _(T,v){T.metalness.value=v.metalness,v.metalnessMap&&(T.metalnessMap.value=v.metalnessMap,t(v.metalnessMap,T.metalnessMapTransform)),T.roughness.value=v.roughness,v.roughnessMap&&(T.roughnessMap.value=v.roughnessMap,t(v.roughnessMap,T.roughnessMapTransform)),v.envMap&&(T.envMapIntensity.value=v.envMapIntensity)}function g(T,v,x){T.ior.value=v.ior,v.sheen>0&&(T.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),T.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(T.sheenColorMap.value=v.sheenColorMap,t(v.sheenColorMap,T.sheenColorMapTransform)),v.sheenRoughnessMap&&(T.sheenRoughnessMap.value=v.sheenRoughnessMap,t(v.sheenRoughnessMap,T.sheenRoughnessMapTransform))),v.clearcoat>0&&(T.clearcoat.value=v.clearcoat,T.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(T.clearcoatMap.value=v.clearcoatMap,t(v.clearcoatMap,T.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(T.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,t(v.clearcoatRoughnessMap,T.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(T.clearcoatNormalMap.value=v.clearcoatNormalMap,t(v.clearcoatNormalMap,T.clearcoatNormalMapTransform),T.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===gs&&T.clearcoatNormalScale.value.negate())),v.dispersion>0&&(T.dispersion.value=v.dispersion),v.iridescence>0&&(T.iridescence.value=v.iridescence,T.iridescenceIOR.value=v.iridescenceIOR,T.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],T.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(T.iridescenceMap.value=v.iridescenceMap,t(v.iridescenceMap,T.iridescenceMapTransform)),v.iridescenceThicknessMap&&(T.iridescenceThicknessMap.value=v.iridescenceThicknessMap,t(v.iridescenceThicknessMap,T.iridescenceThicknessMapTransform))),v.transmission>0&&(T.transmission.value=v.transmission,T.transmissionSamplerMap.value=x.texture,T.transmissionSamplerSize.value.set(x.width,x.height),v.transmissionMap&&(T.transmissionMap.value=v.transmissionMap,t(v.transmissionMap,T.transmissionMapTransform)),T.thickness.value=v.thickness,v.thicknessMap&&(T.thicknessMap.value=v.thicknessMap,t(v.thicknessMap,T.thicknessMapTransform)),T.attenuationDistance.value=v.attenuationDistance,T.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(T.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(T.anisotropyMap.value=v.anisotropyMap,t(v.anisotropyMap,T.anisotropyMapTransform))),T.specularIntensity.value=v.specularIntensity,T.specularColor.value.copy(v.specularColor),v.specularColorMap&&(T.specularColorMap.value=v.specularColorMap,t(v.specularColorMap,T.specularColorMapTransform)),v.specularIntensityMap&&(T.specularIntensityMap.value=v.specularIntensityMap,t(v.specularIntensityMap,T.specularIntensityMapTransform))}function y(T,v){v.matcap&&(T.matcap.value=v.matcap)}function b(T,v){const x=e.get(v).light;T.referencePosition.value.setFromMatrixPosition(x.matrixWorld),T.nearDistance.value=x.shadow.camera.near,T.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function Yz(n,e,t,i){let s={},o={},l=[];const u=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function d(x,P){const w=P.program;i.uniformBlockBinding(x,w)}function f(x,P){let w=s[x.id];w===void 0&&(y(x),w=m(x),s[x.id]=w,x.addEventListener("dispose",T));const C=P.program;i.updateUBOMapping(x,C);const E=e.render.frame;o[x.id]!==E&&(_(x),o[x.id]=E)}function m(x){const P=h();x.__bindingPointIndex=P;const w=n.createBuffer(),C=x.__size,E=x.usage;return n.bindBuffer(n.UNIFORM_BUFFER,w),n.bufferData(n.UNIFORM_BUFFER,C,E),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,P,w),w}function h(){for(let x=0;x0&&(w+=C-E),x.__size=w,x.__cache={},this}function b(x){const P={boundary:0,storage:0};return typeof x=="number"||typeof x=="boolean"?(P.boundary=4,P.storage=4):x.isVector2?(P.boundary=8,P.storage=8):x.isVector3||x.isColor?(P.boundary=16,P.storage=12):x.isVector4?(P.boundary=16,P.storage=16):x.isMatrix3?(P.boundary=48,P.storage=48):x.isMatrix4?(P.boundary=64,P.storage=64):x.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",x),P}function T(x){const P=x.target;P.removeEventListener("dispose",T);const w=l.indexOf(P.__bindingPointIndex);l.splice(w,1),n.deleteBuffer(s[P.id]),delete s[P.id],delete o[P.id]}function v(){for(const x in s)n.deleteBuffer(s[x]);l=[],s={},o={}}return{bind:d,update:f,dispose:v}}class Qz{constructor(e={}){const{canvas:t=gO(),context:i=null,depth:s=!0,stencil:o=!1,alpha:l=!1,antialias:u=!1,premultipliedAlpha:d=!0,preserveDrawingBuffer:f=!1,powerPreference:m="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:_=!1}=e;this.isWebGLRenderer=!0;let g;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=i.getContextAttributes().alpha}else g=l;const y=new Uint32Array(4),b=new Int32Array(4);let T=null,v=null;const x=[],P=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=kc,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const w=this;let C=!1;this._outputColorSpace=ca;let E=0,A=0,L=null,I=-1,O=null;const H=new fr,Z=new fr;let $=null;const J=new wi(0);let ee=0,X=t.width,ne=t.height,Q=1,oe=null,W=null;const q=new fr(0,0,X,ne),G=new fr(0,0,X,ne);let te=!1;const B=new tP;let le=!1,ye=!1;const me=new hr,xe=new hr,ze=new Ge,Me=new fr,ce={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let ae=!1;function we(){return L===null?Q:1}let re=i;function He(ue,Oe){return t.getContext(ue,Oe)}try{const ue={alpha:!0,depth:s,stencil:o,antialias:u,premultipliedAlpha:d,preserveDrawingBuffer:f,powerPreference:m,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${ZM}`),t.addEventListener("webglcontextlost",it,!1),t.addEventListener("webglcontextrestored",yt,!1),t.addEventListener("webglcontextcreationerror",tt,!1),re===null){const Oe="webgl2";if(re=He(Oe,ue),re===null)throw He(Oe)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(ue){throw console.error("THREE.WebGLRenderer: "+ue.message),ue}let Ne,We,ke,st,Ke,F,U,j,se,_e,ge,Ce,Ie,Ee,je,Qe,ot,bt,_t,nt,ft,vt,mn,Se;function St(){Ne=new oN(re),Ne.init(),vt=new Gz(re,Ne),We=new eN(re,Ne,e,vt),ke=new $z(re,Ne),We.reverseDepthBuffer&&_&&ke.buffers.depth.setReversed(!0),st=new uN(re),Ke=new Cz,F=new Vz(re,Ne,ke,Ke,We,vt,st),U=new nN(w),j=new aN(w),se=new _L(re),mn=new Zk(re,se),_e=new lN(re,se,st,mn),ge=new fN(re,_e,se,st),_t=new dN(re,We,F),Qe=new tN(Ke),Ce=new Az(w,U,j,Ne,We,mn,Qe),Ie=new Kz(w,Ke),Ee=new Rz,je=new kz(Ne),bt=new Qk(w,U,j,ke,ge,g,d),ot=new Uz(w,ge,We),Se=new Yz(re,st,We,ke),nt=new Jk(re,Ne,st),ft=new cN(re,Ne,st),st.programs=Ce.programs,w.capabilities=We,w.extensions=Ne,w.properties=Ke,w.renderLists=Ee,w.shadowMap=ot,w.state=ke,w.info=st}St();const Ze=new qz(w,re);this.xr=Ze,this.getContext=function(){return re},this.getContextAttributes=function(){return re.getContextAttributes()},this.forceContextLoss=function(){const ue=Ne.get("WEBGL_lose_context");ue&&ue.loseContext()},this.forceContextRestore=function(){const ue=Ne.get("WEBGL_lose_context");ue&&ue.restoreContext()},this.getPixelRatio=function(){return Q},this.setPixelRatio=function(ue){ue!==void 0&&(Q=ue,this.setSize(X,ne,!1))},this.getSize=function(ue){return ue.set(X,ne)},this.setSize=function(ue,Oe,qe=!0){if(Ze.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}X=ue,ne=Oe,t.width=Math.floor(ue*Q),t.height=Math.floor(Oe*Q),qe===!0&&(t.style.width=ue+"px",t.style.height=Oe+"px"),this.setViewport(0,0,ue,Oe)},this.getDrawingBufferSize=function(ue){return ue.set(X*Q,ne*Q).floor()},this.setDrawingBufferSize=function(ue,Oe,qe){X=ue,ne=Oe,Q=qe,t.width=Math.floor(ue*qe),t.height=Math.floor(Oe*qe),this.setViewport(0,0,ue,Oe)},this.getCurrentViewport=function(ue){return ue.copy(H)},this.getViewport=function(ue){return ue.copy(q)},this.setViewport=function(ue,Oe,qe,Ue){ue.isVector4?q.set(ue.x,ue.y,ue.z,ue.w):q.set(ue,Oe,qe,Ue),ke.viewport(H.copy(q).multiplyScalar(Q).round())},this.getScissor=function(ue){return ue.copy(G)},this.setScissor=function(ue,Oe,qe,Ue){ue.isVector4?G.set(ue.x,ue.y,ue.z,ue.w):G.set(ue,Oe,qe,Ue),ke.scissor(Z.copy(G).multiplyScalar(Q).round())},this.getScissorTest=function(){return te},this.setScissorTest=function(ue){ke.setScissorTest(te=ue)},this.setOpaqueSort=function(ue){oe=ue},this.setTransparentSort=function(ue){W=ue},this.getClearColor=function(ue){return ue.copy(bt.getClearColor())},this.setClearColor=function(){bt.setClearColor(...arguments)},this.getClearAlpha=function(){return bt.getClearAlpha()},this.setClearAlpha=function(){bt.setClearAlpha(...arguments)},this.clear=function(ue=!0,Oe=!0,qe=!0){let Ue=0;if(ue){let Fe=!1;if(L!==null){const wt=L.texture.format;Fe=wt===rb||wt===ib||wt===nb}if(Fe){const wt=L.texture.type,Ct=wt===Sl||wt===ud||wt===Ym||wt===Qm||wt===eb||wt===tb,Nt=bt.getClearColor(),Rt=bt.getClearAlpha(),qt=Nt.r,sn=Nt.g,Jt=Nt.b;Ct?(y[0]=qt,y[1]=sn,y[2]=Jt,y[3]=Rt,re.clearBufferuiv(re.COLOR,0,y)):(b[0]=qt,b[1]=sn,b[2]=Jt,b[3]=Rt,re.clearBufferiv(re.COLOR,0,b))}else Ue|=re.COLOR_BUFFER_BIT}Oe&&(Ue|=re.DEPTH_BUFFER_BIT),qe&&(Ue|=re.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),re.clear(Ue)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",it,!1),t.removeEventListener("webglcontextrestored",yt,!1),t.removeEventListener("webglcontextcreationerror",tt,!1),bt.dispose(),Ee.dispose(),je.dispose(),Ke.dispose(),U.dispose(),j.dispose(),ge.dispose(),mn.dispose(),Se.dispose(),Ce.dispose(),Ze.dispose(),Ze.removeEventListener("sessionstart",vi),Ze.removeEventListener("sessionend",On),ut.stop()};function it(ue){ue.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),C=!0}function yt(){console.log("THREE.WebGLRenderer: Context Restored."),C=!1;const ue=st.autoReset,Oe=ot.enabled,qe=ot.autoUpdate,Ue=ot.needsUpdate,Fe=ot.type;St(),st.autoReset=ue,ot.enabled=Oe,ot.autoUpdate=qe,ot.needsUpdate=Ue,ot.type=Fe}function tt(ue){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",ue.statusMessage)}function gt(ue){const Oe=ue.target;Oe.removeEventListener("dispose",gt),Pt(Oe)}function Pt(ue){tn(ue),Ke.remove(ue)}function tn(ue){const Oe=Ke.get(ue).programs;Oe!==void 0&&(Oe.forEach(function(qe){Ce.releaseProgram(qe)}),ue.isShaderMaterial&&Ce.releaseShaderCache(ue))}this.renderBufferDirect=function(ue,Oe,qe,Ue,Fe,wt){Oe===null&&(Oe=ce);const Ct=Fe.isMesh&&Fe.matrixWorld.determinant()<0,Nt=Ns(ue,Oe,qe,Ue,Fe);ke.setMaterial(Ue,Ct);let Rt=qe.index,qt=1;if(Ue.wireframe===!0){if(Rt=_e.getWireframeAttribute(qe),Rt===void 0)return;qt=2}const sn=qe.drawRange,Jt=qe.attributes.position;let yn=sn.start*qt,Sn=(sn.start+sn.count)*qt;wt!==null&&(yn=Math.max(yn,wt.start*qt),Sn=Math.min(Sn,(wt.start+wt.count)*qt)),Rt!==null?(yn=Math.max(yn,0),Sn=Math.min(Sn,Rt.count)):Jt!=null&&(yn=Math.max(yn,0),Sn=Math.min(Sn,Jt.count));const Jn=Sn-yn;if(Jn<0||Jn===1/0)return;mn.setup(Fe,Ue,Nt,qe,Rt);let Ln,dn=nt;if(Rt!==null&&(Ln=se.get(Rt),dn=ft,dn.setIndex(Ln)),Fe.isMesh)Ue.wireframe===!0?(ke.setLineWidth(Ue.wireframeLinewidth*we()),dn.setMode(re.LINES)):dn.setMode(re.TRIANGLES);else if(Fe.isLine){let nn=Ue.linewidth;nn===void 0&&(nn=1),ke.setLineWidth(nn*we()),Fe.isLineSegments?dn.setMode(re.LINES):Fe.isLineLoop?dn.setMode(re.LINE_LOOP):dn.setMode(re.LINE_STRIP)}else Fe.isPoints?dn.setMode(re.POINTS):Fe.isSprite&&dn.setMode(re.TRIANGLES);if(Fe.isBatchedMesh)if(Fe._multiDrawInstances!==null)Vg("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),dn.renderMultiDrawInstances(Fe._multiDrawStarts,Fe._multiDrawCounts,Fe._multiDrawCount,Fe._multiDrawInstances);else if(Ne.get("WEBGL_multi_draw"))dn.renderMultiDraw(Fe._multiDrawStarts,Fe._multiDrawCounts,Fe._multiDrawCount);else{const nn=Fe._multiDrawStarts,li=Fe._multiDrawCounts,An=Fe._multiDrawCount,sr=Rt?se.get(Rt).bytesPerElement:1,yr=Ke.get(Ue).currentProgram.getUniforms();for(let Xi=0;Xi{function wt(){if(Ue.forEach(function(Ct){Ke.get(Ct).currentProgram.isReady()&&Ue.delete(Ct)}),Ue.size===0){Fe(ue);return}setTimeout(wt,10)}Ne.get("KHR_parallel_shader_compile")!==null?wt():setTimeout(wt,10)})};let Pn=null;function ln(ue){Pn&&Pn(ue)}function vi(){ut.stop()}function On(){ut.start()}const ut=new sP;ut.setAnimationLoop(ln),typeof self<"u"&&ut.setContext(self),this.setAnimationLoop=function(ue){Pn=ue,Ze.setAnimationLoop(ue),ue===null?ut.stop():ut.start()},Ze.addEventListener("sessionstart",vi),Ze.addEventListener("sessionend",On),this.render=function(ue,Oe){if(Oe!==void 0&&Oe.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(C===!0)return;if(ue.matrixWorldAutoUpdate===!0&&ue.updateMatrixWorld(),Oe.parent===null&&Oe.matrixWorldAutoUpdate===!0&&Oe.updateMatrixWorld(),Ze.enabled===!0&&Ze.isPresenting===!0&&(Ze.cameraAutoUpdate===!0&&Ze.updateCamera(Oe),Oe=Ze.getCamera()),ue.isScene===!0&&ue.onBeforeRender(w,ue,Oe,L),v=je.get(ue,P.length),v.init(Oe),P.push(v),xe.multiplyMatrices(Oe.projectionMatrix,Oe.matrixWorldInverse),B.setFromProjectionMatrix(xe),ye=this.localClippingEnabled,le=Qe.init(this.clippingPlanes,ye),T=Ee.get(ue,x.length),T.init(),x.push(T),Ze.enabled===!0&&Ze.isPresenting===!0){const wt=w.xr.getDepthSensingMesh();wt!==null&&It(wt,Oe,-1/0,w.sortObjects)}It(ue,Oe,0,w.sortObjects),T.finish(),w.sortObjects===!0&&T.sort(oe,W),ae=Ze.enabled===!1||Ze.isPresenting===!1||Ze.hasDepthSensing()===!1,ae&&bt.addToRenderList(T,ue),this.info.render.frame++,le===!0&&Qe.beginShadows();const qe=v.state.shadowsArray;ot.render(qe,ue,Oe),le===!0&&Qe.endShadows(),this.info.autoReset===!0&&this.info.reset();const Ue=T.opaque,Fe=T.transmissive;if(v.setupLights(),Oe.isArrayCamera){const wt=Oe.cameras;if(Fe.length>0)for(let Ct=0,Nt=wt.length;Ct0&&Vi(Ue,Fe,ue,Oe),ae&&bt.render(ue),Bt(T,ue,Oe);L!==null&&A===0&&(F.updateMultisampleRenderTarget(L),F.updateRenderTargetMipmap(L)),ue.isScene===!0&&ue.onAfterRender(w,ue,Oe),mn.resetDefaultState(),I=-1,O=null,P.pop(),P.length>0?(v=P[P.length-1],le===!0&&Qe.setGlobalState(w.clippingPlanes,v.state.camera)):v=null,x.pop(),x.length>0?T=x[x.length-1]:T=null};function It(ue,Oe,qe,Ue){if(ue.visible===!1)return;if(ue.layers.test(Oe.layers)){if(ue.isGroup)qe=ue.renderOrder;else if(ue.isLOD)ue.autoUpdate===!0&&ue.update(Oe);else if(ue.isLight)v.pushLight(ue),ue.castShadow&&v.pushShadow(ue);else if(ue.isSprite){if(!ue.frustumCulled||B.intersectsSprite(ue)){Ue&&Me.setFromMatrixPosition(ue.matrixWorld).applyMatrix4(xe);const Ct=ge.update(ue),Nt=ue.material;Nt.visible&&T.push(ue,Ct,Nt,qe,Me.z,null)}}else if((ue.isMesh||ue.isLine||ue.isPoints)&&(!ue.frustumCulled||B.intersectsObject(ue))){const Ct=ge.update(ue),Nt=ue.material;if(Ue&&(ue.boundingSphere!==void 0?(ue.boundingSphere===null&&ue.computeBoundingSphere(),Me.copy(ue.boundingSphere.center)):(Ct.boundingSphere===null&&Ct.computeBoundingSphere(),Me.copy(Ct.boundingSphere.center)),Me.applyMatrix4(ue.matrixWorld).applyMatrix4(xe)),Array.isArray(Nt)){const Rt=Ct.groups;for(let qt=0,sn=Rt.length;qt0&&rr(Fe,Oe,qe),wt.length>0&&rr(wt,Oe,qe),Ct.length>0&&rr(Ct,Oe,qe),ke.buffers.depth.setTest(!0),ke.buffers.depth.setMask(!0),ke.buffers.color.setMask(!0),ke.setPolygonOffset(!1)}function Vi(ue,Oe,qe,Ue){if((qe.isScene===!0?qe.overrideMaterial:null)!==null)return;v.state.transmissionRenderTarget[Ue.id]===void 0&&(v.state.transmissionRenderTarget[Ue.id]=new dd(1,1,{generateMipmaps:!0,type:Ne.has("EXT_color_buffer_half_float")||Ne.has("EXT_color_buffer_float")?t_:Sl,minFilter:ad,samples:4,stencilBuffer:o,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:oi.workingColorSpace}));const wt=v.state.transmissionRenderTarget[Ue.id],Ct=Ue.viewport||H;wt.setSize(Ct.z*w.transmissionResolutionScale,Ct.w*w.transmissionResolutionScale);const Nt=w.getRenderTarget();w.setRenderTarget(wt),w.getClearColor(J),ee=w.getClearAlpha(),ee<1&&w.setClearColor(16777215,.5),w.clear(),ae&&bt.render(qe);const Rt=w.toneMapping;w.toneMapping=kc;const qt=Ue.viewport;if(Ue.viewport!==void 0&&(Ue.viewport=void 0),v.setupLightsView(Ue),le===!0&&Qe.setGlobalState(w.clippingPlanes,Ue),rr(ue,qe,Ue),F.updateMultisampleRenderTarget(wt),F.updateRenderTargetMipmap(wt),Ne.has("WEBGL_multisampled_render_to_texture")===!1){let sn=!1;for(let Jt=0,yn=Oe.length;Jt0),Jt=!!qe.morphAttributes.position,yn=!!qe.morphAttributes.normal,Sn=!!qe.morphAttributes.color;let Jn=kc;Ue.toneMapped&&(L===null||L.isXRRenderTarget===!0)&&(Jn=w.toneMapping);const Ln=qe.morphAttributes.position||qe.morphAttributes.normal||qe.morphAttributes.color,dn=Ln!==void 0?Ln.length:0,nn=Ke.get(Ue),li=v.state.lights;if(le===!0&&(ye===!0||ue!==O)){const fe=ue===O&&Ue.id===I;Qe.setState(Ue,ue,fe)}let An=!1;Ue.version===nn.__version?(nn.needsLights&&nn.lightsStateVersion!==li.state.version||nn.outputColorSpace!==Nt||Fe.isBatchedMesh&&nn.batching===!1||!Fe.isBatchedMesh&&nn.batching===!0||Fe.isBatchedMesh&&nn.batchingColor===!0&&Fe.colorTexture===null||Fe.isBatchedMesh&&nn.batchingColor===!1&&Fe.colorTexture!==null||Fe.isInstancedMesh&&nn.instancing===!1||!Fe.isInstancedMesh&&nn.instancing===!0||Fe.isSkinnedMesh&&nn.skinning===!1||!Fe.isSkinnedMesh&&nn.skinning===!0||Fe.isInstancedMesh&&nn.instancingColor===!0&&Fe.instanceColor===null||Fe.isInstancedMesh&&nn.instancingColor===!1&&Fe.instanceColor!==null||Fe.isInstancedMesh&&nn.instancingMorph===!0&&Fe.morphTexture===null||Fe.isInstancedMesh&&nn.instancingMorph===!1&&Fe.morphTexture!==null||nn.envMap!==Rt||Ue.fog===!0&&nn.fog!==wt||nn.numClippingPlanes!==void 0&&(nn.numClippingPlanes!==Qe.numPlanes||nn.numIntersection!==Qe.numIntersection)||nn.vertexAlphas!==qt||nn.vertexTangents!==sn||nn.morphTargets!==Jt||nn.morphNormals!==yn||nn.morphColors!==Sn||nn.toneMapping!==Jn||nn.morphTargetsCount!==dn)&&(An=!0):(An=!0,nn.__version=Ue.version);let sr=nn.currentProgram;An===!0&&(sr=Ti(Ue,Oe,Fe));let yr=!1,Xi=!1,yi=!1;const Kn=sr.getUniforms(),Pe=nn.uniforms;if(ke.useProgram(sr.program)&&(yr=!0,Xi=!0,yi=!0),Ue.id!==I&&(I=Ue.id,Xi=!0),yr||O!==ue){ke.buffers.depth.getReversed()?(me.copy(ue.projectionMatrix),yO(me),MO(me),Kn.setValue(re,"projectionMatrix",me)):Kn.setValue(re,"projectionMatrix",ue.projectionMatrix),Kn.setValue(re,"viewMatrix",ue.matrixWorldInverse);const ve=Kn.map.cameraPosition;ve!==void 0&&ve.setValue(re,ze.setFromMatrixPosition(ue.matrixWorld)),We.logarithmicDepthBuffer&&Kn.setValue(re,"logDepthBufFC",2/(Math.log(ue.far+1)/Math.LN2)),(Ue.isMeshPhongMaterial||Ue.isMeshToonMaterial||Ue.isMeshLambertMaterial||Ue.isMeshBasicMaterial||Ue.isMeshStandardMaterial||Ue.isShaderMaterial)&&Kn.setValue(re,"isOrthographic",ue.isOrthographicCamera===!0),O!==ue&&(O=ue,Xi=!0,yi=!0)}if(Fe.isSkinnedMesh){Kn.setOptional(re,Fe,"bindMatrix"),Kn.setOptional(re,Fe,"bindMatrixInverse");const fe=Fe.skeleton;fe&&(fe.boneTexture===null&&fe.computeBoneTexture(),Kn.setValue(re,"boneTexture",fe.boneTexture,F))}Fe.isBatchedMesh&&(Kn.setOptional(re,Fe,"batchingTexture"),Kn.setValue(re,"batchingTexture",Fe._matricesTexture,F),Kn.setOptional(re,Fe,"batchingIdTexture"),Kn.setValue(re,"batchingIdTexture",Fe._indirectTexture,F),Kn.setOptional(re,Fe,"batchingColorTexture"),Fe._colorsTexture!==null&&Kn.setValue(re,"batchingColorTexture",Fe._colorsTexture,F));const V=qe.morphAttributes;if((V.position!==void 0||V.normal!==void 0||V.color!==void 0)&&_t.update(Fe,qe,sr),(Xi||nn.receiveShadow!==Fe.receiveShadow)&&(nn.receiveShadow=Fe.receiveShadow,Kn.setValue(re,"receiveShadow",Fe.receiveShadow)),Ue.isMeshGouraudMaterial&&Ue.envMap!==null&&(Pe.envMap.value=Rt,Pe.flipEnvMap.value=Rt.isCubeTexture&&Rt.isRenderTargetTexture===!1?-1:1),Ue.isMeshStandardMaterial&&Ue.envMap===null&&Oe.environment!==null&&(Pe.envMapIntensity.value=Oe.environmentIntensity),Xi&&(Kn.setValue(re,"toneMappingExposure",w.toneMappingExposure),nn.needsLights&&Sr(Pe,yi),wt&&Ue.fog===!0&&Ie.refreshFogUniforms(Pe,wt),Ie.refreshMaterialUniforms(Pe,Ue,Q,ne,v.state.transmissionRenderTarget[ue.id]),Gg.upload(re,Er(nn),Pe,F)),Ue.isShaderMaterial&&Ue.uniformsNeedUpdate===!0&&(Gg.upload(re,Er(nn),Pe,F),Ue.uniformsNeedUpdate=!1),Ue.isSpriteMaterial&&Kn.setValue(re,"center",Fe.center),Kn.setValue(re,"modelViewMatrix",Fe.modelViewMatrix),Kn.setValue(re,"normalMatrix",Fe.normalMatrix),Kn.setValue(re,"modelMatrix",Fe.matrixWorld),Ue.isShaderMaterial||Ue.isRawShaderMaterial){const fe=Ue.uniformsGroups;for(let ve=0,Te=fe.length;ve0&&F.useMultisampledRTT(ue)===!1?Fe=Ke.get(ue).__webglMultisampledFramebuffer:Array.isArray(sn)?Fe=sn[qe]:Fe=sn,H.copy(ue.viewport),Z.copy(ue.scissor),$=ue.scissorTest}else H.copy(q).multiplyScalar(Q).floor(),Z.copy(G).multiplyScalar(Q).floor(),$=te;if(qe!==0&&(Fe=Ii),ke.bindFramebuffer(re.FRAMEBUFFER,Fe)&&Ue&&ke.drawBuffers(ue,Fe),ke.viewport(H),ke.scissor(Z),ke.setScissorTest($),wt){const Rt=Ke.get(ue.texture);re.framebufferTexture2D(re.FRAMEBUFFER,re.COLOR_ATTACHMENT0,re.TEXTURE_CUBE_MAP_POSITIVE_X+Oe,Rt.__webglTexture,qe)}else if(Ct){const Rt=Ke.get(ue.texture),qt=Oe;re.framebufferTextureLayer(re.FRAMEBUFFER,re.COLOR_ATTACHMENT0,Rt.__webglTexture,qe,qt)}else if(ue!==null&&qe!==0){const Rt=Ke.get(ue.texture);re.framebufferTexture2D(re.FRAMEBUFFER,re.COLOR_ATTACHMENT0,re.TEXTURE_2D,Rt.__webglTexture,qe)}I=-1},this.readRenderTargetPixels=function(ue,Oe,qe,Ue,Fe,wt,Ct){if(!(ue&&ue.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Nt=Ke.get(ue).__webglFramebuffer;if(ue.isWebGLCubeRenderTarget&&Ct!==void 0&&(Nt=Nt[Ct]),Nt){ke.bindFramebuffer(re.FRAMEBUFFER,Nt);try{const Rt=ue.texture,qt=Rt.format,sn=Rt.type;if(!We.textureFormatReadable(qt)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!We.textureTypeReadable(sn)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Oe>=0&&Oe<=ue.width-Ue&&qe>=0&&qe<=ue.height-Fe&&re.readPixels(Oe,qe,Ue,Fe,vt.convert(qt),vt.convert(sn),wt)}finally{const Rt=L!==null?Ke.get(L).__webglFramebuffer:null;ke.bindFramebuffer(re.FRAMEBUFFER,Rt)}}},this.readRenderTargetPixelsAsync=async function(ue,Oe,qe,Ue,Fe,wt,Ct){if(!(ue&&ue.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Nt=Ke.get(ue).__webglFramebuffer;if(ue.isWebGLCubeRenderTarget&&Ct!==void 0&&(Nt=Nt[Ct]),Nt)if(Oe>=0&&Oe<=ue.width-Ue&&qe>=0&&qe<=ue.height-Fe){ke.bindFramebuffer(re.FRAMEBUFFER,Nt);const Rt=ue.texture,qt=Rt.format,sn=Rt.type;if(!We.textureFormatReadable(qt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!We.textureTypeReadable(sn))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Jt=re.createBuffer();re.bindBuffer(re.PIXEL_PACK_BUFFER,Jt),re.bufferData(re.PIXEL_PACK_BUFFER,wt.byteLength,re.STREAM_READ),re.readPixels(Oe,qe,Ue,Fe,vt.convert(qt),vt.convert(sn),0);const yn=L!==null?Ke.get(L).__webglFramebuffer:null;ke.bindFramebuffer(re.FRAMEBUFFER,yn);const Sn=re.fenceSync(re.SYNC_GPU_COMMANDS_COMPLETE,0);return re.flush(),await vO(re,Sn,4),re.bindBuffer(re.PIXEL_PACK_BUFFER,Jt),re.getBufferSubData(re.PIXEL_PACK_BUFFER,0,wt),re.deleteBuffer(Jt),re.deleteSync(Sn),wt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(ue,Oe=null,qe=0){const Ue=Math.pow(2,-qe),Fe=Math.floor(ue.image.width*Ue),wt=Math.floor(ue.image.height*Ue),Ct=Oe!==null?Oe.x:0,Nt=Oe!==null?Oe.y:0;F.setTexture2D(ue,0),re.copyTexSubImage2D(re.TEXTURE_2D,qe,0,0,Ct,Nt,Fe,wt),ke.unbindTexture()};const Yr=re.createFramebuffer(),vr=re.createFramebuffer();this.copyTextureToTexture=function(ue,Oe,qe=null,Ue=null,Fe=0,wt=null){wt===null&&(Fe!==0?(Vg("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),wt=Fe,Fe=0):wt=0);let Ct,Nt,Rt,qt,sn,Jt,yn,Sn,Jn;const Ln=ue.isCompressedTexture?ue.mipmaps[wt]:ue.image;if(qe!==null)Ct=qe.max.x-qe.min.x,Nt=qe.max.y-qe.min.y,Rt=qe.isBox3?qe.max.z-qe.min.z:1,qt=qe.min.x,sn=qe.min.y,Jt=qe.isBox3?qe.min.z:0;else{const V=Math.pow(2,-Fe);Ct=Math.floor(Ln.width*V),Nt=Math.floor(Ln.height*V),ue.isDataArrayTexture?Rt=Ln.depth:ue.isData3DTexture?Rt=Math.floor(Ln.depth*V):Rt=1,qt=0,sn=0,Jt=0}Ue!==null?(yn=Ue.x,Sn=Ue.y,Jn=Ue.z):(yn=0,Sn=0,Jn=0);const dn=vt.convert(Oe.format),nn=vt.convert(Oe.type);let li;Oe.isData3DTexture?(F.setTexture3D(Oe,0),li=re.TEXTURE_3D):Oe.isDataArrayTexture||Oe.isCompressedArrayTexture?(F.setTexture2DArray(Oe,0),li=re.TEXTURE_2D_ARRAY):(F.setTexture2D(Oe,0),li=re.TEXTURE_2D),re.pixelStorei(re.UNPACK_FLIP_Y_WEBGL,Oe.flipY),re.pixelStorei(re.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Oe.premultiplyAlpha),re.pixelStorei(re.UNPACK_ALIGNMENT,Oe.unpackAlignment);const An=re.getParameter(re.UNPACK_ROW_LENGTH),sr=re.getParameter(re.UNPACK_IMAGE_HEIGHT),yr=re.getParameter(re.UNPACK_SKIP_PIXELS),Xi=re.getParameter(re.UNPACK_SKIP_ROWS),yi=re.getParameter(re.UNPACK_SKIP_IMAGES);re.pixelStorei(re.UNPACK_ROW_LENGTH,Ln.width),re.pixelStorei(re.UNPACK_IMAGE_HEIGHT,Ln.height),re.pixelStorei(re.UNPACK_SKIP_PIXELS,qt),re.pixelStorei(re.UNPACK_SKIP_ROWS,sn),re.pixelStorei(re.UNPACK_SKIP_IMAGES,Jt);const Kn=ue.isDataArrayTexture||ue.isData3DTexture,Pe=Oe.isDataArrayTexture||Oe.isData3DTexture;if(ue.isDepthTexture){const V=Ke.get(ue),fe=Ke.get(Oe),ve=Ke.get(V.__renderTarget),Te=Ke.get(fe.__renderTarget);ke.bindFramebuffer(re.READ_FRAMEBUFFER,ve.__webglFramebuffer),ke.bindFramebuffer(re.DRAW_FRAMEBUFFER,Te.__webglFramebuffer);for(let Be=0;Be{if(!t.current)return;let s;const o=30,l=5.6,u=Math.PI*2,d=.035,f=.12,m=1.8,h=1;let _=d,g=0,y=h;const b=i.current,T=new ua(65,1,1,1e4);T.position.z=150;const v=new HO;v.background=new wi("#d1684e");const x=new Vm;v.add(x);class P extends Ro{constructor(X=1){super(),this.scale=X}getPoint(X){const ne=o*Math.sin(u*X),Q=l*Math.cos(u*3*X);let oe,W;return W=X%.25/.25,W=X%.25-(2*(1-W)*W*-.0185+W*W*.25),(Math.floor(X/.25)==0||Math.floor(X/.25)==2)&&(W*=-1),oe=l*Math.sin(u*2*(X-W)),new Ge(ne,Q,oe).multiplyScalar(this.scale)}}const w=new P(1),C=new Os(new cb(w,200,1.1,2,!0),new sh({color:16777215}));x.add(C);const E=new Os(new vh(50,15,1),new sh({color:13723726,opacity:0,transparent:!0}));E.position.x=o+1,E.rotation.y=Math.PI/2,x.add(E);const A=new Os(new lb(4.3,5.55,32),new sh({color:16777215,opacity:0,transparent:!0}));A.position.x=o+1.1,A.rotation.y=Math.PI/2,x.add(A);for(let ee=0;ee<10;ee++){const X=new Os(new vh(o*2+1,l*3,1),new sh({color:13723726,transparent:!0,opacity:.13}));X.position.z=-2.5+ee*.5,x.add(X)}const L=new Qz({antialias:!0,alpha:!0});L.setPixelRatio(window.devicePixelRatio);const I=()=>{const ee=Math.min(window.innerWidth,window.innerHeight)*.9;L.setSize(ee,ee)};I(),window.addEventListener("resize",I),L.setClearColor("#d1684e"),t.current.innerHTML="",t.current.appendChild(L.domElement);const O=()=>{b.toend=!0},H=()=>{b.toend=!1},Z=(ee,X,ne,Q)=>(ee/=Q/2)<1?ne/2*ee*ee+X:ne/2*((ee-=2)*ee*ee+2)+X,$=()=>{if(_=n?f:d,e&&!b.toend?(b.toend=!0,y=m):!e&&b.toend&&!document.body.matches(":active")&&(b.toend=!1,y=h),b.toend?b.animatestep=Math.min(240,b.animatestep+y):b.animatestep=Math.max(0,b.animatestep-y*1.4),g=Z(b.animatestep,0,1,240),g>.35){const ee=(g-.35)/.65;x.rotation.y=-Math.PI/2*ee,x.position.z=50*ee;const X=Math.max(0,(g-.97)/.03);C.material.opacity=1-X,E.material.opacity=A.material.opacity=X,A.scale.x=A.scale.y=.9+.1*X}L.render(v,T)},J=()=>{C.rotation.x+=_+g,$(),s=requestAnimationFrame(J)};return J(),()=>{cancelAnimationFrame(s),document.body.removeEventListener("mousedown",O),document.body.removeEventListener("touchstart",O),document.body.removeEventListener("mouseup",H),document.body.removeEventListener("touchend",H),window.removeEventListener("resize",I),L.dispose(),t.current&&(t.current.innerHTML="")}},[n,e]),Un.jsx("div",{ref:t,id:"wrap"})}function Jz({stream:n,className:e=""}){const t=mt.useRef(null),i=mt.useRef(0),s=mt.useRef(null),o=mt.useRef(null);return mt.useEffect(()=>{if(!n||!t.current)return;o.current=new AudioContext,s.current=o.current.createAnalyser(),s.current.fftSize=256,o.current.createMediaStreamSource(n).connect(s.current);const u=t.current,d=u.getContext("2d");if(!d)return;const f=s.current.frequencyBinCount,m=new Uint8Array(f),h=()=>{if(!s.current||!d)return;i.current=requestAnimationFrame(h),s.current.getByteFrequencyData(m);const _=u.width,g=u.height;d.clearRect(0,0,_,g);const y=Math.min(f,24),b=_/y;d.save(),d.filter="blur(15px)",d.globalCompositeOperation="lighter";for(let T=0;T<3;T++){const v=.4-T*.1,x=1-T*.15;d.beginPath();for(let w=0;w<=y;w++){const C=Math.floor(w*f/y),E=Math.floor((w+1)*f/y);let A=0;for(let J=C;J{cancelAnimationFrame(i.current),o.current&&o.current.close()}},[n]),Un.jsx("canvas",{ref:t,className:`audio-visualizer ${e}`,width:500,height:60})}const ch=16e3,eU=30,tU=500,nU=6e4,iU=200,rU=.005,cy=1500,sU=async n=>{try{const e=URL.createObjectURL(n),t=new AudioContext,s=await(await fetch(e)).arrayBuffer();if(s.byteLength<100)return console.warn("Skipping decode for very small ArrayBuffer:",s.byteLength),URL.revokeObjectURL(e),await t.close(),null;const o=await t.decodeAudioData(s);URL.revokeObjectURL(e),await t.close();const l=o.getChannelData(0);let u=l;const d=eU*o.sampleRate;if(l.length>d&&(u=l.slice(-d)),o.sampleRate===ch)return u;const f=new OfflineAudioContext(1,Math.ceil(u.length*ch/o.sampleRate),ch),m=new AudioContext({sampleRate:o.sampleRate}),h=m.createBuffer(1,u.length,o.sampleRate);h.copyToChannel(u,0),await m.close();const _=f.createBufferSource();return _.buffer=h,_.connect(f.destination),_.start(),(await f.startRendering()).getChannelData(0)}catch{return null}};function aU({onTranscriptionUpdate:n,onRecordingStateChange:e,onTranscriptionComplete:t,onSilenceDetected:i}){const[s,o]=mt.useState(!1),[l,u]=mt.useState(!1),[d,f]=mt.useState(!1),[m,h]=mt.useState(null),[_,g]=mt.useState(null),[y,b]=mt.useState(""),T=mt.useRef(null),v=mt.useRef(null),x=mt.useRef(null),P=mt.useRef([]),w=mt.useRef(0),C=mt.useRef(null),E=mt.useRef(0),A=mt.useRef(!1),L=mt.useRef(null),I=mt.useRef(null),O=mt.useRef(null),H=mt.useRef(!1),Z=mt.useRef(!1),$=mt.useRef(null),J=mt.useRef(0),ee=1e3;mt.useEffect(()=>{Z.current=s,e&&e(s)},[s,e]),mt.useEffect(()=>{T.current=new Worker(new URL(""+new URL("whisper-worker-6wf5zhRk.js",import.meta.url).href,import.meta.url),{type:"module"});const me=xe=>{const{status:ze,data:Me,output:ce,tps:ae}=xe.data;switch(ze){case"loading":f(!1);break;case"ready":f(!0),g(null);break;case"error":g(Me||"Error loading Whisper model"),f(!1),u(!1);break;case"start":u(!0);break;case"update":ae&&console.log(`Whisper processing at ${ae.toFixed(2)} tokens/sec`);break;case"complete":if(u(!1),ce&&Array.isArray(ce)&&ce.length>0){const we=ce[0].trim();if(b(we),we&&!["[BLANK_AUDIO]","[ Silence ]","[Silence]",""].includes(we)){H.current=!0;const re=Date.now();we===$.current&&re-J.current{T.current?.terminate(),T.current?.removeEventListener("message",me),u(!1),f(!1)}},[n,t]),mt.useEffect(()=>{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){g("Speech recognition is not supported in your browser.");return}let me=null,xe=null,ze=null;return navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:ch}}).then(Me=>{me=Me,h(Me),xe=new AudioContext({sampleRate:ch}),x.current=xe;let ae=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"].find(we=>MediaRecorder.isTypeSupported(we))||"audio/webm";ze=new MediaRecorder(Me,{mimeType:ae}),v.current=ze,ze.onstart=()=>{P.current=[],w.current=Date.now(),E.current=Date.now()},ze.ondataavailable=we=>{we.data.size>0?P.current.push(we.data):console.warn("Received empty audio chunk")},ze.onstop=()=>{const we=Z.current,re=A.current;!we&&!re||re||console.warn("Internal: Recorder stopped unexpectedly while isRecordingRef was true."),!re&&P.current.length>0&&!l&&X()},ze.onerror=we=>{console.error("MediaRecorder error:",we),g("An error occurred with the audio recorder."),Z.current&&le()},g(null)}).catch(Me=>{console.error("Error accessing microphone:",Me),g("Failed to access microphone. Please grant permission."),h(null)}),()=>{if(oe(),W(),ze&&ze.state==="recording")try{ze.stop()}catch(Me){console.error("Error stopping recorder on cleanup:",Me)}if(me&&me.getTracks().forEach(Me=>Me.stop()),xe)try{xe.close()}catch(Me){console.error("Error closing AudioContext on cleanup:",Me)}v.current=null,x.current=null,h(null),Z.current&&o(!1)}},[]);const X=mt.useCallback(async()=>{if(!x.current||!T.current||l||P.current.length===0)return;u(!0);const me=[...P.current];let xe=null;try{const ze=v.current?.mimeType||"audio/webm",Me=new Blob(me,{type:ze}),ce=await sU(Me);if(xe=ce,!ce){u(!1),P.current=[],te(),Z.current&&G();return}const ae=Math.floor(ch*(cy/1e3)),we=Math.max(0,ce.length-ae),re=ce.slice(we);let He=0;re.length>0&&(He=Math.sqrt(re.reduce((Ne,We)=>Ne+We*We,0)/re.length)),He{if(I.current!==null&&Z.current){const Ne=Date.now()-I.current;Ne>=cy?(console.log(`Silence duration (${Ne}ms) threshold met.`),P.current=[],i&&i(y,xe),te(),H.current=!1):te()}else te()},cy)),u(!1)):(te(),T.current.postMessage({type:"generate",data:{audio:ce,language:"en"}})),E.current=Date.now()}catch(ze){console.error("Error processing audio:",ze),u(!1),te(),g("Error processing recorded audio.")}},[l,i]),ne=mt.useCallback(()=>{if(P.current.length>iU*.8&&Z.current&&!A.current){G();return}Z.current&&!l&&P.current.length>0&&X()},[l,X]),Q=mt.useCallback(()=>{oe(),C.current=window.setInterval(ne,tU)},[ne]),oe=mt.useCallback(()=>{C.current&&(clearInterval(C.current),C.current=null)},[]);mt.useEffect(()=>{s?(Q(),q()):(oe(),W())},[s,Q,oe]);const W=mt.useCallback(()=>{L.current&&(window.clearTimeout(L.current),L.current=null)},[]),q=mt.useCallback(()=>{W(),L.current=window.setTimeout(()=>{G()},nU)},[W]),G=mt.useCallback(()=>{if(!(!Z.current||!v.current||A.current)){A.current=!0;try{if(v.current.state==="recording")v.current.stop();else{console.warn("Recorder not recording during refresh attempt, state:",v.current.state),A.current=!1;return}}catch(me){console.error("Error stopping recorder during refresh:",me),A.current=!1;return}setTimeout(()=>{if(Z.current&&v.current)try{v.current.state==="inactive"?(P.current=[],v.current.start(500),q()):console.warn(`Recorder not inactive (state: ${v.current.state}) after refresh stop timeout, cannot restart.`)}catch(me){console.error("Error restarting recorder after refresh:",me),g("Failed to restart recorder after refresh."),le()}A.current=!1},300)}},[l,X,q]),te=mt.useCallback(()=>{O.current&&(clearTimeout(O.current),O.current=null),I.current=null},[]),B=mt.useCallback(()=>{if(!v.current||!d||Z.current){console.warn("Cannot start recording:",{hasRecorder:!!v.current,transcriptionReady:d,isRecording:Z.current});return}try{P.current=[],te(),H.current=!1,v.current.start(500),o(!0)}catch(me){console.error("Error starting recording:",me),g("Failed to start recording."),o(!1)}},[d,te]),le=mt.useCallback((me=!1)=>{if(!(!v.current||!Z.current)){W(),te(),H.current=!1;try{v.current.state==="recording"?v.current.stop():(console.warn("Stop called but recorder wasn't recording, state:",v.current.state),me&&P.current.length>0&&!l&&X())}catch(xe){console.error("Error stopping recording:",xe),g("Failed to stop recording cleanly.")}finally{o(!1)}}},[W,te,l,X]),ye=mt.useCallback(()=>{le(!0)},[le]);return{isRecording:s,isTranscribing:l,transcriptionReady:d,startRecording:B,stopRecording:ye,micStream:m,error:_}}function oU({isOpen:n,memories:e,onDelete:t,isLoading:i}){const s=o=>new Date(o).toLocaleString();return Un.jsx("div",{className:`memory-viewer ${n?"open":""}`,children:i?Un.jsx("div",{className:"memory-loading",children:"Loading memories..."}):e.length===0?Un.jsx("div",{className:"memory-empty",children:"No memories found."}):Un.jsx("ul",{className:"memory-list",children:e.map(o=>Un.jsxs("li",{className:"memory-item",children:[Un.jsxs("div",{className:"memory-item-content",children:[Un.jsx("p",{className:"memory-text",children:o.text}),Un.jsxs("p",{className:"memory-meta",children:["Added: ",s(o.timestamp)]})]}),Un.jsx("button",{className:"memory-delete-button",onClick:()=>t(o.id),title:"Delete Memory",children:Un.jsx(KR,{size:16})})]},o.id))})})}const lU=["don't have personal memories","don't retain information","start from a blank slate","cannot recall past conversations","don't have memory","i cannot recall","i don't recall","i am unable to recall","i don't have information about you","i don't know your name"];function cU(){const[n,e]=mt.useState(""),[t,i]=mt.useState([]),[s,o]=mt.useState(!1),l=1,u="af_heart",[d,f]=mt.useState(!1),[m,h]=mt.useState([]),[_,g]=mt.useState(!1),y=mt.useRef([]),b=mt.useRef(!1),T=mt.useRef(!1),v=mt.useRef(null),x=mt.useRef(null),P=mt.useRef(null),[w,C]=mt.useState("loading"),[E,A]=mt.useState("loading"),[L,I]=mt.useState("loading"),[O,H]=mt.useState(null),[Z,$]=mt.useState(0),[J,ee]=mt.useState(!1),[X,ne]=mt.useState(!1),Q=mt.useRef(null),oe=mt.useRef(null),W=mt.useRef(null),q=mt.useRef(""),G=mt.useRef(""),te=mt.useRef([]),B=mt.useRef(""),le=mt.useRef(null),ye=mt.useRef(n),me=mt.useRef(s),[xe,ze]=mt.useState(!1),[Me,ce]=mt.useState([]),[ae,we]=mt.useState(!1),re=mt.useRef(xe);mt.useEffect(()=>{ye.current=n},[n]),mt.useEffect(()=>{te.current=t},[t]),mt.useEffect(()=>{me.current=s},[s]),mt.useEffect(()=>(document.body.classList.add("os1-theme"),()=>{document.body.classList.remove("os1-theme")}),[]);const He=mt.useCallback(async nt=>{try{return await AI(nt)}catch{return""}},[]),Ne=mt.useCallback(nt=>{i(ft=>{const vt=[...ft];return vt.length>0&&vt[vt.length-1].role==="assistant"&&(vt[vt.length-1]={...vt[vt.length-1],content:nt}),vt})},[]),We=mt.useCallback(()=>{x.current?.postMessage({type:"interrupt"}),P.current?.postMessage({type:"interrupt"}),oe.current&&(oe.current.paused||oe.current.pause(),oe.current.removeAttribute("src")),g(!1),W.current&&(URL.revokeObjectURL(W.current),W.current=null),h([]),y.current=[],b.current=!1,f(!1),B.current="",T.current=!1,o(!1),me.current=!1},[o]),ke=nt=>{if(!nt||!P.current)return;const ft=nt.trim();if(ft==="")return;const vt=ft.replace(/\*/g,"");y.current.push({text:vt,voice:u,speed:l}),b.current||st()},st=()=>{if(b.current||y.current.length===0){b.current&&y.current.length===0&&(b.current=!1,f(!1));return}b.current=!0,f(!0);const nt=y.current[0];P.current?(v.current=performance.now(),P.current.postMessage(nt)):(console.error("Kokoro worker not available when trying to process TTS queue"),y.current.shift(),b.current=!1,f(!1),v.current=null,Cs.error("Text-to-speech worker not available."))},Ke=mt.useCallback(()=>{if(m.length===0||_)return;const nt=m[0];W.current&&(URL.revokeObjectURL(W.current),W.current=null);const ft=URL.createObjectURL(nt);W.current=ft,oe.current||(oe.current=new Audio,oe.current.onended=()=>{g(!1)},oe.current.onerror=vt=>{console.error("Audio playback error:",vt),W.current===oe.current?.src&&(URL.revokeObjectURL(W.current),W.current=null),g(!1)}),h(vt=>vt.slice(1)),oe.current.src=ft,g(!0),oe.current.play().then(()=>{}).catch(vt=>{console.error(`Error starting audio playback for ${ft}:`,vt),W.current===ft&&(URL.revokeObjectURL(W.current),W.current=null),g(!1)})},[m.length,_]),F=mt.useCallback(async()=>{if(me.current||w!=="ready")return;We();let nt="";try{nt=await He("You are OS1. Briefly welcome the user back by knowing what is the user's name."),nt||(console.warn("Context builder returned empty for welcome message, using fallback."),nt="You are OS1. Briefly welcome the user back.")}catch(ft){console.error("Error building context for welcome message:",ft),Cs.error("Failed to build context for greeting."),nt="You are OS1. Briefly welcome the user back."}queueMicrotask(()=>{o(!0),me.current=!0,T.current=!0;const ft=[{role:"system",content:nt}];i([{role:"assistant",content:""}]),setTimeout(()=>{x.current?x.current.postMessage({type:"generate",data:{messages:ft,audio:null}}):(console.error("Llama worker not available for welcome back message."),o(!1),me.current=!1,Cs.error("Cannot connect to AI model worker for greeting."))},50)})},[w,We,o,He]),U=mt.useCallback(async nt=>{We(),queueMicrotask(async()=>{const ft=nt||ye.current;if(!ft.trim())return;e(""),o(!0),me.current=!0;const vt=ft.trim();G.current=vt;const mn=le.current;le.current=null;let Se="";try{Se=await He(vt)}catch(Pt){console.error("Error building Llama context:",Pt),Cs.error("Failed to process memories for context."),Se=""}let St=vt;mn&&(St="<|audio|>");const Ze={role:"user",content:St},it={role:"user",content:vt},yt=[...te.current,it];i([...yt,{role:"assistant",content:""}]);let gt=[...te.current,Ze].slice(-10);Se&>.unshift({role:"system",content:Se}),setTimeout(()=>{if(x.current){const Pt=mn?"generate_with_audio":"generate",tn={messages:gt,audio:mn||null};x.current.postMessage({type:Pt,data:tn})}else console.error("Llama worker not available"),o(!1),me.current=!1,i(yt),Cs.error("Cannot connect to AI model worker.")},50)})},[He,We]),j=mt.useCallback(nt=>{nt&&e(nt)},[]),se=mt.useCallback((nt,ft)=>{le.current=ft,U()},[U]),{isRecording:_e,transcriptionReady:ge,startRecording:Ce,stopRecording:Ie,micStream:Ee,error:je}=aU({onTranscriptionUpdate:j,onSilenceDetected:se});mt.useEffect(()=>{let nt=!0;const ft=setInterval(()=>{nt&&$(Se=>Math.min(Se+(Math.random()*4+1),90))},300);x.current=new Worker(new URL(""+new URL("llama-worker-DNNMVgbD.js",import.meta.url).href,import.meta.url),{type:"module"}),P.current=new Worker(new URL(""+new URL("worker-OwHPUuym.js",import.meta.url).href,import.meta.url),{type:"module"});const vt=Se=>{const{status:St,output:Ze,data:it,summary:yt,error:tt}=Se.data;switch(St){case"ready":A("ready"),$(ln=>Math.max(ln,60));break;case"error":A("error"),H(it||"Error loading Llama model"),clearInterval(ft),B.current="";break;case"start":q.current="",T.current=!1,B.current="",i(ln=>ln.length>0&&ln[ln.length-1].role==="assistant"&&ln[ln.length-1].content===""?ln:[...ln,{role:"assistant",content:""}]);break;case"update":const gt=Ze;if(typeof gt=="string"&&(B.current+=gt,q.current+=gt,Ne(q.current),/[.?!]/.test(gt))){const vi=B.current.trim();vi&&(ke(vi),T.current=!0),B.current=""}break;case"complete":o(!1);const Pt=B.current.trim();Pt&&(ke(Pt),T.current=!0),B.current="";const tn=Ze||q.current,rn=G.current;Ne(tn);const Pn=tn?.trim();if(Pn&&!T.current&&(T.current=!0,queueMicrotask(()=>ke(Pn))),tn?.trim()&&rn){const ln=tn.toLowerCase();if(!lU.some(On=>ln.includes(On))){const It=rn.split(/\s+/).filter(Boolean).length;if(It>1&&It<15)PE(rn,"user").then(()=>{re.current&&ot()}).catch(Bt=>{console.error("Failed to add short user input to memory:",Bt),Cs.error("Failed to save short memory input.")});else if(It>=15){const Bt=rn;x.current?x.current.postMessage({type:"summarize",data:{textToSummarize:Bt}}):(console.error("Llama worker not available for summarization request."),Cs.error("Could not save memory summary: Worker unavailable."))}}}setTimeout(()=>{G.current="",q.current=""},100);break;case"summarization_start":break;case"summary_complete":if(yt&&typeof yt=="string"&&yt.trim()){const ln=()=>{PE(yt.trim(),"user").then(()=>{re.current&&ot()}).catch(vi=>{console.error("Failed to add summary to memory:",vi),Cs.error("Failed to save summarized memory.")})};typeof requestIdleCallback=="function"?requestIdleCallback(ln,{timeout:1e3}):setTimeout(ln,0)}else console.warn("Received empty or invalid summary from worker, not saving to memory.");break;case"summary_error":console.error("Summarization failed in worker:",it||tt),Cs.error("Failed to generate memory summary.");break}},mn=Se=>{const{status:St,data:Ze,chunk:it}=Se.data;switch(St){case"device":break;case"ready":I("ready"),$(yt=>Math.max(yt,75));break;case"stream":it&&it.audio instanceof Blob?Qe(it.audio):console.warn("Received stream message without valid audio blob:",it);break;case"error":if(v.current!==null){const tt=performance.now()-v.current;console.error(`TTS Error after ${tt.toFixed(2)} ms`),v.current=null}else console.error("TTS Error: Received error message without a recorded start time.");h([]),_&&oe.current&&(oe.current.pause(),oe.current.currentTime=0,g(!1),W.current&&(URL.revokeObjectURL(W.current),W.current=null)),b.current?(y.current.shift(),b.current=!1,f(!1),setTimeout(st,100)):(I("error"),H(Ze||"Error loading Kokoro model"));break;case"complete":v.current!==null&&(v.current=null),y.current.shift(),b.current=!1,f(!1),st();break}};return x.current.addEventListener("message",vt),P.current.addEventListener("message",mn),console.log("Requesting model loads for Llama, Kokoro..."),x.current.postMessage({type:"load"}),P.current.postMessage({type:"load"}),console.log("Initiating preload for Embedding model..."),U3().catch(Se=>{console.error("Embedding model preload failed:",Se)}),()=>{nt=!1,clearInterval(ft),x.current?.terminate(),P.current?.terminate(),x.current?.removeEventListener("message",vt),P.current?.removeEventListener("message",mn),oe.current&&(oe.current.pause(),oe.current.onended=null,oe.current.onerror=null,oe.current.src=""),W.current&&(URL.revokeObjectURL(W.current),W.current=null)}},[]),mt.useEffect(()=>{je&&(console.error("Error from useWhisperRecorder:",je),H(je),Cs.error(`Recording Error: ${je}`))},[je]),mt.useEffect(()=>{const nt=E==="ready"&&L==="ready"&&ge,ft=E==="error"||L==="error";if(nt){$(100),ee(!0);const vt=setTimeout(()=>{C("ready");const mn=setTimeout(()=>{ee(!1)},2500),Se=setTimeout(()=>{ne(!0)},1300);return()=>{clearTimeout(mn),clearTimeout(Se)}},1e3);return()=>clearTimeout(vt)}else ft?(C("error"),$(vt=>vt===100?100:0)):$(vt=>vt===100?100:0)},[E,L,ge]),mt.useEffect(()=>{if(X&&t.length===0&&!T.current&&!me.current)if(localStorage.getItem("os1_hasVisited"))F();else{const ft="Welcome! I'm OS1, your conversational companion. Everything we talk about, including memories of our chat, stays right here in your browser – nothing is sent to a server, and the AI runs entirely on your machine. To help me remember you next time, what should I call you? You can type your answer or click the microphone to speak.";localStorage.setItem("os1_hasVisited","true"),i([{role:"assistant",content:ft}]),ke(ft),T.current=!0}},[X,t.length,T.current,F]),mt.useEffect(()=>{Q.current?.scrollIntoView({behavior:"smooth"})},[t]);const Qe=mt.useCallback(nt=>{h(ft=>ft.length>=10?[...ft.slice(1),nt]:[...ft,nt])},[]);mt.useEffect(()=>{!_&&m.length>0&&Ke()},[_,m.length,Ke]);const ot=mt.useCallback(async()=>{we(!0);try{const nt=await q3();nt.sort((ft,vt)=>vt.timestamp-ft.timestamp),ce(nt)}catch(nt){console.error("Failed to fetch memories:",nt),Cs.error("Could not load memories."),ce([])}finally{we(!1)}},[]),bt=mt.useCallback(async()=>{const nt=!xe;ze(nt),nt&&await ot()},[xe,ot]),_t=mt.useCallback(async nt=>{try{await X3(nt),Cs.success("Memory deleted."),await ot()}catch{Cs.error("Could not delete memory.")}},[ot]);return mt.useEffect(()=>{re.current=xe},[xe]),Un.jsxs("div",{className:"os1-container",children:[Un.jsx(Zz,{isTTSProcessing:d||s,showTransformation:J}),w==="loading"&&Un.jsx("div",{className:"loading-bar-container",children:Un.jsx("div",{className:"loading-bar",style:{width:`${Z}%`}})}),w==="error"&&Un.jsx("div",{className:"message error",children:Un.jsxs("span",{children:["Error: ",O||"Failed to load OS1"]})}),w==="ready"&&Un.jsxs(Un.Fragment,{children:[Ee&&_e&&Un.jsxs("div",{className:"audio-visualizer-container",children:[Un.jsx("div",{className:"visualizer-glow"}),Un.jsx("div",{className:"visualizer-inner",children:Un.jsx(Jz,{stream:Ee,className:"os1-visualizer"})})]}),Un.jsxs("div",{className:`input-container ${X?"ready":""}`,children:[Un.jsx(U1,{value:n,onChange:nt=>e(nt.target.value),placeholder:"Ask me anything...",disabled:s,onKeyDown:nt=>{nt.key==="Enter"&&!nt.shiftKey&&(nt.preventDefault(),U())}}),Un.jsx("button",{className:`memory-button ${xe?"active":""}`,onClick:bt,disabled:ae,title:"View Memories",children:Un.jsx($R,{className:"icon"})}),Un.jsx("div",{className:"mic-button-wrapper",children:Un.jsx("button",{className:`mic-button ${_e?"recording":""}`,onClick:()=>_e?Ie():Ce(),disabled:!ge||!!je,title:je||(_e?"Stop recording":"Start recording"),children:_e?Un.jsx(GR,{className:"icon"}):Un.jsx(WR,{className:"icon"})})}),Un.jsx("button",{className:"send-button",onClick:()=>U(),disabled:!n.trim()||s,children:Un.jsx(qR,{})})]}),Un.jsx(oU,{isOpen:xe,memories:Me,onDelete:_t,isLoading:ae})]}),Un.jsx("div",{ref:Q})]})}function uU(){return Un.jsx(cU,{})}qP.createRoot(document.getElementById("root")).render(Un.jsx(mt.StrictMode,{children:Un.jsx(uU,{})}));