@rqmii_immersive/agent-react-sdk 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -14,16 +14,16 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var hp;function mg(){return hp||(hp=1,process.env.NODE_ENV!=="production"&&(function(){function c(Q){if(Q==null)return null;if(typeof Q=="function")return Q.$$typeof===ft?null:Q.displayName||Q.name||null;if(typeof Q=="string")return Q;switch(Q){case ue:return"Fragment";case ke:return"Profiler";case Be:return"StrictMode";case pe:return"Suspense";case Ie:return"SuspenseList";case Qe:return"Activity"}if(typeof Q=="object")switch(typeof Q.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),Q.$$typeof){case ce:return"Portal";case re:return Q.displayName||"Context";case he:return(Q._context.displayName||"Context")+".Consumer";case de:var Me=Q.render;return Q=Q.displayName,Q||(Q=Me.displayName||Me.name||"",Q=Q!==""?"ForwardRef("+Q+")":"ForwardRef"),Q;case ge:return Me=Q.displayName||null,Me!==null?Me:c(Q.type)||"Memo";case ut:Me=Q._payload,Q=Q._init;try{return c(Q(Me))}catch{}}return null}function r(Q){return""+Q}function n(Q){try{r(Q);var Me=!1}catch{Me=!0}if(Me){Me=console;var et=Me.error,gt=typeof Symbol=="function"&&Symbol.toStringTag&&Q[Symbol.toStringTag]||Q.constructor.name||"Object";return et.call(Me,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",gt),r(Q)}}function a(Q){if(Q===ue)return"<>";if(typeof Q=="object"&&Q!==null&&Q.$$typeof===ut)return"<...>";try{var Me=c(Q);return Me?"<"+Me+">":"<...>"}catch{return"<...>"}}function f(){var Q=Ne.A;return Q===null?null:Q.getOwner()}function v(){return Error("react-stack-top-frame")}function C(Q){if(Xe.call(Q,"key")){var Me=Object.getOwnPropertyDescriptor(Q,"key").get;if(Me&&Me.isReactWarning)return!1}return Q.key!==void 0}function R(Q,Me){function et(){ot||(ot=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",Me))}et.isReactWarning=!0,Object.defineProperty(Q,"key",{get:et,configurable:!0})}function b(){var Q=c(this.type);return Ye[Q]||(Ye[Q]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),Q=this.props.ref,Q!==void 0?Q:null}function U(Q,Me,et,gt,Gt,
|
|
17
|
+
*/var hp;function mg(){return hp||(hp=1,process.env.NODE_ENV!=="production"&&(function(){function c(Q){if(Q==null)return null;if(typeof Q=="function")return Q.$$typeof===ft?null:Q.displayName||Q.name||null;if(typeof Q=="string")return Q;switch(Q){case ue:return"Fragment";case ke:return"Profiler";case Be:return"StrictMode";case pe:return"Suspense";case Ie:return"SuspenseList";case Qe:return"Activity"}if(typeof Q=="object")switch(typeof Q.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),Q.$$typeof){case ce:return"Portal";case re:return Q.displayName||"Context";case he:return(Q._context.displayName||"Context")+".Consumer";case de:var Me=Q.render;return Q=Q.displayName,Q||(Q=Me.displayName||Me.name||"",Q=Q!==""?"ForwardRef("+Q+")":"ForwardRef"),Q;case ge:return Me=Q.displayName||null,Me!==null?Me:c(Q.type)||"Memo";case ut:Me=Q._payload,Q=Q._init;try{return c(Q(Me))}catch{}}return null}function r(Q){return""+Q}function n(Q){try{r(Q);var Me=!1}catch{Me=!0}if(Me){Me=console;var et=Me.error,gt=typeof Symbol=="function"&&Symbol.toStringTag&&Q[Symbol.toStringTag]||Q.constructor.name||"Object";return et.call(Me,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",gt),r(Q)}}function a(Q){if(Q===ue)return"<>";if(typeof Q=="object"&&Q!==null&&Q.$$typeof===ut)return"<...>";try{var Me=c(Q);return Me?"<"+Me+">":"<...>"}catch{return"<...>"}}function f(){var Q=Ne.A;return Q===null?null:Q.getOwner()}function v(){return Error("react-stack-top-frame")}function C(Q){if(Xe.call(Q,"key")){var Me=Object.getOwnPropertyDescriptor(Q,"key").get;if(Me&&Me.isReactWarning)return!1}return Q.key!==void 0}function R(Q,Me){function et(){ot||(ot=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",Me))}et.isReactWarning=!0,Object.defineProperty(Q,"key",{get:et,configurable:!0})}function b(){var Q=c(this.type);return Ye[Q]||(Ye[Q]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),Q=this.props.ref,Q!==void 0?Q:null}function U(Q,Me,et,gt,Gt,Ct){var lt=et.ref;return Q={$$typeof:ie,type:Q,key:Me,props:et,_owner:gt},(lt!==void 0?lt:null)!==null?Object.defineProperty(Q,"ref",{enumerable:!1,get:b}):Object.defineProperty(Q,"ref",{enumerable:!1,value:null}),Q._store={},Object.defineProperty(Q._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(Q,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(Q,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:Gt}),Object.defineProperty(Q,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Ct}),Object.freeze&&(Object.freeze(Q.props),Object.freeze(Q)),Q}function B(Q,Me,et,gt,Gt,Ct){var lt=Me.children;if(lt!==void 0)if(gt)if(mt(lt)){for(gt=0;gt<lt.length;gt++)te(lt[gt]);Object.freeze&&Object.freeze(lt)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else te(lt);if(Xe.call(Me,"key")){lt=c(Q);var tt=Object.keys(Me).filter(function(vt){return vt!=="key"});gt=0<tt.length?"{key: someKey, "+tt.join(": ..., ")+": ...}":"{key: someKey}",Ze[lt+gt]||(tt=0<tt.length?"{"+tt.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
18
18
|
let props = %s;
|
|
19
19
|
<%s {...props} />
|
|
20
20
|
React keys must be passed directly to JSX without using spread:
|
|
21
21
|
let props = %s;
|
|
22
|
-
<%s key={someKey} {...props} />`,gt,lt,tt,lt),Ze[lt+gt]=!0)}if(lt=null,et!==void 0&&(n(et),lt=""+et),C(Me)&&(n(Me.key),lt=""+Me.key),"key"in Me){et={};for(var Xt in Me)Xt!=="key"&&(et[Xt]=Me[Xt])}else et=Me;return lt&&R(et,typeof Q=="function"?Q.displayName||Q.name||"Unknown":Q),U(Q,lt,et,f(),Gt,Et)}function te(Q){X(Q)?Q._store&&(Q._store.validated=1):typeof Q=="object"&&Q!==null&&Q.$$typeof===ut&&(Q._payload.status==="fulfilled"?X(Q._payload.value)&&Q._payload.value._store&&(Q._payload.value._store.validated=1):Q._store&&(Q._store.validated=1))}function X(Q){return typeof Q=="object"&&Q!==null&&Q.$$typeof===ie}var ee=le,ie=Symbol.for("react.transitional.element"),ce=Symbol.for("react.portal"),ue=Symbol.for("react.fragment"),Be=Symbol.for("react.strict_mode"),ke=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),re=Symbol.for("react.context"),de=Symbol.for("react.forward_ref"),pe=Symbol.for("react.suspense"),Ie=Symbol.for("react.suspense_list"),ge=Symbol.for("react.memo"),ut=Symbol.for("react.lazy"),Qe=Symbol.for("react.activity"),ft=Symbol.for("react.client.reference"),Ne=ee.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Xe=Object.prototype.hasOwnProperty,mt=Array.isArray,yt=console.createTask?console.createTask:function(){return null};ee={react_stack_bottom_frame:function(Q){return Q()}};var ot,Ye={},Le=ee.react_stack_bottom_frame.bind(ee,v)(),rt=yt(a(v)),Ze={};Qs.Fragment=ue,Qs.jsx=function(Q,Me,et){var gt=1e4>Ne.recentlyCreatedOwnerStacks++;return B(Q,Me,et,!1,gt?Error("react-stack-top-frame"):Le,gt?yt(a(Q)):rt)},Qs.jsxs=function(Q,Me,et){var gt=1e4>Ne.recentlyCreatedOwnerStacks++;return B(Q,Me,et,!0,gt?Error("react-stack-top-frame"):Le,gt?yt(a(Q)):rt)}})()),Qs}var pp;function gg(){return pp||(pp=1,process.env.NODE_ENV==="production"?Ci.exports=fg():Ci.exports=mg()),Ci.exports}var ar=gg();const Or=Object.create(null);Or.open="0";Or.close="1";Or.ping="2";Or.pong="3";Or.message="4";Or.upgrade="5";Or.noop="6";const Mi=Object.create(null);Object.keys(Or).forEach(c=>{Mi[Or[c]]=c});const po={type:"error",data:"parser error"},Kp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Qp=typeof ArrayBuffer=="function",Xp=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer,xo=({type:c,data:r},n,a)=>Kp&&r instanceof Blob?n?a(r):fp(r,a):Qp&&(r instanceof ArrayBuffer||Xp(r))?n?a(r):fp(new Blob([r]),a):a(Or[c]+(r||"")),fp=(c,r)=>{const n=new FileReader;return n.onload=function(){const a=n.result.split(",")[1];r("b"+(a||""))},n.readAsDataURL(c)};function mp(c){return c instanceof Uint8Array?c:c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let Za;function yg(c,r){if(Kp&&c.data instanceof Blob)return c.data.arrayBuffer().then(mp).then(r);if(Qp&&(c.data instanceof ArrayBuffer||Xp(c.data)))return r(mp(c.data));xo(c,!1,n=>{Za||(Za=new TextEncoder),r(Za.encode(n))})}const gp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",si=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let c=0;c<gp.length;c++)si[gp.charCodeAt(c)]=c;const wg=c=>{let r=c.length*.75,n=c.length,a,f=0,v,C,R,b;c[c.length-1]==="="&&(r--,c[c.length-2]==="="&&r--);const U=new ArrayBuffer(r),B=new Uint8Array(U);for(a=0;a<n;a+=4)v=si[c.charCodeAt(a)],C=si[c.charCodeAt(a+1)],R=si[c.charCodeAt(a+2)],b=si[c.charCodeAt(a+3)],B[f++]=v<<2|C>>4,B[f++]=(C&15)<<4|R>>2,B[f++]=(R&3)<<6|b&63;return U},vg=typeof ArrayBuffer=="function",Eo=(c,r)=>{if(typeof c!="string")return{type:"message",data:Yp(c,r)};const n=c.charAt(0);return n==="b"?{type:"message",data:bg(c.substring(1),r)}:Mi[n]?c.length>1?{type:Mi[n],data:c.substring(1)}:{type:Mi[n]}:po},bg=(c,r)=>{if(vg){const n=wg(c);return Yp(n,r)}else return{base64:!0,data:c}},Yp=(c,r)=>{switch(r){case"blob":return c instanceof Blob?c:new Blob([c]);case"arraybuffer":default:return c instanceof ArrayBuffer?c:c.buffer}},Jp="",_g=(c,r)=>{const n=c.length,a=new Array(n);let f=0;c.forEach((v,C)=>{xo(v,!1,R=>{a[C]=R,++f===n&&r(a.join(Jp))})})},Sg=(c,r)=>{const n=c.split(Jp),a=[];for(let f=0;f<n.length;f++){const v=Eo(n[f],r);if(a.push(v),v.type==="error")break}return a};function Tg(){return new TransformStream({transform(c,r){yg(c,n=>{const a=n.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const v=new DataView(f.buffer);v.setUint8(0,126),v.setUint16(1,a)}else{f=new Uint8Array(9);const v=new DataView(f.buffer);v.setUint8(0,127),v.setBigUint64(1,BigInt(a))}c.data&&typeof c.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(n)})}})}let eo;function ki(c){return c.reduce((r,n)=>r+n.length,0)}function Ri(c,r){if(c[0].length===r)return c.shift();const n=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)n[f]=c[0][a++],a===c[0].length&&(c.shift(),a=0);return c.length&&a<c[0].length&&(c[0]=c[0].slice(a)),n}function $g(c,r){eo||(eo=new TextDecoder);const n=[];let a=0,f=-1,v=!1;return new TransformStream({transform(C,R){for(n.push(C);;){if(a===0){if(ki(n)<1)break;const b=Ri(n,1);v=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(ki(n)<2)break;const b=Ri(n,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(ki(n)<8)break;const b=Ri(n,8),U=new DataView(b.buffer,b.byteOffset,b.length),B=U.getUint32(0);if(B>Math.pow(2,21)-1){R.enqueue(po);break}f=B*Math.pow(2,32)+U.getUint32(4),a=3}else{if(ki(n)<f)break;const b=Ri(n,f);R.enqueue(Eo(v?b:eo.decode(b),r)),a=0}if(f===0||f>c){R.enqueue(po);break}}}})}const Zp=4;function Dt(c){if(c)return xg(c)}function xg(c){for(var r in Dt.prototype)c[r]=Dt.prototype[r];return c}Dt.prototype.on=Dt.prototype.addEventListener=function(c,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+c]=this._callbacks["$"+c]||[]).push(r),this};Dt.prototype.once=function(c,r){function n(){this.off(c,n),r.apply(this,arguments)}return n.fn=r,this.on(c,n),this};Dt.prototype.off=Dt.prototype.removeListener=Dt.prototype.removeAllListeners=Dt.prototype.removeEventListener=function(c,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+c];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+c],this;for(var a,f=0;f<n.length;f++)if(a=n[f],a===r||a.fn===r){n.splice(f,1);break}return n.length===0&&delete this._callbacks["$"+c],this};Dt.prototype.emit=function(c){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),n=this._callbacks["$"+c],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(n){n=n.slice(0);for(var a=0,f=n.length;a<f;++a)n[a].apply(this,r)}return this};Dt.prototype.emitReserved=Dt.prototype.emit;Dt.prototype.listeners=function(c){return this._callbacks=this._callbacks||{},this._callbacks["$"+c]||[]};Dt.prototype.hasListeners=function(c){return!!this.listeners(c).length};const Ni=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,n)=>n(r,0),or=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Eg="arraybuffer";function ef(c,...r){return r.reduce((n,a)=>(c.hasOwnProperty(a)&&(n[a]=c[a]),n),{})}const Cg=or.setTimeout,kg=or.clearTimeout;function Ui(c,r){r.useNativeTimers?(c.setTimeoutFn=Cg.bind(or),c.clearTimeoutFn=kg.bind(or)):(c.setTimeoutFn=or.setTimeout.bind(or),c.clearTimeoutFn=or.clearTimeout.bind(or))}const Rg=1.33;function Ag(c){return typeof c=="string"?Mg(c):Math.ceil((c.byteLength||c.size)*Rg)}function Mg(c){let r=0,n=0;for(let a=0,f=c.length;a<f;a++)r=c.charCodeAt(a),r<128?n+=1:r<2048?n+=2:r<55296||r>=57344?n+=3:(a++,n+=4);return n}function tf(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ig(c){let r="";for(let n in c)c.hasOwnProperty(n)&&(r.length&&(r+="&"),r+=encodeURIComponent(n)+"="+encodeURIComponent(c[n]));return r}function Pg(c){let r={},n=c.split("&");for(let a=0,f=n.length;a<f;a++){let v=n[a].split("=");r[decodeURIComponent(v[0])]=decodeURIComponent(v[1])}return r}class Og extends Error{constructor(r,n,a){super(r),this.description=n,this.context=a,this.type="TransportError"}}class Co extends Dt{constructor(r){super(),this.writable=!1,Ui(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,n,a){return super.emitReserved("error",new Og(r,n,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const n=Eo(r,this.socket.binaryType);this.onPacket(n)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,n={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const n=Ig(r);return n.length?"?"+n:""}}class zg extends Co{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const n=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||n()})),this.writable||(a++,this.once("drain",function(){--a||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const n=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};Sg(r,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,_g(r,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=tf()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(r,n)}}let rf=!1;try{rf=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Dg=rf;function Lg(){}class Bg extends zg{constructor(r){if(super(r),typeof location<"u"){const n=location.protocol==="https:";let a=location.port;a||(a=n?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,n){const a=this.request({method:"POST",data:r});a.on("success",n),a.on("error",(f,v)=>{this.onError("xhr post error",f,v)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(n,a)=>{this.onError("xhr poll error",n,a)}),this.pollXhr=r}}class Pr extends Dt{constructor(r,n,a){super(),this.createRequest=r,Ui(this,a),this._opts=a,this._method=a.method||"GET",this._uri=n,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const n=ef(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(n);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Lg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",yp);else if(typeof addEventListener=="function"){const c="onpagehide"in or?"pagehide":"unload";addEventListener(c,yp,!1)}}function yp(){for(let c in Pr.requests)Pr.requests.hasOwnProperty(c)&&Pr.requests[c].abort()}const Ng=(function(){const c=nf({xdomain:!1});return c&&c.responseType!==null})();class Ug extends Bg{constructor(r){super(r);const n=r&&r.forceBase64;this.supportsBinary=Ng&&!n}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(nf,this.uri(),r)}}function nf(c){const r=c.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Dg))return new XMLHttpRequest}catch{}if(!r)try{return new or[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const sf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fg extends Co{get name(){return"websocket"}doOpen(){const r=this.uri(),n=this.opts.protocols,a=sf?{}:ef(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,n,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;xo(a,this.supportsBinary,v=>{try{this.doWrite(a,v)}catch{}f&&Ni(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=tf()),this.supportsBinary||(n.b64=1),this.createUri(r,n)}}const to=or.WebSocket||or.MozWebSocket;class Vg extends Fg{createSocket(r,n,a){return sf?new to(r,n,a):n?new to(r,n):new to(r)}doWrite(r,n){this.ws.send(n)}}class Gg extends Co{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const n=$g(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(n).getReader(),f=Tg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const v=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),v())}).catch(R=>{})};v();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;this._writer.write(a).then(()=>{f&&Ni(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const qg={websocket:Vg,webtransport:Gg,polling:Ug},Wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function fo(c){if(c.length>8e3)throw"URI too long";const r=c,n=c.indexOf("["),a=c.indexOf("]");n!=-1&&a!=-1&&(c=c.substring(0,n)+c.substring(n,a).replace(/:/g,";")+c.substring(a,c.length));let f=Wg.exec(c||""),v={},C=14;for(;C--;)v[Hg[C]]=f[C]||"";return n!=-1&&a!=-1&&(v.source=r,v.host=v.host.substring(1,v.host.length-1).replace(/;/g,":"),v.authority=v.authority.replace("[","").replace("]","").replace(/;/g,":"),v.ipv6uri=!0),v.pathNames=jg(v,v.path),v.queryKey=Kg(v,v.query),v}function jg(c,r){const n=/\/{2,9}/g,a=r.replace(n,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Kg(c,r){const n={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(n[f]=v)}),n}const mo=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ii=[];mo&&addEventListener("offline",()=>{Ii.forEach(c=>c())},!1);class nn extends Dt{constructor(r,n){if(super(),this.binaryType=Eg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(n=r,r=null),r){const a=fo(r);n.hostname=a.host,n.secure=a.protocol==="https"||a.protocol==="wss",n.port=a.port,a.query&&(n.query=a.query)}else n.host&&(n.hostname=fo(n.host).host);Ui(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Pg(this.opts.query)),mo&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Ii.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const n=Object.assign({},this.opts.query);n.EIO=Zp,n.transport=r,this.id&&(n.sid=this.id);const a=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&nn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(r);n.open(),this.setTransport(n)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",nn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=r.data,this._onError(n);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(n+=Ag(f)),a>0&&n>this._maxPayload)return this.writeBuffer.slice(0,a);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Ni(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,n,a){return this._sendPacket("message",r,n,a),this}send(r,n,a){return this._sendPacket("message",r,n,a),this}_sendPacket(r,n,a,f){if(typeof n=="function"&&(f=n,n=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const v={type:r,data:n,options:a};this.emitReserved("packetCreate",v),this.writeBuffer.push(v),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),r()},a=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(nn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),mo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=Ii.indexOf(this._offlineEventListener);a!==-1&&Ii.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,n),this.writeBuffer=[],this._prevBufferLen=0}}}nn.protocol=Zp;class Qg extends nn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let n=this.createTransport(r),a=!1;nn.priorWebsocketSuccess=!1;const f=()=>{a||(n.send([{type:"ping",data:"probe"}]),n.once("packet",te=>{if(!a)if(te.type==="pong"&&te.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;nn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(B(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const X=new Error("probe error");X.transport=n.name,this.emitReserved("upgradeError",X)}}))};function v(){a||(a=!0,B(),n.close(),n=null)}const C=te=>{const X=new Error("probe error: "+te);X.transport=n.name,v(),this.emitReserved("upgradeError",X)};function R(){C("transport closed")}function b(){C("socket closed")}function U(te){n&&te.name!==n.name&&v()}const B=()=>{n.removeListener("open",f),n.removeListener("error",C),n.removeListener("close",R),this.off("close",b),this.off("upgrading",U)};n.once("open",f),n.once("error",C),n.once("close",R),this.once("close",b),this.once("upgrading",U),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||n.open()},200):n.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const n=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&n.push(r[a]);return n}}let Xg=class extends Qg{constructor(r,n={}){const a=typeof r=="object"?r:n;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>qg[f]).filter(f=>!!f)),super(r,a)}};function Yg(c,r="",n){let a=c;n=n||typeof location<"u"&&location,c==null&&(c=n.protocol+"//"+n.host),typeof c=="string"&&(c.charAt(0)==="/"&&(c.charAt(1)==="/"?c=n.protocol+c:c=n.host+c),/^(https?|wss?):\/\//.test(c)||(typeof n<"u"?c=n.protocol+"//"+c:c="https://"+c),a=fo(c)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const v=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+v+":"+a.port+r,a.href=a.protocol+"://"+v+(n&&n.port===a.port?"":":"+a.port),a}const Jg=typeof ArrayBuffer=="function",Zg=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c.buffer instanceof ArrayBuffer,af=Object.prototype.toString,ey=typeof Blob=="function"||typeof Blob<"u"&&af.call(Blob)==="[object BlobConstructor]",ty=typeof File=="function"||typeof File<"u"&&af.call(File)==="[object FileConstructor]";function ko(c){return Jg&&(c instanceof ArrayBuffer||Zg(c))||ey&&c instanceof Blob||ty&&c instanceof File}function Pi(c,r){if(!c||typeof c!="object")return!1;if(Array.isArray(c)){for(let n=0,a=c.length;n<a;n++)if(Pi(c[n]))return!0;return!1}if(ko(c))return!0;if(c.toJSON&&typeof c.toJSON=="function"&&arguments.length===1)return Pi(c.toJSON(),!0);for(const n in c)if(Object.prototype.hasOwnProperty.call(c,n)&&Pi(c[n]))return!0;return!1}function ry(c){const r=[],n=c.data,a=c;return a.data=go(n,r),a.attachments=r.length,{packet:a,buffers:r}}function go(c,r){if(!c)return c;if(ko(c)){const n={_placeholder:!0,num:r.length};return r.push(c),n}else if(Array.isArray(c)){const n=new Array(c.length);for(let a=0;a<c.length;a++)n[a]=go(c[a],r);return n}else if(typeof c=="object"&&!(c instanceof Date)){const n={};for(const a in c)Object.prototype.hasOwnProperty.call(c,a)&&(n[a]=go(c[a],r));return n}return c}function ny(c,r){return c.data=yo(c.data,r),delete c.attachments,c}function yo(c,r){if(!c)return c;if(c&&c._placeholder===!0){if(typeof c.num=="number"&&c.num>=0&&c.num<r.length)return r[c.num];throw new Error("illegal attachments")}else if(Array.isArray(c))for(let n=0;n<c.length;n++)c[n]=yo(c[n],r);else if(typeof c=="object")for(const n in c)Object.prototype.hasOwnProperty.call(c,n)&&(c[n]=yo(c[n],r));return c}const sy=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var nt;(function(c){c[c.CONNECT=0]="CONNECT",c[c.DISCONNECT=1]="DISCONNECT",c[c.EVENT=2]="EVENT",c[c.ACK=3]="ACK",c[c.CONNECT_ERROR=4]="CONNECT_ERROR",c[c.BINARY_EVENT=5]="BINARY_EVENT",c[c.BINARY_ACK=6]="BINARY_ACK"})(nt||(nt={}));class iy{constructor(r){this.replacer=r}encode(r){return(r.type===nt.EVENT||r.type===nt.ACK)&&Pi(r)?this.encodeAsBinary({type:r.type===nt.EVENT?nt.BINARY_EVENT:nt.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let n=""+r.type;return(r.type===nt.BINARY_EVENT||r.type===nt.BINARY_ACK)&&(n+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(n+=r.nsp+","),r.id!=null&&(n+=r.id),r.data!=null&&(n+=JSON.stringify(r.data,this.replacer)),n}encodeAsBinary(r){const n=ry(r),a=this.encodeAsString(n.packet),f=n.buffers;return f.unshift(a),f}}class Ro extends Dt{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let n;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(r);const a=n.type===nt.BINARY_EVENT;a||n.type===nt.BINARY_ACK?(n.type=a?nt.EVENT:nt.ACK,this.reconstructor=new ay(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(ko(r)||r.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(r),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let n=0;const a={type:Number(r.charAt(0))};if(nt[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===nt.BINARY_EVENT||a.type===nt.BINARY_ACK){const v=n+1;for(;r.charAt(++n)!=="-"&&n!=r.length;);const C=r.substring(v,n);if(C!=Number(C)||r.charAt(n)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!oy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(n+1)==="/"){const v=n+1;for(;++n&&!(r.charAt(n)===","||n===r.length););a.nsp=r.substring(v,n)}else a.nsp="/";const f=r.charAt(n+1);if(f!==""&&Number(f)==f){const v=n+1;for(;++n;){const C=r.charAt(n);if(C==null||Number(C)!=C){--n;break}if(n===r.length)break}a.id=Number(r.substring(v,n+1))}if(r.charAt(++n)){const v=this.tryParse(r.substr(n));if(Ro.isPayloadValid(a.type,v))a.data=v;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,n){switch(r){case nt.CONNECT:return wp(n);case nt.DISCONNECT:return n===void 0;case nt.CONNECT_ERROR:return typeof n=="string"||wp(n);case nt.EVENT:case nt.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&sy.indexOf(n[0])===-1);case nt.ACK:case nt.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ay{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const n=ny(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oy=Number.isInteger||function(c){return typeof c=="number"&&isFinite(c)&&Math.floor(c)===c};function wp(c){return Object.prototype.toString.call(c)==="[object Object]"}const ly=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ro,Encoder:iy,get PacketType(){return nt}},Symbol.toStringTag,{value:"Module"}));function Tr(c,r,n){return c.on(r,n),function(){c.off(r,n)}}const uy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class of extends Dt{constructor(r,n,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=n,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[Tr(r,"open",this.onopen.bind(this)),Tr(r,"packet",this.onpacket.bind(this)),Tr(r,"error",this.onerror.bind(this)),Tr(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...n){var a,f,v;if(uy.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(n.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const C={type:nt.EVENT,data:n};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const B=this.ids++,te=n.pop();this._registerAckCallback(B,te),C.id=B}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,b=this.connected&&!(!((v=this.io.engine)===null||v===void 0)&&v._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,n){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=n;return}const v=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);n.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(v),n.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...n){return new Promise((a,f)=>{const v=(C,R)=>C?f(C):a(R);v.withError=!0,n.push(v),this.emit(r,...n)})}_addToQueue(r){let n;typeof r[r.length-1]=="function"&&(n=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,...v)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(f)):(this._queue.shift(),n&&n(null,...v)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!r||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:nt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case nt.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case nt.EVENT:case nt.BINARY_EVENT:this.onevent(r);break;case nt.ACK:case nt.BINARY_ACK:this.onack(r);break;case nt.DISCONNECT:this.ondisconnect();break;case nt.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const n=r.data||[];r.id!=null&&n.push(this.ack(r.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const a of n)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const n=this;let a=!1;return function(...f){a||(a=!0,n.packet({type:nt.ACK,id:r,data:f}))}}onack(r){const n=this.acks[r.id];typeof n=="function"&&(delete this.acks[r.id],n.withError&&r.data.unshift(null),n.apply(this,r.data))}onconnect(r,n){this.id=r,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:nt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const n=this._anyListeners;for(let a=0;a<n.length;a++)if(r===n[a])return n.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const n=this._anyOutgoingListeners;for(let a=0;a<n.length;a++)if(r===n[a])return n.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const a of n)a.apply(this,r.data)}}}function ns(c){c=c||{},this.ms=c.min||100,this.max=c.max||1e4,this.factor=c.factor||2,this.jitter=c.jitter>0&&c.jitter<=1?c.jitter:0,this.attempts=0}ns.prototype.duration=function(){var c=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),n=Math.floor(r*this.jitter*c);c=(Math.floor(r*10)&1)==0?c-n:c+n}return Math.min(c,this.max)|0};ns.prototype.reset=function(){this.attempts=0};ns.prototype.setMin=function(c){this.ms=c};ns.prototype.setMax=function(c){this.max=c};ns.prototype.setJitter=function(c){this.jitter=c};class wo extends Dt{constructor(r,n){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(n=r,r=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Ui(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((a=n.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new ns({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=r;const f=n.parser||ly;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var n;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(n=this.backoff)===null||n===void 0||n.setMin(r),this)}randomizationFactor(r){var n;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(n=this.backoff)===null||n===void 0||n.setJitter(r),this)}reconnectionDelayMax(r){var n;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(n=this.backoff)===null||n===void 0||n.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Xg(this.uri,this.opts);const n=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=Tr(n,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Tr(n,"error",v);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),v(new Error("timeout")),n.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(Tr(r,"ping",this.onping.bind(this)),Tr(r,"data",this.ondata.bind(this)),Tr(r,"error",this.onerror.bind(this)),Tr(r,"close",this.onclose.bind(this)),Tr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(n){this.onclose("parse error",n)}}ondecoded(r){Ni(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,n){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new of(this,r,n),this.nsps[r]=a),a}_destroy(r){const n=Object.keys(this.nsps);for(const a of n)if(this.nsps[a].active)return;this._close()}_packet(r){const n=this.encoder.encode(r);for(let a=0;a<n.length;a++)this.engine.write(n[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,n){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},n);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const Xs={};function Oi(c,r){typeof c=="object"&&(r=c,c=void 0),r=r||{};const n=Yg(c,r.path||"/socket.io"),a=n.source,f=n.id,v=n.path,C=Xs[f]&&v in Xs[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new wo(a,r):(Xs[f]||(Xs[f]=new wo(a,r)),b=Xs[f]),n.query&&!r.query&&(r.query=n.queryKey),b.socket(n.path,r)}Object.assign(Oi,{Manager:wo,Socket:of,io:Oi,connect:Oi});const dy=c=>{if(window.audioCtx=c,c.state!=="suspended")return;const r=document.body,n=["touchstart","touchend","mousedown","keydown"];n.forEach(v=>r.addEventListener(v,a,!1));function a(){c.resume().then(f)}function f(){n.forEach(v=>r.removeEventListener(v,a))}};function Vt(c){this.init(c)}Vt.prototype.init=function(c){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,c),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Vt.prototype.getMaxValue=function(){var c={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Vt.prototype.getTypedArray=function(){var c={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Vt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),dy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Vt.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Vt.prototype.isTypedArray=function(c){return c.byteLength&&c.buffer&&c.buffer.constructor==ArrayBuffer};Vt.prototype.feed=function(c){if(this.isTypedArray(c)){c=this.getFormatedValue(c);var r=new Float32Array(this.samples.length+c.length);r.set(this.samples,0),r.set(c,this.samples.length),this.samples=r,this.timeout||this.flush()}};Vt.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),n=new Float32Array(r.length),a;for(a=0;a<r.length;a++)n[a]=r[a]/this.maxValue;return n};Vt.prototype.volume=function(c){this.gainNode.gain.value=c};Vt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Vt.prototype.getTimestamp=function(c){if(this.playingStartTime>=0){if(!c)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=c/1e3,r}return 0};Vt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Vt.prototype.setOnEnd=function(c){this.onEnd=c};Vt.prototype.interrupt=function(c){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Vt.prototype.ensuredSetTimeout=(function(){let c;return function(r,n){c=performance.now();const a=f=>{f-c>=n?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Vt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Vt.prototype.flush=function(){if(this.samples.length){var c=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,n=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,v,C,R;for(f=0;f<this.option.channels;f++)for(a=n.getChannelData(f),v=f,R=50,C=0;C<r;C++)a[C]=this.samples[v],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),v+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,c.buffer=n,c.connect(this.gainNode),c.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=c,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=n.duration,this.flag_request_stop)this.flag_request_stop=!1,c.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};const qr={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},at={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",REFRESH_SESSION_ACTIVITY:"refresh_session_activity",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",RECONNECT_CREDENTIAL:"reconnect_credential",RECONNECT_SUCCESS:"reconnect_success",RECONNECT_FAILED:"reconnect_failed"},Bt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",FAILED:"failed",ENDED:"ended"},Qt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},vp={enabled:!0,maxAttempts:8,initialDelayMs:500,maxDelayMs:5e3,timeoutMs:8e3},cy={encoding:"16bitInt",channels:1,sampleRate:16e3},hy=c=>new Promise(r=>setTimeout(r,c)),py=c=>{if(!c)return null;if(c instanceof Uint8Array)return c;if(c instanceof ArrayBuffer)return new Uint8Array(c);if(c?.buffer instanceof ArrayBuffer){const r=Number.isInteger(c.byteOffset)?c.byteOffset:0,n=Number.isInteger(c.byteLength)?c.byteLength:c.buffer.byteLength-r;return new Uint8Array(c.buffer,r,n)}if(typeof c=="object"&&c.type==="Buffer"&&Array.isArray(c.data))return new Uint8Array(c.data);try{return new Uint8Array(c)}catch{return null}},ro=c=>String(c||"").toLowerCase().replaceAll("-","_"),fy=()=>{const c=new Map;return{addChunk:(f,v)=>{const C=f||`request-${Date.now()}`,b=`${c.get(C)||""}${v||""}`;return c.set(C,b),{id:C,text:b}},consume:(f,v="")=>{const C=f||`request-${Date.now()}`,R=c.get(C)||v||"";return c.delete(C),{id:C,text:R}},clear:()=>{c.clear()}}},lf=le.createContext(null),bp={connectionState:Bt.IDLE,isConnected:!1,isSessionReady:!1,error:null,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,cloudStream:{state:Qt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]},my=(c,r)=>{const n=new Vt(c),a=n.destroy.bind(n);let f=!1;return n.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},n.setOnEnd(()=>{f||r?.()}),n._isDestroyed=()=>f,n},_p=async c=>{if(!c?.ok){let r=`HTTP ${c.status}`;try{const n=await c.json();r=n?.detail||n?.message||r}catch{}throw new Error(r)}return c.json()};function uf({children:c,wsUrl:r,restUrl:n,reconnectOptions:a,enableAudio:f=!0,pcmOptions:v,debug:C=!1}){const[R,b]=le.useState(bp),U=le.useRef(null),B=le.useRef(null),te=le.useRef(!1),X=le.useRef(!1),ee=le.useRef({...vp,...a}),ie=le.useRef(fy()),ce=le.useRef(null),ue=le.useRef(!1),Be=le.useRef(null),ke=le.useRef(bp.session.agentType);le.useEffect(()=>{ee.current={...vp,...a}},[a]),le.useEffect(()=>{ke.current=R.session.agentType},[R.session.agentType]);const he=le.useCallback((...fe)=>{C&&console.log("[RqmiiSDK]",...fe)},[C]),re=le.useCallback(fe=>{b(Ue=>({...Ue,connectionState:fe,isConnected:fe===Bt.CONNECTED}))},[]),de=le.useCallback(fe=>{b(Ue=>({...Ue,error:fe?String(fe):null}))},[]),pe=le.useCallback(()=>{if(!f||ce.current)return ce.current;const fe={...cy,...v||{}};return ce.current=my(fe,()=>{b(Ue=>({...Ue,isAudioPlaying:!1}))}),ce.current},[f,v]),Ie=le.useCallback(()=>{if(ce.current){try{ce.current.interrupt?.(),ce.current.destroy?.()}catch{}ce.current=null}},[]),ge=le.useCallback(async()=>{const fe=pe();if(fe)try{fe.audioCtx?.state==="suspended"&&await fe.audioCtx.resume()}catch(Ue){he("audio resume failed",Ue)}},[pe,he]),ut=le.useCallback(fe=>{Be.current=fe||null},[]),Qe=le.useCallback((fe,Ue=null)=>{b(wt=>({...wt,cloudStream:{state:fe,error:Ue?String(Ue):null}}))},[]),ft=le.useCallback(()=>{if(U.current){try{U.current.removeAllListeners(),U.current.disconnect()}catch{}U.current=null}},[]),Ne=le.useCallback(({keepManualDisconnect:fe=!1}={})=>{X.current=!0,B.current=null,te.current=!1,ue.current=!1,ie.current.clear(),Ie(),ft(),fe||(X.current=!1),b(Ue=>({...Ue,connectionState:Bt.IDLE,isConnected:!1,isSessionReady:!1,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,error:null,transcript:null,partialTranscript:null,cloudStream:{state:Qt.IDLE,error:null},session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]}))},[ft,Ie]),Xe=le.useCallback(fe=>{!fe?.sessionId||!fe?.reconnectToken||!fe?.role||(B.current={sessionId:fe.sessionId,reconnectToken:fe.reconnectToken,role:fe.role},b(Ue=>({...Ue,session:{...Ue.session,sessionId:fe.sessionId,role:fe.role}})))},[]),mt=le.useCallback((fe,{isReconnect:Ue=!1,resolve:wt,reject:dt}={})=>{const ct=(me,Fe)=>{me&&me(Fe)};fe.on(at.CONNECT,()=>{he("socket connected"),de(null),Ue||(re(Bt.CONNECTED),ct(wt))}),fe.on(at.CONNECT_ERROR,me=>{he("socket connect_error",me),Ue||(re(Bt.FAILED),de(me?.message||"Connection error"),ct(dt,me))}),fe.on(at.DISCONNECT,me=>{he("socket disconnected",me),b(Fe=>({...Fe,isConnected:!1,isSessionReady:!1})),!X.current&&(ee.current.enabled?re(Bt.RECONNECTING):(re(Bt.FAILED),de("Connection lost")))}),fe.on(at.SESSION_READY,me=>{b(Fe=>({...Fe,isSessionReady:!0,error:null,session:{...Fe.session,agentType:ro(me?.agentType||Fe.session.agentType)}}))}),fe.on(at.SESSION_JOINED,()=>{b(me=>({...me,isSessionReady:!0,error:null}))}),fe.on(at.SESSION_TERMINATED,()=>{re(Bt.ENDED),b(me=>({...me,isSessionReady:!1}))}),fe.on(at.TRANSCRIPT,me=>{b(Fe=>({...Fe,transcript:me||null}))}),fe.on(at.PARTIAL_TRANSCRIPT,me=>{b(Fe=>({...Fe,partialTranscript:me||null}))}),fe.on(at.AGENT_RESPONSE_CHUNK,me=>{const{id:Fe,text:It}=ie.current.addChunk(me?.requestId,me?.text);b(Pt=>{const ur=Pt.messages.filter(dr=>dr.id!==Fe);return{...Pt,messages:[...ur,{id:Fe,role:"assistant",text:It,streaming:!0,timestamp:new Date().toISOString()}]}})}),fe.on(at.AGENT_RESPONSE,me=>{const{id:Fe,text:It}=ie.current.consume(me?.requestId,me?.text);b(Pt=>{const ur=Pt.messages.filter(dr=>dr.id!==Fe);return{...Pt,messages:[...ur,{id:Fe,role:"assistant",text:It,streaming:!1,timestamp:new Date().toISOString()}]}})}),fe.on(at.AVATAR_SPEAKING,()=>{b(me=>({...me,isAvatarSpeaking:!0}))}),fe.on(at.AVATAR_SPEAKING_DONE,()=>{b(me=>({...me,isAvatarSpeaking:!1}))}),fe.on(at.AGENT_AUDIO_CHUNK,me=>{if(!f||ue.current)return;const Fe=ro(ke.current);if(Fe===qr.CLOUD_AVATAR||Fe===qr.DESKTOP_AVATAR)return;const It=py(me?.audio);if(!It)return;const Pt=pe();if(Pt)try{Pt.feed(It),b(ur=>({...ur,isAudioPlaying:!0}))}catch(ur){he("feed pcm failed",ur)}}),fe.on(at.AGENT_AUDIO_COMPLETE,()=>{if(!f||!ce.current)return;const me=ro(ke.current);if(!(me===qr.CLOUD_AVATAR||me===qr.DESKTOP_AVATAR))try{ce.current.setRequestStop()}catch{b(Fe=>({...Fe,isAudioPlaying:!1}))}}),fe.on(at.INTERRUPTED,()=>{ue.current=!1,Ie(),b(me=>({...me,isAudioPlaying:!1}))}),fe.on(at.RECONNECT_CREDENTIAL,me=>{he("received reconnect credential"),Xe(me)}),fe.on(at.RECONNECT_SUCCESS,me=>{Xe(me),b(Fe=>({...Fe,reconnectAttempt:0})),te.current=!1,re(Bt.CONNECTED)}),fe.on(at.RECONNECT_FAILED,me=>{he("reconnect failed",me),re(Bt.FAILED),de(me?.reason||"Reconnect failed")}),fe.on(at.AUTH_ERROR,me=>{re(Bt.FAILED),de(me?.message||"Authentication error")}),fe.on(at.ERROR,me=>{if(me?.code==="TTS_ERROR"){he("non-fatal TTS error",me);return}de(me?.message||me?.detail||"Server error")})},[Ie,f,pe,Xe,he,re,de]),yt=le.useCallback(({authPayload:fe,queryToken:Ue,expectReconnectSuccess:wt=!1})=>new Promise((dt,ct)=>{ft();const me=Oi(r,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:fe,query:Ue?{token:Ue}:void 0});if(U.current=me,mt(me,{isReconnect:wt,resolve:dt,reject:ct}),wt){const Fe=()=>{me.off(at.RECONNECT_FAILED,It),dt()},It=Pt=>{me.off(at.RECONNECT_SUCCESS,Fe),ct(new Error(Pt?.reason||"Reconnect failed"))};me.once(at.RECONNECT_SUCCESS,Fe),me.once(at.RECONNECT_FAILED,It),setTimeout(()=>{me.off(at.RECONNECT_SUCCESS,Fe),me.off(at.RECONNECT_FAILED,It),ct(new Error("Reconnect timed out"))},ee.current.timeoutMs)}}),[ft,mt,r]),ot=le.useCallback(async()=>{if(te.current)return;const fe=B.current;if(!fe){re(Bt.FAILED),de("Reconnect token unavailable. Please initialize a new session.");return}te.current=!0;for(let Ue=1;Ue<=ee.current.maxAttempts;Ue+=1){if(X.current){te.current=!1;return}b(wt=>({...wt,reconnectAttempt:Ue}));try{await yt({authPayload:{reconnectToken:fe.reconnectToken,sessionId:fe.sessionId,role:fe.role},expectReconnectSuccess:!0}),te.current=!1;return}catch(wt){he(`reconnect attempt ${Ue} failed`,wt);const dt=Math.min(ee.current.maxDelayMs,ee.current.initialDelayMs*2**(Ue-1));await hy(dt)}}te.current=!1,re(Bt.FAILED),de("Reconnect window expired. Please initialize a new session.")},[yt,he,re,de]);le.useEffect(()=>{R.connectionState===Bt.RECONNECTING&&ee.current.enabled&&ot()},[R.connectionState,ot]);const Ye=le.useCallback(async({apiKey:fe,publicChatId:Ue,agentId:wt,language:dt="en"}={})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!fe&&!Ue&&!wt)throw new Error("Provide one of apiKey, publicChatId, or agentId");Ne(),re(Bt.INITIALIZING),de(null);const ct={...fe?{api_key:fe}:{},...Ue?{public_chat_id:Ue}:{},...wt?{agent_id:wt}:{},language:dt},me=await fetch(`${n}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ct)}).then(_p),Fe=me?.session_id||null,It=me?.session_token;if(!Fe||!It)throw new Error("Invalid initialize session response");return b(Pt=>({...Pt,session:{...Pt.session,sessionId:Fe,agentType:me?.streaming_url?qr.CLOUD_AVATAR:Pt.session.agentType,streamingUrl:me?.streaming_url||null,uniqueId:me?.unique_id||null,role:null}})),re(Bt.CONNECTING),me?.streaming_url?Qe(Qt.CONNECTING):Qe(Qt.IDLE),await yt({authPayload:{token:It},queryToken:It}),me},[yt,Ne,n,Qe,re,de,r]),Le=le.useCallback(async({uniqueId:fe})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!fe)throw new Error("uniqueId is required");Ne(),re(Bt.INITIALIZING),de(null);const Ue=await fetch(`${n}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:fe})}).then(_p),wt=Ue?.session_id||null,dt=Ue?.session_token;if(!wt||!dt)throw new Error("Invalid join session response");return b(ct=>({...ct,session:{...ct.session,sessionId:wt,uniqueId:fe,role:"user",agentType:qr.DESKTOP_AVATAR}})),re(Bt.CONNECTING),Qe(Qt.IDLE),await yt({authPayload:{token:dt},queryToken:dt}),Ue},[yt,Ne,n,Qe,re,de,r]),rt=le.useCallback(()=>{Ne({keepManualDisconnect:!0})},[Ne]),Ze=le.useCallback(async()=>(rt(),{success:!0}),[rt]),Q=le.useCallback((fe,Ue={})=>!U.current||!R.isConnected?!1:(U.current.emit(fe,Ue),!0),[R.isConnected]),Me=le.useCallback(fe=>{if(!fe||!String(fe).trim())return!1;const Ue={id:`user-${Date.now()}`,role:"user",text:String(fe),timestamp:new Date().toISOString()};return b(wt=>({...wt,messages:[...wt.messages,Ue]})),Q(at.USER_MESSAGE,{message:String(fe)})},[Q]),et=le.useCallback(fe=>Q(at.AUDIO_CHUNK,{audio:fe}),[Q]),gt=le.useCallback(()=>Q(at.AUDIO_END,{}),[Q]),Gt=le.useCallback(()=>(ue.current=!0,Ie(),b(fe=>({...fe,isAudioPlaying:!1})),Q(at.INTERRUPT,{})),[Ie,Q]),Et=le.useCallback(()=>Q(at.REFRESH_SESSION_ACTIVITY,{}),[Q]),lt=le.useCallback(()=>Q(at.CLEAR_SESSION_HISTORY,{}),[Q]),tt=le.useCallback(fe=>fe?Q(at.CHANGE_SESSION_LANGUAGE,{language:fe}):!1,[Q]),Xt=le.useCallback(()=>{ie.current.clear(),b(fe=>({...fe,messages:[]}))},[]);le.useEffect(()=>()=>{X.current=!0,ft(),Ie()},[ft,Ie]);const vt=le.useMemo(()=>({...R,initializeSession:Ye,joinDesktopSession:Le,disconnect:rt,terminateSession:Ze,emit:Q,sendTextMessage:Me,sendAudioChunk:et,endAudioStream:gt,interrupt:Gt,refreshSessionActivity:Et,clearSessionHistory:lt,changeSessionLanguage:tt,clearMessages:Xt,resumeAudioPlayback:ge,attachAudioElement:ut,setCloudStreamState:Qe,audioElement:Be.current,socket:U.current}),[ut,Xt,lt,rt,Q,gt,Ye,Gt,tt,Le,Ze,Et,ge,et,Me,Qe,R]);return ar.jsx(lf.Provider,{value:vt,children:c})}const Hr=()=>{const c=le.useContext(lf);if(!c)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return c},gy=["Cannot read properties of null (reading 'state')","MicVAD has null stream"],Sp=c=>c?gy.some(r=>String(c).includes(r)):!1;function df(){typeof window>"u"||window.__rqmiiAudioErrorSuppressorsInstalled||(window.__rqmiiAudioErrorSuppressorsInstalled=!0,window.addEventListener("error",c=>{if(Sp(c?.message))return c.preventDefault(),!0}),window.addEventListener("unhandledrejection",c=>{const r=c?.reason?.message||String(c?.reason||"");Sp(r)&&c.preventDefault()}))}df();const yy={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:16e3},wy=["audio/webm;codecs=opus","audio/webm","audio/mp4"],vy=()=>typeof window>"u"||!window.MediaRecorder?.isTypeSupported?"":wy.find(c=>window.MediaRecorder.isTypeSupported(c))||"";function by(c={}){const{onAudioChunk:r,onAudioEnd:n,onError:a,holdDelayMs:f=220,timesliceMs:v=100,interruptOnHoldStart:C=!0,audioConstraints:R=yy}=c,{sendAudioChunk:b,endAudioStream:U,interrupt:B}=Hr(),te=le.useRef(null),X=le.useRef(null),ee=le.useRef(null),ie=le.useRef(!0),[ce,ue]=le.useState(!1),[Be,ke]=le.useState(!1),[he,re]=le.useState(null),de=le.useCallback(async Ne=>{if(!Ne||Ne.size<=0)return;const Xe=await Ne.arrayBuffer();if(r){r(Xe);return}b(Xe)},[r,b]),pe=le.useCallback(()=>{X.current&&(X.current.getTracks().forEach(Ne=>Ne.stop()),X.current=null)},[]),Ie=le.useCallback(({discard:Ne=!1}={})=>{const Xe=te.current;if(!Xe)return!1;if(ie.current=!Ne,te.current=null,Xe.state==="inactive")return Ne||(n?n():U()),pe(),ke(!1),!0;try{Xe.requestData()}catch{}Xe.onstop=()=>{ie.current&&(n?n():U()),pe(),ke(!1)};try{Xe.stop()}catch(mt){pe(),ke(!1),a?.(mt)}return!0},[pe,U,n,a]),ge=le.useCallback(async()=>{if(te.current)return!0;if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||typeof window>"u"||typeof window.MediaRecorder>"u"){const Ne=new Error("MediaRecorder or microphone APIs are unavailable in this browser");return re(Ne.message),a?.(Ne),!1}try{const Ne=await navigator.mediaDevices.getUserMedia({audio:R});X.current=Ne;const Xe=vy(),mt=Xe?{mimeType:Xe}:void 0,yt=new window.MediaRecorder(Ne,mt);return yt.ondataavailable=ot=>{de(ot.data)},yt.onerror=ot=>{const Ye=ot?.error||new Error("Microphone recording failed");re(Ye?.message||"recording_failed"),a?.(Ye)},te.current=yt,ke(!0),re(null),yt.start(v),!0}catch(Ne){return pe(),ke(!1),re("permission_denied"),a?.(Ne),!1}},[R,pe,de,a,v]),ut=le.useCallback(()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),ue(!0),ee.current=setTimeout(()=>{C&&B(),ge()},f)},[f,B,C,ge]),Qe=le.useCallback(()=>{ue(!1),ee.current&&(clearTimeout(ee.current),ee.current=null),Ie()},[Ie]);le.useEffect(()=>()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),Ie({discard:!0}),pe()},[pe,Ie]);const ft=le.useMemo(()=>({onPointerDown:Ne=>{Ne.preventDefault(),ut()},onPointerUp:Ne=>{Ne.preventDefault(),Qe()},onPointerCancel:Ne=>{Ne.preventDefault(),Qe()},onPointerLeave:Ne=>{Ne.preventDefault(),Qe()}}),[ut,Qe]);return{isPressing:ce,isRecording:Be,micError:he,startRecording:ge,stopRecording:Ie,startPress:ut,stopPress:Qe,eventHandlers:ft}}var no={},so={},Ys={},Tp;function cf(){if(Tp)return Ys;Tp=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let n="/";return r&&(n=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Ys.baseAssetPath=n,Ys}var Js={},$p;function Ao(){if($p)return Js;$p=1,Object.defineProperty(Js,"__esModule",{value:!0}),Js.defaultModelFetcher=void 0;const c=r=>fetch(r).then(n=>n.arrayBuffer());return Js.defaultModelFetcher=c,Js}var Fr={},Zs={},xp;function oi(){if(xp)return Zs;xp=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.log=void 0;const c=r=>n=>{console.log(`VAD | ${r} >`,n)};return Zs.log={error:c("error"),debug:c("debug"),warn:c("warn")},Zs}var ei={},Ep;function Fi(){if(Ep)return ei;Ep=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.Message=void 0;var c;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(c||(ei.Message=c={})),ei}var Cp;function Mo(){if(Cp)return Fr;Cp=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.FrameProcessor=Fr.validateOptions=Fr.defaultFrameProcessorOptions=void 0;const c=oi(),r=Fi();Fr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&c.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&c.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&c.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&c.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&c.log.error("minSpeechMs should be positive")}Fr.validateOptions=n;const a=C=>{const R=C.reduce((U,B)=>(U.push(U.at(-1)+B.length),U),[0]),b=new Float32Array(R.at(-1));return C.forEach((U,B)=>{const te=R[B];b.set(U,te)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),B=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:U,minSpeechFrames:B}}class v{constructor(R,b,U,B){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=U,this.msPerFrame=B,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=ie=>{this.options={...this.options,...ie};const{redemptionFrames:ce,preSpeechPadFrames:ue,minSpeechFrames:Be}=f(this.options,this.msPerFrame);this.redemptionFrames=ce,this.preSpeechPadFrames=ue,this.minSpeechFrames=Be},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=ie=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(ie):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=ie=>{const ce=this.audioBuffer;this.audioBuffer=[];const ue=this.speaking;if(this.reset(),ue)if(ce.reduce((ke,he)=>he.isSpeech?ke+1:ke,0)>=this.minSpeechFrames){const ke=a(ce.map(he=>he.frame));ie({msg:r.Message.SpeechEnd,audio:ke})}else ie({msg:r.Message.VADMisfire});return{}},this.process=async(ie,ce)=>{if(!this.active)return;const ue=await this.modelProcessFunc(ie),Be=ue.isSpeech>=this.options.positiveSpeechThreshold;if(ce({probs:ue,msg:r.Message.FrameProcessed,frame:ie}),this.audioBuffer.push({frame:ie,isSpeech:Be}),Be&&(this.speechFrameCount++,this.redemptionCounter=0),Be&&!this.speaking&&(this.speaking=!0,ce({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,ce({msg:r.Message.SpeechRealStart})),ue.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ke=this.audioBuffer;if(this.audioBuffer=[],ke.reduce((re,de)=>de.isSpeech?re+1:re,0)>=this.minSpeechFrames){const re=a(ke.map(de=>de.frame));ce({msg:r.Message.SpeechEnd,audio:re})}else ce({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:te,preSpeechPadFrames:X,minSpeechFrames:ee}=f(this.options,this.msPerFrame);this.redemptionFrames=te,this.preSpeechPadFrames=X,this.minSpeechFrames=ee,this.reset()}}return Fr.FrameProcessor=v,Fr}var Vr={};function lr(c){throw new Error('Could not dynamically require "'+c+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var io={exports:{}};/*!
|
|
22
|
+
<%s key={someKey} {...props} />`,gt,lt,tt,lt),Ze[lt+gt]=!0)}if(lt=null,et!==void 0&&(n(et),lt=""+et),C(Me)&&(n(Me.key),lt=""+Me.key),"key"in Me){et={};for(var Xt in Me)Xt!=="key"&&(et[Xt]=Me[Xt])}else et=Me;return lt&&R(et,typeof Q=="function"?Q.displayName||Q.name||"Unknown":Q),U(Q,lt,et,f(),Gt,Ct)}function te(Q){X(Q)?Q._store&&(Q._store.validated=1):typeof Q=="object"&&Q!==null&&Q.$$typeof===ut&&(Q._payload.status==="fulfilled"?X(Q._payload.value)&&Q._payload.value._store&&(Q._payload.value._store.validated=1):Q._store&&(Q._store.validated=1))}function X(Q){return typeof Q=="object"&&Q!==null&&Q.$$typeof===ie}var ee=le,ie=Symbol.for("react.transitional.element"),ce=Symbol.for("react.portal"),ue=Symbol.for("react.fragment"),Be=Symbol.for("react.strict_mode"),ke=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),re=Symbol.for("react.context"),de=Symbol.for("react.forward_ref"),pe=Symbol.for("react.suspense"),Ie=Symbol.for("react.suspense_list"),ge=Symbol.for("react.memo"),ut=Symbol.for("react.lazy"),Qe=Symbol.for("react.activity"),ft=Symbol.for("react.client.reference"),Ne=ee.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Xe=Object.prototype.hasOwnProperty,mt=Array.isArray,yt=console.createTask?console.createTask:function(){return null};ee={react_stack_bottom_frame:function(Q){return Q()}};var ot,Ye={},Le=ee.react_stack_bottom_frame.bind(ee,v)(),rt=yt(a(v)),Ze={};Qs.Fragment=ue,Qs.jsx=function(Q,Me,et){var gt=1e4>Ne.recentlyCreatedOwnerStacks++;return B(Q,Me,et,!1,gt?Error("react-stack-top-frame"):Le,gt?yt(a(Q)):rt)},Qs.jsxs=function(Q,Me,et){var gt=1e4>Ne.recentlyCreatedOwnerStacks++;return B(Q,Me,et,!0,gt?Error("react-stack-top-frame"):Le,gt?yt(a(Q)):rt)}})()),Qs}var pp;function gg(){return pp||(pp=1,process.env.NODE_ENV==="production"?Ci.exports=fg():Ci.exports=mg()),Ci.exports}var ar=gg();const Or=Object.create(null);Or.open="0";Or.close="1";Or.ping="2";Or.pong="3";Or.message="4";Or.upgrade="5";Or.noop="6";const Mi=Object.create(null);Object.keys(Or).forEach(c=>{Mi[Or[c]]=c});const po={type:"error",data:"parser error"},Kp=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",Qp=typeof ArrayBuffer=="function",Xp=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c&&c.buffer instanceof ArrayBuffer,xo=({type:c,data:r},n,a)=>Kp&&r instanceof Blob?n?a(r):fp(r,a):Qp&&(r instanceof ArrayBuffer||Xp(r))?n?a(r):fp(new Blob([r]),a):a(Or[c]+(r||"")),fp=(c,r)=>{const n=new FileReader;return n.onload=function(){const a=n.result.split(",")[1];r("b"+(a||""))},n.readAsDataURL(c)};function mp(c){return c instanceof Uint8Array?c:c instanceof ArrayBuffer?new Uint8Array(c):new Uint8Array(c.buffer,c.byteOffset,c.byteLength)}let Za;function yg(c,r){if(Kp&&c.data instanceof Blob)return c.data.arrayBuffer().then(mp).then(r);if(Qp&&(c.data instanceof ArrayBuffer||Xp(c.data)))return r(mp(c.data));xo(c,!1,n=>{Za||(Za=new TextEncoder),r(Za.encode(n))})}const gp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",si=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let c=0;c<gp.length;c++)si[gp.charCodeAt(c)]=c;const wg=c=>{let r=c.length*.75,n=c.length,a,f=0,v,C,R,b;c[c.length-1]==="="&&(r--,c[c.length-2]==="="&&r--);const U=new ArrayBuffer(r),B=new Uint8Array(U);for(a=0;a<n;a+=4)v=si[c.charCodeAt(a)],C=si[c.charCodeAt(a+1)],R=si[c.charCodeAt(a+2)],b=si[c.charCodeAt(a+3)],B[f++]=v<<2|C>>4,B[f++]=(C&15)<<4|R>>2,B[f++]=(R&3)<<6|b&63;return U},vg=typeof ArrayBuffer=="function",Eo=(c,r)=>{if(typeof c!="string")return{type:"message",data:Yp(c,r)};const n=c.charAt(0);return n==="b"?{type:"message",data:bg(c.substring(1),r)}:Mi[n]?c.length>1?{type:Mi[n],data:c.substring(1)}:{type:Mi[n]}:po},bg=(c,r)=>{if(vg){const n=wg(c);return Yp(n,r)}else return{base64:!0,data:c}},Yp=(c,r)=>{switch(r){case"blob":return c instanceof Blob?c:new Blob([c]);case"arraybuffer":default:return c instanceof ArrayBuffer?c:c.buffer}},Jp="",_g=(c,r)=>{const n=c.length,a=new Array(n);let f=0;c.forEach((v,C)=>{xo(v,!1,R=>{a[C]=R,++f===n&&r(a.join(Jp))})})},Sg=(c,r)=>{const n=c.split(Jp),a=[];for(let f=0;f<n.length;f++){const v=Eo(n[f],r);if(a.push(v),v.type==="error")break}return a};function Tg(){return new TransformStream({transform(c,r){yg(c,n=>{const a=n.length;let f;if(a<126)f=new Uint8Array(1),new DataView(f.buffer).setUint8(0,a);else if(a<65536){f=new Uint8Array(3);const v=new DataView(f.buffer);v.setUint8(0,126),v.setUint16(1,a)}else{f=new Uint8Array(9);const v=new DataView(f.buffer);v.setUint8(0,127),v.setBigUint64(1,BigInt(a))}c.data&&typeof c.data!="string"&&(f[0]|=128),r.enqueue(f),r.enqueue(n)})}})}let eo;function ki(c){return c.reduce((r,n)=>r+n.length,0)}function Ri(c,r){if(c[0].length===r)return c.shift();const n=new Uint8Array(r);let a=0;for(let f=0;f<r;f++)n[f]=c[0][a++],a===c[0].length&&(c.shift(),a=0);return c.length&&a<c[0].length&&(c[0]=c[0].slice(a)),n}function $g(c,r){eo||(eo=new TextDecoder);const n=[];let a=0,f=-1,v=!1;return new TransformStream({transform(C,R){for(n.push(C);;){if(a===0){if(ki(n)<1)break;const b=Ri(n,1);v=(b[0]&128)===128,f=b[0]&127,f<126?a=3:f===126?a=1:a=2}else if(a===1){if(ki(n)<2)break;const b=Ri(n,2);f=new DataView(b.buffer,b.byteOffset,b.length).getUint16(0),a=3}else if(a===2){if(ki(n)<8)break;const b=Ri(n,8),U=new DataView(b.buffer,b.byteOffset,b.length),B=U.getUint32(0);if(B>Math.pow(2,21)-1){R.enqueue(po);break}f=B*Math.pow(2,32)+U.getUint32(4),a=3}else{if(ki(n)<f)break;const b=Ri(n,f);R.enqueue(Eo(v?b:eo.decode(b),r)),a=0}if(f===0||f>c){R.enqueue(po);break}}}})}const Zp=4;function Dt(c){if(c)return xg(c)}function xg(c){for(var r in Dt.prototype)c[r]=Dt.prototype[r];return c}Dt.prototype.on=Dt.prototype.addEventListener=function(c,r){return this._callbacks=this._callbacks||{},(this._callbacks["$"+c]=this._callbacks["$"+c]||[]).push(r),this};Dt.prototype.once=function(c,r){function n(){this.off(c,n),r.apply(this,arguments)}return n.fn=r,this.on(c,n),this};Dt.prototype.off=Dt.prototype.removeListener=Dt.prototype.removeAllListeners=Dt.prototype.removeEventListener=function(c,r){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+c];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+c],this;for(var a,f=0;f<n.length;f++)if(a=n[f],a===r||a.fn===r){n.splice(f,1);break}return n.length===0&&delete this._callbacks["$"+c],this};Dt.prototype.emit=function(c){this._callbacks=this._callbacks||{};for(var r=new Array(arguments.length-1),n=this._callbacks["$"+c],a=1;a<arguments.length;a++)r[a-1]=arguments[a];if(n){n=n.slice(0);for(var a=0,f=n.length;a<f;++a)n[a].apply(this,r)}return this};Dt.prototype.emitReserved=Dt.prototype.emit;Dt.prototype.listeners=function(c){return this._callbacks=this._callbacks||{},this._callbacks["$"+c]||[]};Dt.prototype.hasListeners=function(c){return!!this.listeners(c).length};const Ni=typeof Promise=="function"&&typeof Promise.resolve=="function"?r=>Promise.resolve().then(r):(r,n)=>n(r,0),or=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Eg="arraybuffer";function ef(c,...r){return r.reduce((n,a)=>(c.hasOwnProperty(a)&&(n[a]=c[a]),n),{})}const Cg=or.setTimeout,kg=or.clearTimeout;function Ui(c,r){r.useNativeTimers?(c.setTimeoutFn=Cg.bind(or),c.clearTimeoutFn=kg.bind(or)):(c.setTimeoutFn=or.setTimeout.bind(or),c.clearTimeoutFn=or.clearTimeout.bind(or))}const Rg=1.33;function Ag(c){return typeof c=="string"?Mg(c):Math.ceil((c.byteLength||c.size)*Rg)}function Mg(c){let r=0,n=0;for(let a=0,f=c.length;a<f;a++)r=c.charCodeAt(a),r<128?n+=1:r<2048?n+=2:r<55296||r>=57344?n+=3:(a++,n+=4);return n}function tf(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Ig(c){let r="";for(let n in c)c.hasOwnProperty(n)&&(r.length&&(r+="&"),r+=encodeURIComponent(n)+"="+encodeURIComponent(c[n]));return r}function Pg(c){let r={},n=c.split("&");for(let a=0,f=n.length;a<f;a++){let v=n[a].split("=");r[decodeURIComponent(v[0])]=decodeURIComponent(v[1])}return r}class Og extends Error{constructor(r,n,a){super(r),this.description=n,this.context=a,this.type="TransportError"}}class Co extends Dt{constructor(r){super(),this.writable=!1,Ui(this,r),this.opts=r,this.query=r.query,this.socket=r.socket,this.supportsBinary=!r.forceBase64}onError(r,n,a){return super.emitReserved("error",new Og(r,n,a)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(r){this.readyState==="open"&&this.write(r)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(r){const n=Eo(r,this.socket.binaryType);this.onPacket(n)}onPacket(r){super.emitReserved("packet",r)}onClose(r){this.readyState="closed",super.emitReserved("close",r)}pause(r){}createUri(r,n={}){return r+"://"+this._hostname()+this._port()+this.opts.path+this._query(n)}_hostname(){const r=this.opts.hostname;return r.indexOf(":")===-1?r:"["+r+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(r){const n=Ig(r);return n.length?"?"+n:""}}class zg extends Co{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(r){this.readyState="pausing";const n=()=>{this.readyState="paused",r()};if(this._polling||!this.writable){let a=0;this._polling&&(a++,this.once("pollComplete",function(){--a||n()})),this.writable||(a++,this.once("drain",function(){--a||n()}))}else n()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(r){const n=a=>{if(this.readyState==="opening"&&a.type==="open"&&this.onOpen(),a.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(a)};Sg(r,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const r=()=>{this.write([{type:"close"}])};this.readyState==="open"?r():this.once("open",r)}write(r){this.writable=!1,_g(r,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const r=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=tf()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(r,n)}}let rf=!1;try{rf=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Dg=rf;function Lg(){}class Bg extends zg{constructor(r){if(super(r),typeof location<"u"){const n=location.protocol==="https:";let a=location.port;a||(a=n?"443":"80"),this.xd=typeof location<"u"&&r.hostname!==location.hostname||a!==r.port}}doWrite(r,n){const a=this.request({method:"POST",data:r});a.on("success",n),a.on("error",(f,v)=>{this.onError("xhr post error",f,v)})}doPoll(){const r=this.request();r.on("data",this.onData.bind(this)),r.on("error",(n,a)=>{this.onError("xhr poll error",n,a)}),this.pollXhr=r}}class Pr extends Dt{constructor(r,n,a){super(),this.createRequest=r,Ui(this,a),this._opts=a,this._method=a.method||"GET",this._uri=n,this._data=a.data!==void 0?a.data:null,this._create()}_create(){var r;const n=ef(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this._opts.xd;const a=this._xhr=this.createRequest(n);try{a.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){a.setDisableHeaderCheck&&a.setDisableHeaderCheck(!0);for(let f in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(f)&&a.setRequestHeader(f,this._opts.extraHeaders[f])}}catch{}if(this._method==="POST")try{a.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{a.setRequestHeader("Accept","*/*")}catch{}(r=this._opts.cookieJar)===null||r===void 0||r.addCookies(a),"withCredentials"in a&&(a.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(a.timeout=this._opts.requestTimeout),a.onreadystatechange=()=>{var f;a.readyState===3&&((f=this._opts.cookieJar)===null||f===void 0||f.parseCookies(a.getResponseHeader("set-cookie"))),a.readyState===4&&(a.status===200||a.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof a.status=="number"?a.status:0)},0))},a.send(this._data)}catch(f){this.setTimeoutFn(()=>{this._onError(f)},0);return}typeof document<"u"&&(this._index=Pr.requestsCount++,Pr.requests[this._index]=this)}_onError(r){this.emitReserved("error",r,this._xhr),this._cleanup(!0)}_cleanup(r){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Lg,r)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Pr.requests[this._index],this._xhr=null}}_onLoad(){const r=this._xhr.responseText;r!==null&&(this.emitReserved("data",r),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Pr.requestsCount=0;Pr.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",yp);else if(typeof addEventListener=="function"){const c="onpagehide"in or?"pagehide":"unload";addEventListener(c,yp,!1)}}function yp(){for(let c in Pr.requests)Pr.requests.hasOwnProperty(c)&&Pr.requests[c].abort()}const Ng=(function(){const c=nf({xdomain:!1});return c&&c.responseType!==null})();class Ug extends Bg{constructor(r){super(r);const n=r&&r.forceBase64;this.supportsBinary=Ng&&!n}request(r={}){return Object.assign(r,{xd:this.xd},this.opts),new Pr(nf,this.uri(),r)}}function nf(c){const r=c.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!r||Dg))return new XMLHttpRequest}catch{}if(!r)try{return new or[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const sf=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Fg extends Co{get name(){return"websocket"}doOpen(){const r=this.uri(),n=this.opts.protocols,a=sf?{}:ef(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(a.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(r,n,a)}catch(f){return this.emitReserved("error",f)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=r=>this.onClose({description:"websocket connection closed",context:r}),this.ws.onmessage=r=>this.onData(r.data),this.ws.onerror=r=>this.onError("websocket error",r)}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;xo(a,this.supportsBinary,v=>{try{this.doWrite(a,v)}catch{}f&&Ni(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const r=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=tf()),this.supportsBinary||(n.b64=1),this.createUri(r,n)}}const to=or.WebSocket||or.MozWebSocket;class Vg extends Fg{createSocket(r,n,a){return sf?new to(r,n,a):n?new to(r,n):new to(r)}doWrite(r,n){this.ws.send(n)}}class Gg extends Co{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(r){return this.emitReserved("error",r)}this._transport.closed.then(()=>{this.onClose()}).catch(r=>{this.onError("webtransport error",r)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(r=>{const n=$g(Number.MAX_SAFE_INTEGER,this.socket.binaryType),a=r.readable.pipeThrough(n).getReader(),f=Tg();f.readable.pipeTo(r.writable),this._writer=f.writable.getWriter();const v=()=>{a.read().then(({done:R,value:b})=>{R||(this.onPacket(b),v())}).catch(R=>{})};v();const C={type:"open"};this.query.sid&&(C.data=`{"sid":"${this.query.sid}"}`),this._writer.write(C).then(()=>this.onOpen())})})}write(r){this.writable=!1;for(let n=0;n<r.length;n++){const a=r[n],f=n===r.length-1;this._writer.write(a).then(()=>{f&&Ni(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var r;(r=this._transport)===null||r===void 0||r.close()}}const qg={websocket:Vg,webtransport:Gg,polling:Ug},Wg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function fo(c){if(c.length>8e3)throw"URI too long";const r=c,n=c.indexOf("["),a=c.indexOf("]");n!=-1&&a!=-1&&(c=c.substring(0,n)+c.substring(n,a).replace(/:/g,";")+c.substring(a,c.length));let f=Wg.exec(c||""),v={},C=14;for(;C--;)v[Hg[C]]=f[C]||"";return n!=-1&&a!=-1&&(v.source=r,v.host=v.host.substring(1,v.host.length-1).replace(/;/g,":"),v.authority=v.authority.replace("[","").replace("]","").replace(/;/g,":"),v.ipv6uri=!0),v.pathNames=jg(v,v.path),v.queryKey=Kg(v,v.query),v}function jg(c,r){const n=/\/{2,9}/g,a=r.replace(n,"/").split("/");return(r.slice(0,1)=="/"||r.length===0)&&a.splice(0,1),r.slice(-1)=="/"&&a.splice(a.length-1,1),a}function Kg(c,r){const n={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(a,f,v){f&&(n[f]=v)}),n}const mo=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ii=[];mo&&addEventListener("offline",()=>{Ii.forEach(c=>c())},!1);class nn extends Dt{constructor(r,n){if(super(),this.binaryType=Eg,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,r&&typeof r=="object"&&(n=r,r=null),r){const a=fo(r);n.hostname=a.host,n.secure=a.protocol==="https"||a.protocol==="wss",n.port=a.port,a.query&&(n.query=a.query)}else n.host&&(n.hostname=fo(n.host).host);Ui(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},n.transports.forEach(a=>{const f=a.prototype.name;this.transports.push(f),this._transportsByName[f]=a}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Pg(this.opts.query)),mo&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Ii.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(r){const n=Object.assign({},this.opts.query);n.EIO=Zp,n.transport=r,this.id&&(n.sid=this.id);const a=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[r]);return new this._transportsByName[r](a)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const r=this.opts.rememberUpgrade&&nn.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const n=this.createTransport(r);n.open(),this.setTransport(n)}setTransport(r){this.transport&&this.transport.removeAllListeners(),this.transport=r,r.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",n=>this._onClose("transport close",n))}onOpen(){this.readyState="open",nn.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(r){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",r),this.emitReserved("heartbeat"),r.type){case"open":this.onHandshake(JSON.parse(r.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const n=new Error("server error");n.code=r.data,this._onError(n);break;case"message":this.emitReserved("data",r.data),this.emitReserved("message",r.data);break}}onHandshake(r){this.emitReserved("handshake",r),this.id=r.sid,this.transport.query.sid=r.sid,this._pingInterval=r.pingInterval,this._pingTimeout=r.pingTimeout,this._maxPayload=r.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const r=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+r,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},r),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const r=this._getWritablePackets();this.transport.send(r),this._prevBufferLen=r.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let a=0;a<this.writeBuffer.length;a++){const f=this.writeBuffer[a].data;if(f&&(n+=Ag(f)),a>0&&n>this._maxPayload)return this.writeBuffer.slice(0,a);n+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const r=Date.now()>this._pingTimeoutTime;return r&&(this._pingTimeoutTime=0,Ni(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),r}write(r,n,a){return this._sendPacket("message",r,n,a),this}send(r,n,a){return this._sendPacket("message",r,n,a),this}_sendPacket(r,n,a,f){if(typeof n=="function"&&(f=n,n=void 0),typeof a=="function"&&(f=a,a=null),this.readyState==="closing"||this.readyState==="closed")return;a=a||{},a.compress=a.compress!==!1;const v={type:r,data:n,options:a};this.emitReserved("packetCreate",v),this.writeBuffer.push(v),f&&this.once("flush",f),this.flush()}close(){const r=()=>{this._onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),r()},a=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?a():r()}):this.upgrading?a():r()),this}_onError(r){if(nn.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",r),this._onClose("transport error",r)}_onClose(r,n){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),mo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const a=Ii.indexOf(this._offlineEventListener);a!==-1&&Ii.splice(a,1)}this.readyState="closed",this.id=null,this.emitReserved("close",r,n),this.writeBuffer=[],this._prevBufferLen=0}}}nn.protocol=Zp;class Qg extends nn{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let r=0;r<this._upgrades.length;r++)this._probe(this._upgrades[r])}_probe(r){let n=this.createTransport(r),a=!1;nn.priorWebsocketSuccess=!1;const f=()=>{a||(n.send([{type:"ping",data:"probe"}]),n.once("packet",te=>{if(!a)if(te.type==="pong"&&te.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;nn.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{a||this.readyState!=="closed"&&(B(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const X=new Error("probe error");X.transport=n.name,this.emitReserved("upgradeError",X)}}))};function v(){a||(a=!0,B(),n.close(),n=null)}const C=te=>{const X=new Error("probe error: "+te);X.transport=n.name,v(),this.emitReserved("upgradeError",X)};function R(){C("transport closed")}function b(){C("socket closed")}function U(te){n&&te.name!==n.name&&v()}const B=()=>{n.removeListener("open",f),n.removeListener("error",C),n.removeListener("close",R),this.off("close",b),this.off("upgrading",U)};n.once("open",f),n.once("error",C),n.once("close",R),this.once("close",b),this.once("upgrading",U),this._upgrades.indexOf("webtransport")!==-1&&r!=="webtransport"?this.setTimeoutFn(()=>{a||n.open()},200):n.open()}onHandshake(r){this._upgrades=this._filterUpgrades(r.upgrades),super.onHandshake(r)}_filterUpgrades(r){const n=[];for(let a=0;a<r.length;a++)~this.transports.indexOf(r[a])&&n.push(r[a]);return n}}let Xg=class extends Qg{constructor(r,n={}){const a=typeof r=="object"?r:n;(!a.transports||a.transports&&typeof a.transports[0]=="string")&&(a.transports=(a.transports||["polling","websocket","webtransport"]).map(f=>qg[f]).filter(f=>!!f)),super(r,a)}};function Yg(c,r="",n){let a=c;n=n||typeof location<"u"&&location,c==null&&(c=n.protocol+"//"+n.host),typeof c=="string"&&(c.charAt(0)==="/"&&(c.charAt(1)==="/"?c=n.protocol+c:c=n.host+c),/^(https?|wss?):\/\//.test(c)||(typeof n<"u"?c=n.protocol+"//"+c:c="https://"+c),a=fo(c)),a.port||(/^(http|ws)$/.test(a.protocol)?a.port="80":/^(http|ws)s$/.test(a.protocol)&&(a.port="443")),a.path=a.path||"/";const v=a.host.indexOf(":")!==-1?"["+a.host+"]":a.host;return a.id=a.protocol+"://"+v+":"+a.port+r,a.href=a.protocol+"://"+v+(n&&n.port===a.port?"":":"+a.port),a}const Jg=typeof ArrayBuffer=="function",Zg=c=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(c):c.buffer instanceof ArrayBuffer,af=Object.prototype.toString,ey=typeof Blob=="function"||typeof Blob<"u"&&af.call(Blob)==="[object BlobConstructor]",ty=typeof File=="function"||typeof File<"u"&&af.call(File)==="[object FileConstructor]";function ko(c){return Jg&&(c instanceof ArrayBuffer||Zg(c))||ey&&c instanceof Blob||ty&&c instanceof File}function Pi(c,r){if(!c||typeof c!="object")return!1;if(Array.isArray(c)){for(let n=0,a=c.length;n<a;n++)if(Pi(c[n]))return!0;return!1}if(ko(c))return!0;if(c.toJSON&&typeof c.toJSON=="function"&&arguments.length===1)return Pi(c.toJSON(),!0);for(const n in c)if(Object.prototype.hasOwnProperty.call(c,n)&&Pi(c[n]))return!0;return!1}function ry(c){const r=[],n=c.data,a=c;return a.data=go(n,r),a.attachments=r.length,{packet:a,buffers:r}}function go(c,r){if(!c)return c;if(ko(c)){const n={_placeholder:!0,num:r.length};return r.push(c),n}else if(Array.isArray(c)){const n=new Array(c.length);for(let a=0;a<c.length;a++)n[a]=go(c[a],r);return n}else if(typeof c=="object"&&!(c instanceof Date)){const n={};for(const a in c)Object.prototype.hasOwnProperty.call(c,a)&&(n[a]=go(c[a],r));return n}return c}function ny(c,r){return c.data=yo(c.data,r),delete c.attachments,c}function yo(c,r){if(!c)return c;if(c&&c._placeholder===!0){if(typeof c.num=="number"&&c.num>=0&&c.num<r.length)return r[c.num];throw new Error("illegal attachments")}else if(Array.isArray(c))for(let n=0;n<c.length;n++)c[n]=yo(c[n],r);else if(typeof c=="object")for(const n in c)Object.prototype.hasOwnProperty.call(c,n)&&(c[n]=yo(c[n],r));return c}const sy=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var nt;(function(c){c[c.CONNECT=0]="CONNECT",c[c.DISCONNECT=1]="DISCONNECT",c[c.EVENT=2]="EVENT",c[c.ACK=3]="ACK",c[c.CONNECT_ERROR=4]="CONNECT_ERROR",c[c.BINARY_EVENT=5]="BINARY_EVENT",c[c.BINARY_ACK=6]="BINARY_ACK"})(nt||(nt={}));class iy{constructor(r){this.replacer=r}encode(r){return(r.type===nt.EVENT||r.type===nt.ACK)&&Pi(r)?this.encodeAsBinary({type:r.type===nt.EVENT?nt.BINARY_EVENT:nt.BINARY_ACK,nsp:r.nsp,data:r.data,id:r.id}):[this.encodeAsString(r)]}encodeAsString(r){let n=""+r.type;return(r.type===nt.BINARY_EVENT||r.type===nt.BINARY_ACK)&&(n+=r.attachments+"-"),r.nsp&&r.nsp!=="/"&&(n+=r.nsp+","),r.id!=null&&(n+=r.id),r.data!=null&&(n+=JSON.stringify(r.data,this.replacer)),n}encodeAsBinary(r){const n=ry(r),a=this.encodeAsString(n.packet),f=n.buffers;return f.unshift(a),f}}class Ro extends Dt{constructor(r){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof r=="function"?{reviver:r}:r)}add(r){let n;if(typeof r=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");n=this.decodeString(r);const a=n.type===nt.BINARY_EVENT;a||n.type===nt.BINARY_ACK?(n.type=a?nt.EVENT:nt.ACK,this.reconstructor=new ay(n),n.attachments===0&&super.emitReserved("decoded",n)):super.emitReserved("decoded",n)}else if(ko(r)||r.base64)if(this.reconstructor)n=this.reconstructor.takeBinaryData(r),n&&(this.reconstructor=null,super.emitReserved("decoded",n));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+r)}decodeString(r){let n=0;const a={type:Number(r.charAt(0))};if(nt[a.type]===void 0)throw new Error("unknown packet type "+a.type);if(a.type===nt.BINARY_EVENT||a.type===nt.BINARY_ACK){const v=n+1;for(;r.charAt(++n)!=="-"&&n!=r.length;);const C=r.substring(v,n);if(C!=Number(C)||r.charAt(n)!=="-")throw new Error("Illegal attachments");const R=Number(C);if(!oy(R)||R<0)throw new Error("Illegal attachments");if(R>this.opts.maxAttachments)throw new Error("too many attachments");a.attachments=R}if(r.charAt(n+1)==="/"){const v=n+1;for(;++n&&!(r.charAt(n)===","||n===r.length););a.nsp=r.substring(v,n)}else a.nsp="/";const f=r.charAt(n+1);if(f!==""&&Number(f)==f){const v=n+1;for(;++n;){const C=r.charAt(n);if(C==null||Number(C)!=C){--n;break}if(n===r.length)break}a.id=Number(r.substring(v,n+1))}if(r.charAt(++n)){const v=this.tryParse(r.substr(n));if(Ro.isPayloadValid(a.type,v))a.data=v;else throw new Error("invalid payload")}return a}tryParse(r){try{return JSON.parse(r,this.opts.reviver)}catch{return!1}}static isPayloadValid(r,n){switch(r){case nt.CONNECT:return wp(n);case nt.DISCONNECT:return n===void 0;case nt.CONNECT_ERROR:return typeof n=="string"||wp(n);case nt.EVENT:case nt.BINARY_EVENT:return Array.isArray(n)&&(typeof n[0]=="number"||typeof n[0]=="string"&&sy.indexOf(n[0])===-1);case nt.ACK:case nt.BINARY_ACK:return Array.isArray(n)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ay{constructor(r){this.packet=r,this.buffers=[],this.reconPack=r}takeBinaryData(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){const n=ny(this.reconPack,this.buffers);return this.finishedReconstruction(),n}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const oy=Number.isInteger||function(c){return typeof c=="number"&&isFinite(c)&&Math.floor(c)===c};function wp(c){return Object.prototype.toString.call(c)==="[object Object]"}const ly=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Ro,Encoder:iy,get PacketType(){return nt}},Symbol.toStringTag,{value:"Module"}));function Tr(c,r,n){return c.on(r,n),function(){c.off(r,n)}}const uy=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class of extends Dt{constructor(r,n,a){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=r,this.nsp=n,a&&a.auth&&(this.auth=a.auth),this._opts=Object.assign({},a),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const r=this.io;this.subs=[Tr(r,"open",this.onopen.bind(this)),Tr(r,"packet",this.onpacket.bind(this)),Tr(r,"error",this.onerror.bind(this)),Tr(r,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...r){return r.unshift("message"),this.emit.apply(this,r),this}emit(r,...n){var a,f,v;if(uy.hasOwnProperty(r))throw new Error('"'+r.toString()+'" is a reserved event name');if(n.unshift(r),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;const C={type:nt.EVENT,data:n};if(C.options={},C.options.compress=this.flags.compress!==!1,typeof n[n.length-1]=="function"){const B=this.ids++,te=n.pop();this._registerAckCallback(B,te),C.id=B}const R=(f=(a=this.io.engine)===null||a===void 0?void 0:a.transport)===null||f===void 0?void 0:f.writable,b=this.connected&&!(!((v=this.io.engine)===null||v===void 0)&&v._hasPingExpired());return this.flags.volatile&&!R||(b?(this.notifyOutgoingListeners(C),this.packet(C)):this.sendBuffer.push(C)),this.flags={},this}_registerAckCallback(r,n){var a;const f=(a=this.flags.timeout)!==null&&a!==void 0?a:this._opts.ackTimeout;if(f===void 0){this.acks[r]=n;return}const v=this.io.setTimeoutFn(()=>{delete this.acks[r];for(let R=0;R<this.sendBuffer.length;R++)this.sendBuffer[R].id===r&&this.sendBuffer.splice(R,1);n.call(this,new Error("operation has timed out"))},f),C=(...R)=>{this.io.clearTimeoutFn(v),n.apply(this,R)};C.withError=!0,this.acks[r]=C}emitWithAck(r,...n){return new Promise((a,f)=>{const v=(C,R)=>C?f(C):a(R);v.withError=!0,n.push(v),this.emit(r,...n)})}_addToQueue(r){let n;typeof r[r.length-1]=="function"&&(n=r.pop());const a={id:this._queueSeq++,tryCount:0,pending:!1,args:r,flags:Object.assign({fromQueue:!0},this.flags)};r.push((f,...v)=>(this._queue[0],f!==null?a.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(f)):(this._queue.shift(),n&&n(null,...v)),a.pending=!1,this._drainQueue())),this._queue.push(a),this._drainQueue()}_drainQueue(r=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!r||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(r){r.nsp=this.nsp,this.io._packet(r)}onopen(){typeof this.auth=="function"?this.auth(r=>{this._sendConnectPacket(r)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(r){this.packet({type:nt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},r):r})}onerror(r){this.connected||this.emitReserved("connect_error",r)}onclose(r,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",r,n),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(r=>{if(!this.sendBuffer.some(a=>String(a.id)===r)){const a=this.acks[r];delete this.acks[r],a.withError&&a.call(this,new Error("socket has been disconnected"))}})}onpacket(r){if(r.nsp===this.nsp)switch(r.type){case nt.CONNECT:r.data&&r.data.sid?this.onconnect(r.data.sid,r.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case nt.EVENT:case nt.BINARY_EVENT:this.onevent(r);break;case nt.ACK:case nt.BINARY_ACK:this.onack(r);break;case nt.DISCONNECT:this.ondisconnect();break;case nt.CONNECT_ERROR:this.destroy();const a=new Error(r.data.message);a.data=r.data.data,this.emitReserved("connect_error",a);break}}onevent(r){const n=r.data||[];r.id!=null&&n.push(this.ack(r.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(r){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const a of n)a.apply(this,r)}super.emit.apply(this,r),this._pid&&r.length&&typeof r[r.length-1]=="string"&&(this._lastOffset=r[r.length-1])}ack(r){const n=this;let a=!1;return function(...f){a||(a=!0,n.packet({type:nt.ACK,id:r,data:f}))}}onack(r){const n=this.acks[r.id];typeof n=="function"&&(delete this.acks[r.id],n.withError&&r.data.unshift(null),n.apply(this,r.data))}onconnect(r,n){this.id=r,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(r=>this.emitEvent(r)),this.receiveBuffer=[],this.sendBuffer.forEach(r=>{this.notifyOutgoingListeners(r),this.packet(r)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(r=>r()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:nt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(r){return this.flags.compress=r,this}get volatile(){return this.flags.volatile=!0,this}timeout(r){return this.flags.timeout=r,this}onAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(r),this}prependAny(r){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(r),this}offAny(r){if(!this._anyListeners)return this;if(r){const n=this._anyListeners;for(let a=0;a<n.length;a++)if(r===n[a])return n.splice(a,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(r),this}prependAnyOutgoing(r){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(r),this}offAnyOutgoing(r){if(!this._anyOutgoingListeners)return this;if(r){const n=this._anyOutgoingListeners;for(let a=0;a<n.length;a++)if(r===n[a])return n.splice(a,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(r){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const n=this._anyOutgoingListeners.slice();for(const a of n)a.apply(this,r.data)}}}function ns(c){c=c||{},this.ms=c.min||100,this.max=c.max||1e4,this.factor=c.factor||2,this.jitter=c.jitter>0&&c.jitter<=1?c.jitter:0,this.attempts=0}ns.prototype.duration=function(){var c=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var r=Math.random(),n=Math.floor(r*this.jitter*c);c=(Math.floor(r*10)&1)==0?c-n:c+n}return Math.min(c,this.max)|0};ns.prototype.reset=function(){this.attempts=0};ns.prototype.setMin=function(c){this.ms=c};ns.prototype.setMax=function(c){this.max=c};ns.prototype.setJitter=function(c){this.jitter=c};class wo extends Dt{constructor(r,n){var a;super(),this.nsps={},this.subs=[],r&&typeof r=="object"&&(n=r,r=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,Ui(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((a=n.randomizationFactor)!==null&&a!==void 0?a:.5),this.backoff=new ns({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=r;const f=n.parser||ly;this.encoder=new f.Encoder,this.decoder=new f.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(r){return arguments.length?(this._reconnection=!!r,r||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(r){return r===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=r,this)}reconnectionDelay(r){var n;return r===void 0?this._reconnectionDelay:(this._reconnectionDelay=r,(n=this.backoff)===null||n===void 0||n.setMin(r),this)}randomizationFactor(r){var n;return r===void 0?this._randomizationFactor:(this._randomizationFactor=r,(n=this.backoff)===null||n===void 0||n.setJitter(r),this)}reconnectionDelayMax(r){var n;return r===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=r,(n=this.backoff)===null||n===void 0||n.setMax(r),this)}timeout(r){return arguments.length?(this._timeout=r,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(r){if(~this._readyState.indexOf("open"))return this;this.engine=new Xg(this.uri,this.opts);const n=this.engine,a=this;this._readyState="opening",this.skipReconnect=!1;const f=Tr(n,"open",function(){a.onopen(),r&&r()}),v=R=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",R),r?r(R):this.maybeReconnectOnOpen()},C=Tr(n,"error",v);if(this._timeout!==!1){const R=this._timeout,b=this.setTimeoutFn(()=>{f(),v(new Error("timeout")),n.close()},R);this.opts.autoUnref&&b.unref(),this.subs.push(()=>{this.clearTimeoutFn(b)})}return this.subs.push(f),this.subs.push(C),this}connect(r){return this.open(r)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const r=this.engine;this.subs.push(Tr(r,"ping",this.onping.bind(this)),Tr(r,"data",this.ondata.bind(this)),Tr(r,"error",this.onerror.bind(this)),Tr(r,"close",this.onclose.bind(this)),Tr(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(r){try{this.decoder.add(r)}catch(n){this.onclose("parse error",n)}}ondecoded(r){Ni(()=>{this.emitReserved("packet",r)},this.setTimeoutFn)}onerror(r){this.emitReserved("error",r)}socket(r,n){let a=this.nsps[r];return a?this._autoConnect&&!a.active&&a.connect():(a=new of(this,r,n),this.nsps[r]=a),a}_destroy(r){const n=Object.keys(this.nsps);for(const a of n)if(this.nsps[a].active)return;this._close()}_packet(r){const n=this.encoder.encode(r);for(let a=0;a<n.length;a++)this.engine.write(n[a],r.options)}cleanup(){this.subs.forEach(r=>r()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(r,n){var a;this.cleanup(),(a=this.engine)===null||a===void 0||a.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",r,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const r=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const a=this.setTimeoutFn(()=>{r.skipReconnect||(this.emitReserved("reconnect_attempt",r.backoff.attempts),!r.skipReconnect&&r.open(f=>{f?(r._reconnecting=!1,r.reconnect(),this.emitReserved("reconnect_error",f)):r.onreconnect()}))},n);this.opts.autoUnref&&a.unref(),this.subs.push(()=>{this.clearTimeoutFn(a)})}}onreconnect(){const r=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",r)}}const Xs={};function Oi(c,r){typeof c=="object"&&(r=c,c=void 0),r=r||{};const n=Yg(c,r.path||"/socket.io"),a=n.source,f=n.id,v=n.path,C=Xs[f]&&v in Xs[f].nsps,R=r.forceNew||r["force new connection"]||r.multiplex===!1||C;let b;return R?b=new wo(a,r):(Xs[f]||(Xs[f]=new wo(a,r)),b=Xs[f]),n.query&&!r.query&&(r.query=n.queryKey),b.socket(n.path,r)}Object.assign(Oi,{Manager:wo,Socket:of,io:Oi,connect:Oi});const dy=c=>{if(window.audioCtx=c,c.state!=="suspended")return;const r=document.body,n=["touchstart","touchend","mousedown","keydown"];n.forEach(v=>r.addEventListener(v,a,!1));function a(){c.resume().then(f)}function f(){n.forEach(v=>r.removeEventListener(v,a))}};function Vt(c){this.init(c)}Vt.prototype.init=function(c){var r={encoding:"16bitInt",channels:1,sampleRate:16e3};this.option=Object.assign({},r,c),this.flush=this.flush.bind(this),this.maxValue=this.getMaxValue(),this.typedArray=this.getTypedArray(),this.playingBufferNode=null,this.scheduledBufferNode=null,this.createContext(),this.resetState()};Vt.prototype.getMaxValue=function(){var c={"8bitInt":128,"16bitInt":32768,"32bitInt":2147483648,"32bitFloat":1};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Vt.prototype.getTypedArray=function(){var c={"8bitInt":Int8Array,"16bitInt":Int16Array,"32bitInt":Int32Array,"32bitFloat":Float32Array};return c[this.option.encoding]?c[this.option.encoding]:c["16bitInt"]};Vt.prototype.createContext=function(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCtx.resume(),this.audioCtx.onstatechange=()=>console.log("audioCtx.state",this.audioCtx.state),dy(this.audioCtx),this.gainNode=this.audioCtx.createGain(),this.gainNode.gain.value=1,this.gainNode.connect(this.audioCtx.destination),this.startTime=this.audioCtx.currentTime};Vt.prototype.resetState=function(){this.playingStartTime=-1,this.lastGotTimestamp=0,this.samples=new Float32Array,this.timeout=void 0,this.flag_request_stop=!1,this.startTime=0};Vt.prototype.isTypedArray=function(c){return c.byteLength&&c.buffer&&c.buffer.constructor==ArrayBuffer};Vt.prototype.feed=function(c){if(this.isTypedArray(c)){c=this.getFormatedValue(c);var r=new Float32Array(this.samples.length+c.length);r.set(this.samples,0),r.set(c,this.samples.length),this.samples=r,this.timeout||this.flush()}};Vt.prototype.getFormatedValue=function(r){var r=new this.typedArray(r.buffer),n=new Float32Array(r.length),a;for(a=0;a<r.length;a++)n[a]=r[a]/this.maxValue;return n};Vt.prototype.volume=function(c){this.gainNode.gain.value=c};Vt.prototype.destroy=function(){this.interval&&clearInterval(this.interval),this.samples=null,this.audioCtx.close(),this.audioCtx=null};Vt.prototype.getTimestamp=function(c){if(this.playingStartTime>=0){if(!c)return this.audioCtx.currentTime-this.playingStartTime;const r=this.lastGotTimestamp;return this.lastGotTimestamp+=c/1e3,r}return 0};Vt.prototype.setRequestStop=function(){this.flag_request_stop=!0};Vt.prototype.setOnEnd=function(c){this.onEnd=c};Vt.prototype.interrupt=function(c){this.scheduledBufferNode&&this.scheduledBufferNode.stop(0),this.playingBufferNode&&this.playingBufferNode.stop(0),this.ensuredClearTimeout(),this.resetState(),this.flag_request_stop=!1};Vt.prototype.ensuredSetTimeout=(function(){let c;return function(r,n){c=performance.now();const a=f=>{f-c>=n?(this.timeout=void 0,r()):this.timeout=requestAnimationFrame(a)};this.timeout=requestAnimationFrame(a)}})();Vt.prototype.ensuredClearTimeout=function(){this.timeout&&(cancelAnimationFrame(this.timeout),this.timeout=void 0)};Vt.prototype.flush=function(){if(this.samples.length){var c=this.audioCtx.createBufferSource(),r=this.samples.length/this.option.channels,n=this.audioCtx.createBuffer(this.option.channels,r,this.option.sampleRate),a,f,v,C,R;for(f=0;f<this.option.channels;f++)for(a=n.getChannelData(f),v=f,R=50,C=0;C<r;C++)a[C]=this.samples[v],C<50&&(a[C]=a[C]*C/50),C>=r-51&&(a[C]=a[C]*R--/50),v+=this.option.channels;if(this.startTime<this.audioCtx.currentTime&&(this.startTime=this.audioCtx.currentTime),this.samples=new Float32Array,c.buffer=n,c.connect(this.gainNode),c.start(this.startTime),this.playingBufferNode=this.scheduledBufferNode,this.scheduledBufferNode=c,this.playingStartTime<0&&(this.playingStartTime=this.startTime),this.startTime+=n.duration,this.flag_request_stop)this.flag_request_stop=!1,c.onended=()=>{this.resetState(),this.onEnd&&this.onEnd()};else{const b=(this.startTime-this.audioCtx.currentTime)*1e3;this.ensuredSetTimeout(this.flush,b-50)}}};const qr={TEXT:"text",VOICE:"voice",TEXT_AND_VOICE:"text_and_voice",CLOUD_AVATAR:"cloud_avatar",DESKTOP_AVATAR:"desktop_avatar"},at={CONNECT:"connect",DISCONNECT:"disconnect",CONNECT_ERROR:"connect_error",SESSION_READY:"session_ready",SESSION_JOINED:"session_joined",SESSION_TERMINATED:"session_terminated",USER_MESSAGE:"user_message",AUDIO_CHUNK:"audio_chunk",AUDIO_END:"audio_end",INTERRUPT:"interrupt",CHANGE_SESSION_LANGUAGE:"change_session_language",REFRESH_SESSION_ACTIVITY:"refresh_session_activity",CLEAR_SESSION_HISTORY:"clear_session_history",TRANSCRIPT:"transcript",PARTIAL_TRANSCRIPT:"partial_transcript",AGENT_RESPONSE_CHUNK:"agent_response_chunk",AGENT_RESPONSE:"agent_response",AGENT_AUDIO_CHUNK:"agent_audio_chunk",AGENT_AUDIO_COMPLETE:"agent_audio_complete",AVATAR_SPEAKING:"avatar_speaking",AVATAR_SPEAKING_DONE:"avatar_speaking_done",INTERRUPTED:"interrupted",ERROR:"error",AUTH_ERROR:"auth_error",RECONNECT_CREDENTIAL:"reconnect_credential",RECONNECT_SUCCESS:"reconnect_success",RECONNECT_FAILED:"reconnect_failed"},Bt={IDLE:"idle",INITIALIZING:"initializing",CONNECTING:"connecting",CONNECTED:"connected",RECONNECTING:"reconnecting",FAILED:"failed",ENDED:"ended"},Qt={IDLE:"idle",CONNECTING:"connecting",LOADING:"loading",CONNECTED:"connected",DISCONNECTED:"disconnected",ERROR:"error"},vp={enabled:!0,maxAttempts:8,initialDelayMs:500,maxDelayMs:5e3,timeoutMs:8e3},cy={encoding:"16bitInt",channels:1,sampleRate:16e3},hy=c=>new Promise(r=>setTimeout(r,c)),py=c=>{if(!c)return null;if(c instanceof Uint8Array)return c;if(c instanceof ArrayBuffer)return new Uint8Array(c);if(c?.buffer instanceof ArrayBuffer){const r=Number.isInteger(c.byteOffset)?c.byteOffset:0,n=Number.isInteger(c.byteLength)?c.byteLength:c.buffer.byteLength-r;return new Uint8Array(c.buffer,r,n)}if(typeof c=="object"&&c.type==="Buffer"&&Array.isArray(c.data))return new Uint8Array(c.data);try{return new Uint8Array(c)}catch{return null}},ro=c=>String(c||"").toLowerCase().replaceAll("-","_"),fy=()=>{const c=new Map;return{addChunk:(f,v)=>{const C=f||`request-${Date.now()}`,b=`${c.get(C)||""}${v||""}`;return c.set(C,b),{id:C,text:b}},consume:(f,v="")=>{const C=f||`request-${Date.now()}`,R=c.get(C)||v||"";return c.delete(C),{id:C,text:R}},clear:()=>{c.clear()}}},lf=le.createContext(null),bp={connectionState:Bt.IDLE,isConnected:!1,isSessionReady:!1,error:null,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,cloudStream:{state:Qt.IDLE,error:null},transcript:null,partialTranscript:null,session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]},my=(c,r)=>{const n=new Vt(c),a=n.destroy.bind(n);let f=!1;return n.destroy=()=>{if(!f){f=!0;try{a()}catch{}}},n.setOnEnd(()=>{f||r?.()}),n._isDestroyed=()=>f,n},_p=async c=>{if(!c?.ok){let r=`HTTP ${c.status}`;try{const n=await c.json();r=n?.detail||n?.message||r}catch{}throw new Error(r)}return c.json()};function uf({children:c,wsUrl:r,restUrl:n,reconnectOptions:a,enableAudio:f=!0,pcmOptions:v,debug:C=!1}){const[R,b]=le.useState(bp),U=le.useRef(null),B=le.useRef(null),te=le.useRef(!1),X=le.useRef(!1),ee=le.useRef({...vp,...a}),ie=le.useRef(fy()),ce=le.useRef(null),ue=le.useRef(!1),Be=le.useRef(null),ke=le.useRef(bp.session.agentType);le.useEffect(()=>{ee.current={...vp,...a}},[a]),le.useEffect(()=>{ke.current=R.session.agentType},[R.session.agentType]);const he=le.useCallback((...fe)=>{C&&console.log("[RqmiiSDK]",...fe)},[C]),re=le.useCallback(fe=>{b(Ue=>({...Ue,connectionState:fe,isConnected:fe===Bt.CONNECTED}))},[]),de=le.useCallback(fe=>{b(Ue=>({...Ue,error:fe?String(fe):null}))},[]),pe=le.useCallback(()=>{if(!f||ce.current)return ce.current;const fe={...cy,...v||{}};return ce.current=my(fe,()=>{b(Ue=>({...Ue,isAudioPlaying:!1}))}),ce.current},[f,v]),Ie=le.useCallback(()=>{if(ce.current){try{ce.current.interrupt?.(),ce.current.destroy?.()}catch{}ce.current=null}},[]),ge=le.useCallback(async()=>{const fe=pe();if(fe)try{fe.audioCtx?.state==="suspended"&&await fe.audioCtx.resume()}catch(Ue){he("audio resume failed",Ue)}},[pe,he]),ut=le.useCallback(fe=>{Be.current=fe||null},[]),Qe=le.useCallback((fe,Ue=null)=>{b(wt=>({...wt,cloudStream:{state:fe,error:Ue?String(Ue):null}}))},[]),ft=le.useCallback(()=>{if(U.current){try{U.current.removeAllListeners(),U.current.disconnect()}catch{}U.current=null}},[]),Ne=le.useCallback(({keepManualDisconnect:fe=!1}={})=>{X.current=!0,B.current=null,te.current=!1,ue.current=!1,ie.current.clear(),Ie(),ft(),fe||(X.current=!1),b(Ue=>({...Ue,connectionState:Bt.IDLE,isConnected:!1,isSessionReady:!1,reconnectAttempt:0,isAudioPlaying:!1,isAvatarSpeaking:!1,error:null,transcript:null,partialTranscript:null,cloudStream:{state:Qt.IDLE,error:null},session:{sessionId:null,role:null,agentType:null,streamingUrl:null,uniqueId:null},messages:[]}))},[ft,Ie]),Xe=le.useCallback(fe=>{!fe?.sessionId||!fe?.reconnectToken||!fe?.role||(B.current={sessionId:fe.sessionId,reconnectToken:fe.reconnectToken,role:fe.role},b(Ue=>({...Ue,session:{...Ue.session,sessionId:fe.sessionId,role:fe.role}})))},[]),mt=le.useCallback((fe,{isReconnect:Ue=!1,resolve:wt,reject:dt}={})=>{const ct=(me,Fe)=>{me&&me(Fe)};fe.on(at.CONNECT,()=>{he("socket connected"),de(null),Ue||(re(Bt.CONNECTED),ct(wt))}),fe.on(at.CONNECT_ERROR,me=>{he("socket connect_error",me),Ue||(re(Bt.FAILED),de(me?.message||"Connection error"),ct(dt,me))}),fe.on(at.DISCONNECT,me=>{he("socket disconnected",me),b(Fe=>({...Fe,isConnected:!1,isSessionReady:!1})),!X.current&&(ee.current.enabled?re(Bt.RECONNECTING):(re(Bt.FAILED),de("Connection lost")))}),fe.on(at.SESSION_READY,me=>{b(Fe=>({...Fe,isSessionReady:!0,error:null,session:{...Fe.session,agentType:ro(me?.agentType||Fe.session.agentType)}}))}),fe.on(at.SESSION_JOINED,()=>{b(me=>({...me,isSessionReady:!0,error:null}))}),fe.on(at.SESSION_TERMINATED,()=>{re(Bt.ENDED),b(me=>({...me,isSessionReady:!1}))}),fe.on(at.TRANSCRIPT,me=>{b(Fe=>{const xt={...Fe,transcript:me||null};if(me?.is_final&&me?.text?.trim()){const kt={id:`transcript-${Date.now()}`,role:"user",text:me.text.trim(),timestamp:new Date().toISOString()};xt.messages=[...Fe.messages,kt]}return xt})}),fe.on(at.PARTIAL_TRANSCRIPT,me=>{b(Fe=>({...Fe,partialTranscript:me||null}))}),fe.on(at.AGENT_RESPONSE_CHUNK,me=>{const{id:Fe,text:xt}=ie.current.addChunk(me?.requestId,me?.text);b(kt=>{const ur=kt.messages.filter(dr=>dr.id!==Fe);return{...kt,messages:[...ur,{id:Fe,role:"assistant",text:xt,streaming:!0,timestamp:new Date().toISOString()}]}})}),fe.on(at.AGENT_RESPONSE,me=>{const{id:Fe,text:xt}=ie.current.consume(me?.requestId,me?.text);b(kt=>{const ur=kt.messages.filter(dr=>dr.id!==Fe);return{...kt,messages:[...ur,{id:Fe,role:"assistant",text:xt,streaming:!1,timestamp:new Date().toISOString()}]}})}),fe.on(at.AVATAR_SPEAKING,()=>{b(me=>({...me,isAvatarSpeaking:!0}))}),fe.on(at.AVATAR_SPEAKING_DONE,()=>{b(me=>({...me,isAvatarSpeaking:!1}))}),fe.on(at.AGENT_AUDIO_CHUNK,me=>{if(!f||ue.current)return;const Fe=ro(ke.current);if(Fe===qr.CLOUD_AVATAR||Fe===qr.DESKTOP_AVATAR)return;const xt=py(me?.audio);if(!xt)return;const kt=pe();if(kt)try{kt.feed(xt),b(ur=>({...ur,isAudioPlaying:!0}))}catch(ur){he("feed pcm failed",ur)}}),fe.on(at.AGENT_AUDIO_COMPLETE,()=>{if(!f||!ce.current)return;const me=ro(ke.current);if(!(me===qr.CLOUD_AVATAR||me===qr.DESKTOP_AVATAR))try{ce.current.setRequestStop()}catch{b(Fe=>({...Fe,isAudioPlaying:!1}))}}),fe.on(at.INTERRUPTED,()=>{ue.current=!1,Ie(),b(me=>({...me,isAudioPlaying:!1}))}),fe.on(at.RECONNECT_CREDENTIAL,me=>{he("received reconnect credential"),Xe(me)}),fe.on(at.RECONNECT_SUCCESS,me=>{Xe(me),b(Fe=>({...Fe,reconnectAttempt:0})),te.current=!1,re(Bt.CONNECTED)}),fe.on(at.RECONNECT_FAILED,me=>{he("reconnect failed",me),re(Bt.FAILED),de(me?.reason||"Reconnect failed")}),fe.on(at.AUTH_ERROR,me=>{re(Bt.FAILED),de(me?.message||"Authentication error")}),fe.on(at.ERROR,me=>{if(me?.code==="TTS_ERROR"){he("non-fatal TTS error",me);return}de(me?.message||me?.detail||"Server error")})},[Ie,f,pe,Xe,he,re,de]),yt=le.useCallback(({authPayload:fe,queryToken:Ue,expectReconnectSuccess:wt=!1})=>new Promise((dt,ct)=>{ft();const me=Oi(r,{transports:["websocket","polling"],timeout:2e4,reconnection:!1,auth:fe,query:Ue?{token:Ue}:void 0});if(U.current=me,mt(me,{isReconnect:wt,resolve:dt,reject:ct}),wt){const Fe=()=>{me.off(at.RECONNECT_FAILED,xt),dt()},xt=kt=>{me.off(at.RECONNECT_SUCCESS,Fe),ct(new Error(kt?.reason||"Reconnect failed"))};me.once(at.RECONNECT_SUCCESS,Fe),me.once(at.RECONNECT_FAILED,xt),setTimeout(()=>{me.off(at.RECONNECT_SUCCESS,Fe),me.off(at.RECONNECT_FAILED,xt),ct(new Error("Reconnect timed out"))},ee.current.timeoutMs)}}),[ft,mt,r]),ot=le.useCallback(async()=>{if(te.current)return;const fe=B.current;if(!fe){re(Bt.FAILED),de("Reconnect token unavailable. Please initialize a new session.");return}te.current=!0;for(let Ue=1;Ue<=ee.current.maxAttempts;Ue+=1){if(X.current){te.current=!1;return}b(wt=>({...wt,reconnectAttempt:Ue}));try{await yt({authPayload:{reconnectToken:fe.reconnectToken,sessionId:fe.sessionId,role:fe.role},expectReconnectSuccess:!0}),te.current=!1;return}catch(wt){he(`reconnect attempt ${Ue} failed`,wt);const dt=Math.min(ee.current.maxDelayMs,ee.current.initialDelayMs*2**(Ue-1));await hy(dt)}}te.current=!1,re(Bt.FAILED),de("Reconnect window expired. Please initialize a new session.")},[yt,he,re,de]);le.useEffect(()=>{R.connectionState===Bt.RECONNECTING&&ee.current.enabled&&ot()},[R.connectionState,ot]);const Ye=le.useCallback(async({apiKey:fe,publicChatId:Ue,agentId:wt,language:dt="en"}={})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!fe&&!Ue&&!wt)throw new Error("Provide one of apiKey, publicChatId, or agentId");Ne(),re(Bt.INITIALIZING),de(null);const ct={...fe?{api_key:fe}:{},...Ue?{public_chat_id:Ue}:{},...wt?{agent_id:wt}:{},language:dt},me=await fetch(`${n}/sessions/init`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ct)}).then(_p),Fe=me?.session_id||null,xt=me?.session_token;if(!Fe||!xt)throw new Error("Invalid initialize session response");return b(kt=>({...kt,session:{...kt.session,sessionId:Fe,agentType:me?.streaming_url?qr.CLOUD_AVATAR:kt.session.agentType,streamingUrl:me?.streaming_url||null,uniqueId:me?.unique_id||null,role:null}})),re(Bt.CONNECTING),me?.streaming_url?Qe(Qt.CONNECTING):Qe(Qt.IDLE),await yt({authPayload:{token:xt},queryToken:xt}),me},[yt,Ne,n,Qe,re,de,r]),Le=le.useCallback(async({uniqueId:fe})=>{if(!n)throw new Error("Missing restUrl in RqmiiAgentProvider");if(!r)throw new Error("Missing wsUrl in RqmiiAgentProvider");if(!fe)throw new Error("uniqueId is required");Ne(),re(Bt.INITIALIZING),de(null);const Ue=await fetch(`${n}/sessions/join`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({unique_id:fe})}).then(_p),wt=Ue?.session_id||null,dt=Ue?.session_token;if(!wt||!dt)throw new Error("Invalid join session response");return b(ct=>({...ct,session:{...ct.session,sessionId:wt,uniqueId:fe,role:"user",agentType:qr.DESKTOP_AVATAR}})),re(Bt.CONNECTING),Qe(Qt.IDLE),await yt({authPayload:{token:dt},queryToken:dt}),Ue},[yt,Ne,n,Qe,re,de,r]),rt=le.useCallback(()=>{Ne({keepManualDisconnect:!0})},[Ne]),Ze=le.useCallback(async()=>(rt(),{success:!0}),[rt]),Q=le.useCallback((fe,Ue={})=>!U.current||!R.isConnected?!1:(U.current.emit(fe,Ue),!0),[R.isConnected]),Me=le.useCallback(fe=>{if(!fe||!String(fe).trim())return!1;const Ue={id:`user-${Date.now()}`,role:"user",text:String(fe),timestamp:new Date().toISOString()};return b(wt=>({...wt,messages:[...wt.messages,Ue]})),Q(at.USER_MESSAGE,{message:String(fe)})},[Q]),et=le.useCallback(fe=>Q(at.AUDIO_CHUNK,{audio:fe}),[Q]),gt=le.useCallback(()=>Q(at.AUDIO_END,{}),[Q]),Gt=le.useCallback(()=>(ue.current=!0,Ie(),b(fe=>({...fe,isAudioPlaying:!1})),Q(at.INTERRUPT,{})),[Ie,Q]),Ct=le.useCallback(()=>Q(at.REFRESH_SESSION_ACTIVITY,{}),[Q]),lt=le.useCallback(()=>Q(at.CLEAR_SESSION_HISTORY,{}),[Q]),tt=le.useCallback(fe=>fe?Q(at.CHANGE_SESSION_LANGUAGE,{language:fe}):!1,[Q]),Xt=le.useCallback(()=>{ie.current.clear(),b(fe=>({...fe,messages:[]}))},[]);le.useEffect(()=>()=>{X.current=!0,ft(),Ie()},[ft,Ie]);const vt=le.useMemo(()=>({...R,initializeSession:Ye,joinDesktopSession:Le,disconnect:rt,terminateSession:Ze,emit:Q,sendTextMessage:Me,sendAudioChunk:et,endAudioStream:gt,interrupt:Gt,refreshSessionActivity:Ct,clearSessionHistory:lt,changeSessionLanguage:tt,clearMessages:Xt,resumeAudioPlayback:ge,attachAudioElement:ut,setCloudStreamState:Qe,audioElement:Be.current,socket:U.current}),[ut,Xt,lt,rt,Q,gt,Ye,Gt,tt,Le,Ze,Ct,ge,et,Me,Qe,R]);return ar.jsx(lf.Provider,{value:vt,children:c})}const Hr=()=>{const c=le.useContext(lf);if(!c)throw new Error("useRqmiiAgentContext must be used inside <RqmiiAgentProvider>");return c},gy=["Cannot read properties of null (reading 'state')","MicVAD has null stream"],Sp=c=>c?gy.some(r=>String(c).includes(r)):!1;function df(){typeof window>"u"||window.__rqmiiAudioErrorSuppressorsInstalled||(window.__rqmiiAudioErrorSuppressorsInstalled=!0,window.addEventListener("error",c=>{if(Sp(c?.message))return c.preventDefault(),!0}),window.addEventListener("unhandledrejection",c=>{const r=c?.reason?.message||String(c?.reason||"");Sp(r)&&c.preventDefault()}))}df();const yy={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:16e3},wy=["audio/webm;codecs=opus","audio/webm","audio/mp4"],vy=()=>typeof window>"u"||!window.MediaRecorder?.isTypeSupported?"":wy.find(c=>window.MediaRecorder.isTypeSupported(c))||"";function by(c={}){const{onAudioChunk:r,onAudioEnd:n,onError:a,holdDelayMs:f=220,timesliceMs:v=100,interruptOnHoldStart:C=!0,audioConstraints:R=yy}=c,{sendAudioChunk:b,endAudioStream:U,interrupt:B}=Hr(),te=le.useRef(null),X=le.useRef(null),ee=le.useRef(null),ie=le.useRef(!0),[ce,ue]=le.useState(!1),[Be,ke]=le.useState(!1),[he,re]=le.useState(null),de=le.useCallback(async Ne=>{if(!Ne||Ne.size<=0)return;const Xe=await Ne.arrayBuffer();if(r){r(Xe);return}b(Xe)},[r,b]),pe=le.useCallback(()=>{X.current&&(X.current.getTracks().forEach(Ne=>Ne.stop()),X.current=null)},[]),Ie=le.useCallback(({discard:Ne=!1}={})=>{const Xe=te.current;if(!Xe)return!1;if(ie.current=!Ne,te.current=null,Xe.state==="inactive")return Ne||(n?n():U()),pe(),ke(!1),!0;try{Xe.requestData()}catch{}Xe.onstop=()=>{ie.current&&(n?n():U()),pe(),ke(!1)};try{Xe.stop()}catch(mt){pe(),ke(!1),a?.(mt)}return!0},[pe,U,n,a]),ge=le.useCallback(async()=>{if(te.current)return!0;if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||typeof window>"u"||typeof window.MediaRecorder>"u"){const Ne=new Error("MediaRecorder or microphone APIs are unavailable in this browser");return re(Ne.message),a?.(Ne),!1}try{const Ne=await navigator.mediaDevices.getUserMedia({audio:R});X.current=Ne;const Xe=vy(),mt=Xe?{mimeType:Xe}:void 0,yt=new window.MediaRecorder(Ne,mt);return yt.ondataavailable=ot=>{de(ot.data)},yt.onerror=ot=>{const Ye=ot?.error||new Error("Microphone recording failed");re(Ye?.message||"recording_failed"),a?.(Ye)},te.current=yt,ke(!0),re(null),yt.start(v),!0}catch(Ne){return pe(),ke(!1),re("permission_denied"),a?.(Ne),!1}},[R,pe,de,a,v]),ut=le.useCallback(()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),ue(!0),ee.current=setTimeout(()=>{C&&B(),ge()},f)},[f,B,C,ge]),Qe=le.useCallback(()=>{ue(!1),ee.current&&(clearTimeout(ee.current),ee.current=null),Ie()},[Ie]);le.useEffect(()=>()=>{ee.current&&(clearTimeout(ee.current),ee.current=null),Ie({discard:!0}),pe()},[pe,Ie]);const ft=le.useMemo(()=>({onPointerDown:Ne=>{Ne.preventDefault(),ut()},onPointerUp:Ne=>{Ne.preventDefault(),Qe()},onPointerCancel:Ne=>{Ne.preventDefault(),Qe()},onPointerLeave:Ne=>{Ne.preventDefault(),Qe()}}),[ut,Qe]);return{isPressing:ce,isRecording:Be,micError:he,startRecording:ge,stopRecording:Ie,startPress:ut,stopPress:Qe,eventHandlers:ft}}var no={},so={},Ys={},Tp;function cf(){if(Tp)return Ys;Tp=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.baseAssetPath=void 0;const r=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let n="/";return r&&(n=r.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Ys.baseAssetPath=n,Ys}var Js={},$p;function Ao(){if($p)return Js;$p=1,Object.defineProperty(Js,"__esModule",{value:!0}),Js.defaultModelFetcher=void 0;const c=r=>fetch(r).then(n=>n.arrayBuffer());return Js.defaultModelFetcher=c,Js}var Fr={},Zs={},xp;function oi(){if(xp)return Zs;xp=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.log=void 0;const c=r=>n=>{console.log(`VAD | ${r} >`,n)};return Zs.log={error:c("error"),debug:c("debug"),warn:c("warn")},Zs}var ei={},Ep;function Fi(){if(Ep)return ei;Ep=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.Message=void 0;var c;return(function(r){r.AudioFrame="AUDIO_FRAME",r.SpeechStart="SPEECH_START",r.VADMisfire="VAD_MISFIRE",r.SpeechEnd="SPEECH_END",r.SpeechStop="SPEECH_STOP",r.SpeechRealStart="SPEECH_REAL_START",r.FrameProcessed="FRAME_PROCESSED"})(c||(ei.Message=c={})),ei}var Cp;function Mo(){if(Cp)return Fr;Cp=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.FrameProcessor=Fr.validateOptions=Fr.defaultFrameProcessorOptions=void 0;const c=oi(),r=Fi();Fr.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(C){(C.positiveSpeechThreshold<0||C.positiveSpeechThreshold>1)&&c.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(C.negativeSpeechThreshold<0||C.negativeSpeechThreshold>C.positiveSpeechThreshold)&&c.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),C.preSpeechPadMs<0&&c.log.error("preSpeechPadMs should be positive"),C.redemptionMs<0&&c.log.error("redemptionMs should be positive"),C.minSpeechMs<0&&c.log.error("minSpeechMs should be positive")}Fr.validateOptions=n;const a=C=>{const R=C.reduce((U,B)=>(U.push(U.at(-1)+B.length),U),[0]),b=new Float32Array(R.at(-1));return C.forEach((U,B)=>{const te=R[B];b.set(U,te)}),b};function f(C,R){const b=Math.floor(C.redemptionMs/R),U=Math.floor(C.preSpeechPadMs/R),B=Math.floor(C.minSpeechMs/R);return{redemptionFrames:b,preSpeechPadFrames:U,minSpeechFrames:B}}class v{constructor(R,b,U,B){this.modelProcessFunc=R,this.modelResetFunc=b,this.options=U,this.msPerFrame=B,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=ie=>{this.options={...this.options,...ie};const{redemptionFrames:ce,preSpeechPadFrames:ue,minSpeechFrames:Be}=f(this.options,this.msPerFrame);this.redemptionFrames=ce,this.preSpeechPadFrames=ue,this.minSpeechFrames=Be},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=ie=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(ie):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=ie=>{const ce=this.audioBuffer;this.audioBuffer=[];const ue=this.speaking;if(this.reset(),ue)if(ce.reduce((ke,he)=>he.isSpeech?ke+1:ke,0)>=this.minSpeechFrames){const ke=a(ce.map(he=>he.frame));ie({msg:r.Message.SpeechEnd,audio:ke})}else ie({msg:r.Message.VADMisfire});return{}},this.process=async(ie,ce)=>{if(!this.active)return;const ue=await this.modelProcessFunc(ie),Be=ue.isSpeech>=this.options.positiveSpeechThreshold;if(ce({probs:ue,msg:r.Message.FrameProcessed,frame:ie}),this.audioBuffer.push({frame:ie,isSpeech:Be}),Be&&(this.speechFrameCount++,this.redemptionCounter=0),Be&&!this.speaking&&(this.speaking=!0,ce({msg:r.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,ce({msg:r.Message.SpeechRealStart})),ue.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const ke=this.audioBuffer;if(this.audioBuffer=[],ke.reduce((re,de)=>de.isSpeech?re+1:re,0)>=this.minSpeechFrames){const re=a(ke.map(de=>de.frame));ce({msg:r.Message.SpeechEnd,audio:re})}else ce({msg:r.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:te,preSpeechPadFrames:X,minSpeechFrames:ee}=f(this.options,this.msPerFrame);this.redemptionFrames=te,this.preSpeechPadFrames=X,this.minSpeechFrames=ee,this.reset()}}return Fr.FrameProcessor=v,Fr}var Vr={};function lr(c){throw new Error('Could not dynamically require "'+c+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var io={exports:{}};/*!
|
|
23
23
|
* ONNX Runtime Web v1.24.3
|
|
24
24
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
25
25
|
* Licensed under the MIT License.
|
|
26
|
-
*/var kp;function _y(){return kp||(kp=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof lr<"u"?lr:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof lr<"u"?lr:t)[s]}):e)(function(e){if(typeof lr<"u")return lr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),b=(e,t)=>()=>(e&&(t=e(e=0)),t),U=(e,t)=>{for(var s in t)a(e,s,{get:t[s],enumerable:!0})},B=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of v(t))!C.call(e,o)&&o!==s&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},te=e=>B(a({},"__esModule",{value:!0}),e),X,ee,ie,ce,ue,Be=b(()=>{X=new Map,ee=[],ie=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=X.get(e);if(i===void 0)X.set(e,{backend:t,priority:s});else{if(i.priority>s)return;if(i.priority===s&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=ee.indexOf(e);o!==-1&&ee.splice(o,1);for(let l=0;l<ee.length;l++)if(X.get(ee[l]).priority<=s){ee.splice(l,0,e);return}ee.push(e)}return}throw new TypeError("not a valid backend")},ce=async e=>{let t=X.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return s||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ue=async e=>{let t=e.executionProviders||[],s=t.map(h=>typeof h=="string"?h:h.name),i=s.length===0?ee:s,o,l=[],u=new Set;for(let h of i){let p=await ce(h);typeof p=="string"?l.push({name:h,err:p}):(o||(o=p),o===p&&u.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${l.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of l)s.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${p}`);let d=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?d:Reflect.get(h,p)})]}}),ke=b(()=>{Be()}),he,re=b(()=>{he="1.24.3"}),de,pe,Ie=b(()=>{re(),de="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:he},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);de=e}},get logLevel(){return de}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),ge,ut=b(()=>{Ie(),ge=pe}),Qe,ft,Ne=b(()=>{Qe=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let i=s.getContext("2d");if(i!=null){let o,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);let u=t?.format!==void 0?t.format:"RGB",d=t?.norm,h,p;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));let g=l*o,m=0,w=g,_=g*2,S=-1;u==="RGBA"?(m=0,w=g,_=g*2,S=g*3):u==="RGB"?(m=0,w=g,_=g*2):u==="RBG"&&(m=0,_=g,w=g*2);for(let E=0;E<l;E++)for(let I=0;I<o;I++){let k=(e.data[m++]-p[0])*h[0],x=(e.data[w++]-p[1])*h[1],O=(e.data[_++]-p[2])*h[2],M=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+x+","+O+","+M+")",i.fillRect(I,E,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ft=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(s!=null){let o,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",h=t?.norm,p,g;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?g=[0,0,0,0]:typeof h.bias=="number"?g=[h.bias,h.bias,h.bias,h.bias]:(g=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(g[3]=h.bias[3]));let m=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,_=0,S=1,E=2,I=3,k=0,x=m,O=m*2,M=-1;d==="RGBA"?(k=0,x=m,O=m*2,M=m*3):d==="RGB"?(k=0,x=m,O=m*2):d==="RBG"&&(k=0,O=m,x=m*2),i=s.createImageData(o,l);for(let D=0;D<l*o;_+=w,S+=w,E+=w,I+=w,D++)i.data[_]=(e.data[k++]-g[0])*p[0],i.data[S]=(e.data[x++]-g[1])*p[1],i.data[E]=(e.data[O++]-g[2])*p[2],i.data[I]=M===-1?255:(e.data[M++]-g[3])*p[3]}else throw new Error("Can not access image data");return i}}),Xe,mt,yt,ot,Ye,Le,rt=b(()=>{Xt(),Xe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:i}=t,o=t.norm??{mean:255,bias:0},l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=s*i,g=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),m=4,w=0,_=1,S=2,E=3,I=0,k=p,x=p*2,O=-1;d==="RGB"&&(m=3,w=0,_=1,S=2,E=-1),h==="RGBA"?O=p*3:h==="RBG"?(I=0,x=p,k=p*2):h==="BGR"&&(x=0,k=p,I=p*2);for(let M=0;M<p;M++,w+=m,S+=m,_+=m,E+=m)g[I++]=(e[w]+u[0])/l[0],g[k++]=(e[_]+u[1])/l[1],g[x++]=(e[S]+u[2])/l[2],O!==-1&&E!==-1&&(g[O++]=(e[E]+u[3])/l[3]);return h==="RGBA"?new tt("float32",g,[1,4,s,i]):new tt("float32",g,[1,3,s,i])},mt=async(e,t)=>{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",u,d=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(s){let g=h();g.width=e.width,g.height=e.height;let m=p(g);if(m!=null){let w=e.height,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,_=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=w,d.width=_}else d.tensorFormat="RGBA",d.height=w,d.width=_;m.drawImage(e,0,0),u=m.getImageData(0,0,_,w).data}else throw new Error("Can not access image data")}else if(i){let g,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,m=t.resizedWidth):(g=e.height,m=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=g,d.width=m,t!==void 0){let w=h();w.width=m,w.height=g;let _=p(w);if(_!=null)_.putImageData(e,0,0),u=_.getImageData(0,0,m,g).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=h();g.width=e.width,g.height=e.height;let m=p(g);if(m!=null){let w=e.height,_=e.width;return m.drawImage(e,0,0,_,w),u=m.getImageData(0,0,_,w).data,d.height=w,d.width=_,Xe(u,d)}else throw new Error("Can not access image data")}else{if(l)return new Promise((g,m)=>{let w=h(),_=p(w);if(!e||!_)return m();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,_.drawImage(S,0,0,w.width,w.height);let E=_.getImageData(0,0,w.width,w.height);d.height=w.height,d.width=w.width,g(Xe(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return Xe(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},yt=(e,t)=>{let{width:s,height:i,download:o,dispose:l}=t,u=[1,i,s,4];return new tt({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},ot=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new tt({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},Ye=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new tt({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:i,download:o,dispose:l})},Le=(e,t,s)=>new tt({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ze,Q,Me,et,gt=b(()=>{Ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Me=!1,et=()=>{if(!Me){Me=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,i=typeof s<"u"&&s.from;e&&(Ze.set("int64",BigInt64Array),Q.set(BigInt64Array,"int64")),t&&(Ze.set("uint64",BigUint64Array),Q.set(BigUint64Array,"uint64")),i?(Ze.set("float16",s),Q.set(s,"float16")):Ze.set("float16",Uint16Array)}}}),Gt,Et,lt=b(()=>{Xt(),Gt=e=>{let t=1;for(let s=0;s<e.length;s++){let i=e[s];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${s}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${i}`);t*=i}return t},Et=(e,t)=>{switch(e.location){case"cpu":return new tt(e.type,e.data,t);case"cpu-pinned":return new tt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new tt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new tt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new tt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),tt,Xt=b(()=>{Ne(),rt(),gt(),lt(),tt=class{constructor(e,t,s){et();let i,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,o=e.dims,e.location){case"cpu-pinned":{let u=Ze.get(i);if(!u)throw new TypeError(`unsupported type "${i}" 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(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(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=e.gpuBuffer,this.downloader=e.download,this.disposer=e.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=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(i=e,d=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{let h=Ze.get(e);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&h===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${h.name} as data.`);e==="uint64"||e==="int64"?u=h.from(t,BigInt):u=h.from(t)}else if(t instanceof h)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&&h!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${h}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof e[0];if(h==="string")i="string",u=e;else if(h==="boolean")i="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",u=Uint8Array.from(e);else{let h=Q.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,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"}let l=Gt(o);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="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=i,this.dims=o,this.size=l}static async fromImage(e,t){return mt(e,t)}static fromTexture(e,t){return yt(e,t)}static fromGpuBuffer(e,t){return ot(e,t)}static fromMLTensor(e,t){return Ye(e,t)}static fromPinnedBuffer(e,t,s){return Le(e,t,s)}toDataURL(e){return Qe(this,e)}toImageData(e){return ft(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(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 Et(this,e)}}}),vt,fe=b(()=>{Xt(),vt=tt}),Ue,wt,dt,ct,me,Fe,It=b(()=>{Ie(),Ue=(e,t)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${e}::ORT::${t}`)},wt=(e,t)=>{let s=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let o=0;o<s.length;o++){if(i&&!s[o].includes("TRACE_FUNC")){let l=`FUNC_${e}::${s[o].trim().split(" ")[1]}`;t&&(l+=`::${t}`),Ue("CPU",l);return}s[o].includes("TRACE_FUNC")&&(i=!0)}},dt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("BEGIN",e)},ct=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("END",e)},me=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${e}`)},Fe=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${e}`)}}),Pt,ur=b(()=>{Be(),fe(),It(),Pt=class hf{constructor(t){this.handler=t}async run(t,s,i){dt(),me("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof vt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let p of s){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(s);for(let m of this.outputNames)if(g.indexOf(m)!==-1){let w=s[m];(w===null||w instanceof vt)&&(p=!0,u=!1,o[m]=w)}if(p){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(u)for(let p of this.outputNames)o[p]=null;let d=await this.handler.run(t,o,l),h={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let g=d[p];g instanceof vt?h[p]=g:h[p]=new vt(g.type,g.data,g.dims)}return Fe("InferenceSession.run"),ct(),h}async release(){return this.handler.dispose()}static async create(t,s,i,o){dt(),me("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof s=="object"&&s!==null)u=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof s=="object"&&s!==null)u=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,m=0,w=t.byteLength;if(typeof s=="object"&&s!==null)u=s;else if(typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(w=t.byteLength-m,typeof i=="number"){if(w=i,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||m+w>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-m}].`);if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"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 s<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(g,m,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,h]=await ue(u),p=await d.createInferenceSessionHandler(l,h);return Fe("InferenceSession.create"),ct(),new hf(p)}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}}}),dr,Vi=b(()=>{ur(),dr=Pt}),Gi=b(()=>{}),qi=b(()=>{}),Wi=b(()=>{}),Hi=b(()=>{}),is={};U(is,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,env:()=>ge,registerBackend:()=>ie});var Ot=b(()=>{ke(),ut(),Vi(),fe(),Gi(),qi(),It(),Wi(),Hi()}),sn=b(()=>{}),as={};U(as,{default:()=>os});var an,on,os,ji=b(()=>{Xh(),Yt(),hn(),an="ort-wasm-proxy-worker",on=globalThis.self?.name===an,on&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":mn(s.wasm).then(()=>{Ua(s).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:o}=s;Fa(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=s,o=$i(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=s;Ga(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":qa(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:d}=s;Ha(i,o,l,u,new Array(u.length).fill(null),d).then(h=>{h.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},Ka([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":ja(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),os=on?null:e=>new Worker(e??bt,{type:"classic",name:an})}),ls,us,bt,ln,zr,ds,cs,un,hs,dn,ps,cn,fs,hn=b(()=>{sn(),ls=typeof location>"u"?void 0:location.origin,us=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,bt=us(),ln=()=>{if(bt&&!bt.startsWith("blob:"))return bt.substring(0,bt.lastIndexOf("/")+1)},zr=(e,t)=>{try{let s=t??bt;return(s?new URL(e,s):new URL(e)).origin===ls}catch{return!1}},ds=(e,t)=>{let s=t??bt;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},cs=(e,t)=>`${t??"./"}${e}`,un=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},hs=async e=>(await import(e)).default,dn=(ji(),te(as)).default,ps=async()=>{if(!bt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(bt))return[void 0,dn()];let e=await un(bt);return[e,dn(e)]},cn=void 0,fs=async(e,t,s,i)=>{let o=cn&&!(e||t);if(o)if(bt)o=zr(bt)||i&&!s;else if(i&&!s)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,cn];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??ds(l,t),d=s&&u&&!zr(u,t),h=d?await un(u):u??cs(l,t);return[d?h:void 0,await hs(h)]}}}),pn,Dr,cr,fn,ms,gs,ys,mn,ze,Yt=b(()=>{hn(),Dr=!1,cr=!1,fn=!1,ms=()=>{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}},gs=()=>{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}},ys=()=>{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}},mn=async e=>{if(Dr)return Promise.resolve();if(cr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(fn)throw new Error("previous call to 'initializeWebAssembly()' failed.");cr=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ys())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!gs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=ms();s>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let o=e.wasmPaths,l=typeof o=="string"?o:void 0,u=o?.mjs,d=u?.href??u,h=o?.wasm,p=h?.href??h,g=e.wasmBinary,[m,w]=await fs(d,l,s>1,!!g||!!p),_=!1,S=[];if(t>0&&S.push(new Promise(E=>{setTimeout(()=>{_=!0,E()},t)})),S.push(new Promise((E,I)=>{let k={numThreads:s};if(g)k.wasmBinary=g,k.locateFile=x=>x;else if(p||l)k.locateFile=x=>p??l+x;else if(d&&d.indexOf("blob:")!==0)k.locateFile=x=>new URL(x,d).href;else if(m){let x=ln();x&&(k.locateFile=O=>x+O)}w(k).then(x=>{cr=!1,Dr=!0,pn=x,E(),m&&URL.revokeObjectURL(m)},x=>{cr=!1,fn=!0,I(x)})})),await Promise.race(S),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(Dr&&pn)return pn;throw new Error("WebAssembly is not initialized yet.")}}),xt,Lr,Re,gn=b(()=>{Yt(),xt=(e,t)=>{let s=ze(),i=s.lengthBytesUTF8(e)+1,o=s._malloc(i);return s.stringToUTF8(e,o,i),t.push(o),o},Lr=(e,t,s,i)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,l])=>{let u=t?t+o:o;if(typeof l=="object")Lr(l,u+".",s,i);else if(typeof l=="string"||typeof l=="number")i(u,l.toString());else if(typeof l=="boolean")i(u,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Re=e=>{let t=ze(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetLastError(o,o+i);let l=Number(t.getValue(o,i===4?"i32":"i64")),u=t.getValue(o+i,"*"),d=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),ws,Ki=b(()=>{Yt(),gn(),ws=e=>{let t=ze(),s=0,i=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=xt(e.tag,i)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),s===0&&Re("Can't create run options."),e?.extra!==void 0&&Lr(e.extra,"",new WeakSet,(u,d)=>{let h=xt(u,i),p=xt(d,i);t._OrtAddRunConfigEntry(s,h,p)!==0&&Re(`Can't set a run config entry: ${u} - ${d}.`)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseRunOptions(s),i.forEach(u=>t._free(u)),l}}}),vs,bs,_s,hr,Ss,Ts,Qi=b(()=>{Yt(),gn(),vs=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},bs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},_s=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},hr=(e,t,s,i)=>{let o=xt(t,i),l=xt(s,i);ze()._OrtAddSessionConfigEntry(e,o,l)!==0&&Re(`Can't set a session config entry: ${t} - ${s}.`)},Ss=async(e,t,s)=>{let i=t.executionProviders;for(let o of i){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",typeof o!="string"){let m=o?.deviceType;m&&hr(e,"deviceType",m,s)}break;case"webgpu":if(l="JS",typeof o!="string"){let m=o;if(m?.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);hr(e,"preferredLayout",m.preferredLayout,s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let d=xt(l,s),h=u.length,p=0,g=0;if(h>0){p=ze()._malloc(h*ze().PTR_SIZE),s.push(p),g=ze()._malloc(h*ze().PTR_SIZE),s.push(g);for(let m=0;m<h;m++)ze().setValue(p+m*ze().PTR_SIZE,u[m][0],"*"),ze().setValue(g+m*ze().PTR_SIZE,u[m][1],"*")}await ze()._OrtAppendExecutionProvider(e,d,p,g,h)!==0&&Re(`Can't append execution provider: ${l}.`)}},Ts=async e=>{let t=ze(),s=0,i=[],o=e||{};_s(o);try{let l=vs(o.graphOptimizationLevel??"all"),u=bs(o.executionMode??"sequential"),d=typeof o.logId=="string"?xt(o.logId,i):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let g=typeof o.optimizedModelFilePath=="string"?xt(o.optimizedModelFilePath,i):0;if(s=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,d,h,p,g),s===0&&Re("Can't create session options."),o.executionProviders&&await Ss(s,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);hr(s,"enableGraphCapture",o.enableGraphCapture.toString(),i)}if(o.freeDimensionOverrides)for(let[m,w]of Object.entries(o.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let _=xt(m,i);t._OrtAddFreeDimensionOverride(s,_,w)!==0&&Re(`Can't set a free dimension override: ${m} - ${w}.`)}return o.extra!==void 0&&Lr(o.extra,"",new WeakSet,(m,w)=>{hr(s,m,w,i)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&Re("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Jt,Zt,er,yn,wn,vn,bn,Ln,Pe=b(()=>{Jt=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Zt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},er=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((o,l)=>o*l,1);return s>0?Math.ceil(i*s):void 0},yn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},wn=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},vn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",bn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ln=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),_n,$s=b(()=>{sn(),_n=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),i=s?parseInt(s,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(d){if(d instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw d}let u=0;for(;;){let{done:d,value:h}=await o.read();if(d)break;let p=h.byteLength;new Uint8Array(l,u,p).set(h),u+=p}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),xs,Bn,Nn,xr,Un,Fn,Je,tr=b(()=>{Pe(),xs=["V","I","W","E","F"],Bn=(e,t)=>{console.log(`[${xs[e]},${new Date().toISOString()}]${t}`)},Un=(e,t)=>{Nn=e,xr=t},Fn=(e,t)=>{let s=wn(e),i=wn(Nn);s>=i&&Bn(s,typeof t=="function"?t():t)},Je=(...e)=>{xr&&Fn(...e)}}),Vn,Er,H,Kr,Gn,Es,pr,Ae=b(()=>{Vn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Er=class{static calcShape(e,t,s=!1){let i=e.length,o=t.length;if(i===0)return t;if(o===0)return e;let l=Math.max(e.length,t.length),u=new Array(l);if(s){if(i<2||o<2)return;let d=Vn.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(d===void 0)return;[u[l-2],u[l-1]]=d}for(let d=s?3:1;d<=l;d++){let h=i-d<0?1:e[i-d],p=o-d<0?1:t[o-d];if(h!==p&&h>1&&p>1)return;let g=Math.max(h,p);if(h&&p)u[l-d]=Math.max(h,p);else{if(g>1)return;u[l-d]=0}}return u}static isValidBroadcast(e,t){let s=e.length,i=t.length;if(s>i)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[i-o])return!1;return!0}},H=class zi{static size(t){return zi.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let i=t.length;if(i===0)return[];let o=new Array(i),l=i-1;for(;l>=0;){if(t[l]%s===0){o[l]=t[l]/s;break}if(s%t[l]!==0)throw new Error("cannot convert shape");o[l]=1,s/=t[l],l--}for(l--;l>=0;l--)o[l]=t[l];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return zi.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return zi.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,i){let o=1;for(let l=s;l<i;l++){if(t[l]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");o*=Number(t[l])}return o}static computeStrides(t){let s=t.length;if(s===0)return[];if(s===1)return[1];let i=new Array(s);i[s-1]=1,i[s-2]=t[s-1];for(let o=s-3;o>=0;--o)i[o]=i[o+1]*t[o+1];return i}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(i=>this.normalizeAxis(i,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(i=>t[i]):t.slice().reverse()}static padShape(t,s){let i=t.length;return t.map((o,l)=>o+s[l]+s[l+i])}static areEqual(t,s){return t.length!==s.length?!1:t.every((i,o)=>i===s[o])}},Kr=class ii{static adjustPoolAttributes(t,s,i,o,l,u){if(!t&&i.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d<s.length-2;d++)d>=i.length?i.push(s[d+2]):i[d]=s[d+2];for(let d=0;d<i.length;d++)if(d<o.length){if(o[d]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let d=0;d<i.length;d++)if(d<l.length){if(l[d]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let d=0;d<i.length*2;d++)if(d<u.length){if(u[d]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let d=0;d<i.length;d++){if(i[d]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[d]>=i[d]||u[d+i.length]>=i[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,i,o,l,u,d){if(d){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h<t.length-2;h++)ii.adjustPadAndReturnShape(t[h+(u?1:2)],s[h],i[h],o[h],l,h,h+t.length-2,d)}}static computePoolOutputShape(t,s,i,o,l,u,d){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let h=[s[0],s[1]];return ii.computeShapeHelper(t,s,h,i,o,l,u,d),h}static computeConvOutputShape(t,s,i,o,l,u,d){if(t.length<=0||s.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let h=[t[0],s[0]];return ii.computeShapeHelper(!1,t,h,i,o,l,u,d),h}static computeShapeHelper(t,s,i,o,l,u,d,h){if(t)for(let p=0;p<s.length-2;p++)i.push(1);else for(let p=0;p<s.length-2;p++)i.push(ii.adjustPadAndReturnShape(s[p+2],o[p],l[p],u[p],d,p,p+s.length-2,h))}static adjustPadAndReturnShape(t,s,i,o,l,u,d,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[d]=0,Math.floor((t-p)/s+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let g=((t+s-1)/s-1)*s+o-t;return l[u]=Math.floor(h==="SAME_LOWER"?(g+1)/2:g/2),l[d]=g-l[u],Math.floor((t+g-o)/s+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+l[u]+l[d]-p)/s+1)}},Gn=class{static getShapeOfGemmResult(e,t,s,i,o){if(e.length!==2||s.length!==2)throw new Error("shape need to be of size 2");let l,u,d;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(d=s[0],h=1):(d=s[1],h=0),s[h]!==u)throw new Error("dimension mismatch");if(l<=0||d<=0||u<=0)throw new Error("invalid shape specified");if(o&&!Er.isValidBroadcast(o,[l,d]))throw new Error("gemm: invalid bias shape for broadcast");return[l,d,u]}},Es=-34028234663852886e22,pr=34028234663852886e22}),Cr,Qr=b(()=>{Pe(),Cr=(e,t)=>new(yn(t))(e)}),Br,Xr,Sn,Tn,fr,kr,qn,Wn,Hn,Cs,ks,ui=b(()=>{Pe(),tr(),Br=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Xr=(e,t)=>{if(t==="int32")return e;let s=Br.get(t);if(!s)throw new Error(`WebNN backend does not support data type: ${t}`);let i=s/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let o=e.byteLength/i,l=new(yn(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let d=0;d<o;d++){let h=l[d];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[d]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(d=>d>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(l,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Sn=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let s=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,s);switch(t){case"int64":{let o=BigInt64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let o=BigUint64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let o=Int8Array.from(i,Number);return new Uint8Array(o.buffer)}case"uint8":{if(i.some(o=>o<0||o>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let o=Uint32Array.from(i,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Tn=1,fr=()=>Tn++,kr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),qn=(e,t)=>{let s=Br.get(e);if(!s)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*s/8):0},Wn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:s,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=s,this.mlTensor=i,this.dataType=o,this.tensorShape=l,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return qn(this.dataType,this.tensorShape)}destroy(){Je("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),s=Sn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(s);return}else return s.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((i,o)=>i===s[o])}setIsDataConverted(e){this.isDataConverted=e}},Hn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=kr.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);Je("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,s))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==qn(t,s))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 d=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,s,d,!0,!0,u),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Xr(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Je("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Sn(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Cs=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=fr();return this.tensorTrackersById.set(e,new Hn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,i,o){Je("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${s}, shape: ${i}, copyOld: ${o}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,s,i,o)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){Je("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,i){let o=this.getMLContext(e),l=fr(),u=new Wn({sessionId:e,context:o,tensor:t,dataType:s,shape:i});return this.tensorTrackersById.set(l,new Hn(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,s,i,o,l,u){let d=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(d,t,s)){Je("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}`);let m=this.freeTensors.splice(p,1)[0];return m.sessionId=e,m}Je("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}}`);let h=await d.createTensor({dataType:u??t,shape:s,dimensions:s,usage:i,writable:o,readable:l});return new Wn({sessionId:e,context:d,tensor:h,dataType:t,shape:s,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},ks=(...e)=>new Cs(...e)}),Yr,Rs,As,Ms=b(()=>{Pe(),Yt(),Qr(),ui(),tr(),Yr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Rs=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),i=Object.keys(t).sort();return s.length===i.length&&s.every((o,l)=>o===i[l]&&e[o]===t[o])},As=class{constructor(e){this.tensorManager=ks(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Un(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Je("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Je("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)Je("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let s=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(s=>Rs(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(o=>o.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Je("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,i,o){let l=Yr.get(s);if(!l)throw new Error(`Unsupported ONNX data type: ${s}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,o)}async createTemporaryTensor(e,t,s){Je("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let i=Yr.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,i,s,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!ze().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Je("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return Cr(s,t)}}registerMLTensor(e,t,s,i){let o=Yr.get(s);if(!o)throw new Error(`Unsupported ONNX data type: ${s}`);let l=this.tensorManager.registerTensor(e,t,o,i);return Je("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,s,i,o,l,u=!1){if(!l)throw new Error("External mounted files are not available.");let d=e;e.startsWith("./")&&(d=e.substring(2));let h=l.get(d);if(!h)throw new Error(`File with name ${d} not found in preloaded files.`);if(t+s>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(t,t+s).buffer,g;switch(o.dataType){case"float32":g=new Float32Array(p);break;case"float16":g=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":g=new Int32Array(p);break;case"uint32":g=new Uint32Array(p);break;case"int64":if(u){let m=Xr(new Uint8Array(p),"int64");g=new Int32Array(m.buffer),o.dataType="int32"}else g=new BigInt64Array(p);break;case"uint64":g=new BigUint64Array(p);break;case"int8":g=new Int8Array(p);break;case"int4":case"uint4":case"uint8":g=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Je("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(o,g)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let s=this.sessionGraphInputs.get(e);return s?s.includes(t):!1}isGraphOutput(e,t){let s=this.sessionGraphOutputs.get(e);return s?s.includes(t):!1}isGraphInputOutputTypeSupported(e,t,s=!0){let i=Yr.get(Jt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:s?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),jn=b(()=>{}),Kn,Qn,$n,Xn,Yn,Jn,Is,Ps,di,Xi=b(()=>{tr(),jn(),Kn=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]]),Qn=[],$n=e=>Math.ceil(Number(e)/16)*16,Xn=e=>{for(let t=0;t<Qn.length;t++){let s=Qn[t];if(e<=s)return s}return Math.ceil(e/16)*16},Yn=1,Jn=()=>Yn++,Is=async(e,t,s,i)=>{let o=$n(s),l=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,l,0,o),e.flush(),await l.mapAsync(GPUMapMode.READ);let d=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(d,0,s)),h}else return new Uint8Array(d.slice(0,s))}finally{l.destroy()}},Ps=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Kn)Qn.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,i=t.byteOffset,o=t.byteLength,l=$n(o),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(Number(u.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${o}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=d.getMappedRange();new Uint8Array(h).set(new Uint8Array(s,i,o)),d.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(d,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),d.destroy(),Je("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=$n(s.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(s.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let i;if(s){if(i=s[0],e===s[1])return Je("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
26
|
+
*/var kp;function _y(){return kp||(kp=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(e=>typeof lr<"u"?lr:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof lr<"u"?lr:t)[s]}):e)(function(e){if(typeof lr<"u")return lr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),b=(e,t)=>()=>(e&&(t=e(e=0)),t),U=(e,t)=>{for(var s in t)a(e,s,{get:t[s],enumerable:!0})},B=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of v(t))!C.call(e,o)&&o!==s&&a(e,o,{get:()=>t[o],enumerable:!(i=f(t,o))||i.enumerable});return e},te=e=>B(a({},"__esModule",{value:!0}),e),X,ee,ie,ce,ue,Be=b(()=>{X=new Map,ee=[],ie=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=X.get(e);if(i===void 0)X.set(e,{backend:t,priority:s});else{if(i.priority>s)return;if(i.priority===s&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=ee.indexOf(e);o!==-1&&ee.splice(o,1);for(let l=0;l<ee.length;l++)if(X.get(ee[l]).priority<=s){ee.splice(l,0,e);return}ee.push(e)}return}throw new TypeError("not a valid backend")},ce=async e=>{let t=X.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return s||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ue=async e=>{let t=e.executionProviders||[],s=t.map(h=>typeof h=="string"?h:h.name),i=s.length===0?ee:s,o,l=[],u=new Set;for(let h of i){let p=await ce(h);typeof p=="string"?l.push({name:h,err:p}):(o||(o=p),o===p&&u.add(h))}if(!o)throw new Error(`no available backend found. ERR: ${l.map(h=>`[${h.name}] ${h.err}`).join(", ")}`);for(let{name:h,err:p}of l)s.includes(h)&&console.warn(`removing requested execution provider "${h}" from session options because it is not available: ${p}`);let d=t.filter(h=>u.has(typeof h=="string"?h:h.name));return[o,new Proxy(e,{get:(h,p)=>p==="executionProviders"?d:Reflect.get(h,p)})]}}),ke=b(()=>{Be()}),he,re=b(()=>{he="1.24.3"}),de,pe,Ie=b(()=>{re(),de="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:he},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);de=e}},get logLevel(){return de}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),ge,ut=b(()=>{Ie(),ge=pe}),Qe,ft,Ne=b(()=>{Qe=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let i=s.getContext("2d");if(i!=null){let o,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[3]):(o=e.dims[3],l=e.dims[2]);let u=t?.format!==void 0?t.format:"RGB",d=t?.norm,h,p;d===void 0||d.mean===void 0?h=[255,255,255,255]:typeof d.mean=="number"?h=[d.mean,d.mean,d.mean,d.mean]:(h=[d.mean[0],d.mean[1],d.mean[2],0],d.mean[3]!==void 0&&(h[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));let g=l*o,m=0,w=g,_=g*2,S=-1;u==="RGBA"?(m=0,w=g,_=g*2,S=g*3):u==="RGB"?(m=0,w=g,_=g*2):u==="RBG"&&(m=0,_=g,w=g*2);for(let E=0;E<l;E++)for(let I=0;I<o;I++){let k=(e.data[m++]-p[0])*h[0],x=(e.data[w++]-p[1])*h[1],O=(e.data[_++]-p[2])*h[2],M=S===-1?255:(e.data[S++]-p[3])*h[3];i.fillStyle="rgba("+k+","+x+","+O+","+M+")",i.fillRect(I,E,1,1)}if("toDataURL"in s)return s.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ft=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(s!=null){let o,l,u;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],l=e.dims[1],u=e.dims[3]):(o=e.dims[3],l=e.dims[2],u=e.dims[1]);let d=t!==void 0&&t.format!==void 0?t.format:"RGB",h=t?.norm,p,g;h===void 0||h.mean===void 0?p=[255,255,255,255]:typeof h.mean=="number"?p=[h.mean,h.mean,h.mean,h.mean]:(p=[h.mean[0],h.mean[1],h.mean[2],255],h.mean[3]!==void 0&&(p[3]=h.mean[3])),h===void 0||h.bias===void 0?g=[0,0,0,0]:typeof h.bias=="number"?g=[h.bias,h.bias,h.bias,h.bias]:(g=[h.bias[0],h.bias[1],h.bias[2],0],h.bias[3]!==void 0&&(g[3]=h.bias[3]));let m=l*o;if(t!==void 0&&(t.format!==void 0&&u===4&&t.format!=="RGBA"||u===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let w=4,_=0,S=1,E=2,I=3,k=0,x=m,O=m*2,M=-1;d==="RGBA"?(k=0,x=m,O=m*2,M=m*3):d==="RGB"?(k=0,x=m,O=m*2):d==="RBG"&&(k=0,O=m,x=m*2),i=s.createImageData(o,l);for(let D=0;D<l*o;_+=w,S+=w,E+=w,I+=w,D++)i.data[_]=(e.data[k++]-g[0])*p[0],i.data[S]=(e.data[x++]-g[1])*p[1],i.data[E]=(e.data[O++]-g[2])*p[2],i.data[I]=M===-1?255:(e.data[M++]-g[3])*p[3]}else throw new Error("Can not access image data");return i}}),Xe,mt,yt,ot,Ye,Le,rt=b(()=>{Xt(),Xe=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:i}=t,o=t.norm??{mean:255,bias:0},l,u;typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:l=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?u=[o.bias,o.bias,o.bias,o.bias]:u=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let d=t.format!==void 0?t.format:"RGBA",h=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=s*i,g=h==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),m=4,w=0,_=1,S=2,E=3,I=0,k=p,x=p*2,O=-1;d==="RGB"&&(m=3,w=0,_=1,S=2,E=-1),h==="RGBA"?O=p*3:h==="RBG"?(I=0,x=p,k=p*2):h==="BGR"&&(x=0,k=p,I=p*2);for(let M=0;M<p;M++,w+=m,S+=m,_+=m,E+=m)g[I++]=(e[w]+u[0])/l[0],g[k++]=(e[_]+u[1])/l[1],g[x++]=(e[S]+u[2])/l[2],O!==-1&&E!==-1&&(g[O++]=(e[E]+u[3])/l[3]);return h==="RGBA"?new tt("float32",g,[1,4,s,i]):new tt("float32",g,[1,3,s,i])},mt=async(e,t)=>{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",u,d=t??{},h=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},p=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(s){let g=h();g.width=e.width,g.height=e.height;let m=p(g);if(m!=null){let w=e.height,_=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(w=t.resizedHeight,_=t.resizedWidth),t!==void 0){if(d=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");d.tensorFormat="RGBA",d.height=w,d.width=_}else d.tensorFormat="RGBA",d.height=w,d.width=_;m.drawImage(e,0,0),u=m.getImageData(0,0,_,w).data}else throw new Error("Can not access image data")}else if(i){let g,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,m=t.resizedWidth):(g=e.height,m=e.width),t!==void 0&&(d=t),d.format="RGBA",d.height=g,d.width=m,t!==void 0){let w=h();w.width=m,w.height=g;let _=p(w);if(_!=null)_.putImageData(e,0,0),u=_.getImageData(0,0,m,g).data;else throw new Error("Can not access image data")}else u=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=h();g.width=e.width,g.height=e.height;let m=p(g);if(m!=null){let w=e.height,_=e.width;return m.drawImage(e,0,0,_,w),u=m.getImageData(0,0,_,w).data,d.height=w,d.width=_,Xe(u,d)}else throw new Error("Can not access image data")}else{if(l)return new Promise((g,m)=>{let w=h(),_=p(w);if(!e||!_)return m();let S=new Image;S.crossOrigin="Anonymous",S.src=e,S.onload=()=>{w.width=S.width,w.height=S.height,_.drawImage(S,0,0,w.width,w.height);let E=_.getImageData(0,0,w.width,w.height);d.height=w.height,d.width=w.width,g(Xe(E.data,d))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(u!==void 0)return Xe(u,d);throw new Error("Input data provided is not supported - aborted tensor creation")},yt=(e,t)=>{let{width:s,height:i,download:o,dispose:l}=t,u=[1,i,s,4];return new tt({location:"texture",type:"float32",texture:e,dims:u,download:o,dispose:l})},ot=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new tt({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:i,download:o,dispose:l})},Ye=(e,t)=>{let{dataType:s,dims:i,download:o,dispose:l}=t;return new tt({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:i,download:o,dispose:l})},Le=(e,t,s)=>new tt({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ze,Q,Me,et,gt=b(()=>{Ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Me=!1,et=()=>{if(!Me){Me=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,i=typeof s<"u"&&s.from;e&&(Ze.set("int64",BigInt64Array),Q.set(BigInt64Array,"int64")),t&&(Ze.set("uint64",BigUint64Array),Q.set(BigUint64Array,"uint64")),i?(Ze.set("float16",s),Q.set(s,"float16")):Ze.set("float16",Uint16Array)}}}),Gt,Ct,lt=b(()=>{Xt(),Gt=e=>{let t=1;for(let s=0;s<e.length;s++){let i=e[s];if(typeof i!="number"||!Number.isSafeInteger(i))throw new TypeError(`dims[${s}] must be an integer, got: ${i}`);if(i<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${i}`);t*=i}return t},Ct=(e,t)=>{switch(e.location){case"cpu":return new tt(e.type,e.data,t);case"cpu-pinned":return new tt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new tt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new tt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new tt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),tt,Xt=b(()=>{Ne(),rt(),gt(),lt(),tt=class{constructor(e,t,s){et();let i,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,o=e.dims,e.location){case"cpu-pinned":{let u=Ze.get(i);if(!u)throw new TypeError(`unsupported type "${i}" 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(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(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=e.gpuBuffer,this.downloader=e.download,this.disposer=e.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=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(i=e,d=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");u=t}else{let h=Ze.get(e);if(h===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&h===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${h.name} as data.`);e==="uint64"||e==="int64"?u=h.from(t,BigInt):u=h.from(t)}else if(t instanceof h)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&&h!==Uint16Array)u=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${h}`)}else if(d=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let h=typeof e[0];if(h==="string")i="string",u=e;else if(h==="boolean")i="bool",u=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${h}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",u=Uint8Array.from(e);else{let h=Q.get(e.constructor);if(h===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=h,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"}let l=Gt(o);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="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=i,this.dims=o,this.size=l}static async fromImage(e,t){return mt(e,t)}static fromTexture(e,t){return yt(e,t)}static fromGpuBuffer(e,t){return ot(e,t)}static fromMLTensor(e,t){return Ye(e,t)}static fromPinnedBuffer(e,t,s){return Le(e,t,s)}toDataURL(e){return Qe(this,e)}toImageData(e){return ft(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(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 Ct(this,e)}}}),vt,fe=b(()=>{Xt(),vt=tt}),Ue,wt,dt,ct,me,Fe,xt=b(()=>{Ie(),Ue=(e,t)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${e}::ORT::${t}`)},wt=(e,t)=>{let s=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let o=0;o<s.length;o++){if(i&&!s[o].includes("TRACE_FUNC")){let l=`FUNC_${e}::${s[o].trim().split(" ")[1]}`;t&&(l+=`::${t}`),Ue("CPU",l);return}s[o].includes("TRACE_FUNC")&&(i=!0)}},dt=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("BEGIN",e)},ct=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("END",e)},me=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${e}`)},Fe=e=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${e}`)}}),kt,ur=b(()=>{Be(),fe(),xt(),kt=class hf{constructor(t){this.handler=t}async run(t,s,i){dt(),me("InferenceSession.run");let o={},l={};if(typeof t!="object"||t===null||t instanceof vt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let u=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");u=!1;for(let p of s){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);o[p]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(s);for(let m of this.outputNames)if(g.indexOf(m)!==-1){let w=s[m];(w===null||w instanceof vt)&&(p=!0,u=!1,o[m]=w)}if(p){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(u)for(let p of this.outputNames)o[p]=null;let d=await this.handler.run(t,o,l),h={};for(let p in d)if(Object.hasOwnProperty.call(d,p)){let g=d[p];g instanceof vt?h[p]=g:h[p]=new vt(g.type,g.data,g.dims)}return Fe("InferenceSession.run"),ct(),h}async release(){return this.handler.dispose()}static async create(t,s,i,o){dt(),me("InferenceSession.create");let l,u={};if(typeof t=="string"){if(l=t,typeof s=="object"&&s!==null)u=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof s=="object"&&s!==null)u=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let g=t,m=0,w=t.byteLength;if(typeof s=="object"&&s!==null)u=s;else if(typeof s=="number"){if(m=s,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(w=t.byteLength-m,typeof i=="number"){if(w=i,!Number.isSafeInteger(w))throw new RangeError("'byteLength' must be an integer.");if(w<=0||m+w>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-m}].`);if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"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 s<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(g,m,w)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[d,h]=await ue(u),p=await d.createInferenceSessionHandler(l,h);return Fe("InferenceSession.create"),ct(),new hf(p)}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}}}),dr,Vi=b(()=>{ur(),dr=kt}),Gi=b(()=>{}),qi=b(()=>{}),Wi=b(()=>{}),Hi=b(()=>{}),is={};U(is,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,env:()=>ge,registerBackend:()=>ie});var Ot=b(()=>{ke(),ut(),Vi(),fe(),Gi(),qi(),xt(),Wi(),Hi()}),sn=b(()=>{}),as={};U(as,{default:()=>os});var an,on,os,ji=b(()=>{Xh(),Yt(),hn(),an="ort-wasm-proxy-worker",on=globalThis.self?.name===an,on&&(self.onmessage=e=>{let{type:t,in:s}=e.data;try{switch(t){case"init-wasm":mn(s.wasm).then(()=>{Ua(s).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:o}=s;Fa(o,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=s,o=$i(i);postMessage({type:t,out:o});break}case"create":{let{model:i,options:o}=s;Ga(i,o).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":qa(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:o,inputs:l,outputIndices:u,options:d}=s;Ha(i,o,l,u,new Array(u.length).fill(null),d).then(h=>{h.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:h},Ka([...l,...h]))},h=>{postMessage({type:t,err:h})});break}case"end-profiling":ja(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),os=on?null:e=>new Worker(e??bt,{type:"classic",name:an})}),ls,us,bt,ln,zr,ds,cs,un,hs,dn,ps,cn,fs,hn=b(()=>{sn(),ls=typeof location>"u"?void 0:location.origin,us=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,bt=us(),ln=()=>{if(bt&&!bt.startsWith("blob:"))return bt.substring(0,bt.lastIndexOf("/")+1)},zr=(e,t)=>{try{let s=t??bt;return(s?new URL(e,s):new URL(e)).origin===ls}catch{return!1}},ds=(e,t)=>{let s=t??bt;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},cs=(e,t)=>`${t??"./"}${e}`,un=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},hs=async e=>(await import(e)).default,dn=(ji(),te(as)).default,ps=async()=>{if(!bt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(bt))return[void 0,dn()];let e=await un(bt);return[e,dn(e)]},cn=void 0,fs=async(e,t,s,i)=>{let o=cn&&!(e||t);if(o)if(bt)o=zr(bt)||i&&!s;else if(i&&!s)o=!0;else throw new Error("cannot determine the script source URL.");if(o)return[void 0,cn];{let l="ort-wasm-simd-threaded.jsep.mjs",u=e??ds(l,t),d=s&&u&&!zr(u,t),h=d?await un(u):u??cs(l,t);return[d?h:void 0,await hs(h)]}}}),pn,Dr,cr,fn,ms,gs,ys,mn,ze,Yt=b(()=>{hn(),Dr=!1,cr=!1,fn=!1,ms=()=>{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}},gs=()=>{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}},ys=()=>{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}},mn=async e=>{if(Dr)return Promise.resolve();if(cr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(fn)throw new Error("previous call to 'initializeWebAssembly()' failed.");cr=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ys())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!gs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=ms();s>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let o=e.wasmPaths,l=typeof o=="string"?o:void 0,u=o?.mjs,d=u?.href??u,h=o?.wasm,p=h?.href??h,g=e.wasmBinary,[m,w]=await fs(d,l,s>1,!!g||!!p),_=!1,S=[];if(t>0&&S.push(new Promise(E=>{setTimeout(()=>{_=!0,E()},t)})),S.push(new Promise((E,I)=>{let k={numThreads:s};if(g)k.wasmBinary=g,k.locateFile=x=>x;else if(p||l)k.locateFile=x=>p??l+x;else if(d&&d.indexOf("blob:")!==0)k.locateFile=x=>new URL(x,d).href;else if(m){let x=ln();x&&(k.locateFile=O=>x+O)}w(k).then(x=>{cr=!1,Dr=!0,pn=x,E(),m&&URL.revokeObjectURL(m)},x=>{cr=!1,fn=!0,I(x)})})),await Promise.race(S),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(Dr&&pn)return pn;throw new Error("WebAssembly is not initialized yet.")}}),Et,Lr,Re,gn=b(()=>{Yt(),Et=(e,t)=>{let s=ze(),i=s.lengthBytesUTF8(e)+1,o=s._malloc(i);return s.stringToUTF8(e,o,i),t.push(o),o},Lr=(e,t,s,i)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,l])=>{let u=t?t+o:o;if(typeof l=="object")Lr(l,u+".",s,i);else if(typeof l=="string"||typeof l=="number")i(u,l.toString());else if(typeof l=="boolean")i(u,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Re=e=>{let t=ze(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetLastError(o,o+i);let l=Number(t.getValue(o,i===4?"i32":"i64")),u=t.getValue(o+i,"*"),d=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${d}`)}finally{t.stackRestore(s)}}}),ws,Ki=b(()=>{Yt(),gn(),ws=e=>{let t=ze(),s=0,i=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let l=0;return e?.tag!==void 0&&(l=Et(e.tag,i)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,l),s===0&&Re("Can't create run options."),e?.extra!==void 0&&Lr(e.extra,"",new WeakSet,(u,d)=>{let h=Et(u,i),p=Et(d,i);t._OrtAddRunConfigEntry(s,h,p)!==0&&Re(`Can't set a run config entry: ${u} - ${d}.`)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseRunOptions(s),i.forEach(u=>t._free(u)),l}}}),vs,bs,_s,hr,Ss,Ts,Qi=b(()=>{Yt(),gn(),vs=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},bs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},_s=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},hr=(e,t,s,i)=>{let o=Et(t,i),l=Et(s,i);ze()._OrtAddSessionConfigEntry(e,o,l)!==0&&Re(`Can't set a session config entry: ${t} - ${s}.`)},Ss=async(e,t,s)=>{let i=t.executionProviders;for(let o of i){let l=typeof o=="string"?o:o.name,u=[];switch(l){case"webnn":if(l="WEBNN",typeof o!="string"){let m=o?.deviceType;m&&hr(e,"deviceType",m,s)}break;case"webgpu":if(l="JS",typeof o!="string"){let m=o;if(m?.preferredLayout){if(m.preferredLayout!=="NCHW"&&m.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${m.preferredLayout}`);hr(e,"preferredLayout",m.preferredLayout,s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let d=Et(l,s),h=u.length,p=0,g=0;if(h>0){p=ze()._malloc(h*ze().PTR_SIZE),s.push(p),g=ze()._malloc(h*ze().PTR_SIZE),s.push(g);for(let m=0;m<h;m++)ze().setValue(p+m*ze().PTR_SIZE,u[m][0],"*"),ze().setValue(g+m*ze().PTR_SIZE,u[m][1],"*")}await ze()._OrtAppendExecutionProvider(e,d,p,g,h)!==0&&Re(`Can't append execution provider: ${l}.`)}},Ts=async e=>{let t=ze(),s=0,i=[],o=e||{};_s(o);try{let l=vs(o.graphOptimizationLevel??"all"),u=bs(o.executionMode??"sequential"),d=typeof o.logId=="string"?Et(o.logId,i):0,h=o.logSeverityLevel??2;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log severity level is not valid: ${h}`);let p=o.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let g=typeof o.optimizedModelFilePath=="string"?Et(o.optimizedModelFilePath,i):0;if(s=t._OrtCreateSessionOptions(l,!!o.enableCpuMemArena,!!o.enableMemPattern,u,!!o.enableProfiling,0,d,h,p,g),s===0&&Re("Can't create session options."),o.executionProviders&&await Ss(s,o,i),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);hr(s,"enableGraphCapture",o.enableGraphCapture.toString(),i)}if(o.freeDimensionOverrides)for(let[m,w]of Object.entries(o.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let _=Et(m,i);t._OrtAddFreeDimensionOverride(s,_,w)!==0&&Re(`Can't set a free dimension override: ${m} - ${w}.`)}return o.extra!==void 0&&Lr(o.extra,"",new WeakSet,(m,w)=>{hr(s,m,w,i)}),[s,i]}catch(l){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&Re("Can't release session options."),i.forEach(u=>t._free(u)),l}}}),Jt,Zt,er,yn,wn,vn,bn,Ln,Pe=b(()=>{Jt=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Zt=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},er=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((o,l)=>o*l,1);return s>0?Math.ceil(i*s):void 0},yn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},wn=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},vn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",bn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ln=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),_n,$s=b(()=>{sn(),_n=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),i=s?parseInt(s,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(d){if(d instanceof RangeError){let h=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:h,maximum:h}).buffer}else throw d}let u=0;for(;;){let{done:d,value:h}=await o.read();if(d)break;let p=h.byteLength;new Uint8Array(l,u,p).set(h),u+=p}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),xs,Bn,Nn,xr,Un,Fn,Je,tr=b(()=>{Pe(),xs=["V","I","W","E","F"],Bn=(e,t)=>{console.log(`[${xs[e]},${new Date().toISOString()}]${t}`)},Un=(e,t)=>{Nn=e,xr=t},Fn=(e,t)=>{let s=wn(e),i=wn(Nn);s>=i&&Bn(s,typeof t=="function"?t():t)},Je=(...e)=>{xr&&Fn(...e)}}),Vn,Er,H,Kr,Gn,Es,pr,Ae=b(()=>{Vn=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Er=class{static calcShape(e,t,s=!1){let i=e.length,o=t.length;if(i===0)return t;if(o===0)return e;let l=Math.max(e.length,t.length),u=new Array(l);if(s){if(i<2||o<2)return;let d=Vn.calcMatMulShape([e[i-2],e[i-1]],[t[o-2],t[o-1]]);if(d===void 0)return;[u[l-2],u[l-1]]=d}for(let d=s?3:1;d<=l;d++){let h=i-d<0?1:e[i-d],p=o-d<0?1:t[o-d];if(h!==p&&h>1&&p>1)return;let g=Math.max(h,p);if(h&&p)u[l-d]=Math.max(h,p);else{if(g>1)return;u[l-d]=0}}return u}static isValidBroadcast(e,t){let s=e.length,i=t.length;if(s>i)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[i-o])return!1;return!0}},H=class zi{static size(t){return zi.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let i=t.length;if(i===0)return[];let o=new Array(i),l=i-1;for(;l>=0;){if(t[l]%s===0){o[l]=t[l]/s;break}if(s%t[l]!==0)throw new Error("cannot convert shape");o[l]=1,s/=t[l],l--}for(l--;l>=0;l--)o[l]=t[l];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return zi.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return zi.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,i){let o=1;for(let l=s;l<i;l++){if(t[l]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");o*=Number(t[l])}return o}static computeStrides(t){let s=t.length;if(s===0)return[];if(s===1)return[1];let i=new Array(s);i[s-1]=1,i[s-2]=t[s-1];for(let o=s-3;o>=0;--o)i[o]=i[o+1]*t[o+1];return i}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(i=>this.normalizeAxis(i,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(i=>t[i]):t.slice().reverse()}static padShape(t,s){let i=t.length;return t.map((o,l)=>o+s[l]+s[l+i])}static areEqual(t,s){return t.length!==s.length?!1:t.every((i,o)=>i===s[o])}},Kr=class ii{static adjustPoolAttributes(t,s,i,o,l,u){if(!t&&i.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let d=0;d<s.length-2;d++)d>=i.length?i.push(s[d+2]):i[d]=s[d+2];for(let d=0;d<i.length;d++)if(d<o.length){if(o[d]<0)throw new Error("strides should be greater than or equal to 1")}else o.push(1);for(let d=0;d<i.length;d++)if(d<l.length){if(l[d]<0)throw new Error("dilations should be greater than or equal to 1")}else l.push(1);for(let d=0;d<i.length*2;d++)if(d<u.length){if(u[d]<0)throw new Error("pad should be greater than or equal to 1")}else u.push(0);for(let d=0;d<i.length;d++){if(i[d]<=0)throw new Error("kernel shapes need to be greater than 0");if(u[d]>=i[d]||u[d+i.length]>=i[d])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,i,o,l,u,d){if(d){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let h=0;h<t.length-2;h++)ii.adjustPadAndReturnShape(t[h+(u?1:2)],s[h],i[h],o[h],l,h,h+t.length-2,d)}}static computePoolOutputShape(t,s,i,o,l,u,d){if(s.length<=0)throw new Error("input shape must be of size greater than 0");let h=[s[0],s[1]];return ii.computeShapeHelper(t,s,h,i,o,l,u,d),h}static computeConvOutputShape(t,s,i,o,l,u,d){if(t.length<=0||s.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let h=[t[0],s[0]];return ii.computeShapeHelper(!1,t,h,i,o,l,u,d),h}static computeShapeHelper(t,s,i,o,l,u,d,h){if(t)for(let p=0;p<s.length-2;p++)i.push(1);else for(let p=0;p<s.length-2;p++)i.push(ii.adjustPadAndReturnShape(s[p+2],o[p],l[p],u[p],d,p,p+s.length-2,h))}static adjustPadAndReturnShape(t,s,i,o,l,u,d,h){let p=i*(o-1)+1;if(h&&h!=="NOTSET")switch(h){case"VALID":return l[u]=0,l[d]=0,Math.floor((t-p)/s+1);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let g=((t+s-1)/s-1)*s+o-t;return l[u]=Math.floor(h==="SAME_LOWER"?(g+1)/2:g/2),l[d]=g-l[u],Math.floor((t+g-o)/s+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((t+l[u]+l[d]-p)/s+1)}},Gn=class{static getShapeOfGemmResult(e,t,s,i,o){if(e.length!==2||s.length!==2)throw new Error("shape need to be of size 2");let l,u,d;t?(l=e[1],u=e[0]):(l=e[0],u=e[1]);let h=-1;if(i?(d=s[0],h=1):(d=s[1],h=0),s[h]!==u)throw new Error("dimension mismatch");if(l<=0||d<=0||u<=0)throw new Error("invalid shape specified");if(o&&!Er.isValidBroadcast(o,[l,d]))throw new Error("gemm: invalid bias shape for broadcast");return[l,d,u]}},Es=-34028234663852886e22,pr=34028234663852886e22}),Cr,Qr=b(()=>{Pe(),Cr=(e,t)=>new(yn(t))(e)}),Br,Xr,Sn,Tn,fr,kr,qn,Wn,Hn,Cs,ks,ui=b(()=>{Pe(),tr(),Br=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Xr=(e,t)=>{if(t==="int32")return e;let s=Br.get(t);if(!s)throw new Error(`WebNN backend does not support data type: ${t}`);let i=s/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let o=e.byteLength/i,l=new(yn(t))(e.buffer,e.byteOffset,o);switch(t){case"int64":case"uint64":{let u=new Int32Array(o);for(let d=0;d<o;d++){let h=l[d];if(h>2147483647n||h<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");u[d]=Number(h)}return new Uint8Array(u.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(d=>d>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let u=Int32Array.from(l,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Sn=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let s=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,s);switch(t){case"int64":{let o=BigInt64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let o=BigUint64Array.from(i,BigInt);return new Uint8Array(o.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let o=Int8Array.from(i,Number);return new Uint8Array(o.buffer)}case"uint8":{if(i.some(o=>o<0||o>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let o=Uint32Array.from(i,Number);return new Uint8Array(o.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Tn=1,fr=()=>Tn++,kr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),qn=(e,t)=>{let s=Br.get(e);if(!s)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,o)=>i*o)*s/8):0},Wn=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:s,tensor:i,dataType:o,shape:l,fallbackDataType:u}=e;this.sessionId=t,this.mlContext=s,this.mlTensor=i,this.dataType=o,this.tensorShape=l,this.fallbackDataType=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return qn(this.dataType,this.tensorShape)}destroy(){Je("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),s=Sn(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(s);return}else return s.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((i,o)=>i===s[o])}setIsDataConverted(e){this.isDataConverted=e}},Hn=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s,i){let o=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),u;if(!l?.input.dataTypes.includes(t)){if(u=kr.get(t),!u||l?.input.dataTypes.includes(u))throw new Error(`WebNN backend does not support data type: ${t}`);Je("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${u}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(o,t,s))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==qn(t,s))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 d=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,s,d,!0,!0,u),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Xr(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Je("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Sn(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Cs=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=fr();return this.tensorTrackersById.set(e,new Hn(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,i,o){Je("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${s}, shape: ${i}, copyOld: ${o}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,s,i,o)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){Je("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,i){let o=this.getMLContext(e),l=fr(),u=new Wn({sessionId:e,context:o,tensor:t,dataType:s,shape:i});return this.tensorTrackersById.set(l,new Hn(this,u)),this.externalTensors.add(u),l}async getCachedTensor(e,t,s,i,o,l,u){let d=this.getMLContext(e);for(let[p,g]of this.freeTensors.entries())if(g.canReuseTensor(d,t,s)){Je("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}`);let m=this.freeTensors.splice(p,1)[0];return m.sessionId=e,m}Je("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${u?`fallbackDataType: ${u},`:""} shape: ${s}}`);let h=await d.createTensor({dataType:u??t,shape:s,dimensions:s,usage:i,writable:o,readable:l});return new Wn({sessionId:e,context:d,tensor:h,dataType:t,shape:s,fallbackDataType:u})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},ks=(...e)=>new Cs(...e)}),Yr,Rs,As,Ms=b(()=>{Pe(),Yt(),Qr(),ui(),tr(),Yr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Rs=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),i=Object.keys(t).sort();return s.length===i.length&&s.every((o,l)=>o===i[l]&&e[o]===t[o])},As=class{constructor(e){this.tensorManager=ks(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Un(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Je("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Je("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)Je("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let s=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(s=>Rs(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(o=>o.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Je("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,i,o){let l=Yr.get(s);if(!l)throw new Error(`Unsupported ONNX data type: ${s}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,o)}async createTemporaryTensor(e,t,s){Je("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let i=Yr.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,i,s,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,t){if(!ze().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Je("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return Cr(s,t)}}registerMLTensor(e,t,s,i){let o=Yr.get(s);if(!o)throw new Error(`Unsupported ONNX data type: ${s}`);let l=this.tensorManager.registerTensor(e,t,o,i);return Je("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${o}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerMLConstant(e,t,s,i,o,l,u=!1){if(!l)throw new Error("External mounted files are not available.");let d=e;e.startsWith("./")&&(d=e.substring(2));let h=l.get(d);if(!h)throw new Error(`File with name ${d} not found in preloaded files.`);if(t+s>h.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=h.slice(t,t+s).buffer,g;switch(o.dataType){case"float32":g=new Float32Array(p);break;case"float16":g=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":g=new Int32Array(p);break;case"uint32":g=new Uint32Array(p);break;case"int64":if(u){let m=Xr(new Uint8Array(p),"int64");g=new Int32Array(m.buffer),o.dataType="int32"}else g=new BigInt64Array(p);break;case"uint64":g=new BigUint64Array(p);break;case"int8":g=new Int8Array(p);break;case"int4":case"uint4":case"uint8":g=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Je("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),i.constant(o,g)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let s=this.sessionGraphInputs.get(e);return s?s.includes(t):!1}isGraphOutput(e,t){let s=this.sessionGraphOutputs.get(e);return s?s.includes(t):!1}isGraphInputOutputTypeSupported(e,t,s=!0){let i=Yr.get(Jt(t)),o=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:s?!!o?.input.dataTypes.includes(i):!!o?.output.dataTypes.includes(i)}flush(){}}}),jn=b(()=>{}),Kn,Qn,$n,Xn,Yn,Jn,Is,Ps,di,Xi=b(()=>{tr(),jn(),Kn=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]]),Qn=[],$n=e=>Math.ceil(Number(e)/16)*16,Xn=e=>{for(let t=0;t<Qn.length;t++){let s=Qn[t];if(e<=s)return s}return Math.ceil(e/16)*16},Yn=1,Jn=()=>Yn++,Is=async(e,t,s,i)=>{let o=$n(s),l=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,l,0,o),e.flush(),await l.mapAsync(GPUMapMode.READ);let d=l.getMappedRange();if(i){let h=i();return h.set(new Uint8Array(d,0,s)),h}else return new Uint8Array(d.slice(0,s))}finally{l.destroy()}},Ps=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of Kn)Qn.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,i=t.byteOffset,o=t.byteLength,l=$n(o),u=this.storageCache.get(e);if(!u)throw new Error("gpu data for uploading does not exist");if(Number(u.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${o}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:l,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=d.getMappedRange();new Uint8Array(h).set(new Uint8Array(s,i,o)),d.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(d,0,u.gpuData.buffer,0,l),this.backend.device.queue.submit([p.finish()]),d.destroy(),Je("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=$n(s.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(s.gpuData.buffer,0,i.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let i;if(s){if(i=s[0],e===s[1])return Je("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
27
27
|
Please use the previous external buffer!`)}else i=Jn();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Je("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Je("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=Xn(e),i,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,l=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||l){let d=(o?this.freeBuffers:this.freeUniformBuffers).get(s);d?d.length>0?i=d.pop():i=this.backend.device.createBuffer({size:s,usage:t}):i=this.backend.device.createBuffer({size:s,usage:t})}else i=this.backend.device.createBuffer({size:s,usage:t});let u={id:Jn(),type:0,buffer:i};return this.storageCache.set(u.id,{gpuData:u,originalSize:Number(e)}),Je("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${u.id}`),u}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Je("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await Is(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=Kn.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Je("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},di=(...e)=>new Ps(...e)}),y,$,A=b(()=>{y=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},$=e=>new y(e)}),z,P,G,N,L,V,Z,se,J,j,$e,F,oe,_t,qe,xe,We,_e=b(()=>{Pe(),Ae(),z=64,P=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}<f16>`:"f16";case 1:return t>1?`vec${t}<f32>`:"f32";case 6:return t>1?`vec${t}<i32>`:"i32";case 12:return t>1?`vec${t}<u32>`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},G=(e,t=1)=>{let s=P(e,t);return typeof s=="string"?s:s[0]},N=(e,t=1)=>{let s=P(e,t);return typeof s=="string"?s:s[1]},L=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:H.computeStrides(s)})}),t},V=e=>e%4===0?4:e%2===0?2:1,Z=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,se=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}<f32>(${s})`,J=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,j=(e,t,s,i)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?i==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:i==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,$e=(e,t,s,i,o)=>{let l=typeof s=="number",u=l?s:s.length,d=[...new Array(u).keys()],h=u<2?"u32":u<=4?`vec${u}<u32>`:`array<u32, ${u}>`,p=P(t,o),g=typeof p=="string"?p:p[1],m=typeof p=="string"?p:p[0],w={indices:h,value:g,storage:m,tensor:t},_=ne=>typeof ne=="string"?ne:`${ne}u`,S={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=l?"uniforms.":"",I=`${E}${e}_shape`,k=`${E}${e}_strides`,x="";for(let ne=0;ne<u-1;ne++)x+=`
|
|
28
28
|
let dim${ne} = current / ${j(k,ne,u)};
|
|
29
29
|
let rest${ne} = current % ${j(k,ne,u)};
|
|
@@ -108,7 +108,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
108
108
|
let aIndices = perm(indices);
|
|
109
109
|
|
|
110
110
|
${I.setByOffset("global_idx",E.getByIndices("aIndices"))}
|
|
111
|
-
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let S=H.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(u,d)]}},getShaderSource:p}},nr=(e,t)=>{Lt(e.inputs,t.perm),e.compute(Tt(e.inputs[0],t.perm))},zs=e=>$({perm:e.perm})}),rr,ci,mr,xn,
|
|
111
|
+
}`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let S=H.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(u,d)]}},getShaderSource:p}},nr=(e,t)=>{Lt(e.inputs,t.perm),e.compute(Tt(e.inputs[0],t.perm))},zs=e=>$({perm:e.perm})}),rr,ci,mr,xn,Rt,Wt,es,En,Ds,hi,zt,gr,Zr,At,$t,sr,pi,fi,Io,Po,Oo,ym=b(()=>{Pe(),Ae(),_e(),Ji(),He(),rr={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"},ci={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"},mr={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},xn={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Rt=(e,t)=>{let s=[];for(let i=t-e;i<t;++i)s.push(i);return s},Wt=(e,t)=>{let s=[],i=e.length;for(let l=0;l<i;l++)t.indexOf(l)===-1&&s.push(e[l]);let o=t.map(l=>e[l]);return[s,o]},es=(e,t)=>{let s=e.length+t.length,i=[],o=0;for(let l=0;l<s;l++)t.indexOf(l)===-1?i.push(e[o++]):i.push(1);return i},En=(e,t)=>{for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0},Ds=(e,t)=>{let s=[];if(!En(e,t)){for(let i=0;i<t;++i)e.indexOf(i)===-1&&s.push(i);e.forEach(i=>s.push(i))}return s},hi=(e,t,s,i,o,l,u)=>{let d=s[0].dims,h=H.size(l),p=H.size(u),g=F("_A",s[0].dataType,d),m=oe("output",o,l),w=64;h===1&&(w=256);let _=`
|
|
112
112
|
var<workgroup> aBestValues : array<f32, ${w}>;
|
|
113
113
|
`,S=E=>`
|
|
114
114
|
${E.registerUniform("reduceSize","u32").declareVariables(g,m)}
|
|
@@ -146,7 +146,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
146
146
|
if (local_idx == 0u) {
|
|
147
147
|
${m.setByOffset("outputIndex",`${i==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${xn[i]})`}`)};
|
|
148
148
|
}
|
|
149
|
-
}`;return{name:e,shaderCache:{hint:`${t};${w}`,inputDependencies:["type"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:h},programUniforms:[{type:12,data:p}]})}},zt=(e,t,s,i)=>{let o=e.inputs.length===1?s:Yi(e.inputs,s),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((_,S)=>S));let u=H.normalizeAxes(l,e.inputs[0].dims.length),d=u,h=e.inputs[0],p=Ds(d,e.inputs[0].dims.length);p.length>0&&(h=e.compute(Tt(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],d=
|
|
149
|
+
}`;return{name:e,shaderCache:{hint:`${t};${w}`,inputDependencies:["type"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:h},programUniforms:[{type:12,data:p}]})}},zt=(e,t,s,i)=>{let o=e.inputs.length===1?s:Yi(e.inputs,s),l=o.axes;l.length===0&&!o.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((_,S)=>S));let u=H.normalizeAxes(l,e.inputs[0].dims.length),d=u,h=e.inputs[0],p=Ds(d,e.inputs[0].dims.length);p.length>0&&(h=e.compute(Tt(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],d=Rt(d.length,h.dims.length));let[g,m]=Wt(h.dims,d),w=g;o.keepDims&&(w=es(g,u)),e.compute(hi(t,o.cacheKey,[h],i,e.inputs[0].dataType,w,m),{inputs:[h]})},gr=(e,t)=>{zt(e,"ReduceMeanShared",t,"mean")},Zr=(e,t)=>{zt(e,"ReduceL1Shared",t,"l1")},At=(e,t)=>{zt(e,"ReduceL2Shared",t,"l2")},$t=(e,t)=>{zt(e,"ReduceLogSumExpShared",t,"logSumExp")},sr=(e,t)=>{zt(e,"ReduceMaxShared",t,"max")},pi=(e,t)=>{zt(e,"ReduceMinShared",t,"min")},fi=(e,t)=>{zt(e,"ReduceProdShared",t,"prod")},Io=(e,t)=>{zt(e,"ReduceSumShared",t,"sum")},Po=(e,t)=>{zt(e,"ReduceSumSquareShared",t,"sumSquare")},Oo=(e,t)=>{zt(e,"ReduceLogSumShared",t,"logSum")}}),yr,zo,mi,Yi,wr,Do,Lo,Bo,No,Uo,Fo,Vo,Go,qo,Wo,vr,Ho,jo,Ko,Qo,Xo,Yo,Jo,Zo,el,tl,Ji=b(()=>{Pe(),Ae(),A(),_e(),ym(),yr=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},zo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],mi=(e,t,s,i,o,l,u=!1,d=!1)=>{let h=[],p=s[0].dims,g=p.length,m=H.normalizeAxes(o,g),w=!d&&m.length===0;p.forEach((E,I)=>{w||m.indexOf(I)>=0?u&&h.push(1):h.push(E)});let _=h.length,S=H.size(h);return{name:e,shaderCache:t,getShaderSource:E=>{let I=[],k=F("_A",s[0].dataType,g),x=oe("output",l,_),O=i(k,x,m),M=O[2];for(let D=0,W=0;D<g;D++)w||m.indexOf(D)>=0?(u&&W++,M=`for(var j${D}: u32 = 0; j${D} < ${p[D]}; j${D}++) {
|
|
150
150
|
${O[2].includes("last_index")?`let last_index = j${D};`:""}
|
|
151
151
|
${k.indicesSet("input_indices",D,`j${D}`)}
|
|
152
152
|
${M}
|
|
@@ -169,7 +169,7 @@ React keys must be passed directly to JSX without using spread:
|
|
|
169
169
|
`)}
|
|
170
170
|
}`},getRunData:()=>({outputs:[{dims:h,dataType:l}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...L(p,h)]})}},Yi=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),$({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},wr=(e,t,s,i)=>{let o=e.inputs,l=o.length===1?s:Yi(o,s);e.compute(mi(t,{hint:l.cacheKey,inputDependencies:["rank"]},[o[0]],l.noopWithEmptyAxes&&l.axes.length===0?zo:i,l.axes,o[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},Do=(e,t)=>{yr(e.inputs),wr(e,"ReduceLogSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Lo=(e,t)=>{yr(e.inputs),wr(e,"ReduceL1",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Bo=(e,t)=>{yr(e.inputs),wr(e,"ReduceL2",t,(s,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},No=(e,t)=>{yr(e.inputs),wr(e,"ReduceLogSumExp",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},Uo=(e,t)=>{yr(e.inputs),wr(e,"ReduceMax",t,(s,i,o)=>{let l=[];for(let u=0;u<s.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(s.indicesSet("input_indices",u,0));return[`${l.join(`
|
|
171
171
|
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Fo=(e,t)=>{yr(e.inputs),wr(e,"ReduceMean",t,(s,i,o)=>{let l=1;for(let u=0;u<s.rank;u++)(o.indexOf(u)>=0||o.length===0)&&(l*=e.inputs[0].dims[u]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${l});`]})},Vo=(e,t)=>{yr(e.inputs),wr(e,"ReduceMin",t,(s,i,o)=>{let l=[];for(let u=0;u<s.rank;u++)(o.indexOf(u)>=0||o.length===0)&&l.push(`input_indices[${u}] = 0;`);return[`${l.join(`
|
|
172
|
-
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Go=(e,t)=>{yr(e.inputs),wr(e,"ReduceProd",t,(s,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},qo=(e,t)=>{yr(e.inputs),wr(e,"ReduceSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Wo=(e,t)=>{yr(e.inputs),wr(e,"ReduceSumSquare",t,(s,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},vr=(e,t,s)=>{if(t.length===0)return s;let i=1,o=1;for(let l=0;l<t.length;l++)t.indexOf(l)===-1?i*=e[l]:o*=e[l];return o<32&&i>1024},Ho=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):gr(e,t)},jo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):Zr(e,t)},Ko=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):
|
|
172
|
+
`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Go=(e,t)=>{yr(e.inputs),wr(e,"ReduceProd",t,(s,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},qo=(e,t)=>{yr(e.inputs),wr(e,"ReduceSum",t,(s,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Wo=(e,t)=>{yr(e.inputs),wr(e,"ReduceSumSquare",t,(s,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},vr=(e,t,s)=>{if(t.length===0)return s;let i=1,o=1;for(let l=0;l<t.length;l++)t.indexOf(l)===-1?i*=e[l]:o*=e[l];return o<32&&i>1024},Ho=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fo(e,t):gr(e,t)},jo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lo(e,t):Zr(e,t)},Ko=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bo(e,t):At(e,t)},Qo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?No(e,t):$t(e,t)},Xo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uo(e,t):sr(e,t)},Yo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vo(e,t):pi(e,t)},Jo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Go(e,t):fi(e,t)},Zo=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qo(e,t):Io(e,t)},el=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Wo(e,t):Po(e,t)},tl=(e,t)=>{vr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Do(e,t):Oo(e,t)}}),Zi,rl,nl,ea,wm=b(()=>{Pe(),A(),Ji(),Zi=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},rl=(e,t)=>{Zi(e.inputs);let s=(i,o,l)=>{let u=[];for(let d=0;d<i.rank;d++)(l.indexOf(d)>=0||l.length===0)&&u.push(`input_indices[${d}] = 0;`);return[`${u.join(`
|
|
173
173
|
`)}`,`var value = ${i.getByIndices("input_indices")};
|
|
174
174
|
var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {
|
|
175
175
|
value = ${i.getByIndices("input_indices")};
|
|
@@ -2806,7 +2806,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2806
2806
|
}`},Dh=e=>{let t=e[1].dims,s=e[2].dims,i=e[0].dims,o=e[1].dataType,l=!(H.areEqual(t,s)&&H.areEqual(s,i)),u=t,d=H.size(t);if(l){let p=Er.calcShape(Er.calcShape(t,s,!1),i,!1);if(!p)throw new Error("Can't perform where op on the given tensors");u=p,d=H.size(u)}let h=Math.ceil(d/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>zh(p,e,u,l,o),getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:h},...L(i,t,s,u)]})}},Lh=e=>{e.compute(Dh(e.inputs))}}),Bh,sg=b(()=>{wm(),ta(),vm(),bm(),_m(),Sm(),Tm(),km(),Am(),Mm(),Im(),Pm(),Om(),zm(),Dm(),Lm(),Bm(),Nm(),Um(),Fm(),Vm(),Gm(),qm(),Wm(),Hm(),Xd(),jm(),Km(),Qm(),Xm(),Ym(),Ji(),Jm(),ac(),Zm(),eg(),tg(),nc(),rg(),He(),ia(),ng(),Bh=new Map([["Abs",[wl]],["Acos",[vl]],["Acosh",[bl]],["Add",[ou]],["ArgMax",[nl,ea]],["ArgMin",[rl,ea]],["Asin",[_l]],["Asinh",[Sl]],["Atan",[Tl]],["Atanh",[$l]],["Attention",[ul]],["AveragePool",[Dc,zc]],["BatchNormalization",[pl]],["BiasAdd",[gl]],["BiasSplitGelu",[su]],["Cast",[El,xl]],["Ceil",[Rl]],["Clip",[kl]],["Concat",[_u,Su]],["Conv",[wa,ga]],["ConvTranspose",[Qu,Hu]],["Cos",[Al]],["Cosh",[Ml]],["CumSum",[Yu,Ju]],["DepthToSpace",[rd,nd]],["DequantizeLinear",[Wc,Hc]],["Div",[lu]],["Einsum",[ud,dd]],["Elu",[Il,Bs]],["Equal",[uu]],["Erf",[Pl]],["Exp",[Ol]],["Expand",[fd]],["FastGelu",[gd]],["Floor",[zl]],["FusedConv",[wa,ga]],["Gather",[bd,vd]],["GatherElements",[Md,Ad]],["GatherBlockQuantized",[Ed,Cd]],["GatherND",[Sd,Td]],["Gelu",[Dl]],["Gemm",[zd,Od]],["GlobalAveragePool",[Bc,Lc]],["GlobalMaxPool",[Vc,Fc]],["Greater",[pu]],["GreaterOrEqual",[mu]],["GridSample",[qd,Wd]],["GroupQueryAttention",[dc]],["HardSigmoid",[ql,Gl]],["InstanceNormalization",[pc]],["LayerNormalization",[gc]],["LeakyRelu",[Ll,Bs]],["Less",[fu]],["LessOrEqual",[gu]],["Log",[Jl]],["MatMul",[wc]],["MatMulNBits",[Sc,Tc]],["MaxPool",[Nc,Uc]],["Mul",[du]],["MultiHeadAttention",[Qd,jd]],["Neg",[Nl]],["Not",[Bl]],["Pad",[Ic]],["Pow",[cu]],["QuickGelu",[tu,Bs]],["Range",[Qc]],["Reciprocal",[Ul]],["ReduceMin",[Yo]],["ReduceMean",[Ho]],["ReduceMax",[Xo]],["ReduceSum",[Zo]],["ReduceProd",[Jo]],["ReduceL1",[jo]],["ReduceL2",[Ko]],["ReduceLogSum",[tl]],["ReduceLogSumExp",[Qo]],["ReduceSumSquare",[el]],["Relu",[Fl]],["Resize",[gh,yh]],["RotaryEmbedding",[ic]],["ScatterND",[Zc,Jc]],["Sigmoid",[Vl]],["Sin",[Wl]],["Sinh",[Hl]],["Slice",[xh,Eh]],["SkipLayerNormalization",[bh]],["Split",[tc,rc]],["Sqrt",[jl]],["Softmax",[Rh,Ah]],["Sub",[hu]],["Tan",[Kl]],["Tanh",[Ql]],["ThresholdedRelu",[Yl,Bs]],["Tile",[Oh]],["Transpose",[nr,zs]],["Where",[Lh]]])}),Nh,ig=b(()=>{Ot(),tr(),_e(),Nh=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,i,o){dt(e.programInfo.name);let l=this.backend.device,u=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let p of t)d.push({binding:d.length,resource:{buffer:p.buffer}});for(let p of s)d.push({binding:d.length,resource:{buffer:p.buffer}});o&&d.push({binding:d.length,resource:o});let h=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:d,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}u.setPipeline(e.computePipeline),u.setBindGroup(0,h),u.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(),ct(e.programInfo.name)}dispose(){}build(e,t){dt(e.name);let s=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(p=>{s.features.has(p.feature)&&i.push(`enable ${p.extension};`)});let o=We(t,this.backend.device.limits),l=e.getShaderSource(o),u=`${i.join(`
|
|
2807
2807
|
`)}
|
|
2808
2808
|
${o.additionalImplementations}
|
|
2809
|
-
${l}`,d=s.createShaderModule({code:u,label:e.name});Je("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return ct(e.name),{programInfo:e,computePipeline:h,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&i<=o)return[t,s,i];let l=t*s*i,u=Math.ceil(Math.sqrt(l));if(u>o){if(u=Math.ceil(Math.cbrt(l)),u>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[u,u,u]}else return[u,u,1]}}}),Uh={};U(Uh,{WebGpuBackend:()=>qh});var Fh,Vh,Gh,qh,ag=b(()=>{Ot(),Pe(),tr(),Qr(),Xi(),sg(),ig(),Fh=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let i=0;i<e.length;++i){let o=e[i].dataType;switch(t[i]){case"none":{s.push("");break}case"type":{s.push(`${o}`);break}case"rank":{let l=e[i].dims.length;s.push(`${o};${l}`);break}case"dims":{let l=e[i].dims.join(",");s.push(`${o};${l}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return s.join("|")},Vh=(e,t,s)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+s+`:${Fh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},Gh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},qh=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let s=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},o=l=>t.features.has(l)&&s.push(l)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new Gh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=di(this),this.programManager=new Nh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Un(e.logLevel,!!e.debug),this.device.onuncapturederror=l=>{l.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${l.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;dt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let o=s[i],l=o.kernelId,u=this.kernels.get(l),d=u.kernelType,h=u.kernelName,p=o.programName,g=o.inputTensorViews,m=o.outputTensorViews,w=t[i*2],_=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let S=Number(w-this.queryTimeBase),E=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(E))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(I=>({dims:I.dims,dataType:Zt(I.dataType)})),outputsMetadata:m.map(I=>({dims:I.dims,dataType:Zt(I.dataType)})),kernelId:l,kernelType:d,kernelName:h,programName:p,startTime:S,endTime:E});else{let I="";g.forEach((x,O)=>{I+=`input[${O}]: [${x.dims}] | ${Zt(x.dataType)}, `});let k="";m.forEach((x,O)=>{k+=`output[${O}]: [${x.dims}] | ${Zt(x.dataType)}, `}),console.log(`[profiling] kernel "${l}|${d}|${h}|${p}" ${I}${k}start time: ${S} ns, execution time: ${E-S} ns`)}Ue("GPU",`${p}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),ct()}run(e,t,s,i,o,l){dt(e.name);let u=[];for(let x=0;x<t.length;++x){let O=t[x].data;if(O===0)continue;let M=this.gpuDataManager.get(O);if(!M)throw new Error(`no GPU data for input: ${O}`);u.push(M)}let{outputs:d,dispatchGroup:h,programUniforms:p}=e.getRunData(t),g=s.length===0?d.map((x,O)=>O):s;if(g.length!==d.length)throw new Error(`Output size ${g.length} must be equal to ${d.length}.`);let m=[],w=[];for(let x=0;x<d.length;++x){if(!Number.isInteger(g[x])||g[x]<-3||g[x]>=l)throw new Error(`Invalid output index: ${g[x]}`);if(g[x]===-3)continue;let O=g[x]===-1,M=g[x]===-2,D=O||M?o(d[x].dataType,d[x].dims):i(g[x],d[x].dataType,d[x].dims);if(m.push(D),D.data===0)continue;let W=this.gpuDataManager.get(D.data);if(!W)throw new Error(`no GPU data for output: ${D.data}`);if(O&&this.temporaryData.push(W),M){let q=this.kernelPersistentData.get(this.currentKernelId);q||(q=[],this.kernelPersistentData.set(this.currentKernelId,q)),q.push(W)}w.push(W)}if(u.length!==t.length||w.length!==m.length){if(w.length===0)return ct(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(p){let x=0,O=[];p.forEach(q=>{let Y=typeof q.data=="number"?[q.data]:q.data;if(Y.length===0)return;let ae=q.type===10?2:4,ye,je;q.type===10?(je=Y.length>4?16:Y.length>2?8:Y.length*ae,ye=Y.length>4?16:ae*Y.length):(je=Y.length<=2?Y.length*ae:16,ye=16),x=Math.ceil(x/je)*je,O.push(x);let Ce=q.type===10?8:4;x+=Y.length>4?Math.ceil(Y.length/Ce)*ye:Y.length*ae});let M=16;x=Math.ceil(x/M)*M;let D=new ArrayBuffer(x);p.forEach((q,Y)=>{let ae=O[Y],ye=typeof q.data=="number"?[q.data]:q.data;if(q.type===6)new Int32Array(D,ae,ye.length).set(ye);else if(q.type===12)new Uint32Array(D,ae,ye.length).set(ye);else if(q.type===10)new Uint16Array(D,ae,ye.length).set(ye);else if(q.type===1)new Float32Array(D,ae,ye.length).set(ye);else throw new Error(`Unsupported uniform type: ${Zt(q.type)}`)});let W=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(W.buffer,0,D,0,x),this.gpuDataManager.release(W.id),_={offset:0,size:x,buffer:W.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),E=S[1]===1&&S[2]===1,I=Vh(e,t,E),k=this.programManager.getArtifact(I);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(I,k),Je("info",()=>`[artifact] key: ${I}, programName: ${e.name}`)),p&&k.uniformVariablesInfo){if(p.length!==k.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${k.uniformVariablesInfo.length}, got ${p.length} in program "${k.programInfo.name}".`);for(let x=0;x<p.length;x++){let O=p[x],M=O.type,D=typeof O.data=="number"?1:O.data.length,[W,q]=k.uniformVariablesInfo[x];if(M!==W||D!==q)throw new Error(`Uniform variable ${x} mismatch: expect type ${W} with size ${q}, got type ${M} with size ${D} in program "${k.programInfo.name}".`)}}if(Je("info",()=>`[ProgramManager] run "${e.name}" (key=${I}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let x={kernelId:this.currentKernelId,programName:k.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(x),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(x)}return this.programManager.run(k,u,w,S,_),ct(e.name),m}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,i){let o=Bh.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let o=i.kernelType,l=i.kernelName,u=i.kernelEntry,d=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),Je("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,d[1]),0}catch(p){return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${p}`)),1}finally{h&&s.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${o}] ${l}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let l=o.get(t),u=this.gpuDataManager.registerExternalBuffer(s,i,l);return o.set(t,[u,s]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let i=await Is(this,e,t);return Cr(i.buffer,s)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}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(){Je("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(){Je("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Je("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let i=0;i<s;i++){let o=this.getComputePassEncoder(),l=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),o.setPipeline(l.computePipeline),o.setBindGroup(0,l.bindGroup),o.dispatchWorkgroups(...l.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(t[i]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Wh={};U(Wh,{init:()=>jh});var Ti,Hh,jh,og=b(()=>{Pe(),tr(),Ae(),Ms(),Ti=class pf{constructor(t,s,i,o){this.module=t,this.dataType=s,this.data=i,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(H.size(t)!==H.size(this.dims))throw new Error("Invalid new shape");return new pf(this.module,this.dataType,this.data,t)}},Hh=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=s/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*o++,l));let u=Number(e.getValue(i*o++,l));this.outputCount=Number(e.getValue(i*o++,l)),this.customDataOffset=Number(e.getValue(i*o++,"*")),this.customDataSize=Number(e.getValue(i*o++,l));let d=[];for(let h=0;h<u;h++){let p=Number(e.getValue(i*o++,l)),g=Number(e.getValue(i*o++,"*")),m=Number(e.getValue(i*o++,l)),w=[];for(let _=0;_<m;_++)w.push(Number(e.getValue(i*o++,l)));d.push(new Ti(e,p,g,w))}this.inputs=d}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let s=t?.inputs?.map(u=>typeof u=="number"?this.inputs[u]:u)??this.inputs,i=t?.outputs??[],o=(u,d,h)=>new Ti(this.module,d,this.output(u,h),h),l=(u,d)=>{let h=er(u,d);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new Ti(this.module,u,p,d)};return this.backend.run(e,s,i,o,l,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let i=this.module.PTR_SIZE,o=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,o);for(let u=0;u<t.length;u++)this.module.setValue(l+i*(u+1),t[u],o);return this.module._JsepOutput(this.opKernelContext,e,l)}catch(i){throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${i}`)}finally{this.module.stackRestore(s)}}},jh=async(e,t,s,i)=>{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(ag(),te(Uh)).WebGpuBackend,u=new l;await u.initialize(s,i),o("webgpu",[u,d=>u.alloc(Number(d)),d=>u.free(d),(d,h,p,g=!1)=>{if(g)Je("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(d)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(d),Number(h));else{Je("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(d)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let m=t.HEAPU8.subarray(Number(d>>>0),Number(d>>>0)+Number(p));u.upload(Number(h),m)}},async(d,h,p)=>{Je("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${h}, size=${p}`),await u.download(Number(d),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(d,h,p)=>u.createKernel(d,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),d=>u.releaseKernel(d),(d,h,p,g)=>{Je("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${d}, contextDataOffset=${h}`);let m=new Hh(t,u,Number(h));return u.computeKernel(Number(d),m,g)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new As(s);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,d,h,p,g)=>l.ensureTensor(u,d,h,p,g),(u,d)=>{l.uploadTensor(u,d)},async(u,d)=>l.downloadTensor(u,d),(u,d)=>l.registerMLContext(u,d),!!s.trace])}}}),Kh,Ua,Fa,en,Qh,Va,$i,Ga,qa,Wa,Ha,ja,Ka,Xh=b(()=>{Ot(),Ki(),Qi(),Pe(),Yt(),gn(),$s(),Kh=(e,t)=>{ze()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},Ua=async e=>{Kh(e.wasm.numThreads,wn(e.logLevel))},Fa=async(e,t)=>{ze().asyncInit?.();let s=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(og(),te(Wh)).init;t==="webgpu"&&await i("webgpu",ze(),e,s),t==="webnn"&&await i("webnn",ze(),e)}},en=new Map,Qh=e=>{let t=ze(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Re("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(o,l)),Number(t.getValue(o+i,l))]}finally{t.stackRestore(s)}},Va=(e,t)=>{let s=ze(),i=s.stackSave(),o=0;try{let l=s.PTR_SIZE,u=s.stackAlloc(2*l);s._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Re("Can't get session input/output metadata.");let d=Number(s.getValue(u,"*"));o=Number(s.getValue(u+l,"*"));let h=s.HEAP32[o/4];if(h===0)return[d,0];let p=s.HEAPU32[o/4+1],g=[];for(let m=0;m<p;m++){let w=Number(s.getValue(o+8+m*l,"*"));g.push(w!==0?s.UTF8ToString(w):Number(s.getValue(o+8+(m+p)*l,"*")))}return[d,h,g]}finally{s.stackRestore(i),o!==0&&s._OrtFree(o)}},$i=e=>{let t=ze(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Ga=async(e,t)=>{let s,i,o=ze();Array.isArray(e)?[s,i]=e:e.buffer===o.HEAPU8.buffer?[s,i]=[e.byteOffset,e.byteLength]:[s,i]=$i(e);let l=0,u=0,d=0,h=[],p=[],g=[];try{if([u,h]=await Ts(t),t?.externalData&&o.mountExternalData){let M=[];for(let D of t.externalData){let W=typeof D=="string"?D:D.path;M.push(_n(typeof D=="string"?D:D.data).then(q=>{o.mountExternalData(W,q)}))}await Promise.all(M)}for(let M of t?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof M!="string"){let D=M,W=D?.context,q=D?.gpuDevice,Y=D?.deviceType,ae=D?.powerPreference;W?o.currentContext=W:q?o.currentContext=await o.webnnCreateMLContext(q):o.currentContext=await o.webnnCreateMLContext({deviceType:Y,powerPreference:ae})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(s,i,u),o.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[m,w]=Qh(l),_=!!t?.enableGraphCapture,S=[],E=[],I=[],k=[],x=[];for(let M=0;M<m;M++){let[D,W,q]=Va(l,M);D===0&&Re("Can't get an input name."),p.push(D);let Y=o.UTF8ToString(D);S.push(Y),I.push(W===0?{name:Y,isTensor:!1}:{name:Y,isTensor:!0,type:Zt(W),shape:q})}for(let M=0;M<w;M++){let[D,W,q]=Va(l,M+m);D===0&&Re("Can't get an output name."),g.push(D);let Y=o.UTF8ToString(D);E.push(Y),k.push(W===0?{name:Y,isTensor:!1}:{name:Y,isTensor:!0,type:Zt(W),shape:q});{if(_&&t?.preferredOutputLocation===void 0){x.push("gpu-buffer");continue}let ae=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[Y]??"cpu",ye=o.webnnIsGraphOutput;if(ae==="cpu"&&ye&&ye(l,Y)){x.push("ml-tensor-cpu-output");continue}if(ae!=="cpu"&&ae!=="cpu-pinned"&&ae!=="gpu-buffer"&&ae!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ae}.`);if(_&&ae!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ae}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);x.push(ae)}}let O=null;return x.some(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(d=o._OrtCreateBinding(l),d===0&&Re("Can't create IO binding."),O={handle:d,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>Ln(M))}),en.set(l,[l,p,g,O,_,!1]),[l,S,E,I,k]}catch(m){throw p.forEach(w=>o._OrtFree(w)),g.forEach(w=>o._OrtFree(w)),d!==0&&o._OrtReleaseBinding(d)!==0&&Re("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Re("Can't release session."),m}finally{o._free(s),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Re("Can't release session options."),h.forEach(m=>o._free(m)),o.unmountExternalData?.()}},qa=e=>{let t=ze(),s=en.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,d]=s;u&&(d&&t._OrtClearBoundOutputs(u.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(h=>t._OrtFree(h)),l.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(i)!==0&&Re("Can't release session."),en.delete(e)},Wa=async(e,t,s,i,o,l,u=!1)=>{if(!e){t.push(0);return}let d=ze(),h=d.PTR_SIZE,p=e[0],g=e[1],m=e[3],w=m,_,S;if(p==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let k=e[2].gpuBuffer;S=er(Jt(p),g);{let x=d.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=x(i,l,k,S)}}else if(m==="ml-tensor"){let k=e[2].mlTensor;S=er(Jt(p),g);let x=d.webnnRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=x(i,k,Jt(p),g)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,_=d._malloc(S),s.push(_);for(let x=0;x<k.length;x++){if(typeof k[x]!="string")throw new TypeError(`tensor data at index ${x} is not a string`);d.setValue(_+x*h,xt(k[x],s),"*")}}else{let x=d.webnnIsGraphInput,O=d.webnnIsGraphOutput;if(p!=="string"&&x&&O){let M=d.UTF8ToString(o);if(x(i,M)||O(i,M)){let D=Jt(p);S=er(D,g),w="ml-tensor";let W=d.webnnCreateTemporaryTensor,q=d.webnnUploadTensor;if(!W||!q)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Y=await W(i,D,g);q(Y,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),_=Y}else S=k.byteLength,_=d._malloc(S),s.push(_),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}else S=k.byteLength,_=d._malloc(S),s.push(_),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}}let E=d.stackSave(),I=d.stackAlloc(4*g.length);try{g.forEach((x,O)=>d.setValue(I+O*h,x,h===4?"i32":"i64"));let k=d._OrtCreateTensor(Jt(p),_,S,I,g.length,Ln(w));k===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{d.stackRestore(E)}},Ha=async(e,t,s,i,o,l)=>{let u=ze(),d=u.PTR_SIZE,h=en.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],g=h[1],m=h[2],w=h[3],_=h[4],S=h[5],E=t.length,I=i.length,k=0,x=[],O=[],M=[],D=[],W=[],q=u.stackSave(),Y=u.stackAlloc(E*d),ae=u.stackAlloc(E*d),ye=u.stackAlloc(I*d),je=u.stackAlloc(I*d);try{[k,x]=ws(l),me("wasm prepareInputOutputTensor");for(let ve=0;ve<E;ve++)await Wa(s[ve],O,D,e,g[t[ve]],t[ve],_);for(let ve=0;ve<I;ve++)await Wa(o[ve],M,D,e,m[i[ve]],E+i[ve],_);Fe("wasm prepareInputOutputTensor");for(let ve=0;ve<E;ve++)u.setValue(Y+ve*d,O[ve],"*"),u.setValue(ae+ve*d,g[t[ve]],"*");for(let ve=0;ve<I;ve++)u.setValue(ye+ve*d,M[ve],"*"),u.setValue(je+ve*d,m[i[ve]],"*");if(w&&!S){let{handle:ve,outputPreferredLocations:Ee,outputPreferredLocationsEncoded:Ke}=w;if(g.length!==E)throw new Error(`input count from feeds (${E}) is expected to be always equal to model's input count (${g.length}).`);me("wasm bindInputsOutputs");for(let Ve=0;Ve<E;Ve++){let De=t[Ve];await u._OrtBindInput(ve,g[De],O[Ve])!==0&&Re(`Can't bind input[${Ve}] for session=${e}.`)}for(let Ve=0;Ve<I;Ve++){let De=i[Ve];o[Ve]?.[3]?(W.push(M[Ve]),u._OrtBindOutput(ve,m[De],M[Ve],0)!==0&&Re(`Can't bind pre-allocated output[${Ve}] for session=${e}.`)):u._OrtBindOutput(ve,m[De],0,Ke[De])!==0&&Re(`Can't bind output[${Ve}] to ${Ee[Ve]} for session=${e}.`)}Fe("wasm bindInputsOutputs"),en.set(e,[p,g,m,w,_,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Ce;w?Ce=await u._OrtRunWithBinding(p,w.handle,I,ye,k):Ce=await u._OrtRun(p,ae,Y,E,je,I,ye,k),Ce!==0&&Re("failed to call OrtRun().");let Oe=[],it=[];me("wasm ProcessOutputTensor");for(let ve=0;ve<I;ve++){let Ee=Number(u.getValue(ye+ve*d,"*"));if(Ee===M[ve]||W.includes(M[ve])){Oe.push(o[ve]),Ee!==M[ve]&&u._OrtReleaseTensor(Ee)!==0&&Re("Can't release tensor.");continue}let Ke=u.stackSave(),Ve=u.stackAlloc(4*d),De=!1,ht,ne=0;try{u._OrtGetTensorData(Ee,Ve,Ve+d,Ve+2*d,Ve+3*d)!==0&&Re(`Can't access output tensor data on index ${ve}.`);let be=d===4?"i32":"i64",Ge=Number(u.getValue(Ve,be));ne=u.getValue(Ve+d,"*");let pt=u.getValue(Ve+d*2,"*"),_r=Number(u.getValue(Ve+d*3,be)),Mr=[];for(let Ft=0;Ft<_r;Ft++)Mr.push(Number(u.getValue(pt+Ft*d,be)));u._OrtFree(pt)!==0&&Re("Can't free memory for tensor dims.");let rn=Mr.reduce((Ft,Rt)=>Ft*Rt,1);ht=Zt(Ge);let js=w?.outputPreferredLocations[i[ve]];if(ht==="string"){if(js==="gpu-buffer"||js==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ft=[];for(let Rt=0;Rt<rn;Rt++){let Ur=u.getValue(ne+Rt*d,"*"),hg=u.getValue(ne+(Rt+1)*d,"*"),pg=Rt===rn-1?void 0:hg-Ur;Ft.push(u.UTF8ToString(Ur,pg))}Oe.push([ht,Mr,Ft,"cpu"])}else if(js==="gpu-buffer"&&rn>0){let Ft=u.jsepGetBuffer;if(!Ft)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Rt=Ft(ne),Ur=er(Ge,rn);if(Ur===void 0||!vn(ht))throw new Error(`Unsupported data type: ${ht}`);De=!0,Oe.push([ht,Mr,{gpuBuffer:Rt,download:u.jsepCreateDownloader(Rt,Ur,ht),dispose:()=>{u._OrtReleaseTensor(Ee)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(js==="ml-tensor"&&rn>0){let Ft=u.webnnEnsureTensor,Rt=u.webnnIsGraphInputOutputTypeSupported;if(!Ft||!Rt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(Ge,rn)===void 0||!bn(ht))throw new Error(`Unsupported data type: ${ht}`);if(!Rt(e,ht,!1))throw new Error(`preferredLocation "ml-tensor" for ${ht} output is not supported by current WebNN Context.`);let Ur=await Ft(e,ne,Ge,Mr,!1);De=!0,Oe.push([ht,Mr,{mlTensor:Ur,download:u.webnnCreateMLTensorDownloader(ne,ht),dispose:()=>{u.webnnReleaseTensorId(ne),u._OrtReleaseTensor(Ee)}},"ml-tensor"])}else if(js==="ml-tensor-cpu-output"&&rn>0){let Ft=u.webnnCreateMLTensorDownloader(ne,ht)(),Rt=Oe.length;De=!0,it.push((async()=>{let Ur=[Rt,await Ft];return u.webnnReleaseTensorId(ne),u._OrtReleaseTensor(Ee),Ur})()),Oe.push([ht,Mr,[],"cpu"])}else{let Ft=yn(ht),Rt=new Ft(rn);new Uint8Array(Rt.buffer,Rt.byteOffset,Rt.byteLength).set(u.HEAPU8.subarray(ne,ne+Rt.byteLength)),Oe.push([ht,Mr,Rt,"cpu"])}}finally{u.stackRestore(Ke),ht==="string"&&ne&&u._free(ne),De||u._OrtReleaseTensor(Ee)}}w&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Re("Can't clear bound outputs."),en.set(e,[p,g,m,w,_,!1]));for(let[ve,Ee]of await Promise.all(it))Oe[ve][2]=Ee;return Fe("wasm ProcessOutputTensor"),Oe}finally{u.webnnOnRunEnd?.(p),u.stackRestore(q),O.forEach(Ce=>u._OrtReleaseTensor(Ce)),M.forEach(Ce=>u._OrtReleaseTensor(Ce)),D.forEach(Ce=>u._free(Ce)),k!==0&&u._OrtReleaseRunOptions(k),x.forEach(Ce=>u._free(Ce))}},ja=e=>{let t=ze(),s=en.get(e);if(!s)throw new Error("invalid session id");let i=s[0],o=t._OrtEndProfiling(i);o===0&&Re("Can't get an profile file name."),t._OrtFree(o)},Ka=e=>{let t=[];for(let s of e){let i=s[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),tn,ir,ts,Ws,Hs,xi,Qa,Ei,Pn,On,Yh,Jh,Zh,ep,tp,rp,np,sp,ip=b(()=>{Ot(),Xh(),Yt(),hn(),tn=()=>!!ge.wasm.proxy&&typeof document<"u",ts=!1,Ws=!1,Hs=!1,Ei=new Map,Pn=(e,t)=>{let s=Ei.get(e);s?s.push(t):Ei.set(e,[t])},On=()=>{if(ts||!Ws||Hs||!ir)throw new Error("worker not ready")},Yh=e=>{switch(e.data.type){case"init-wasm":ts=!1,e.data.err?(Hs=!0,Qa[1](e.data.err)):(Ws=!0,Qa[0]()),xi&&(URL.revokeObjectURL(xi),xi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ei.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Jh=async()=>{if(!Ws){if(ts)throw new Error("multiple calls to 'initWasm()' detected.");if(Hs)throw new Error("previous call to 'initWasm()' failed.");if(ts=!0,tn())return new Promise((e,t)=>{ir?.terminate(),ps().then(([s,i])=>{try{ir=i,ir.onerror=l=>t(l),ir.onmessage=Yh,Qa=[e,t];let o={type:"init-wasm",in:ge};if(!o.in.wasm.wasmPaths&&s){let l=ln();l&&(o.in.wasm.wasmPaths=l)}ir.postMessage(o),xi=s}catch(o){t(o)}},t)});try{await mn(ge.wasm),await Ua(ge),Ws=!0}catch(e){throw Hs=!0,e}finally{ts=!1}}},Zh=async e=>{if(tn())return On(),new Promise((t,s)=>{Pn("init-ep",[t,s]);let i={type:"init-ep",in:{epName:e,env:ge}};ir.postMessage(i)});await Fa(ge,e)},ep=async e=>tn()?(On(),new Promise((t,s)=>{Pn("copy-from",[t,s]);let i={type:"copy-from",in:{buffer:e}};ir.postMessage(i,[e.buffer])})):$i(e),tp=async(e,t)=>{if(tn()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return On(),new Promise((s,i)=>{Pn("create",[s,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),ir.postMessage(o,l)})}else return Ga(e,t)},rp=async e=>{if(tn())return On(),new Promise((t,s)=>{Pn("release",[t,s]);let i={type:"release",in:e};ir.postMessage(i)});qa(e)},np=async(e,t,s,i,o,l)=>{if(tn()){if(s.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return On(),new Promise((u,d)=>{Pn("run",[u,d]);let h=s,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};ir.postMessage(p,Ka(h))})}else return Ha(e,t,s,i,o,l)},sp=async e=>{if(tn())return On(),new Promise((t,s)=>{Pn("end-profiling",[t,s]);let i={type:"end-profiling",in:e};ir.postMessage(i)});ja(e)}}),Xa,ap,op,lg=b(()=>{Ot(),ip(),Pe(),sn(),$s(),Xa=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},ap=e=>{switch(e[3]){case"cpu":return new vt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!vn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:i,dispose:o}=e[2];return vt.fromGpuBuffer(s,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!bn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:i,dispose:o}=e[2];return vt.fromMLTensor(s,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},op=class{async fetchModelAndCopyToWasmMemory(e){return ep(await _n(e))}async loadModel(e,t){dt();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await tp(s,t),ct()}async dispose(){return rp(this.sessionId)}async run(e,t,s){dt();let i=[],o=[];Object.entries(e).forEach(m=>{let w=m[0],_=m[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);i.push(_),o.push(S)});let l=[],u=[];Object.entries(t).forEach(m=>{let w=m[0],_=m[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(_),u.push(S)});let d=i.map((m,w)=>Xa(m,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((m,w)=>m?Xa(m,()=>`output "${this.outputNames[u[w]]}"`):null),p=await np(this.sessionId,o,d,u,h,s),g={};for(let m=0;m<p.length;m++)g[this.outputNames[u[m]]]=l[m]??ap(p[m]);return ct(),g}startProfiling(){}endProfiling(){sp(this.sessionId)}}}),lp={};U(lp,{OnnxruntimeWebAssemblyBackend:()=>Ja,initializeFlags:()=>Ya,wasmBackend:()=>up});var Ya,Ja,up,ug=b(()=>{Ot(),ip(),lg(),Ya=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let e=ge.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ja=class{async init(e){Ya(),await Jh(),await Zh(e)}async createInferenceSessionHandler(e,t){let s=new op;return await s.loadModel(e,t),s}},up=new Ja}),dp={};U(dp,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,default:()=>cg,env:()=>ge,registerBackend:()=>ie}),Ot(),Ot(),Ot();var dg="1.24.3",cg=is;{let e=(ug(),te(lp)).wasmBackend;ie("webgpu",e,5),ie("webnn",e,5),ie("cpu",e,10),ie("wasm",e,10)}return Object.defineProperty(ge.versions,"web",{value:dg,enumerable:!0}),te(dp)})();/**
|
|
2809
|
+
${l}`,d=s.createShaderModule({code:u,label:e.name});Je("verbose",()=>`[WebGPU] ${e.name} shader code: ${u}`);let h=s.createComputePipeline({compute:{module:d,entryPoint:"main"},layout:"auto",label:e.name});return ct(e.name),{programInfo:e,computePipeline:h,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&i<=o)return[t,s,i];let l=t*s*i,u=Math.ceil(Math.sqrt(l));if(u>o){if(u=Math.ceil(Math.cbrt(l)),u>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[u,u,u]}else return[u,u,1]}}}),Uh={};U(Uh,{WebGpuBackend:()=>qh});var Fh,Vh,Gh,qh,ag=b(()=>{Ot(),Pe(),tr(),Qr(),Xi(),sg(),ig(),Fh=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let i=0;i<e.length;++i){let o=e[i].dataType;switch(t[i]){case"none":{s.push("");break}case"type":{s.push(`${o}`);break}case"rank":{let l=e[i].dims.length;s.push(`${o};${l}`);break}case"dims":{let l=e[i].dims.join(",");s.push(`${o};${l}`);break}default:throw new Error(`unsupported input dependency: ${t[i]}`)}}return s.join("|")},Vh=(e,t,s)=>{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+s+`:${Fh(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},Gh=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},qh=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let s=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},o=l=>t.features.has(l)&&s.push(l)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await t.requestDevice(i),this.adapterInfo=new Gh(t.info||await t.requestAdapterInfo()),this.gpuDataManager=di(this),this.programManager=new Nh(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Un(e.logLevel,!!e.debug),this.device.onuncapturederror=l=>{l.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${l.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;dt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let i=0;i<t.length/2;i++){let o=s[i],l=o.kernelId,u=this.kernels.get(l),d=u.kernelType,h=u.kernelName,p=o.programName,g=o.inputTensorViews,m=o.outputTensorViews,w=t[i*2],_=t[i*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=w);let S=Number(w-this.queryTimeBase),E=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(E))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map(I=>({dims:I.dims,dataType:Zt(I.dataType)})),outputsMetadata:m.map(I=>({dims:I.dims,dataType:Zt(I.dataType)})),kernelId:l,kernelType:d,kernelName:h,programName:p,startTime:S,endTime:E});else{let I="";g.forEach((x,O)=>{I+=`input[${O}]: [${x.dims}] | ${Zt(x.dataType)}, `});let k="";m.forEach((x,O)=>{k+=`output[${O}]: [${x.dims}] | ${Zt(x.dataType)}, `}),console.log(`[profiling] kernel "${l}|${d}|${h}|${p}" ${I}${k}start time: ${S} ns, execution time: ${E-S} ns`)}Ue("GPU",`${p}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),ct()}run(e,t,s,i,o,l){dt(e.name);let u=[];for(let x=0;x<t.length;++x){let O=t[x].data;if(O===0)continue;let M=this.gpuDataManager.get(O);if(!M)throw new Error(`no GPU data for input: ${O}`);u.push(M)}let{outputs:d,dispatchGroup:h,programUniforms:p}=e.getRunData(t),g=s.length===0?d.map((x,O)=>O):s;if(g.length!==d.length)throw new Error(`Output size ${g.length} must be equal to ${d.length}.`);let m=[],w=[];for(let x=0;x<d.length;++x){if(!Number.isInteger(g[x])||g[x]<-3||g[x]>=l)throw new Error(`Invalid output index: ${g[x]}`);if(g[x]===-3)continue;let O=g[x]===-1,M=g[x]===-2,D=O||M?o(d[x].dataType,d[x].dims):i(g[x],d[x].dataType,d[x].dims);if(m.push(D),D.data===0)continue;let W=this.gpuDataManager.get(D.data);if(!W)throw new Error(`no GPU data for output: ${D.data}`);if(O&&this.temporaryData.push(W),M){let q=this.kernelPersistentData.get(this.currentKernelId);q||(q=[],this.kernelPersistentData.set(this.currentKernelId,q)),q.push(W)}w.push(W)}if(u.length!==t.length||w.length!==m.length){if(w.length===0)return ct(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(p){let x=0,O=[];p.forEach(q=>{let Y=typeof q.data=="number"?[q.data]:q.data;if(Y.length===0)return;let ae=q.type===10?2:4,ye,je;q.type===10?(je=Y.length>4?16:Y.length>2?8:Y.length*ae,ye=Y.length>4?16:ae*Y.length):(je=Y.length<=2?Y.length*ae:16,ye=16),x=Math.ceil(x/je)*je,O.push(x);let Ce=q.type===10?8:4;x+=Y.length>4?Math.ceil(Y.length/Ce)*ye:Y.length*ae});let M=16;x=Math.ceil(x/M)*M;let D=new ArrayBuffer(x);p.forEach((q,Y)=>{let ae=O[Y],ye=typeof q.data=="number"?[q.data]:q.data;if(q.type===6)new Int32Array(D,ae,ye.length).set(ye);else if(q.type===12)new Uint32Array(D,ae,ye.length).set(ye);else if(q.type===10)new Uint16Array(D,ae,ye.length).set(ye);else if(q.type===1)new Float32Array(D,ae,ye.length).set(ye);else throw new Error(`Unsupported uniform type: ${Zt(q.type)}`)});let W=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(W.buffer,0,D,0,x),this.gpuDataManager.release(W.id),_={offset:0,size:x,buffer:W.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),E=S[1]===1&&S[2]===1,I=Vh(e,t,E),k=this.programManager.getArtifact(I);if(k||(k=this.programManager.build(e,S),this.programManager.setArtifact(I,k),Je("info",()=>`[artifact] key: ${I}, programName: ${e.name}`)),p&&k.uniformVariablesInfo){if(p.length!==k.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${k.uniformVariablesInfo.length}, got ${p.length} in program "${k.programInfo.name}".`);for(let x=0;x<p.length;x++){let O=p[x],M=O.type,D=typeof O.data=="number"?1:O.data.length,[W,q]=k.uniformVariablesInfo[x];if(M!==W||D!==q)throw new Error(`Uniform variable ${x} mismatch: expect type ${W} with size ${q}, got type ${M} with size ${D} in program "${k.programInfo.name}".`)}}if(Je("info",()=>`[ProgramManager] run "${e.name}" (key=${I}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let x={kernelId:this.currentKernelId,programName:k.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(x),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(x)}return this.programManager.run(k,u,w,S,_),ct(e.name),m}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,i){let o=Bh.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let o=i.kernelType,l=i.kernelName,u=i.kernelEntry,d=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),Je("info",()=>`[WebGPU] Start to run kernel "[${o}] ${l}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),u(t,d[1]),0}catch(p){return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${l}" failed. ${p}`)),1}finally{h&&s.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${o}] ${l}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,i){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let l=o.get(t),u=this.gpuDataManager.registerExternalBuffer(s,i,l);return o.set(t,[u,s]),u}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let i=await Is(this,e,t);return Cr(i.buffer,s)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}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(){Je("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(){Je("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Je("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let i=0;i<s;i++){let o=this.getComputePassEncoder(),l=e[i];this.writeTimestamp(this.pendingDispatchNumber*2),o.setPipeline(l.computePipeline),o.setBindGroup(0,l.bindGroup),o.dispatchWorkgroups(...l.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(t[i]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Wh={};U(Wh,{init:()=>jh});var Ti,Hh,jh,og=b(()=>{Pe(),tr(),Ae(),Ms(),Ti=class pf{constructor(t,s,i,o){this.module=t,this.dataType=s,this.data=i,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=H.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(H.size(t)!==H.size(this.dims))throw new Error("Invalid new shape");return new pf(this.module,this.dataType,this.data,t)}},Hh=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,o=s/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*o++,l));let u=Number(e.getValue(i*o++,l));this.outputCount=Number(e.getValue(i*o++,l)),this.customDataOffset=Number(e.getValue(i*o++,"*")),this.customDataSize=Number(e.getValue(i*o++,l));let d=[];for(let h=0;h<u;h++){let p=Number(e.getValue(i*o++,l)),g=Number(e.getValue(i*o++,"*")),m=Number(e.getValue(i*o++,l)),w=[];for(let _=0;_<m;_++)w.push(Number(e.getValue(i*o++,l)));d.push(new Ti(e,p,g,w))}this.inputs=d}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(e,t){let s=t?.inputs?.map(u=>typeof u=="number"?this.inputs[u]:u)??this.inputs,i=t?.outputs??[],o=(u,d,h)=>new Ti(this.module,d,this.output(u,h),h),l=(u,d)=>{let h=er(u,d);if(!h)throw new Error(`Unsupported data type: ${u}`);let p=h>0?this.backend.gpuDataManager.create(h).id:0;return new Ti(this.module,u,p,d)};return this.backend.run(e,s,i,o,l,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let i=this.module.PTR_SIZE,o=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,o);for(let u=0;u<t.length;u++)this.module.setValue(l+i*(u+1),t[u],o);return this.module._JsepOutput(this.opKernelContext,e,l)}catch(i){throw new Error(`Failed to generate kernel's output[${e}] with dims [${t}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${i}`)}finally{this.module.stackRestore(s)}}},jh=async(e,t,s,i)=>{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(ag(),te(Uh)).WebGpuBackend,u=new l;await u.initialize(s,i),o("webgpu",[u,d=>u.alloc(Number(d)),d=>u.free(d),(d,h,p,g=!1)=>{if(g)Je("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(d)}, dst=${Number(h)}, size=${Number(p)}`),u.memcpy(Number(d),Number(h));else{Je("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(d)}, gpuDataId=${Number(h)}, size=${Number(p)}`);let m=t.HEAPU8.subarray(Number(d>>>0),Number(d>>>0)+Number(p));u.upload(Number(h),m)}},async(d,h,p)=>{Je("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${h}, size=${p}`),await u.download(Number(d),()=>t.HEAPU8.subarray(Number(h)>>>0,Number(h+p)>>>0))},(d,h,p)=>u.createKernel(d,Number(h),p,t.UTF8ToString(t._JsepGetNodeName(Number(h)))),d=>u.releaseKernel(d),(d,h,p,g)=>{Je("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${d}, contextDataOffset=${h}`);let m=new Hh(t,u,Number(h));return u.computeKernel(Number(d),m,g)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else{let l=new As(s);o("webnn",[l,()=>l.reserveTensorId(),u=>l.releaseTensorId(u),async(u,d,h,p,g)=>l.ensureTensor(u,d,h,p,g),(u,d)=>{l.uploadTensor(u,d)},async(u,d)=>l.downloadTensor(u,d),(u,d)=>l.registerMLContext(u,d),!!s.trace])}}}),Kh,Ua,Fa,en,Qh,Va,$i,Ga,qa,Wa,Ha,ja,Ka,Xh=b(()=>{Ot(),Ki(),Qi(),Pe(),Yt(),gn(),$s(),Kh=(e,t)=>{ze()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},Ua=async e=>{Kh(e.wasm.numThreads,wn(e.logLevel))},Fa=async(e,t)=>{ze().asyncInit?.();let s=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(og(),te(Wh)).init;t==="webgpu"&&await i("webgpu",ze(),e,s),t==="webnn"&&await i("webnn",ze(),e)}},en=new Map,Qh=e=>{let t=ze(),s=t.stackSave();try{let i=t.PTR_SIZE,o=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,o,o+i)!==0&&Re("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(o,l)),Number(t.getValue(o+i,l))]}finally{t.stackRestore(s)}},Va=(e,t)=>{let s=ze(),i=s.stackSave(),o=0;try{let l=s.PTR_SIZE,u=s.stackAlloc(2*l);s._OrtGetInputOutputMetadata(e,t,u,u+l)!==0&&Re("Can't get session input/output metadata.");let d=Number(s.getValue(u,"*"));o=Number(s.getValue(u+l,"*"));let h=s.HEAP32[o/4];if(h===0)return[d,0];let p=s.HEAPU32[o/4+1],g=[];for(let m=0;m<p;m++){let w=Number(s.getValue(o+8+m*l,"*"));g.push(w!==0?s.UTF8ToString(w):Number(s.getValue(o+8+(m+p)*l,"*")))}return[d,h,g]}finally{s.stackRestore(i),o!==0&&s._OrtFree(o)}},$i=e=>{let t=ze(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Ga=async(e,t)=>{let s,i,o=ze();Array.isArray(e)?[s,i]=e:e.buffer===o.HEAPU8.buffer?[s,i]=[e.byteOffset,e.byteLength]:[s,i]=$i(e);let l=0,u=0,d=0,h=[],p=[],g=[];try{if([u,h]=await Ts(t),t?.externalData&&o.mountExternalData){let M=[];for(let D of t.externalData){let W=typeof D=="string"?D:D.path;M.push(_n(typeof D=="string"?D:D.data).then(q=>{o.mountExternalData(W,q)}))}await Promise.all(M)}for(let M of t?.executionProviders??[])if((typeof M=="string"?M:M.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof M!="string"){let D=M,W=D?.context,q=D?.gpuDevice,Y=D?.deviceType,ae=D?.powerPreference;W?o.currentContext=W:q?o.currentContext=await o.webnnCreateMLContext(q):o.currentContext=await o.webnnCreateMLContext({deviceType:Y,powerPreference:ae})}else o.currentContext=await o.webnnCreateMLContext();break}l=await o._OrtCreateSession(s,i,u),o.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(l,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[m,w]=Qh(l),_=!!t?.enableGraphCapture,S=[],E=[],I=[],k=[],x=[];for(let M=0;M<m;M++){let[D,W,q]=Va(l,M);D===0&&Re("Can't get an input name."),p.push(D);let Y=o.UTF8ToString(D);S.push(Y),I.push(W===0?{name:Y,isTensor:!1}:{name:Y,isTensor:!0,type:Zt(W),shape:q})}for(let M=0;M<w;M++){let[D,W,q]=Va(l,M+m);D===0&&Re("Can't get an output name."),g.push(D);let Y=o.UTF8ToString(D);E.push(Y),k.push(W===0?{name:Y,isTensor:!1}:{name:Y,isTensor:!0,type:Zt(W),shape:q});{if(_&&t?.preferredOutputLocation===void 0){x.push("gpu-buffer");continue}let ae=typeof t?.preferredOutputLocation=="string"?t.preferredOutputLocation:t?.preferredOutputLocation?.[Y]??"cpu",ye=o.webnnIsGraphOutput;if(ae==="cpu"&&ye&&ye(l,Y)){x.push("ml-tensor-cpu-output");continue}if(ae!=="cpu"&&ae!=="cpu-pinned"&&ae!=="gpu-buffer"&&ae!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ae}.`);if(_&&ae!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ae}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);x.push(ae)}}let O=null;return x.some(M=>M==="gpu-buffer"||M==="ml-tensor"||M==="ml-tensor-cpu-output")&&(d=o._OrtCreateBinding(l),d===0&&Re("Can't create IO binding."),O={handle:d,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(M=>M==="ml-tensor-cpu-output"?"ml-tensor":M).map(M=>Ln(M))}),en.set(l,[l,p,g,O,_,!1]),[l,S,E,I,k]}catch(m){throw p.forEach(w=>o._OrtFree(w)),g.forEach(w=>o._OrtFree(w)),d!==0&&o._OrtReleaseBinding(d)!==0&&Re("Can't release IO binding."),l!==0&&o._OrtReleaseSession(l)!==0&&Re("Can't release session."),m}finally{o._free(s),u!==0&&o._OrtReleaseSessionOptions(u)!==0&&Re("Can't release session options."),h.forEach(m=>o._free(m)),o.unmountExternalData?.()}},qa=e=>{let t=ze(),s=en.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,o,l,u,d]=s;u&&(d&&t._OrtClearBoundOutputs(u.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(u.handle)!==0&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(h=>t._OrtFree(h)),l.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(i)!==0&&Re("Can't release session."),en.delete(e)},Wa=async(e,t,s,i,o,l,u=!1)=>{if(!e){t.push(0);return}let d=ze(),h=d.PTR_SIZE,p=e[0],g=e[1],m=e[3],w=m,_,S;if(p==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(u&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let k=e[2].gpuBuffer;S=er(Jt(p),g);{let x=d.jsepRegisterBuffer;if(!x)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=x(i,l,k,S)}}else if(m==="ml-tensor"){let k=e[2].mlTensor;S=er(Jt(p),g);let x=d.webnnRegisterMLTensor;if(!x)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=x(i,k,Jt(p),g)}else{let k=e[2];if(Array.isArray(k)){S=h*k.length,_=d._malloc(S),s.push(_);for(let x=0;x<k.length;x++){if(typeof k[x]!="string")throw new TypeError(`tensor data at index ${x} is not a string`);d.setValue(_+x*h,Et(k[x],s),"*")}}else{let x=d.webnnIsGraphInput,O=d.webnnIsGraphOutput;if(p!=="string"&&x&&O){let M=d.UTF8ToString(o);if(x(i,M)||O(i,M)){let D=Jt(p);S=er(D,g),w="ml-tensor";let W=d.webnnCreateTemporaryTensor,q=d.webnnUploadTensor;if(!W||!q)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Y=await W(i,D,g);q(Y,new Uint8Array(k.buffer,k.byteOffset,k.byteLength)),_=Y}else S=k.byteLength,_=d._malloc(S),s.push(_),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}else S=k.byteLength,_=d._malloc(S),s.push(_),d.HEAPU8.set(new Uint8Array(k.buffer,k.byteOffset,S),_)}}let E=d.stackSave(),I=d.stackAlloc(4*g.length);try{g.forEach((x,O)=>d.setValue(I+O*h,x,h===4?"i32":"i64"));let k=d._OrtCreateTensor(Jt(p),_,S,I,g.length,Ln(w));k===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(k)}finally{d.stackRestore(E)}},Ha=async(e,t,s,i,o,l)=>{let u=ze(),d=u.PTR_SIZE,h=en.get(e);if(!h)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=h[0],g=h[1],m=h[2],w=h[3],_=h[4],S=h[5],E=t.length,I=i.length,k=0,x=[],O=[],M=[],D=[],W=[],q=u.stackSave(),Y=u.stackAlloc(E*d),ae=u.stackAlloc(E*d),ye=u.stackAlloc(I*d),je=u.stackAlloc(I*d);try{[k,x]=ws(l),me("wasm prepareInputOutputTensor");for(let ve=0;ve<E;ve++)await Wa(s[ve],O,D,e,g[t[ve]],t[ve],_);for(let ve=0;ve<I;ve++)await Wa(o[ve],M,D,e,m[i[ve]],E+i[ve],_);Fe("wasm prepareInputOutputTensor");for(let ve=0;ve<E;ve++)u.setValue(Y+ve*d,O[ve],"*"),u.setValue(ae+ve*d,g[t[ve]],"*");for(let ve=0;ve<I;ve++)u.setValue(ye+ve*d,M[ve],"*"),u.setValue(je+ve*d,m[i[ve]],"*");if(w&&!S){let{handle:ve,outputPreferredLocations:Ee,outputPreferredLocationsEncoded:Ke}=w;if(g.length!==E)throw new Error(`input count from feeds (${E}) is expected to be always equal to model's input count (${g.length}).`);me("wasm bindInputsOutputs");for(let Ve=0;Ve<E;Ve++){let De=t[Ve];await u._OrtBindInput(ve,g[De],O[Ve])!==0&&Re(`Can't bind input[${Ve}] for session=${e}.`)}for(let Ve=0;Ve<I;Ve++){let De=i[Ve];o[Ve]?.[3]?(W.push(M[Ve]),u._OrtBindOutput(ve,m[De],M[Ve],0)!==0&&Re(`Can't bind pre-allocated output[${Ve}] for session=${e}.`)):u._OrtBindOutput(ve,m[De],0,Ke[De])!==0&&Re(`Can't bind output[${Ve}] to ${Ee[Ve]} for session=${e}.`)}Fe("wasm bindInputsOutputs"),en.set(e,[p,g,m,w,_,!0])}u.jsepOnRunStart?.(p),u.webnnOnRunStart?.(p);let Ce;w?Ce=await u._OrtRunWithBinding(p,w.handle,I,ye,k):Ce=await u._OrtRun(p,ae,Y,E,je,I,ye,k),Ce!==0&&Re("failed to call OrtRun().");let Oe=[],it=[];me("wasm ProcessOutputTensor");for(let ve=0;ve<I;ve++){let Ee=Number(u.getValue(ye+ve*d,"*"));if(Ee===M[ve]||W.includes(M[ve])){Oe.push(o[ve]),Ee!==M[ve]&&u._OrtReleaseTensor(Ee)!==0&&Re("Can't release tensor.");continue}let Ke=u.stackSave(),Ve=u.stackAlloc(4*d),De=!1,ht,ne=0;try{u._OrtGetTensorData(Ee,Ve,Ve+d,Ve+2*d,Ve+3*d)!==0&&Re(`Can't access output tensor data on index ${ve}.`);let be=d===4?"i32":"i64",Ge=Number(u.getValue(Ve,be));ne=u.getValue(Ve+d,"*");let pt=u.getValue(Ve+d*2,"*"),_r=Number(u.getValue(Ve+d*3,be)),Mr=[];for(let Ft=0;Ft<_r;Ft++)Mr.push(Number(u.getValue(pt+Ft*d,be)));u._OrtFree(pt)!==0&&Re("Can't free memory for tensor dims.");let rn=Mr.reduce((Ft,Mt)=>Ft*Mt,1);ht=Zt(Ge);let js=w?.outputPreferredLocations[i[ve]];if(ht==="string"){if(js==="gpu-buffer"||js==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ft=[];for(let Mt=0;Mt<rn;Mt++){let Ur=u.getValue(ne+Mt*d,"*"),hg=u.getValue(ne+(Mt+1)*d,"*"),pg=Mt===rn-1?void 0:hg-Ur;Ft.push(u.UTF8ToString(Ur,pg))}Oe.push([ht,Mr,Ft,"cpu"])}else if(js==="gpu-buffer"&&rn>0){let Ft=u.jsepGetBuffer;if(!Ft)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Mt=Ft(ne),Ur=er(Ge,rn);if(Ur===void 0||!vn(ht))throw new Error(`Unsupported data type: ${ht}`);De=!0,Oe.push([ht,Mr,{gpuBuffer:Mt,download:u.jsepCreateDownloader(Mt,Ur,ht),dispose:()=>{u._OrtReleaseTensor(Ee)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(js==="ml-tensor"&&rn>0){let Ft=u.webnnEnsureTensor,Mt=u.webnnIsGraphInputOutputTypeSupported;if(!Ft||!Mt)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(Ge,rn)===void 0||!bn(ht))throw new Error(`Unsupported data type: ${ht}`);if(!Mt(e,ht,!1))throw new Error(`preferredLocation "ml-tensor" for ${ht} output is not supported by current WebNN Context.`);let Ur=await Ft(e,ne,Ge,Mr,!1);De=!0,Oe.push([ht,Mr,{mlTensor:Ur,download:u.webnnCreateMLTensorDownloader(ne,ht),dispose:()=>{u.webnnReleaseTensorId(ne),u._OrtReleaseTensor(Ee)}},"ml-tensor"])}else if(js==="ml-tensor-cpu-output"&&rn>0){let Ft=u.webnnCreateMLTensorDownloader(ne,ht)(),Mt=Oe.length;De=!0,it.push((async()=>{let Ur=[Mt,await Ft];return u.webnnReleaseTensorId(ne),u._OrtReleaseTensor(Ee),Ur})()),Oe.push([ht,Mr,[],"cpu"])}else{let Ft=yn(ht),Mt=new Ft(rn);new Uint8Array(Mt.buffer,Mt.byteOffset,Mt.byteLength).set(u.HEAPU8.subarray(ne,ne+Mt.byteLength)),Oe.push([ht,Mr,Mt,"cpu"])}}finally{u.stackRestore(Ke),ht==="string"&&ne&&u._free(ne),De||u._OrtReleaseTensor(Ee)}}w&&!_&&(u._OrtClearBoundOutputs(w.handle)!==0&&Re("Can't clear bound outputs."),en.set(e,[p,g,m,w,_,!1]));for(let[ve,Ee]of await Promise.all(it))Oe[ve][2]=Ee;return Fe("wasm ProcessOutputTensor"),Oe}finally{u.webnnOnRunEnd?.(p),u.stackRestore(q),O.forEach(Ce=>u._OrtReleaseTensor(Ce)),M.forEach(Ce=>u._OrtReleaseTensor(Ce)),D.forEach(Ce=>u._free(Ce)),k!==0&&u._OrtReleaseRunOptions(k),x.forEach(Ce=>u._free(Ce))}},ja=e=>{let t=ze(),s=en.get(e);if(!s)throw new Error("invalid session id");let i=s[0],o=t._OrtEndProfiling(i);o===0&&Re("Can't get an profile file name."),t._OrtFree(o)},Ka=e=>{let t=[];for(let s of e){let i=s[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),tn,ir,ts,Ws,Hs,xi,Qa,Ei,Pn,On,Yh,Jh,Zh,ep,tp,rp,np,sp,ip=b(()=>{Ot(),Xh(),Yt(),hn(),tn=()=>!!ge.wasm.proxy&&typeof document<"u",ts=!1,Ws=!1,Hs=!1,Ei=new Map,Pn=(e,t)=>{let s=Ei.get(e);s?s.push(t):Ei.set(e,[t])},On=()=>{if(ts||!Ws||Hs||!ir)throw new Error("worker not ready")},Yh=e=>{switch(e.data.type){case"init-wasm":ts=!1,e.data.err?(Hs=!0,Qa[1](e.data.err)):(Ws=!0,Qa[0]()),xi&&(URL.revokeObjectURL(xi),xi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Ei.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Jh=async()=>{if(!Ws){if(ts)throw new Error("multiple calls to 'initWasm()' detected.");if(Hs)throw new Error("previous call to 'initWasm()' failed.");if(ts=!0,tn())return new Promise((e,t)=>{ir?.terminate(),ps().then(([s,i])=>{try{ir=i,ir.onerror=l=>t(l),ir.onmessage=Yh,Qa=[e,t];let o={type:"init-wasm",in:ge};if(!o.in.wasm.wasmPaths&&s){let l=ln();l&&(o.in.wasm.wasmPaths=l)}ir.postMessage(o),xi=s}catch(o){t(o)}},t)});try{await mn(ge.wasm),await Ua(ge),Ws=!0}catch(e){throw Hs=!0,e}finally{ts=!1}}},Zh=async e=>{if(tn())return On(),new Promise((t,s)=>{Pn("init-ep",[t,s]);let i={type:"init-ep",in:{epName:e,env:ge}};ir.postMessage(i)});await Fa(ge,e)},ep=async e=>tn()?(On(),new Promise((t,s)=>{Pn("copy-from",[t,s]);let i={type:"copy-from",in:{buffer:e}};ir.postMessage(i,[e.buffer])})):$i(e),tp=async(e,t)=>{if(tn()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return On(),new Promise((s,i)=>{Pn("create",[s,i]);let o={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),ir.postMessage(o,l)})}else return Ga(e,t)},rp=async e=>{if(tn())return On(),new Promise((t,s)=>{Pn("release",[t,s]);let i={type:"release",in:e};ir.postMessage(i)});qa(e)},np=async(e,t,s,i,o,l)=>{if(tn()){if(s.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return On(),new Promise((u,d)=>{Pn("run",[u,d]);let h=s,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:h,outputIndices:i,options:l}};ir.postMessage(p,Ka(h))})}else return Ha(e,t,s,i,o,l)},sp=async e=>{if(tn())return On(),new Promise((t,s)=>{Pn("end-profiling",[t,s]);let i={type:"end-profiling",in:e};ir.postMessage(i)});ja(e)}}),Xa,ap,op,lg=b(()=>{Ot(),ip(),Pe(),sn(),$s(),Xa=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},ap=e=>{switch(e[3]){case"cpu":return new vt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!vn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:i,dispose:o}=e[2];return vt.fromGpuBuffer(s,{dataType:t,dims:e[1],download:i,dispose:o})}case"ml-tensor":{let t=e[0];if(!bn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:i,dispose:o}=e[2];return vt.fromMLTensor(s,{dataType:t,dims:e[1],download:i,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},op=class{async fetchModelAndCopyToWasmMemory(e){return ep(await _n(e))}async loadModel(e,t){dt();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await tp(s,t),ct()}async dispose(){return rp(this.sessionId)}async run(e,t,s){dt();let i=[],o=[];Object.entries(e).forEach(m=>{let w=m[0],_=m[1],S=this.inputNames.indexOf(w);if(S===-1)throw new Error(`invalid input '${w}'`);i.push(_),o.push(S)});let l=[],u=[];Object.entries(t).forEach(m=>{let w=m[0],_=m[1],S=this.outputNames.indexOf(w);if(S===-1)throw new Error(`invalid output '${w}'`);l.push(_),u.push(S)});let d=i.map((m,w)=>Xa(m,()=>`input "${this.inputNames[o[w]]}"`)),h=l.map((m,w)=>m?Xa(m,()=>`output "${this.outputNames[u[w]]}"`):null),p=await np(this.sessionId,o,d,u,h,s),g={};for(let m=0;m<p.length;m++)g[this.outputNames[u[m]]]=l[m]??ap(p[m]);return ct(),g}startProfiling(){}endProfiling(){sp(this.sessionId)}}}),lp={};U(lp,{OnnxruntimeWebAssemblyBackend:()=>Ja,initializeFlags:()=>Ya,wasmBackend:()=>up});var Ya,Ja,up,ug=b(()=>{Ot(),ip(),lg(),Ya=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let e=ge.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let t=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Ja=class{async init(e){Ya(),await Jh(),await Zh(e)}async createInferenceSessionHandler(e,t){let s=new op;return await s.loadModel(e,t),s}},up=new Ja}),dp={};U(dp,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,default:()=>cg,env:()=>ge,registerBackend:()=>ie}),Ot(),Ot(),Ot();var dg="1.24.3",cg=is;{let e=(ug(),te(lp)).wasmBackend;ie("webgpu",e,5),ie("webnn",e,5),ie("cpu",e,10),ie("wasm",e,10)}return Object.defineProperty(ge.versions,"web",{value:dg,enumerable:!0}),te(dp)})();/**
|
|
2810
2810
|
* @license
|
|
2811
2811
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2812
2812
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -2855,7 +2855,7 @@ ${l}`,d=s.createShaderModule({code:u,label:e.name});Je("verbose",()=>`[WebGPU] $
|
|
|
2855
2855
|
* ONNX Runtime Web v1.24.3
|
|
2856
2856
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2857
2857
|
* Licensed under the MIT License.
|
|
2858
|
-
*/var Dp;function Cy(){return Dp||(Dp=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof lr<"u"?lr:typeof Proxy<"u"?new Proxy(y,{get:($,A)=>(typeof lr<"u"?lr:$)[A]}):y)(function(y){if(typeof lr<"u")return lr.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),b=(y,$)=>()=>(y&&($=y(y=0)),$),U=(y,$)=>{for(var A in $)a(y,A,{get:$[A],enumerable:!0})},B=(y,$,A,z)=>{if($&&typeof $=="object"||typeof $=="function")for(let P of v($))!C.call(y,P)&&P!==A&&a(y,P,{get:()=>$[P],enumerable:!(z=f($,P))||z.enumerable});return y},te=y=>B(a({},"__esModule",{value:!0}),y),X,ee,ie,ce,ue,Be=b(()=>{X=new Map,ee=[],ie=(y,$,A)=>{if($&&typeof $.init=="function"&&typeof $.createInferenceSessionHandler=="function"){let z=X.get(y);if(z===void 0)X.set(y,{backend:$,priority:A});else{if(z.priority>A)return;if(z.priority===A&&z.backend!==$)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let P=ee.indexOf(y);P!==-1&&ee.splice(P,1);for(let G=0;G<ee.length;G++)if(X.get(ee[G]).priority<=A){ee.splice(G,0,y);return}ee.push(y)}return}throw new TypeError("not a valid backend")},ce=async y=>{let $=X.get(y);if(!$)return"backend not found.";if($.initialized)return $.backend;if($.aborted)return $.error;{let A=!!$.initPromise;try{return A||($.initPromise=$.backend.init(y)),await $.initPromise,$.initialized=!0,$.backend}catch(z){return A||($.error=`${z}`,$.aborted=!0),$.error}finally{delete $.initPromise}}},ue=async y=>{let $=y.executionProviders||[],A=$.map(V=>typeof V=="string"?V:V.name),z=A.length===0?ee:A,P,G=[],N=new Set;for(let V of z){let Z=await ce(V);typeof Z=="string"?G.push({name:V,err:Z}):(P||(P=Z),P===Z&&N.add(V))}if(!P)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:Z}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${Z}`);let L=$.filter(V=>N.has(typeof V=="string"?V:V.name));return[P,new Proxy(y,{get:(V,Z)=>Z==="executionProviders"?L:Reflect.get(V,Z)})]}}),ke=b(()=>{Be()}),he,re=b(()=>{he="1.24.3"}),de,pe,Ie=b(()=>{re(),de="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:he},set logLevel(y){if(y!==void 0){if(typeof y!="string"||["verbose","info","warning","error","fatal"].indexOf(y)===-1)throw new Error(`Unsupported logging level: ${y}`);de=y}},get logLevel(){return de}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),ge,ut=b(()=>{Ie(),ge=pe}),Qe,ft,Ne=b(()=>{Qe=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let z=A.getContext("2d");if(z!=null){let P,G;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=y.dims[3],G=y.dims[2]);let N=$?.format!==void 0?$.format:"RGB",L=$?.norm,V,Z;L===void 0||L.mean===void 0?V=[255,255,255,255]:typeof L.mean=="number"?V=[L.mean,L.mean,L.mean,L.mean]:(V=[L.mean[0],L.mean[1],L.mean[2],0],L.mean[3]!==void 0&&(V[3]=L.mean[3])),L===void 0||L.bias===void 0?Z=[0,0,0,0]:typeof L.bias=="number"?Z=[L.bias,L.bias,L.bias,L.bias]:(Z=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(Z[3]=L.bias[3]));let se=G*P,J=0,j=se,$e=se*2,F=-1;N==="RGBA"?(J=0,j=se,$e=se*2,F=se*3):N==="RGB"?(J=0,j=se,$e=se*2):N==="RBG"&&(J=0,$e=se,j=se*2);for(let oe=0;oe<G;oe++)for(let _t=0;_t<P;_t++){let qe=(y.data[J++]-Z[0])*V[0],xe=(y.data[j++]-Z[1])*V[1],We=(y.data[$e++]-Z[2])*V[2],_e=F===-1?255:(y.data[F++]-Z[3])*V[3];z.fillStyle="rgba("+qe+","+xe+","+We+","+_e+")",z.fillRect(_t,oe,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ft=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),z;if(A!=null){let P,G,N;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],N=y.dims[3]):(P=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=$!==void 0&&$.format!==void 0?$.format:"RGB",V=$?.norm,Z,se;V===void 0||V.mean===void 0?Z=[255,255,255,255]:typeof V.mean=="number"?Z=[V.mean,V.mean,V.mean,V.mean]:(Z=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(Z[3]=V.mean[3])),V===void 0||V.bias===void 0?se=[0,0,0,0]:typeof V.bias=="number"?se=[V.bias,V.bias,V.bias,V.bias]:(se=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(se[3]=V.bias[3]));let J=G*P;if($!==void 0&&($.format!==void 0&&N===4&&$.format!=="RGBA"||N===3&&$.format!=="RGB"&&$.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let j=4,$e=0,F=1,oe=2,_t=3,qe=0,xe=J,We=J*2,_e=-1;L==="RGBA"?(qe=0,xe=J,We=J*2,_e=J*3):L==="RGB"?(qe=0,xe=J,We=J*2):L==="RBG"&&(qe=0,We=J,xe=J*2),z=A.createImageData(P,G);for(let Lt=0;Lt<G*P;$e+=j,F+=j,oe+=j,_t+=j,Lt++)z.data[$e]=(y.data[qe++]-se[0])*Z[0],z.data[F]=(y.data[xe++]-se[1])*Z[1],z.data[oe]=(y.data[We++]-se[2])*Z[2],z.data[_t]=_e===-1?255:(y.data[_e++]-se[3])*Z[3]}else throw new Error("Can not access image data");return z}}),Xe,mt,yt,ot,Ye,Le,rt=b(()=>{Xt(),Xe=(y,$)=>{if(y===void 0)throw new Error("Image buffer must be defined");if($.height===void 0||$.width===void 0)throw new Error("Image height and width must be defined");if($.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:z}=$,P=$.norm??{mean:255,bias:0},G,N;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?N=[P.bias,P.bias,P.bias,P.bias]:N=[P.bias[0],P.bias[1],P.bias[2],P.bias[3]??0];let L=$.format!==void 0?$.format:"RGBA",V=$.tensorFormat!==void 0&&$.tensorFormat!==void 0?$.tensorFormat:"RGB",Z=A*z,se=V==="RGBA"?new Float32Array(Z*4):new Float32Array(Z*3),J=4,j=0,$e=1,F=2,oe=3,_t=0,qe=Z,xe=Z*2,We=-1;L==="RGB"&&(J=3,j=0,$e=1,F=2,oe=-1),V==="RGBA"?We=Z*3:V==="RBG"?(_t=0,xe=Z,qe=Z*2):V==="BGR"&&(xe=0,qe=Z,_t=Z*2);for(let _e=0;_e<Z;_e++,j+=J,F+=J,$e+=J,oe+=J)se[_t++]=(y[j]+N[0])/G[0],se[qe++]=(y[$e]+N[1])/G[1],se[xe++]=(y[F]+N[2])/G[2],We!==-1&&oe!==-1&&(se[We++]=(y[oe]+N[3])/G[3]);return V==="RGBA"?new tt("float32",se,[1,4,A,z]):new tt("float32",se,[1,3,A,z])},mt=async(y,$)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,z=typeof ImageData<"u"&&y instanceof ImageData,P=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",N,L=$??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Z=se=>typeof HTMLCanvasElement<"u"&&se instanceof HTMLCanvasElement||se instanceof OffscreenCanvas?se.getContext("2d"):null;if(A){let se=V();se.width=y.width,se.height=y.height;let J=Z(se);if(J!=null){let j=y.height,$e=y.width;if($!==void 0&&$.resizedHeight!==void 0&&$.resizedWidth!==void 0&&(j=$.resizedHeight,$e=$.resizedWidth),$!==void 0){if(L=$,$.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=j,L.width=$e}else L.tensorFormat="RGBA",L.height=j,L.width=$e;J.drawImage(y,0,0),N=J.getImageData(0,0,$e,j).data}else throw new Error("Can not access image data")}else if(z){let se,J;if($!==void 0&&$.resizedWidth!==void 0&&$.resizedHeight!==void 0?(se=$.resizedHeight,J=$.resizedWidth):(se=y.height,J=y.width),$!==void 0&&(L=$),L.format="RGBA",L.height=se,L.width=J,$!==void 0){let j=V();j.width=J,j.height=se;let $e=Z(j);if($e!=null)$e.putImageData(y,0,0),N=$e.getImageData(0,0,J,se).data;else throw new Error("Can not access image data")}else N=y.data}else if(P){if($===void 0)throw new Error("Please provide image config with format for Imagebitmap");let se=V();se.width=y.width,se.height=y.height;let J=Z(se);if(J!=null){let j=y.height,$e=y.width;return J.drawImage(y,0,0,$e,j),N=J.getImageData(0,0,$e,j).data,L.height=j,L.width=$e,Xe(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((se,J)=>{let j=V(),$e=Z(j);if(!y||!$e)return J();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{j.width=F.width,j.height=F.height,$e.drawImage(F,0,0,j.width,j.height);let oe=$e.getImageData(0,0,j.width,j.height);L.height=j.height,L.width=j.width,se(Xe(oe.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return Xe(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},yt=(y,$)=>{let{width:A,height:z,download:P,dispose:G}=$,N=[1,z,A,4];return new tt({location:"texture",type:"float32",texture:y,dims:N,download:P,dispose:G})},ot=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new tt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:z,download:P,dispose:G})},Ye=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new tt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:z,download:P,dispose:G})},Le=(y,$,A)=>new tt({location:"cpu-pinned",type:y,data:$,dims:A??[$.length]})}),Ze,Q,Me,et,gt=b(()=>{Ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Me=!1,et=()=>{if(!Me){Me=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,$=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,z=typeof A<"u"&&A.from;y&&(Ze.set("int64",BigInt64Array),Q.set(BigInt64Array,"int64")),$&&(Ze.set("uint64",BigUint64Array),Q.set(BigUint64Array,"uint64")),z?(Ze.set("float16",A),Q.set(A,"float16")):Ze.set("float16",Uint16Array)}}}),Gt,Et,lt=b(()=>{Xt(),Gt=y=>{let $=1;for(let A=0;A<y.length;A++){let z=y[A];if(typeof z!="number"||!Number.isSafeInteger(z))throw new TypeError(`dims[${A}] must be an integer, got: ${z}`);if(z<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${z}`);$*=z}return $},Et=(y,$)=>{switch(y.location){case"cpu":return new tt(y.type,y.data,$);case"cpu-pinned":return new tt({location:"cpu-pinned",data:y.data,type:y.type,dims:$});case"texture":return new tt({location:"texture",texture:y.texture,type:y.type,dims:$});case"gpu-buffer":return new tt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:$});case"ml-tensor":return new tt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:$});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),tt,Xt=b(()=>{Ne(),rt(),gt(),lt(),tt=class{constructor(y,$,A){et();let z,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,z=y.type,P=y.dims,y.location){case"cpu-pinned":{let N=Ze.get(z);if(!N)throw new TypeError(`unsupported type "${z}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(z!=="float32")throw new TypeError(`unsupported type "${z}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint64"&&z!=="int8"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(z=y,L=A,y==="string"){if(!Array.isArray($))throw new TypeError("A string tensor's data must be a string array.");N=$}else{let V=Ze.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray($)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from($,BigInt):N=V.from($)}else if($ instanceof V)N=$;else if($ instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from($);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&$ instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array($.buffer,$.byteOffset,$.length);else throw new TypeError(`A ${z} tensor's data must be type of ${V}`)}else if(L=$,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")z="string",N=y;else if(V==="boolean")z="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)z="uint8",N=Uint8Array.from(y);else{let V=Q.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);z=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");P=L,this.cpuData=N,this.dataLocation="cpu"}let G=Gt(P);if(this.cpuData&&G!==this.cpuData.length&&!((z==="uint4"||z==="int4")&&Math.ceil(G/2)===this.cpuData.length))throw new Error(`Tensor's size(${G}) does not match data length(${this.cpuData.length}).`);this.type=z,this.dims=P,this.size=G}static async fromImage(y,$){return mt(y,$)}static fromTexture(y,$){return yt(y,$)}static fromGpuBuffer(y,$){return ot(y,$)}static fromMLTensor(y,$){return Ye(y,$)}static fromPinnedBuffer(y,$,A){return Le(y,$,A)}toDataURL(y){return Qe(this,y)}toImageData(y){return ft(this,y)}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(y){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 $=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=$,y&&this.disposer&&(this.disposer(),this.disposer=void 0),$}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(y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Et(this,y)}}}),vt,fe=b(()=>{Xt(),vt=tt}),Ue,wt,dt,ct,me,Fe,It=b(()=>{Ie(),Ue=(y,$)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${y}::ORT::${$}`)},wt=(y,$)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],z=!1;for(let P=0;P<A.length;P++){if(z&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;$&&(G+=`::${$}`),Ue("CPU",G);return}A[P].includes("TRACE_FUNC")&&(z=!0)}},dt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("BEGIN",y)},ct=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("END",y)},me=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${y}`)},Fe=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${y}`)}}),Pt,ur=b(()=>{Be(),fe(),It(),Pt=class gf{constructor($){this.handler=$}async run($,A,z){dt(),me("InferenceSession.run");let P={},G={};if(typeof $!="object"||$===null||$ instanceof vt||Array.isArray($))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let Z of A){if(typeof Z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Z}.`);P[Z]=null}if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else{let Z=!1,se=Object.getOwnPropertyNames(A);for(let J of this.outputNames)if(se.indexOf(J)!==-1){let j=A[J];(j===null||j instanceof vt)&&(Z=!0,N=!1,P[J]=j)}if(Z){if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else G=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let Z of this.inputNames)if(typeof $[Z]>"u")throw new Error(`input '${Z}' is missing in 'feeds'.`);if(N)for(let Z of this.outputNames)P[Z]=null;let L=await this.handler.run($,P,G),V={};for(let Z in L)if(Object.hasOwnProperty.call(L,Z)){let se=L[Z];se instanceof vt?V[Z]=se:V[Z]=new vt(se.type,se.data,se.dims)}return Fe("InferenceSession.run"),ct(),V}async release(){return this.handler.dispose()}static async create($,A,z,P){dt(),me("InferenceSession.create");let G,N={};if(typeof $=="string"){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof Uint8Array){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer){let se=$,J=0,j=$.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(J=A,!Number.isSafeInteger(J))throw new RangeError("'byteOffset' must be an integer.");if(J<0||J>=se.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${se.byteLength}).`);if(j=$.byteLength-J,typeof z=="number"){if(j=z,!Number.isSafeInteger(j))throw new RangeError("'byteLength' must be an integer.");if(j<=0||J+j>se.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${se.byteLength-J}].`);if(typeof P=="object"&&P!==null)N=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof z<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(se,J,j)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await ue(N),Z=await L.createInferenceSessionHandler(G,V);return Fe("InferenceSession.create"),ct(),new gf(Z)}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}}}),dr,Vi=b(()=>{ur(),dr=Pt}),Gi=b(()=>{}),qi=b(()=>{}),Wi=b(()=>{}),Hi=b(()=>{}),is={};U(is,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,env:()=>ge,registerBackend:()=>ie});var Ot=b(()=>{ke(),ut(),Vi(),fe(),Gi(),qi(),It(),Wi(),Hi()}),sn=b(()=>{}),as={};U(as,{default:()=>os});var an,on,os,ji=b(()=>{Es(),Yt(),hn(),an="ort-wasm-proxy-worker",on=globalThis.self?.name===an,on&&(self.onmessage=y=>{let{type:$,in:A}=y.data;try{switch($){case"init-wasm":mn(A.wasm).then(()=>{Bn(A).then(()=>{postMessage({type:$})},z=>{postMessage({type:$,err:z})})},z=>{postMessage({type:$,err:z})});break;case"init-ep":{let{epName:z,env:P}=A;Nn(P,z).then(()=>{postMessage({type:$})},G=>{postMessage({type:$,err:G})});break}case"copy-from":{let{buffer:z}=A,P=Je(z);postMessage({type:$,out:P});break}case"create":{let{model:z,options:P}=A;tr(z,P).then(G=>{postMessage({type:$,out:G})},G=>{postMessage({type:$,err:G})});break}case"release":Vn(A),postMessage({type:$});break;case"run":{let{sessionId:z,inputIndices:P,inputs:G,outputIndices:N,options:L}=A;H(z,P,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(Z=>Z[3]!=="cpu")?postMessage({type:$,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:$,out:V},Gn([...G,...V]))},V=>{postMessage({type:$,err:V})});break}case"end-profiling":Kr(A),postMessage({type:$});break;default:}}catch(z){postMessage({type:$,err:z})}}),os=on?null:y=>new Worker(y??bt,{type:"classic",name:an})}),ls,us,bt,ln,zr,ds,cs,un,hs,dn,ps,cn,fs,hn=b(()=>{sn(),ls=typeof location>"u"?void 0:location.origin,us=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,bt=us(),ln=()=>{if(bt&&!bt.startsWith("blob:"))return bt.substring(0,bt.lastIndexOf("/")+1)},zr=(y,$)=>{try{let A=$??bt;return(A?new URL(y,A):new URL(y)).origin===ls}catch{return!1}},ds=(y,$)=>{let A=$??bt;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},cs=(y,$)=>`${$??"./"}${y}`,un=async y=>{let $=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL($)},hs=async y=>(await import(y)).default,dn=(ji(),te(as)).default,ps=async()=>{if(!bt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(bt))return[void 0,dn()];let y=await un(bt);return[y,dn(y)]},cn=void 0,fs=async(y,$,A,z)=>{let P=cn&&!(y||$);if(P)if(bt)P=zr(bt)||z&&!A;else if(z&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,cn];{let G="ort-wasm-simd-threaded.mjs",N=y??ds(G,$),L=A&&N&&!zr(N,$),V=L?await un(N):N??cs(G,$);return[L?V:void 0,await hs(V)]}}}),pn,Dr,cr,fn,ms,gs,ys,mn,ze,Yt=b(()=>{hn(),Dr=!1,cr=!1,fn=!1,ms=()=>{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}},gs=()=>{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}},ys=()=>{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}},mn=async y=>{if(Dr)return Promise.resolve();if(cr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(fn)throw new Error("previous call to 'initializeWebAssembly()' failed.");cr=!0;let $=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!ys())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!gs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let z=ms();A>1&&!z&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", 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."),y.numThreads=A=1);let P=y.wasmPaths,G=typeof P=="string"?P:void 0,N=P?.mjs,L=N?.href??N,V=P?.wasm,Z=V?.href??V,se=y.wasmBinary,[J,j]=await fs(L,G,A>1,!!se||!!Z),$e=!1,F=[];if($>0&&F.push(new Promise(oe=>{setTimeout(()=>{$e=!0,oe()},$)})),F.push(new Promise((oe,_t)=>{let qe={numThreads:A};if(se)qe.wasmBinary=se,qe.locateFile=xe=>xe;else if(Z||G)qe.locateFile=xe=>Z??G+xe;else if(L&&L.indexOf("blob:")!==0)qe.locateFile=xe=>new URL(xe,L).href;else if(J){let xe=ln();xe&&(qe.locateFile=We=>xe+We)}j(qe).then(xe=>{cr=!1,Dr=!0,pn=xe,oe(),J&&URL.revokeObjectURL(J)},xe=>{cr=!1,fn=!0,_t(xe)})})),await Promise.race(F),$e)throw new Error(`WebAssembly backend initializing failed due to timeout: ${$}ms`)},ze=()=>{if(Dr&&pn)return pn;throw new Error("WebAssembly is not initialized yet.")}}),xt,Lr,Re,gn=b(()=>{Yt(),xt=(y,$)=>{let A=ze(),z=A.lengthBytesUTF8(y)+1,P=A._malloc(z);return A.stringToUTF8(y,P,z),$.push(P),P},Lr=(y,$,A,z)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([P,G])=>{let N=$?$+P:P;if(typeof G=="object")Lr(G,N+".",A,z);else if(typeof G=="string"||typeof G=="number")z(N,G.toString());else if(typeof G=="boolean")z(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Re=y=>{let $=ze(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetLastError(P,P+z);let G=Number($.getValue(P,z===4?"i32":"i64")),N=$.getValue(P+z,"*"),L=N?$.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{$.stackRestore(A)}}}),ws,Ki=b(()=>{Yt(),gn(),ws=y=>{let $=ze(),A=0,z=[],P=y||{};try{if(y?.logSeverityLevel===void 0)P.logSeverityLevel=2;else if(typeof y.logSeverityLevel!="number"||!Number.isInteger(y.logSeverityLevel)||y.logSeverityLevel<0||y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${y.logSeverityLevel}`);if(y?.logVerbosityLevel===void 0)P.logVerbosityLevel=0;else if(typeof y.logVerbosityLevel!="number"||!Number.isInteger(y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${y.logVerbosityLevel}`);y?.terminate===void 0&&(P.terminate=!1);let G=0;return y?.tag!==void 0&&(G=xt(y.tag,z)),A=$._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,G),A===0&&Re("Can't create run options."),y?.extra!==void 0&&Lr(y.extra,"",new WeakSet,(N,L)=>{let V=xt(N,z),Z=xt(L,z);$._OrtAddRunConfigEntry(A,V,Z)!==0&&Re(`Can't set a run config entry: ${N} - ${L}.`)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseRunOptions(A),z.forEach(N=>$._free(N)),G}}}),vs,bs,_s,hr,Ss,Ts,Qi=b(()=>{Yt(),gn(),vs=y=>{switch(y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${y}`)}},bs=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},_s=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let $=y.extra.session;$.use_ort_model_bytes_directly||($.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},hr=(y,$,A,z)=>{let P=xt($,z),G=xt(A,z);ze()._OrtAddSessionConfigEntry(y,P,G)!==0&&Re(`Can't set a session config entry: ${$} - ${A}.`)},Ss=async(y,$,A)=>{let z=$.executionProviders;for(let P of z){let G=typeof P=="string"?P:P.name,N=[];switch(G){case"webnn":if(G="WEBNN",typeof P!="string"){let J=P?.deviceType;J&&hr(y,"deviceType",J,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let J=P;if(J?.preferredLayout){if(J.preferredLayout!=="NCHW"&&J.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${J.preferredLayout}`);hr(y,"preferredLayout",J.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=xt(G,A),V=N.length,Z=0,se=0;if(V>0){Z=ze()._malloc(V*ze().PTR_SIZE),A.push(Z),se=ze()._malloc(V*ze().PTR_SIZE),A.push(se);for(let J=0;J<V;J++)ze().setValue(Z+J*ze().PTR_SIZE,N[J][0],"*"),ze().setValue(se+J*ze().PTR_SIZE,N[J][1],"*")}await ze()._OrtAppendExecutionProvider(y,L,Z,se,V)!==0&&Re(`Can't append execution provider: ${G}.`)}},Ts=async y=>{let $=ze(),A=0,z=[],P=y||{};_s(P);try{let G=vs(P.graphOptimizationLevel??"all"),N=bs(P.executionMode??"sequential"),L=typeof P.logId=="string"?xt(P.logId,z):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let Z=P.logVerbosityLevel??0;if(!Number.isInteger(Z)||Z<0||Z>4)throw new Error(`log verbosity level is not valid: ${Z}`);let se=typeof P.optimizedModelFilePath=="string"?xt(P.optimizedModelFilePath,z):0;if(A=$._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,N,!!P.enableProfiling,0,L,V,Z,se),A===0&&Re("Can't create session options."),P.executionProviders&&await Ss(A,P,z),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);hr(A,"enableGraphCapture",P.enableGraphCapture.toString(),z)}if(P.freeDimensionOverrides)for(let[J,j]of Object.entries(P.freeDimensionOverrides)){if(typeof J!="string")throw new Error(`free dimension override name must be a string: ${J}`);if(typeof j!="number"||!Number.isInteger(j)||j<0)throw new Error(`free dimension override value must be a non-negative integer: ${j}`);let $e=xt(J,z);$._OrtAddFreeDimensionOverride(A,$e,j)!==0&&Re(`Can't set a free dimension override: ${J} - ${j}.`)}return P.extra!==void 0&&Lr(P.extra,"",new WeakSet,(J,j)=>{hr(A,J,j,z)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseSessionOptions(A)!==0&&Re("Can't release session options."),z.forEach(N=>$._free(N)),G}}}),Jt,Zt,er,yn,wn,vn,bn,Ln,Pe=b(()=>{Jt=y=>{switch(y){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: ${y}`)}},Zt=y=>{switch(y){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: ${y}`)}},er=(y,$)=>{let A=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][y],z=typeof $=="number"?$:$.reduce((P,G)=>P*G,1);return A>0?Math.ceil(z*A):void 0},yn=y=>{switch(y){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: ${y}`)}},wn=y=>{switch(y){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: ${y}`)}},vn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",bn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Ln=y=>{switch(y){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: ${y}`)}}}),_n,$s=b(()=>{sn(),_n=async y=>{if(typeof y=="string"){let $=await fetch(y);if(!$.ok)throw new Error(`failed to load external data file: ${y}`);let A=$.headers.get("Content-Length"),z=A?parseInt(A,10):0;if(z<1073741824)return new Uint8Array(await $.arrayBuffer());{if(!$.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let P=$.body.getReader(),G;try{G=new ArrayBuffer(z)}catch(L){if(L instanceof RangeError){let V=Math.ceil(z/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let N=0;for(;;){let{done:L,value:V}=await P.read();if(L)break;let Z=V.byteLength;new Uint8Array(G,N,Z).set(V),N+=Z}return new Uint8Array(G,0,z)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),xs,Bn,Nn,xr,Un,Fn,Je,tr,Vn,Er,H,Kr,Gn,Es=b(()=>{Ot(),Ki(),Qi(),Pe(),Yt(),gn(),$s(),xs=(y,$)=>{ze()._OrtInit(y,$)!==0&&Re("Can't initialize onnxruntime.")},Bn=async y=>{xs(y.wasm.numThreads,wn(y.logLevel))},Nn=async(y,$)=>{ze().asyncInit?.();let A=y.webgpu.adapter;if($==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(A){if(typeof A.limits!="object"||typeof A.features!="object"||typeof A.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let z=y.webgpu.powerPreference;if(z!==void 0&&z!=="low-power"&&z!=="high-performance")throw new Error(`Invalid powerPreference setting: "${z}"`);let P=y.webgpu.forceFallbackAdapter;if(P!==void 0&&typeof P!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${P}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:z,forceFallbackAdapter:P}),!A)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if($==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},xr=new Map,Un=y=>{let $=ze(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetInputOutputCount(y,P,P+z)!==0&&Re("Can't get session input/output count.");let G=z===4?"i32":"i64";return[Number($.getValue(P,G)),Number($.getValue(P+z,G))]}finally{$.stackRestore(A)}},Fn=(y,$)=>{let A=ze(),z=A.stackSave(),P=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,$,N,N+G)!==0&&Re("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));P=Number(A.getValue(N+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let Z=A.HEAPU32[P/4+1],se=[];for(let J=0;J<Z;J++){let j=Number(A.getValue(P+8+J*G,"*"));se.push(j!==0?A.UTF8ToString(j):Number(A.getValue(P+8+(J+Z)*G,"*")))}return[L,V,se]}finally{A.stackRestore(z),P!==0&&A._OrtFree(P)}},Je=y=>{let $=ze(),A=$._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return $.HEAPU8.set(y,A),[A,y.byteLength]},tr=async(y,$)=>{let A,z,P=ze();Array.isArray(y)?[A,z]=y:y.buffer===P.HEAPU8.buffer?[A,z]=[y.byteOffset,y.byteLength]:[A,z]=Je(y);let G=0,N=0,L=[],V=[],Z=[];try{if([N,L]=await Ts($),$?.externalData&&P.mountExternalData){let xe=[];for(let We of $.externalData){let _e=typeof We=="string"?We:We.path;xe.push(_n(typeof We=="string"?We:We.data).then(Lt=>{P.mountExternalData(_e,Lt)}))}await Promise.all(xe)}for(let xe of $?.executionProviders??[])if((typeof xe=="string"?xe:xe.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof xe!="string"){let We=xe,_e=We?.context,Lt=We?.gpuDevice,Nt=We?.deviceType,Rr=We?.powerPreference;_e?P.currentContext=_e:Lt?P.currentContext=await P.webnnCreateMLContext(Lt):P.currentContext=await P.webnnCreateMLContext({deviceType:Nt,powerPreference:Rr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,z,N),P.webgpuOnCreateSession?.(G),G===0&&Re("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[se,J]=Un(G),j=!!$?.enableGraphCapture,$e=[],F=[],oe=[],_t=[],qe=[];for(let xe=0;xe<se;xe++){let[We,_e,Lt]=Fn(G,xe);We===0&&Re("Can't get an input name."),V.push(We);let Nt=P.UTF8ToString(We);$e.push(Nt),oe.push(_e===0?{name:Nt,isTensor:!1}:{name:Nt,isTensor:!0,type:Zt(_e),shape:Lt})}for(let xe=0;xe<J;xe++){let[We,_e,Lt]=Fn(G,xe+se);We===0&&Re("Can't get an output name."),Z.push(We);let Nt=P.UTF8ToString(We);F.push(Nt),_t.push(_e===0?{name:Nt,isTensor:!1}:{name:Nt,isTensor:!0,type:Zt(_e),shape:Lt})}return xr.set(G,[G,V,Z,null,j,!1]),[G,$e,F,oe,_t]}catch(se){throw V.forEach(J=>P._OrtFree(J)),Z.forEach(J=>P._OrtFree(J)),G!==0&&P._OrtReleaseSession(G)!==0&&Re("Can't release session."),se}finally{P._free(A),N!==0&&P._OrtReleaseSessionOptions(N)!==0&&Re("Can't release session options."),L.forEach(se=>P._free(se)),P.unmountExternalData?.()}},Vn=y=>{let $=ze(),A=xr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[z,P,G,N,L]=A;N&&(L&&$._OrtClearBoundOutputs(N.handle)!==0&&Re("Can't clear bound outputs."),$._OrtReleaseBinding(N.handle)!==0&&Re("Can't release IO binding.")),$.jsepOnReleaseSession?.(y),$.webnnOnReleaseSession?.(y),$.webgpuOnReleaseSession?.(y),P.forEach(V=>$._OrtFree(V)),G.forEach(V=>$._OrtFree(V)),$._OrtReleaseSession(z)!==0&&Re("Can't release session."),xr.delete(y)},Er=async(y,$,A,z,P,G,N=!1)=>{if(!y){$.push(0);return}let L=ze(),V=L.PTR_SIZE,Z=y[0],se=y[1],J=y[3],j=J,$e,F;if(Z==="string"&&(J==="gpu-buffer"||J==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&J!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(J==="gpu-buffer"){let qe=y[2].gpuBuffer;F=er(Jt(Z),se);{let xe=L.jsepRegisterBuffer;if(!xe)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$e=xe(z,G,qe,F)}}else if(J==="ml-tensor"){let qe=y[2].mlTensor;F=er(Jt(Z),se);let xe=L.webnnRegisterMLTensor;if(!xe)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$e=xe(z,qe,Jt(Z),se)}else{let qe=y[2];if(Array.isArray(qe)){F=V*qe.length,$e=L._malloc(F),A.push($e);for(let xe=0;xe<qe.length;xe++){if(typeof qe[xe]!="string")throw new TypeError(`tensor data at index ${xe} is not a string`);L.setValue($e+xe*V,xt(qe[xe],A),"*")}}else{let xe=L.webnnIsGraphInput,We=L.webnnIsGraphOutput;if(Z!=="string"&&xe&&We){let _e=L.UTF8ToString(P);if(xe(z,_e)||We(z,_e)){let Lt=Jt(Z);F=er(Lt,se),j="ml-tensor";let Nt=L.webnnCreateTemporaryTensor,Rr=L.webnnUploadTensor;if(!Nt||!Rr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Jr=await Nt(z,Lt,se);Rr(Jr,new Uint8Array(qe.buffer,qe.byteOffset,qe.byteLength)),$e=Jr}else F=qe.byteLength,$e=L._malloc(F),A.push($e),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,F),$e)}else F=qe.byteLength,$e=L._malloc(F),A.push($e),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,F),$e)}}let oe=L.stackSave(),_t=L.stackAlloc(4*se.length);try{se.forEach((xe,We)=>L.setValue(_t+We*V,xe,V===4?"i32":"i64"));let qe=L._OrtCreateTensor(Jt(Z),$e,F,_t,se.length,Ln(j));qe===0&&Re(`Can't create tensor for input/output. session=${z}, index=${G}.`),$.push(qe)}finally{L.stackRestore(oe)}},H=async(y,$,A,z,P,G)=>{let N=ze(),L=N.PTR_SIZE,V=xr.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let Z=V[0],se=V[1],J=V[2],j=V[3],$e=V[4];V[5];let F=$.length,oe=z.length,_t=0,qe=[],xe=[],We=[],_e=[],Lt=[],Nt=N.stackSave(),Rr=N.stackAlloc(F*L),Jr=N.stackAlloc(F*L),Zn=N.stackAlloc(oe*L),Os=N.stackAlloc(oe*L);try{[_t,qe]=ws(G),me("wasm prepareInputOutputTensor");for(let He=0;He<F;He++)await Er(A[He],xe,_e,y,se[$[He]],$[He],$e);for(let He=0;He<oe;He++)await Er(P[He],We,_e,y,J[z[He]],F+z[He],$e);Fe("wasm prepareInputOutputTensor");for(let He=0;He<F;He++)N.setValue(Rr+He*L,xe[He],"*"),N.setValue(Jr+He*L,se[$[He]],"*");for(let He=0;He<oe;He++)N.setValue(Zn+He*L,We[He],"*"),N.setValue(Os+He*L,J[z[He]],"*");N.jsepOnRunStart?.(Z),N.webnnOnRunStart?.(Z);let Tt;Tt=await N._OrtRun(Z,Jr,Rr,F,Os,oe,Zn,_t),Tt!==0&&Re("failed to call OrtRun().");let nr=[],zs=[];me("wasm ProcessOutputTensor");for(let He=0;He<oe;He++){let rr=Number(N.getValue(Zn+He*L,"*"));if(rr===We[He]||Lt.includes(We[He])){nr.push(P[He]),rr!==We[He]&&N._OrtReleaseTensor(rr)!==0&&Re("Can't release tensor.");continue}let ci=N.stackSave(),mr=N.stackAlloc(4*L),xn=!1,Ct,Wt=0;try{N._OrtGetTensorData(rr,mr,mr+L,mr+2*L,mr+3*L)!==0&&Re(`Can't access output tensor data on index ${He}.`);let es=L===4?"i32":"i64",En=Number(N.getValue(mr,es));Wt=N.getValue(mr+L,"*");let Ds=N.getValue(mr+L*2,"*"),hi=Number(N.getValue(mr+L*3,es)),zt=[];for(let kt=0;kt<hi;kt++)zt.push(Number(N.getValue(Ds+kt*L,es)));N._OrtFree(Ds)!==0&&Re("Can't free memory for tensor dims.");let gr=zt.reduce((kt,$t)=>kt*$t,1);Ct=Zt(En);let Zr=j?.outputPreferredLocations[z[He]];if(Ct==="string"){if(Zr==="gpu-buffer"||Zr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let kt=[];for(let $t=0;$t<gr;$t++){let sr=N.getValue(Wt+$t*L,"*"),pi=N.getValue(Wt+($t+1)*L,"*"),fi=$t===gr-1?void 0:pi-sr;kt.push(N.UTF8ToString(sr,fi))}nr.push([Ct,zt,kt,"cpu"])}else if(Zr==="gpu-buffer"&&gr>0){let kt=N.jsepGetBuffer;if(!kt)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let $t=kt(Wt),sr=er(En,gr);if(sr===void 0||!vn(Ct))throw new Error(`Unsupported data type: ${Ct}`);xn=!0,nr.push([Ct,zt,{gpuBuffer:$t,download:N.jsepCreateDownloader($t,sr,Ct),dispose:()=>{N._OrtReleaseTensor(rr)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(Zr==="ml-tensor"&&gr>0){let kt=N.webnnEnsureTensor,$t=N.webnnIsGraphInputOutputTypeSupported;if(!kt||!$t)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(En,gr)===void 0||!bn(Ct))throw new Error(`Unsupported data type: ${Ct}`);if(!$t(y,Ct,!1))throw new Error(`preferredLocation "ml-tensor" for ${Ct} output is not supported by current WebNN Context.`);let sr=await kt(y,Wt,En,zt,!1);xn=!0,nr.push([Ct,zt,{mlTensor:sr,download:N.webnnCreateMLTensorDownloader(Wt,Ct),dispose:()=>{N.webnnReleaseTensorId(Wt),N._OrtReleaseTensor(rr)}},"ml-tensor"])}else if(Zr==="ml-tensor-cpu-output"&&gr>0){let kt=N.webnnCreateMLTensorDownloader(Wt,Ct)(),$t=nr.length;xn=!0,zs.push((async()=>{let sr=[$t,await kt];return N.webnnReleaseTensorId(Wt),N._OrtReleaseTensor(rr),sr})()),nr.push([Ct,zt,[],"cpu"])}else{let kt=yn(Ct),$t=new kt(gr);new Uint8Array($t.buffer,$t.byteOffset,$t.byteLength).set(N.HEAPU8.subarray(Wt,Wt+$t.byteLength)),nr.push([Ct,zt,$t,"cpu"])}}finally{N.stackRestore(ci),Ct==="string"&&Wt&&N._free(Wt),xn||N._OrtReleaseTensor(rr)}}j&&!$e&&(N._OrtClearBoundOutputs(j.handle)!==0&&Re("Can't clear bound outputs."),xr.set(y,[Z,se,J,j,$e,!1]));for(let[He,rr]of await Promise.all(zs))nr[He][2]=rr;return Fe("wasm ProcessOutputTensor"),nr}finally{N.webnnOnRunEnd?.(Z),N.stackRestore(Nt),xe.forEach(Tt=>N._OrtReleaseTensor(Tt)),We.forEach(Tt=>N._OrtReleaseTensor(Tt)),_e.forEach(Tt=>N._free(Tt)),_t!==0&&N._OrtReleaseRunOptions(_t),qe.forEach(Tt=>N._free(Tt))}},Kr=y=>{let $=ze(),A=xr.get(y);if(!A)throw new Error("invalid session id");let z=A[0],P=$._OrtEndProfiling(z);P===0&&Re("Can't get an profile file name."),$._OrtFree(P)},Gn=y=>{let $=[];for(let A of y){let z=A[2];!Array.isArray(z)&&"buffer"in z&&$.push(z.buffer)}return $}}),pr,Ae,Cr,Qr,Br,Xr,Sn,Tn,fr,kr,qn,Wn,Hn,Cs,ks,ui,Yr,Rs,As=b(()=>{Ot(),Es(),Yt(),hn(),pr=()=>!!ge.wasm.proxy&&typeof document<"u",Cr=!1,Qr=!1,Br=!1,Tn=new Map,fr=(y,$)=>{let A=Tn.get(y);A?A.push($):Tn.set(y,[$])},kr=()=>{if(Cr||!Qr||Br||!Ae)throw new Error("worker not ready")},qn=y=>{switch(y.data.type){case"init-wasm":Cr=!1,y.data.err?(Br=!0,Sn[1](y.data.err)):(Qr=!0,Sn[0]()),Xr&&(URL.revokeObjectURL(Xr),Xr=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let $=Tn.get(y.data.type);y.data.err?$.shift()[1](y.data.err):$.shift()[0](y.data.out);break}}},Wn=async()=>{if(!Qr){if(Cr)throw new Error("multiple calls to 'initWasm()' detected.");if(Br)throw new Error("previous call to 'initWasm()' failed.");if(Cr=!0,pr())return new Promise((y,$)=>{Ae?.terminate(),ps().then(([A,z])=>{try{Ae=z,Ae.onerror=G=>$(G),Ae.onmessage=qn,Sn=[y,$];let P={type:"init-wasm",in:ge};if(!P.in.wasm.wasmPaths&&A){let G=ln();G&&(P.in.wasm.wasmPaths=G)}Ae.postMessage(P),Xr=A}catch(P){$(P)}},$)});try{await mn(ge.wasm),await Bn(ge),Qr=!0}catch(y){throw Br=!0,y}finally{Cr=!1}}},Hn=async y=>{if(pr())return kr(),new Promise(($,A)=>{fr("init-ep",[$,A]);let z={type:"init-ep",in:{epName:y,env:ge}};Ae.postMessage(z)});await Nn(ge,y)},Cs=async y=>pr()?(kr(),new Promise(($,A)=>{fr("copy-from",[$,A]);let z={type:"copy-from",in:{buffer:y}};Ae.postMessage(z,[y.buffer])})):Je(y),ks=async(y,$)=>{if(pr()){if($?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return kr(),new Promise((A,z)=>{fr("create",[A,z]);let P={type:"create",in:{model:y,options:{...$}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),Ae.postMessage(P,G)})}else return tr(y,$)},ui=async y=>{if(pr())return kr(),new Promise(($,A)=>{fr("release",[$,A]);let z={type:"release",in:y};Ae.postMessage(z)});Vn(y)},Yr=async(y,$,A,z,P,G)=>{if(pr()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return kr(),new Promise((N,L)=>{fr("run",[N,L]);let V=A,Z={type:"run",in:{sessionId:y,inputIndices:$,inputs:V,outputIndices:z,options:G}};Ae.postMessage(Z,Gn(V))})}else return H(y,$,A,z,P,G)},Rs=async y=>{if(pr())return kr(),new Promise(($,A)=>{fr("end-profiling",[$,A]);let z={type:"end-profiling",in:y};Ae.postMessage(z)});Kr(y)}}),Ms,jn,Kn,Qn=b(()=>{Ot(),As(),Pe(),sn(),$s(),Ms=(y,$)=>{switch(y.location){case"cpu":return[y.type,y.dims,y.data,"cpu"];case"gpu-buffer":return[y.type,y.dims,{gpuBuffer:y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[y.type,y.dims,{mlTensor:y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${y.location} for ${$()}`)}},jn=y=>{switch(y[3]){case"cpu":return new vt(y[0],y[2],y[1]);case"gpu-buffer":{let $=y[0];if(!vn($))throw new Error(`not supported data type: ${$} for deserializing GPU tensor`);let{gpuBuffer:A,download:z,dispose:P}=y[2];return vt.fromGpuBuffer(A,{dataType:$,dims:y[1],download:z,dispose:P})}case"ml-tensor":{let $=y[0];if(!bn($))throw new Error(`not supported data type: ${$} for deserializing MLTensor tensor`);let{mlTensor:A,download:z,dispose:P}=y[2];return vt.fromMLTensor(A,{dataType:$,dims:y[1],download:z,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},Kn=class{async fetchModelAndCopyToWasmMemory(y){return Cs(await _n(y))}async loadModel(y,$){dt();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ks(A,$),ct()}async dispose(){return ui(this.sessionId)}async run(y,$,A){dt();let z=[],P=[];Object.entries(y).forEach(J=>{let j=J[0],$e=J[1],F=this.inputNames.indexOf(j);if(F===-1)throw new Error(`invalid input '${j}'`);z.push($e),P.push(F)});let G=[],N=[];Object.entries($).forEach(J=>{let j=J[0],$e=J[1],F=this.outputNames.indexOf(j);if(F===-1)throw new Error(`invalid output '${j}'`);G.push($e),N.push(F)});let L=z.map((J,j)=>Ms(J,()=>`input "${this.inputNames[P[j]]}"`)),V=G.map((J,j)=>J?Ms(J,()=>`output "${this.outputNames[N[j]]}"`):null),Z=await Yr(this.sessionId,P,L,N,V,A),se={};for(let J=0;J<Z.length;J++)se[this.outputNames[N[J]]]=G[J]??jn(Z[J]);return ct(),se}startProfiling(){}endProfiling(){Rs(this.sessionId)}}}),$n={};U($n,{OnnxruntimeWebAssemblyBackend:()=>Yn,initializeFlags:()=>Xn,wasmBackend:()=>Jn});var Xn,Yn,Jn,Is=b(()=>{Ot(),As(),Qn(),Xn=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let y=ge.wasm.simd;if(typeof y!="boolean"&&y!==void 0&&y!=="fixed"&&y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${y}". Reset it to \`false\` and ignore SIMD feature checking.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let $=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil(($||1)/2))}},Yn=class{async init(y){Xn(),await Wn(),await Hn(y)}async createInferenceSessionHandler(y,$){let A=new Kn;return await A.loadModel(y,$),A}},Jn=new Yn}),Ps={};U(Ps,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,default:()=>Xi,env:()=>ge,registerBackend:()=>ie}),Ot(),Ot(),Ot();var di="1.24.3",Xi=is;{let y=(Is(),te($n)).wasmBackend;ie("cpu",y,10),ie("wasm",y,10)}return Object.defineProperty(ge.versions,"web",{value:di,enumerable:!0}),te(Ps)})();c.exports=n})(oo)),oo.exports}var Lp;function ky(){return Lp||(Lp=1,(function(c){var r=Gr&&Gr.__createBinding||(Object.create?(function(he,re,de,pe){pe===void 0&&(pe=de);var Ie=Object.getOwnPropertyDescriptor(re,de);(!Ie||("get"in Ie?!re.__esModule:Ie.writable||Ie.configurable))&&(Ie={enumerable:!0,get:function(){return re[de]}}),Object.defineProperty(he,pe,Ie)}):(function(he,re,de,pe){pe===void 0&&(pe=de),he[pe]=re[de]})),n=Gr&&Gr.__setModuleDefault||(Object.create?(function(he,re){Object.defineProperty(he,"default",{enumerable:!0,value:re})}):function(he,re){he.default=re}),a=Gr&&Gr.__importStar||function(he){if(he&&he.__esModule)return he;var re={};if(he!=null)for(var de in he)de!=="default"&&Object.prototype.hasOwnProperty.call(he,de)&&r(re,he,de);return n(re,he),re};Object.defineProperty(c,"__esModule",{value:!0}),c.MicVAD=c.getDefaultRealTimeVADOptions=c.ort=c.DEFAULT_MODEL=void 0;const f=a(Cy()),v=Ao(),C=Mo(),R=oi(),b=Fi(),U=ff(),B=mf();c.DEFAULT_MODEL="legacy",c.ort=f;const te="vad.worklet.bundle.min.js",X="silero_vad_v5.onnx",ee="silero_vad_legacy.onnx",ie=he=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:he,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async re=>{re.getTracks().forEach(de=>{de.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:re=>{re.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});c.getDefaultRealTimeVADOptions=ie;const ce=he=>"audioWorklet"in he&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function ue(he,re,de,pe,Ie){await de.audioWorklet.addModule(he),re.processorOptions={...re.processorOptions??{},frameSamples:pe};const ge=new AudioWorkletNode(de,"vad-helper-worklet",re);return ge.port.onmessage=async ut=>{const Qe=ut.data;if(!(typeof Qe=="object"&&Qe&&"message"in Qe)){console.error("Invalid message event",Qe);return}switch(Qe.message){case b.Message.AudioFrame:{if(!("data"in Qe&&Qe.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const ft=new Float32Array(Qe.data);await Ie(ft);break}}},ge}async function Be(he,re,de){const pe=new B.Resampler({nativeSampleRate:he.sampleRate,targetSampleRate:16e3,targetFrameSize:re});R.log.debug("using script processor");const ge=he.createScriptProcessor(4096,1,1);let ut=!1;return ge.onaudioprocess=async Qe=>{if(!ut){ut=!0;try{const ft=Qe.inputBuffer.getChannelData(0);Qe.outputBuffer.getChannelData(0).fill(0);const Xe=pe.process(ft);for(const mt of Xe)await de(mt)}catch(ft){console.error("Error processing audio:",ft)}finally{ut=!1}}},ge.connect(he.destination),ge}class ke{constructor(re,de,pe,Ie,ge=!1,ut=null,Qe=null,ft=null,Ne=null,Xe=null,mt=null,yt="uninitialized",ot=!1){this.options=re,this.frameProcessor=de,this.model=pe,this.frameSamples=Ie,this.listening=ge,this.errored=ut,this._stream=Qe,this._audioContext=ft,this._vadNode=Ne,this._mediaStreamAudioSourceNode=Xe,this._audioProcessorAdapterType=mt,this.initializationState=yt,this.ownsAudioContext=ot,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=Ye=>{this.initializationState="errored",this.errored=Ye},this.start=async()=>{switch(this.initializationState){case"uninitialized":{R.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ye){throw Ye instanceof Error?this.setErrored(Ye.message):this.setErrored(String(Ye)),Ye}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?ce(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await ue(this.options.baseAssetPath+te,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await Be(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),R.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{R.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:Ye,audioContext:Le,vadNode:rt}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ye);const Ze=new MediaStreamAudioSourceNode(Le,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Ze,Ze.connect(rt);break}case"destroyed":{R.log.warn("start called after destroyed");break}case"errored":{R.log.error("start called after errored");break}default:{R.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ye,mediaStreamAudioSourceNode:Le}=this.getAudioInstances();await this.options.pauseStream(Ye),Le.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ye}=this.getAudioInstances();Ye instanceof AudioWorkletNode&&Ye.port.postMessage(b.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=Ye=>{this.frameProcessor.setOptions(Ye)},this.processFrame=async Ye=>{await this.frameProcessor.process(Ye,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ye=>{switch(Ye.msg){case b.Message.FrameProcessed:this.options.onFrameProcessed(Ye.probs,Ye.frame);break;case b.Message.SpeechStart:this.options.onSpeechStart();break;case b.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case b.Message.VADMisfire:this.options.onVADMisfire();break;case b.Message.SpeechEnd:this.options.onSpeechEnd(Ye.audio);break}}}static async new(re={}){const de={...(0,c.getDefaultRealTimeVADOptions)(re.model??c.DEFAULT_MODEL),...re};(0,C.validateOptions)(de),c.ort.env.wasm.wasmPaths=de.onnxWASMBasePath,de.ortConfig!==void 0&&de.ortConfig(c.ort);const pe=de.model==="v5"?X:ee,Ie=de.baseAssetPath+pe,ge=de.model==="v5"?U.SileroV5.new:U.SileroLegacy.new;let ut;try{ut=await ge(c.ort,()=>(0,v.defaultModelFetcher)(Ie))}catch(mt){throw console.error(`Encountered an error while loading model file ${Ie}`),mt}const Qe=de.model==="v5"?512:1536,ft=Qe/16,Ne=new C.FrameProcessor(ut.process,ut.reset_state,{positiveSpeechThreshold:de.positiveSpeechThreshold,negativeSpeechThreshold:de.negativeSpeechThreshold,redemptionMs:de.redemptionMs,preSpeechPadMs:de.preSpeechPadMs,minSpeechMs:de.minSpeechMs,submitUserSpeechOnPause:de.submitUserSpeechOnPause},ft),Xe=new ke(de,Ne,ut,Qe);if(de.startOnLoad)try{await Xe.start()}catch(mt){throw console.error("Error starting micVad",mt),mt}return Xe}}c.MicVAD=ke})(Gr)),Gr}var Bp;function Np(){return Bp||(Bp=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.getDefaultRealTimeVADOptions=c.MicVAD=c.DEFAULT_MODEL=c.utils=c.NonRealTimeVAD=c.Message=c.FrameProcessor=c.defaultModelFetcher=c.baseAssetPath=void 0;var r=cf();Object.defineProperty(c,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var n=Ao();Object.defineProperty(c,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var a=Mo();Object.defineProperty(c,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=Fi();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return f.Message}});var v=xy();Object.defineProperty(c,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=Ey();c.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=ky();Object.defineProperty(c,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(c,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(c,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(so)),so}var Up;function Ry(){return Up||(Up=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.useMicVAD=c.getDefaultReactRealTimeVADOptions=c.utils=void 0;const r=Np(),n=le;var a=Np();Object.defineProperty(c,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=b=>({...(0,r.getDefaultRealTimeVADOptions)(b),...f});c.getDefaultReactRealTimeVADOptions=v;function C(b){const U=b.model??r.DEFAULT_MODEL,B={...(0,c.getDefaultReactRealTimeVADOptions)(U),...b},te={userSpeakingThreshold:B.userSpeakingThreshold},X={positiveSpeechThreshold:B.positiveSpeechThreshold,negativeSpeechThreshold:B.negativeSpeechThreshold,redemptionMs:B.redemptionMs,preSpeechPadMs:B.preSpeechPadMs,minSpeechMs:B.minSpeechMs,submitUserSpeechOnPause:B.submitUserSpeechOnPause,onFrameProcessed:B.onFrameProcessed,onVADMisfire:B.onVADMisfire,onSpeechStart:B.onSpeechStart,onSpeechEnd:B.onSpeechEnd,onSpeechRealStart:B.onSpeechRealStart,baseAssetPath:B.baseAssetPath,onnxWASMBasePath:B.onnxWASMBasePath,model:B.model,workletOptions:B.workletOptions,getStream:B.getStream,pauseStream:B.pauseStream,resumeStream:B.resumeStream,startOnLoad:B.startOnLoad,processorType:B.processorType};return B.ortConfig&&(X.ortConfig=B.ortConfig),B.audioContext&&(X.audioContext=B.audioContext),[te,X]}function R(b){const[U,B]=C(b),te=b.model??r.DEFAULT_MODEL,[X,ee]=(0,n.useState)(!1),[ie,ce]=(0,n.useState)(!0),[ue,Be]=(0,n.useState)(!1),[ke,he]=(0,n.useState)(!1),[re,de]=(0,n.useState)(null),pe=(0,n.useRef)(B.onFrameProcessed),Ie=(0,n.useRef)(B.onSpeechEnd),ge=(0,n.useRef)(B.onSpeechStart),ut=(0,n.useRef)(B.onSpeechRealStart),Qe=(0,n.useRef)(B.onVADMisfire),ft=(0,n.useRef)(B.getStream);(0,n.useEffect)(()=>{pe.current=B.onFrameProcessed,Ie.current=B.onSpeechEnd,ge.current=B.onSpeechStart,ut.current=B.onSpeechRealStart,Qe.current=B.onVADMisfire},[B.onFrameProcessed,B.onSpeechEnd,B.onSpeechStart,B.onSpeechRealStart,B.onVADMisfire]),(0,n.useEffect)(()=>{ft.current=B.getStream},[B.getStream]);const Ne=B.getStream.toString();(0,n.useEffect)(()=>{let ot=null,Ye=!1;return(async()=>{try{ce(!0),Be(!1);const rt={...B,onFrameProcessed:(Ze,Q)=>{const Me=Ze.isSpeech>U.userSpeakingThreshold;ee(Me),pe.current(Ze,Q)},onSpeechEnd:Ze=>{Ie.current(Ze)},onSpeechStart:()=>{ge.current()},onSpeechRealStart:()=>{ut.current()},onVADMisfire:()=>{Qe.current()},getStream:()=>ft.current()};if(ot=await r.MicVAD.new(rt),Ye){await ot.destroy();return}de(ot),B.startOnLoad&&(await ot.start(),he(!0)),ce(!1)}catch(rt){ce(!1),rt instanceof Error?Be(rt.message):Be(String(rt))}})().catch(()=>{}),function(){Ye=!0,ot&&ot.destroy(),!ie&&!ue&&he(!1)}},[Ne,te]);const Xe=(0,n.useCallback)(async()=>{!ie&&!ue&&(await re?.pause(),he(!1))},[ie,ue,re]),mt=(0,n.useCallback)(async()=>{!ie&&!ue&&(await re?.start(),he(!0))},[ie,ue,re]),yt=(0,n.useCallback)(async()=>{ke?await Xe():await mt()},[ke,Xe,mt]);return{listening:ke,errored:ue,loading:ie,userSpeaking:X,pause:Xe,start:mt,toggle:yt}}c.useMicVAD=R})(no)),no}var Ay=Ry();df();const Fp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Di=16e3,yf=512,wf=700,My=300,Iy=yf/Di*1e3,Py=Math.ceil(wf/Iy);function Oy(c={}){const{onAudioChunk:r,onAudioEnd:n,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,onError:C,interruptOnSpeechStart:R=!0,forceAudioMp4:b=!1}=c,{sendAudioChunk:U,endAudioStream:B,interrupt:te}=Hr(),[X,ee]=le.useState(!1),[ie,ce]=le.useState(null),ue=le.useRef(null),Be=le.useRef(null),ke=le.useRef(null),he=le.useRef(!1),re=le.useRef(null),de=le.useRef([]),pe=le.useCallback(()=>{if(!(typeof window>"u")){if(!ke.current){const Le=window.AudioContext||window.webkitAudioContext;if(!Le)return;ke.current=new Le({sampleRate:Di})}ke.current.state==="suspended"&&ke.current.resume().catch(()=>{})}},[]);le.useEffect(()=>{typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:Fp}).then(Le=>{ue.current=Le,ce(null)}).catch(Le=>{ce("permission_denied"),C?.(Le)})},[C]);const Ie=le.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(ue.current&&ue.current.getTracks()[0]?.readyState==="live")return ue.current;const Le=await navigator.mediaDevices.getUserMedia({audio:Fp});return ue.current=Le,ce(null),Le},[]),ge=le.useCallback(async Le=>{Le.getTracks().forEach(rt=>{rt.enabled=!1})},[]),ut=le.useCallback(async()=>ue.current&&ue.current.getTracks()[0]?.readyState==="live"?(ue.current.getTracks().forEach(Le=>{Le.enabled=!0}),ue.current):Ie(),[Ie]),Qe=le.useCallback(()=>{const Le=de.current;if(!Le.length)return{samples:new Float32Array(0),duration:0};const rt=Le.reduce((Me,et)=>Me+et.length,0),Ze=new Float32Array(rt);let Q=0;for(const Me of Le)Ze.set(Me,Q),Q+=Me.length;return{samples:Ze,duration:rt/Di}},[]),ft=le.useCallback(()=>{const Le=ue.current,rt=ke.current;if(!Le||!rt||Be.current)return;const{samples:Ze,duration:Q}=Qe();de.current=[];const Me=!b&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"";try{const et=rt.createMediaStreamDestination();if(Ze.length>0){const Et=rt.createBuffer(1,Ze.length,Di);Et.getChannelData(0).set(Ze);const lt=rt.createBufferSource();lt.buffer=Et,lt.connect(et),lt.start(0)}const gt=rt.createMediaStreamSource(Le);if(Q>0){const Et=rt.createDelay(Q+.1);Et.delayTime.value=Q,gt.connect(Et).connect(et)}else gt.connect(et);const Gt=new MediaRecorder(et.stream,Me?{mimeType:Me}:{});Gt.ondataavailable=async Et=>{if(!Et.data||Et.data.size<=0)return;const lt=await Et.data.arrayBuffer();r?r(lt):U(lt)},Be.current=Gt,Gt.start(100)}catch(et){C?.(et)}},[Qe,b,r,C,U]),Ne=le.useCallback(()=>{const Le=Be.current;if(Le){if(Be.current=null,Le.state==="inactive"){n?n():B();return}Le.onstop=()=>{n?n():B()},Le.stop()}},[B,n]),Xe=le.useCallback(()=>{const Le=Be.current;if(Le&&(Be.current=null,Le.state!=="inactive"))try{Le.stop()}catch{}},[]),mt=le.useCallback(()=>{ke.current&&(ke.current.close().catch(()=>{}),ke.current=null)},[]),yt=le.useCallback(()=>{ue.current&&(ue.current.getTracks().forEach(Le=>Le.stop()),ue.current=null)},[]),ot=Ay.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:wf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:yf}},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.1/dist/",ortConfig:Le=>{Le.env.wasm.numThreads=1,Le.env.logLevel="error"},getStream:Ie,pauseStream:ge,resumeStream:ut,onFrameProcessed:(Le,rt)=>{if(!rt)return;const Ze=de.current;Ze.push(new Float32Array(rt)),Ze.length>Py&&Ze.shift()},onSpeechStart:()=>{he.current||(re.current&&(clearTimeout(re.current),re.current=null),ee(!0),R&&te(),ft(),a?.())},onSpeechEnd:()=>{re.current=setTimeout(()=>{ee(!1),Ne(),he.current=!0,setTimeout(()=>{he.current=!1},300),f?.()},My)},onVADMisfire:()=>{re.current&&(clearTimeout(re.current),re.current=null),ee(!1),Xe(),v?.()}}),Ye=le.useCallback(()=>{pe(),ot.listening&&Be.current&&(re.current&&(clearTimeout(re.current),re.current=null),ee(!1),Ne()),ot.toggle()},[Ne,pe,ot]);return le.useEffect(()=>()=>{re.current&&clearTimeout(re.current),Xe(),mt(),yt()},[mt,yt,Xe]),{isListening:ot.listening,isLoading:ot.loading,isSpeaking:X,micError:ie,toggle:Ye,start:ot.start,pause:ot.pause,userSpeaking:ot.userSpeaking}}const zy=()=>Hr(),vf=()=>{const{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:b,terminateSession:U,interrupt:B,refreshSessionActivity:te,clearSessionHistory:X,changeSessionLanguage:ee}=Hr();return{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:b,terminateSession:U,interrupt:B,refreshSessionActivity:te,clearSessionHistory:X,changeSessionLanguage:ee}},Dy=()=>{const{messages:c,sendTextMessage:r,clearMessages:n}=Hr();return{messages:c,sendTextMessage:r,clearMessages:n}},Ly=()=>{const{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}=Hr();return{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}},bf=()=>{const{session:c,isAvatarSpeaking:r,cloudStream:n,setCloudStreamState:a}=Hr(),f=n?.state||Qt.IDLE;return{streamingUrl:c.streamingUrl,isAvatarSpeaking:r,speakingSource:"avatar_events",isCloudAvatar:c.agentType===qr.CLOUD_AVATAR,isDesktopAvatar:c.agentType===qr.DESKTOP_AVATAR,cloudStreamState:f,cloudStreamError:n?.error||null,isCloudStreamConnected:f===Qt.CONNECTED,isCloudStreamLoading:f===Qt.CONNECTING||f===Qt.LOADING,setCloudStreamState:a}},By=c=>{const{attachAudioElement:r,resumeAudioPlayback:n}=Hr();le.useEffect(()=>{if(!c?.current)return;r(c.current);const a=()=>{n()},f=c.current;return f.addEventListener("click",a),f.addEventListener("touchstart",a),()=>{f.removeEventListener("click",a),f.removeEventListener("touchstart",a),r(null)}},[r,c,n])};function Ny({connect:c=!0,session:r,onError:n,onInitialized:a,children:f}){const{initializeSession:v,joinDesktopSession:C,disconnect:R}=vf(),b=le.useRef(!1);return le.useEffect(()=>{if(!c||b.current)return;let U=!1;return b.current=!0,(async()=>{try{if(r?.mode==="join_desktop"){const X=await C({uniqueId:r.uniqueId});U||a?.(X);return}const te=await v({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en"});U||a?.(te)}catch(te){U||n?.(te)}})(),()=>{U=!0,R(),b.current=!1}},[c,R,v,C,n,a,r]),f}function Uy({children:c,wsUrl:r,restUrl:n,session:a,connect:f=!0,reconnectOptions:v,enableAudio:C=!0,pcmOptions:R,debug:b=!1,onError:U,onInitialized:B}){return ar.jsx(uf,{wsUrl:r,restUrl:n,reconnectOptions:v,enableAudio:C,pcmOptions:R,debug:b,children:ar.jsx(Ny,{connect:f,session:a,onError:U,onInitialized:B,children:c})})}var lo={exports:{}},Vp;function Fy(){return Vp||(Vp=1,(function(c){const r={};r.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},r.localCName=r.generateIdentifier(),r.splitLines=function(n){return n.trim().split(`
|
|
2858
|
+
*/var Dp;function Cy(){return Dp||(Dp=1,(function(c,r){var n=(()=>{var a=Object.defineProperty,f=Object.getOwnPropertyDescriptor,v=Object.getOwnPropertyNames,C=Object.prototype.hasOwnProperty,R=(y=>typeof lr<"u"?lr:typeof Proxy<"u"?new Proxy(y,{get:($,A)=>(typeof lr<"u"?lr:$)[A]}):y)(function(y){if(typeof lr<"u")return lr.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')}),b=(y,$)=>()=>(y&&($=y(y=0)),$),U=(y,$)=>{for(var A in $)a(y,A,{get:$[A],enumerable:!0})},B=(y,$,A,z)=>{if($&&typeof $=="object"||typeof $=="function")for(let P of v($))!C.call(y,P)&&P!==A&&a(y,P,{get:()=>$[P],enumerable:!(z=f($,P))||z.enumerable});return y},te=y=>B(a({},"__esModule",{value:!0}),y),X,ee,ie,ce,ue,Be=b(()=>{X=new Map,ee=[],ie=(y,$,A)=>{if($&&typeof $.init=="function"&&typeof $.createInferenceSessionHandler=="function"){let z=X.get(y);if(z===void 0)X.set(y,{backend:$,priority:A});else{if(z.priority>A)return;if(z.priority===A&&z.backend!==$)throw new Error(`cannot register backend "${y}" using priority ${A}`)}if(A>=0){let P=ee.indexOf(y);P!==-1&&ee.splice(P,1);for(let G=0;G<ee.length;G++)if(X.get(ee[G]).priority<=A){ee.splice(G,0,y);return}ee.push(y)}return}throw new TypeError("not a valid backend")},ce=async y=>{let $=X.get(y);if(!$)return"backend not found.";if($.initialized)return $.backend;if($.aborted)return $.error;{let A=!!$.initPromise;try{return A||($.initPromise=$.backend.init(y)),await $.initPromise,$.initialized=!0,$.backend}catch(z){return A||($.error=`${z}`,$.aborted=!0),$.error}finally{delete $.initPromise}}},ue=async y=>{let $=y.executionProviders||[],A=$.map(V=>typeof V=="string"?V:V.name),z=A.length===0?ee:A,P,G=[],N=new Set;for(let V of z){let Z=await ce(V);typeof Z=="string"?G.push({name:V,err:Z}):(P||(P=Z),P===Z&&N.add(V))}if(!P)throw new Error(`no available backend found. ERR: ${G.map(V=>`[${V.name}] ${V.err}`).join(", ")}`);for(let{name:V,err:Z}of G)A.includes(V)&&console.warn(`removing requested execution provider "${V}" from session options because it is not available: ${Z}`);let L=$.filter(V=>N.has(typeof V=="string"?V:V.name));return[P,new Proxy(y,{get:(V,Z)=>Z==="executionProviders"?L:Reflect.get(V,Z)})]}}),ke=b(()=>{Be()}),he,re=b(()=>{he="1.24.3"}),de,pe,Ie=b(()=>{re(),de="warning",pe={wasm:{},webgl:{},webgpu:{},versions:{common:he},set logLevel(y){if(y!==void 0){if(typeof y!="string"||["verbose","info","warning","error","fatal"].indexOf(y)===-1)throw new Error(`Unsupported logging level: ${y}`);de=y}},get logLevel(){return de}},Object.defineProperty(pe,"logLevel",{enumerable:!0})}),ge,ut=b(()=>{Ie(),ge=pe}),Qe,ft,Ne=b(()=>{Qe=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);A.width=y.dims[3],A.height=y.dims[2];let z=A.getContext("2d");if(z!=null){let P,G;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[3]):(P=y.dims[3],G=y.dims[2]);let N=$?.format!==void 0?$.format:"RGB",L=$?.norm,V,Z;L===void 0||L.mean===void 0?V=[255,255,255,255]:typeof L.mean=="number"?V=[L.mean,L.mean,L.mean,L.mean]:(V=[L.mean[0],L.mean[1],L.mean[2],0],L.mean[3]!==void 0&&(V[3]=L.mean[3])),L===void 0||L.bias===void 0?Z=[0,0,0,0]:typeof L.bias=="number"?Z=[L.bias,L.bias,L.bias,L.bias]:(Z=[L.bias[0],L.bias[1],L.bias[2],0],L.bias[3]!==void 0&&(Z[3]=L.bias[3]));let se=G*P,J=0,j=se,$e=se*2,F=-1;N==="RGBA"?(J=0,j=se,$e=se*2,F=se*3):N==="RGB"?(J=0,j=se,$e=se*2):N==="RBG"&&(J=0,$e=se,j=se*2);for(let oe=0;oe<G;oe++)for(let _t=0;_t<P;_t++){let qe=(y.data[J++]-Z[0])*V[0],xe=(y.data[j++]-Z[1])*V[1],We=(y.data[$e++]-Z[2])*V[2],_e=F===-1?255:(y.data[F++]-Z[3])*V[3];z.fillStyle="rgba("+qe+","+xe+","+We+","+_e+")",z.fillRect(_t,oe,1,1)}if("toDataURL"in A)return A.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},ft=(y,$)=>{let A=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),z;if(A!=null){let P,G,N;$?.tensorLayout!==void 0&&$.tensorLayout==="NHWC"?(P=y.dims[2],G=y.dims[1],N=y.dims[3]):(P=y.dims[3],G=y.dims[2],N=y.dims[1]);let L=$!==void 0&&$.format!==void 0?$.format:"RGB",V=$?.norm,Z,se;V===void 0||V.mean===void 0?Z=[255,255,255,255]:typeof V.mean=="number"?Z=[V.mean,V.mean,V.mean,V.mean]:(Z=[V.mean[0],V.mean[1],V.mean[2],255],V.mean[3]!==void 0&&(Z[3]=V.mean[3])),V===void 0||V.bias===void 0?se=[0,0,0,0]:typeof V.bias=="number"?se=[V.bias,V.bias,V.bias,V.bias]:(se=[V.bias[0],V.bias[1],V.bias[2],0],V.bias[3]!==void 0&&(se[3]=V.bias[3]));let J=G*P;if($!==void 0&&($.format!==void 0&&N===4&&$.format!=="RGBA"||N===3&&$.format!=="RGB"&&$.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let j=4,$e=0,F=1,oe=2,_t=3,qe=0,xe=J,We=J*2,_e=-1;L==="RGBA"?(qe=0,xe=J,We=J*2,_e=J*3):L==="RGB"?(qe=0,xe=J,We=J*2):L==="RBG"&&(qe=0,We=J,xe=J*2),z=A.createImageData(P,G);for(let Lt=0;Lt<G*P;$e+=j,F+=j,oe+=j,_t+=j,Lt++)z.data[$e]=(y.data[qe++]-se[0])*Z[0],z.data[F]=(y.data[xe++]-se[1])*Z[1],z.data[oe]=(y.data[We++]-se[2])*Z[2],z.data[_t]=_e===-1?255:(y.data[_e++]-se[3])*Z[3]}else throw new Error("Can not access image data");return z}}),Xe,mt,yt,ot,Ye,Le,rt=b(()=>{Xt(),Xe=(y,$)=>{if(y===void 0)throw new Error("Image buffer must be defined");if($.height===void 0||$.width===void 0)throw new Error("Image height and width must be defined");if($.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:A,width:z}=$,P=$.norm??{mean:255,bias:0},G,N;typeof P.mean=="number"?G=[P.mean,P.mean,P.mean,P.mean]:G=[P.mean[0],P.mean[1],P.mean[2],P.mean[3]??255],typeof P.bias=="number"?N=[P.bias,P.bias,P.bias,P.bias]:N=[P.bias[0],P.bias[1],P.bias[2],P.bias[3]??0];let L=$.format!==void 0?$.format:"RGBA",V=$.tensorFormat!==void 0&&$.tensorFormat!==void 0?$.tensorFormat:"RGB",Z=A*z,se=V==="RGBA"?new Float32Array(Z*4):new Float32Array(Z*3),J=4,j=0,$e=1,F=2,oe=3,_t=0,qe=Z,xe=Z*2,We=-1;L==="RGB"&&(J=3,j=0,$e=1,F=2,oe=-1),V==="RGBA"?We=Z*3:V==="RBG"?(_t=0,xe=Z,qe=Z*2):V==="BGR"&&(xe=0,qe=Z,_t=Z*2);for(let _e=0;_e<Z;_e++,j+=J,F+=J,$e+=J,oe+=J)se[_t++]=(y[j]+N[0])/G[0],se[qe++]=(y[$e]+N[1])/G[1],se[xe++]=(y[F]+N[2])/G[2],We!==-1&&oe!==-1&&(se[We++]=(y[oe]+N[3])/G[3]);return V==="RGBA"?new tt("float32",se,[1,4,A,z]):new tt("float32",se,[1,3,A,z])},mt=async(y,$)=>{let A=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,z=typeof ImageData<"u"&&y instanceof ImageData,P=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,G=typeof y=="string",N,L=$??{},V=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Z=se=>typeof HTMLCanvasElement<"u"&&se instanceof HTMLCanvasElement||se instanceof OffscreenCanvas?se.getContext("2d"):null;if(A){let se=V();se.width=y.width,se.height=y.height;let J=Z(se);if(J!=null){let j=y.height,$e=y.width;if($!==void 0&&$.resizedHeight!==void 0&&$.resizedWidth!==void 0&&(j=$.resizedHeight,$e=$.resizedWidth),$!==void 0){if(L=$,$.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");L.tensorFormat="RGBA",L.height=j,L.width=$e}else L.tensorFormat="RGBA",L.height=j,L.width=$e;J.drawImage(y,0,0),N=J.getImageData(0,0,$e,j).data}else throw new Error("Can not access image data")}else if(z){let se,J;if($!==void 0&&$.resizedWidth!==void 0&&$.resizedHeight!==void 0?(se=$.resizedHeight,J=$.resizedWidth):(se=y.height,J=y.width),$!==void 0&&(L=$),L.format="RGBA",L.height=se,L.width=J,$!==void 0){let j=V();j.width=J,j.height=se;let $e=Z(j);if($e!=null)$e.putImageData(y,0,0),N=$e.getImageData(0,0,J,se).data;else throw new Error("Can not access image data")}else N=y.data}else if(P){if($===void 0)throw new Error("Please provide image config with format for Imagebitmap");let se=V();se.width=y.width,se.height=y.height;let J=Z(se);if(J!=null){let j=y.height,$e=y.width;return J.drawImage(y,0,0,$e,j),N=J.getImageData(0,0,$e,j).data,L.height=j,L.width=$e,Xe(N,L)}else throw new Error("Can not access image data")}else{if(G)return new Promise((se,J)=>{let j=V(),$e=Z(j);if(!y||!$e)return J();let F=new Image;F.crossOrigin="Anonymous",F.src=y,F.onload=()=>{j.width=F.width,j.height=F.height,$e.drawImage(F,0,0,j.width,j.height);let oe=$e.getImageData(0,0,j.width,j.height);L.height=j.height,L.width=j.width,se(Xe(oe.data,L))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(N!==void 0)return Xe(N,L);throw new Error("Input data provided is not supported - aborted tensor creation")},yt=(y,$)=>{let{width:A,height:z,download:P,dispose:G}=$,N=[1,z,A,4];return new tt({location:"texture",type:"float32",texture:y,dims:N,download:P,dispose:G})},ot=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new tt({location:"gpu-buffer",type:A??"float32",gpuBuffer:y,dims:z,download:P,dispose:G})},Ye=(y,$)=>{let{dataType:A,dims:z,download:P,dispose:G}=$;return new tt({location:"ml-tensor",type:A??"float32",mlTensor:y,dims:z,download:P,dispose:G})},Le=(y,$,A)=>new tt({location:"cpu-pinned",type:y,data:$,dims:A??[$.length]})}),Ze,Q,Me,et,gt=b(()=>{Ze=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Me=!1,et=()=>{if(!Me){Me=!0;let y=typeof BigInt64Array<"u"&&BigInt64Array.from,$=typeof BigUint64Array<"u"&&BigUint64Array.from,A=globalThis.Float16Array,z=typeof A<"u"&&A.from;y&&(Ze.set("int64",BigInt64Array),Q.set(BigInt64Array,"int64")),$&&(Ze.set("uint64",BigUint64Array),Q.set(BigUint64Array,"uint64")),z?(Ze.set("float16",A),Q.set(A,"float16")):Ze.set("float16",Uint16Array)}}}),Gt,Ct,lt=b(()=>{Xt(),Gt=y=>{let $=1;for(let A=0;A<y.length;A++){let z=y[A];if(typeof z!="number"||!Number.isSafeInteger(z))throw new TypeError(`dims[${A}] must be an integer, got: ${z}`);if(z<0)throw new RangeError(`dims[${A}] must be a non-negative integer, got: ${z}`);$*=z}return $},Ct=(y,$)=>{switch(y.location){case"cpu":return new tt(y.type,y.data,$);case"cpu-pinned":return new tt({location:"cpu-pinned",data:y.data,type:y.type,dims:$});case"texture":return new tt({location:"texture",texture:y.texture,type:y.type,dims:$});case"gpu-buffer":return new tt({location:"gpu-buffer",gpuBuffer:y.gpuBuffer,type:y.type,dims:$});case"ml-tensor":return new tt({location:"ml-tensor",mlTensor:y.mlTensor,type:y.type,dims:$});default:throw new Error(`tensorReshape: tensor location ${y.location} is not supported`)}}}),tt,Xt=b(()=>{Ne(),rt(),gt(),lt(),tt=class{constructor(y,$,A){et();let z,P;if(typeof y=="object"&&"location"in y)switch(this.dataLocation=y.location,z=y.type,P=y.dims,y.location){case"cpu-pinned":{let N=Ze.get(z);if(!N)throw new TypeError(`unsupported type "${z}" to create tensor from pinned buffer`);if(!(y.data instanceof N))throw new TypeError(`buffer should be of type ${N.name}`);this.cpuData=y.data;break}case"texture":{if(z!=="float32")throw new TypeError(`unsupported type "${z}" to create tensor from texture`);this.gpuTextureData=y.texture,this.downloader=y.download,this.disposer=y.dispose;break}case"gpu-buffer":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from gpu buffer`);this.gpuBufferData=y.gpuBuffer,this.downloader=y.download,this.disposer=y.dispose;break}case"ml-tensor":{if(z!=="float32"&&z!=="float16"&&z!=="int32"&&z!=="int64"&&z!=="uint32"&&z!=="uint64"&&z!=="int8"&&z!=="uint8"&&z!=="bool"&&z!=="uint4"&&z!=="int4")throw new TypeError(`unsupported type "${z}" to create tensor from MLTensor`);this.mlTensorData=y.mlTensor,this.downloader=y.download,this.disposer=y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let N,L;if(typeof y=="string")if(z=y,L=A,y==="string"){if(!Array.isArray($))throw new TypeError("A string tensor's data must be a string array.");N=$}else{let V=Ze.get(y);if(V===void 0)throw new TypeError(`Unsupported tensor type: ${y}.`);if(Array.isArray($)){if(y==="float16"&&V===Uint16Array||y==="uint4"||y==="int4")throw new TypeError(`Creating a ${y} tensor from number array is not supported. Please use ${V.name} as data.`);y==="uint64"||y==="int64"?N=V.from($,BigInt):N=V.from($)}else if($ instanceof V)N=$;else if($ instanceof Uint8ClampedArray)if(y==="uint8")N=Uint8Array.from($);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(y==="float16"&&$ instanceof Uint16Array&&V!==Uint16Array)N=new globalThis.Float16Array($.buffer,$.byteOffset,$.length);else throw new TypeError(`A ${z} tensor's data must be type of ${V}`)}else if(L=$,Array.isArray(y)){if(y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let V=typeof y[0];if(V==="string")z="string",N=y;else if(V==="boolean")z="bool",N=Uint8Array.from(y);else throw new TypeError(`Invalid element type of data array: ${V}.`)}else if(y instanceof Uint8ClampedArray)z="uint8",N=Uint8Array.from(y);else{let V=Q.get(y.constructor);if(V===void 0)throw new TypeError(`Unsupported type for tensor data: ${y.constructor}.`);z=V,N=y}if(L===void 0)L=[N.length];else if(!Array.isArray(L))throw new TypeError("A tensor's dims must be a number array");P=L,this.cpuData=N,this.dataLocation="cpu"}let G=Gt(P);if(this.cpuData&&G!==this.cpuData.length&&!((z==="uint4"||z==="int4")&&Math.ceil(G/2)===this.cpuData.length))throw new Error(`Tensor's size(${G}) does not match data length(${this.cpuData.length}).`);this.type=z,this.dims=P,this.size=G}static async fromImage(y,$){return mt(y,$)}static fromTexture(y,$){return yt(y,$)}static fromGpuBuffer(y,$){return ot(y,$)}static fromMLTensor(y,$){return Ye(y,$)}static fromPinnedBuffer(y,$,A){return Le(y,$,A)}toDataURL(y){return Qe(this,y)}toImageData(y){return ft(this,y)}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(y){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 $=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=$,y&&this.disposer&&(this.disposer(),this.disposer=void 0),$}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(y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ct(this,y)}}}),vt,fe=b(()=>{Xt(),vt=tt}),Ue,wt,dt,ct,me,Fe,xt=b(()=>{Ie(),Ue=(y,$)=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeStamp(`${y}::ORT::${$}`)},wt=(y,$)=>{let A=new Error().stack?.split(/\r\n|\r|\n/g)||[],z=!1;for(let P=0;P<A.length;P++){if(z&&!A[P].includes("TRACE_FUNC")){let G=`FUNC_${y}::${A[P].trim().split(" ")[1]}`;$&&(G+=`::${$}`),Ue("CPU",G);return}A[P].includes("TRACE_FUNC")&&(z=!0)}},dt=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("BEGIN",y)},ct=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||wt("END",y)},me=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.time(`ORT::${y}`)},Fe=y=>{(typeof pe.trace>"u"?!pe.wasm.trace:!pe.trace)||console.timeEnd(`ORT::${y}`)}}),kt,ur=b(()=>{Be(),fe(),xt(),kt=class gf{constructor($){this.handler=$}async run($,A,z){dt(),me("InferenceSession.run");let P={},G={};if(typeof $!="object"||$===null||$ instanceof vt||Array.isArray($))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let N=!0;if(typeof A=="object"){if(A===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(A instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(A)){if(A.length===0)throw new TypeError("'fetches' cannot be an empty array.");N=!1;for(let Z of A){if(typeof Z!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Z)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Z}.`);P[Z]=null}if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else{let Z=!1,se=Object.getOwnPropertyNames(A);for(let J of this.outputNames)if(se.indexOf(J)!==-1){let j=A[J];(j===null||j instanceof vt)&&(Z=!0,N=!1,P[J]=j)}if(Z){if(typeof z=="object"&&z!==null)G=z;else if(typeof z<"u")throw new TypeError("'options' must be an object.")}else G=A}}else if(typeof A<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let Z of this.inputNames)if(typeof $[Z]>"u")throw new Error(`input '${Z}' is missing in 'feeds'.`);if(N)for(let Z of this.outputNames)P[Z]=null;let L=await this.handler.run($,P,G),V={};for(let Z in L)if(Object.hasOwnProperty.call(L,Z)){let se=L[Z];se instanceof vt?V[Z]=se:V[Z]=new vt(se.type,se.data,se.dims)}return Fe("InferenceSession.run"),ct(),V}async release(){return this.handler.dispose()}static async create($,A,z,P){dt(),me("InferenceSession.create");let G,N={};if(typeof $=="string"){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof Uint8Array){if(G=$,typeof A=="object"&&A!==null)N=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer){let se=$,J=0,j=$.byteLength;if(typeof A=="object"&&A!==null)N=A;else if(typeof A=="number"){if(J=A,!Number.isSafeInteger(J))throw new RangeError("'byteOffset' must be an integer.");if(J<0||J>=se.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${se.byteLength}).`);if(j=$.byteLength-J,typeof z=="number"){if(j=z,!Number.isSafeInteger(j))throw new RangeError("'byteLength' must be an integer.");if(j<=0||J+j>se.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${se.byteLength-J}].`);if(typeof P=="object"&&P!==null)N=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof z<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof A<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(se,J,j)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[L,V]=await ue(N),Z=await L.createInferenceSessionHandler(G,V);return Fe("InferenceSession.create"),ct(),new gf(Z)}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}}}),dr,Vi=b(()=>{ur(),dr=kt}),Gi=b(()=>{}),qi=b(()=>{}),Wi=b(()=>{}),Hi=b(()=>{}),is={};U(is,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,env:()=>ge,registerBackend:()=>ie});var Ot=b(()=>{ke(),ut(),Vi(),fe(),Gi(),qi(),xt(),Wi(),Hi()}),sn=b(()=>{}),as={};U(as,{default:()=>os});var an,on,os,ji=b(()=>{Es(),Yt(),hn(),an="ort-wasm-proxy-worker",on=globalThis.self?.name===an,on&&(self.onmessage=y=>{let{type:$,in:A}=y.data;try{switch($){case"init-wasm":mn(A.wasm).then(()=>{Bn(A).then(()=>{postMessage({type:$})},z=>{postMessage({type:$,err:z})})},z=>{postMessage({type:$,err:z})});break;case"init-ep":{let{epName:z,env:P}=A;Nn(P,z).then(()=>{postMessage({type:$})},G=>{postMessage({type:$,err:G})});break}case"copy-from":{let{buffer:z}=A,P=Je(z);postMessage({type:$,out:P});break}case"create":{let{model:z,options:P}=A;tr(z,P).then(G=>{postMessage({type:$,out:G})},G=>{postMessage({type:$,err:G})});break}case"release":Vn(A),postMessage({type:$});break;case"run":{let{sessionId:z,inputIndices:P,inputs:G,outputIndices:N,options:L}=A;H(z,P,G,N,new Array(N.length).fill(null),L).then(V=>{V.some(Z=>Z[3]!=="cpu")?postMessage({type:$,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:$,out:V},Gn([...G,...V]))},V=>{postMessage({type:$,err:V})});break}case"end-profiling":Kr(A),postMessage({type:$});break;default:}}catch(z){postMessage({type:$,err:z})}}),os=on?null:y=>new Worker(y??bt,{type:"classic",name:an})}),ls,us,bt,ln,zr,ds,cs,un,hs,dn,ps,cn,fs,hn=b(()=>{sn(),ls=typeof location>"u"?void 0:location.origin,us=()=>typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0,bt=us(),ln=()=>{if(bt&&!bt.startsWith("blob:"))return bt.substring(0,bt.lastIndexOf("/")+1)},zr=(y,$)=>{try{let A=$??bt;return(A?new URL(y,A):new URL(y)).origin===ls}catch{return!1}},ds=(y,$)=>{let A=$??bt;try{return(A?new URL(y,A):new URL(y)).href}catch{return}},cs=(y,$)=>`${$??"./"}${y}`,un=async y=>{let $=await(await fetch(y,{credentials:"same-origin"})).blob();return URL.createObjectURL($)},hs=async y=>(await import(y)).default,dn=(ji(),te(as)).default,ps=async()=>{if(!bt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zr(bt))return[void 0,dn()];let y=await un(bt);return[y,dn(y)]},cn=void 0,fs=async(y,$,A,z)=>{let P=cn&&!(y||$);if(P)if(bt)P=zr(bt)||z&&!A;else if(z&&!A)P=!0;else throw new Error("cannot determine the script source URL.");if(P)return[void 0,cn];{let G="ort-wasm-simd-threaded.mjs",N=y??ds(G,$),L=A&&N&&!zr(N,$),V=L?await un(N):N??cs(G,$);return[L?V:void 0,await hs(V)]}}}),pn,Dr,cr,fn,ms,gs,ys,mn,ze,Yt=b(()=>{hn(),Dr=!1,cr=!1,fn=!1,ms=()=>{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}},gs=()=>{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}},ys=()=>{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}},mn=async y=>{if(Dr)return Promise.resolve();if(cr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(fn)throw new Error("previous call to 'initializeWebAssembly()' failed.");cr=!0;let $=y.initTimeout,A=y.numThreads;if(y.simd!==!1){if(y.simd==="relaxed"){if(!ys())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!gs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let z=ms();A>1&&!z&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+A+", 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."),y.numThreads=A=1);let P=y.wasmPaths,G=typeof P=="string"?P:void 0,N=P?.mjs,L=N?.href??N,V=P?.wasm,Z=V?.href??V,se=y.wasmBinary,[J,j]=await fs(L,G,A>1,!!se||!!Z),$e=!1,F=[];if($>0&&F.push(new Promise(oe=>{setTimeout(()=>{$e=!0,oe()},$)})),F.push(new Promise((oe,_t)=>{let qe={numThreads:A};if(se)qe.wasmBinary=se,qe.locateFile=xe=>xe;else if(Z||G)qe.locateFile=xe=>Z??G+xe;else if(L&&L.indexOf("blob:")!==0)qe.locateFile=xe=>new URL(xe,L).href;else if(J){let xe=ln();xe&&(qe.locateFile=We=>xe+We)}j(qe).then(xe=>{cr=!1,Dr=!0,pn=xe,oe(),J&&URL.revokeObjectURL(J)},xe=>{cr=!1,fn=!0,_t(xe)})})),await Promise.race(F),$e)throw new Error(`WebAssembly backend initializing failed due to timeout: ${$}ms`)},ze=()=>{if(Dr&&pn)return pn;throw new Error("WebAssembly is not initialized yet.")}}),Et,Lr,Re,gn=b(()=>{Yt(),Et=(y,$)=>{let A=ze(),z=A.lengthBytesUTF8(y)+1,P=A._malloc(z);return A.stringToUTF8(y,P,z),$.push(P),P},Lr=(y,$,A,z)=>{if(typeof y=="object"&&y!==null){if(A.has(y))throw new Error("Circular reference in options");A.add(y)}Object.entries(y).forEach(([P,G])=>{let N=$?$+P:P;if(typeof G=="object")Lr(G,N+".",A,z);else if(typeof G=="string"||typeof G=="number")z(N,G.toString());else if(typeof G=="boolean")z(N,G?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof G}`)})},Re=y=>{let $=ze(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetLastError(P,P+z);let G=Number($.getValue(P,z===4?"i32":"i64")),N=$.getValue(P+z,"*"),L=N?$.UTF8ToString(N):"";throw new Error(`${y} ERROR_CODE: ${G}, ERROR_MESSAGE: ${L}`)}finally{$.stackRestore(A)}}}),ws,Ki=b(()=>{Yt(),gn(),ws=y=>{let $=ze(),A=0,z=[],P=y||{};try{if(y?.logSeverityLevel===void 0)P.logSeverityLevel=2;else if(typeof y.logSeverityLevel!="number"||!Number.isInteger(y.logSeverityLevel)||y.logSeverityLevel<0||y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${y.logSeverityLevel}`);if(y?.logVerbosityLevel===void 0)P.logVerbosityLevel=0;else if(typeof y.logVerbosityLevel!="number"||!Number.isInteger(y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${y.logVerbosityLevel}`);y?.terminate===void 0&&(P.terminate=!1);let G=0;return y?.tag!==void 0&&(G=Et(y.tag,z)),A=$._OrtCreateRunOptions(P.logSeverityLevel,P.logVerbosityLevel,!!P.terminate,G),A===0&&Re("Can't create run options."),y?.extra!==void 0&&Lr(y.extra,"",new WeakSet,(N,L)=>{let V=Et(N,z),Z=Et(L,z);$._OrtAddRunConfigEntry(A,V,Z)!==0&&Re(`Can't set a run config entry: ${N} - ${L}.`)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseRunOptions(A),z.forEach(N=>$._free(N)),G}}}),vs,bs,_s,hr,Ss,Ts,Qi=b(()=>{Yt(),gn(),vs=y=>{switch(y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${y}`)}},bs=y=>{switch(y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${y}`)}},_s=y=>{y.extra||(y.extra={}),y.extra.session||(y.extra.session={});let $=y.extra.session;$.use_ort_model_bytes_directly||($.use_ort_model_bytes_directly="1"),y.executionProviders&&y.executionProviders.some(A=>(typeof A=="string"?A:A.name)==="webgpu")&&(y.enableMemPattern=!1)},hr=(y,$,A,z)=>{let P=Et($,z),G=Et(A,z);ze()._OrtAddSessionConfigEntry(y,P,G)!==0&&Re(`Can't set a session config entry: ${$} - ${A}.`)},Ss=async(y,$,A)=>{let z=$.executionProviders;for(let P of z){let G=typeof P=="string"?P:P.name,N=[];switch(G){case"webnn":if(G="WEBNN",typeof P!="string"){let J=P?.deviceType;J&&hr(y,"deviceType",J,A)}break;case"webgpu":if(G="JS",typeof P!="string"){let J=P;if(J?.preferredLayout){if(J.preferredLayout!=="NCHW"&&J.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${J.preferredLayout}`);hr(y,"preferredLayout",J.preferredLayout,A)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${G}`)}let L=Et(G,A),V=N.length,Z=0,se=0;if(V>0){Z=ze()._malloc(V*ze().PTR_SIZE),A.push(Z),se=ze()._malloc(V*ze().PTR_SIZE),A.push(se);for(let J=0;J<V;J++)ze().setValue(Z+J*ze().PTR_SIZE,N[J][0],"*"),ze().setValue(se+J*ze().PTR_SIZE,N[J][1],"*")}await ze()._OrtAppendExecutionProvider(y,L,Z,se,V)!==0&&Re(`Can't append execution provider: ${G}.`)}},Ts=async y=>{let $=ze(),A=0,z=[],P=y||{};_s(P);try{let G=vs(P.graphOptimizationLevel??"all"),N=bs(P.executionMode??"sequential"),L=typeof P.logId=="string"?Et(P.logId,z):0,V=P.logSeverityLevel??2;if(!Number.isInteger(V)||V<0||V>4)throw new Error(`log severity level is not valid: ${V}`);let Z=P.logVerbosityLevel??0;if(!Number.isInteger(Z)||Z<0||Z>4)throw new Error(`log verbosity level is not valid: ${Z}`);let se=typeof P.optimizedModelFilePath=="string"?Et(P.optimizedModelFilePath,z):0;if(A=$._OrtCreateSessionOptions(G,!!P.enableCpuMemArena,!!P.enableMemPattern,N,!!P.enableProfiling,0,L,V,Z,se),A===0&&Re("Can't create session options."),P.executionProviders&&await Ss(A,P,z),P.enableGraphCapture!==void 0){if(typeof P.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${P.enableGraphCapture}`);hr(A,"enableGraphCapture",P.enableGraphCapture.toString(),z)}if(P.freeDimensionOverrides)for(let[J,j]of Object.entries(P.freeDimensionOverrides)){if(typeof J!="string")throw new Error(`free dimension override name must be a string: ${J}`);if(typeof j!="number"||!Number.isInteger(j)||j<0)throw new Error(`free dimension override value must be a non-negative integer: ${j}`);let $e=Et(J,z);$._OrtAddFreeDimensionOverride(A,$e,j)!==0&&Re(`Can't set a free dimension override: ${J} - ${j}.`)}return P.extra!==void 0&&Lr(P.extra,"",new WeakSet,(J,j)=>{hr(A,J,j,z)}),[A,z]}catch(G){throw A!==0&&$._OrtReleaseSessionOptions(A)!==0&&Re("Can't release session options."),z.forEach(N=>$._free(N)),G}}}),Jt,Zt,er,yn,wn,vn,bn,Ln,Pe=b(()=>{Jt=y=>{switch(y){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: ${y}`)}},Zt=y=>{switch(y){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: ${y}`)}},er=(y,$)=>{let A=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][y],z=typeof $=="number"?$:$.reduce((P,G)=>P*G,1);return A>0?Math.ceil(z*A):void 0},yn=y=>{switch(y){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: ${y}`)}},wn=y=>{switch(y){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: ${y}`)}},vn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",bn=y=>y==="float32"||y==="float16"||y==="int32"||y==="int64"||y==="uint32"||y==="uint64"||y==="int8"||y==="uint8"||y==="bool"||y==="uint4"||y==="int4",Ln=y=>{switch(y){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: ${y}`)}}}),_n,$s=b(()=>{sn(),_n=async y=>{if(typeof y=="string"){let $=await fetch(y);if(!$.ok)throw new Error(`failed to load external data file: ${y}`);let A=$.headers.get("Content-Length"),z=A?parseInt(A,10):0;if(z<1073741824)return new Uint8Array(await $.arrayBuffer());{if(!$.body)throw new Error(`failed to load external data file: ${y}, no response body.`);let P=$.body.getReader(),G;try{G=new ArrayBuffer(z)}catch(L){if(L instanceof RangeError){let V=Math.ceil(z/65536);G=new WebAssembly.Memory({initial:V,maximum:V}).buffer}else throw L}let N=0;for(;;){let{done:L,value:V}=await P.read();if(L)break;let Z=V.byteLength;new Uint8Array(G,N,Z).set(V),N+=Z}return new Uint8Array(G,0,z)}}else return y instanceof Blob?new Uint8Array(await y.arrayBuffer()):y instanceof Uint8Array?y:new Uint8Array(y)}}),xs,Bn,Nn,xr,Un,Fn,Je,tr,Vn,Er,H,Kr,Gn,Es=b(()=>{Ot(),Ki(),Qi(),Pe(),Yt(),gn(),$s(),xs=(y,$)=>{ze()._OrtInit(y,$)!==0&&Re("Can't initialize onnxruntime.")},Bn=async y=>{xs(y.wasm.numThreads,wn(y.logLevel))},Nn=async(y,$)=>{ze().asyncInit?.();let A=y.webgpu.adapter;if($==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(A){if(typeof A.limits!="object"||typeof A.features!="object"||typeof A.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let z=y.webgpu.powerPreference;if(z!==void 0&&z!=="low-power"&&z!=="high-performance")throw new Error(`Invalid powerPreference setting: "${z}"`);let P=y.webgpu.forceFallbackAdapter;if(P!==void 0&&typeof P!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${P}"`);if(A=await navigator.gpu.requestAdapter({powerPreference:z,forceFallbackAdapter:P}),!A)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if($==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},xr=new Map,Un=y=>{let $=ze(),A=$.stackSave();try{let z=$.PTR_SIZE,P=$.stackAlloc(2*z);$._OrtGetInputOutputCount(y,P,P+z)!==0&&Re("Can't get session input/output count.");let G=z===4?"i32":"i64";return[Number($.getValue(P,G)),Number($.getValue(P+z,G))]}finally{$.stackRestore(A)}},Fn=(y,$)=>{let A=ze(),z=A.stackSave(),P=0;try{let G=A.PTR_SIZE,N=A.stackAlloc(2*G);A._OrtGetInputOutputMetadata(y,$,N,N+G)!==0&&Re("Can't get session input/output metadata.");let L=Number(A.getValue(N,"*"));P=Number(A.getValue(N+G,"*"));let V=A.HEAP32[P/4];if(V===0)return[L,0];let Z=A.HEAPU32[P/4+1],se=[];for(let J=0;J<Z;J++){let j=Number(A.getValue(P+8+J*G,"*"));se.push(j!==0?A.UTF8ToString(j):Number(A.getValue(P+8+(J+Z)*G,"*")))}return[L,V,se]}finally{A.stackRestore(z),P!==0&&A._OrtFree(P)}},Je=y=>{let $=ze(),A=$._malloc(y.byteLength);if(A===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${y.byteLength}.`);return $.HEAPU8.set(y,A),[A,y.byteLength]},tr=async(y,$)=>{let A,z,P=ze();Array.isArray(y)?[A,z]=y:y.buffer===P.HEAPU8.buffer?[A,z]=[y.byteOffset,y.byteLength]:[A,z]=Je(y);let G=0,N=0,L=[],V=[],Z=[];try{if([N,L]=await Ts($),$?.externalData&&P.mountExternalData){let xe=[];for(let We of $.externalData){let _e=typeof We=="string"?We:We.path;xe.push(_n(typeof We=="string"?We:We.data).then(Lt=>{P.mountExternalData(_e,Lt)}))}await Promise.all(xe)}for(let xe of $?.executionProviders??[])if((typeof xe=="string"?xe:xe.name)==="webnn"){if(P.shouldTransferToMLTensor=!1,typeof xe!="string"){let We=xe,_e=We?.context,Lt=We?.gpuDevice,Nt=We?.deviceType,Rr=We?.powerPreference;_e?P.currentContext=_e:Lt?P.currentContext=await P.webnnCreateMLContext(Lt):P.currentContext=await P.webnnCreateMLContext({deviceType:Nt,powerPreference:Rr})}else P.currentContext=await P.webnnCreateMLContext();break}G=await P._OrtCreateSession(A,z,N),P.webgpuOnCreateSession?.(G),G===0&&Re("Can't create a session."),P.jsepOnCreateSession?.(),P.currentContext&&(P.webnnRegisterMLContext(G,P.currentContext),P.currentContext=void 0,P.shouldTransferToMLTensor=!0);let[se,J]=Un(G),j=!!$?.enableGraphCapture,$e=[],F=[],oe=[],_t=[],qe=[];for(let xe=0;xe<se;xe++){let[We,_e,Lt]=Fn(G,xe);We===0&&Re("Can't get an input name."),V.push(We);let Nt=P.UTF8ToString(We);$e.push(Nt),oe.push(_e===0?{name:Nt,isTensor:!1}:{name:Nt,isTensor:!0,type:Zt(_e),shape:Lt})}for(let xe=0;xe<J;xe++){let[We,_e,Lt]=Fn(G,xe+se);We===0&&Re("Can't get an output name."),Z.push(We);let Nt=P.UTF8ToString(We);F.push(Nt),_t.push(_e===0?{name:Nt,isTensor:!1}:{name:Nt,isTensor:!0,type:Zt(_e),shape:Lt})}return xr.set(G,[G,V,Z,null,j,!1]),[G,$e,F,oe,_t]}catch(se){throw V.forEach(J=>P._OrtFree(J)),Z.forEach(J=>P._OrtFree(J)),G!==0&&P._OrtReleaseSession(G)!==0&&Re("Can't release session."),se}finally{P._free(A),N!==0&&P._OrtReleaseSessionOptions(N)!==0&&Re("Can't release session options."),L.forEach(se=>P._free(se)),P.unmountExternalData?.()}},Vn=y=>{let $=ze(),A=xr.get(y);if(!A)throw new Error(`cannot release session. invalid session id: ${y}`);let[z,P,G,N,L]=A;N&&(L&&$._OrtClearBoundOutputs(N.handle)!==0&&Re("Can't clear bound outputs."),$._OrtReleaseBinding(N.handle)!==0&&Re("Can't release IO binding.")),$.jsepOnReleaseSession?.(y),$.webnnOnReleaseSession?.(y),$.webgpuOnReleaseSession?.(y),P.forEach(V=>$._OrtFree(V)),G.forEach(V=>$._OrtFree(V)),$._OrtReleaseSession(z)!==0&&Re("Can't release session."),xr.delete(y)},Er=async(y,$,A,z,P,G,N=!1)=>{if(!y){$.push(0);return}let L=ze(),V=L.PTR_SIZE,Z=y[0],se=y[1],J=y[3],j=J,$e,F;if(Z==="string"&&(J==="gpu-buffer"||J==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(N&&J!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${G} when enableGraphCapture is true.`);if(J==="gpu-buffer"){let qe=y[2].gpuBuffer;F=er(Jt(Z),se);{let xe=L.jsepRegisterBuffer;if(!xe)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$e=xe(z,G,qe,F)}}else if(J==="ml-tensor"){let qe=y[2].mlTensor;F=er(Jt(Z),se);let xe=L.webnnRegisterMLTensor;if(!xe)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$e=xe(z,qe,Jt(Z),se)}else{let qe=y[2];if(Array.isArray(qe)){F=V*qe.length,$e=L._malloc(F),A.push($e);for(let xe=0;xe<qe.length;xe++){if(typeof qe[xe]!="string")throw new TypeError(`tensor data at index ${xe} is not a string`);L.setValue($e+xe*V,Et(qe[xe],A),"*")}}else{let xe=L.webnnIsGraphInput,We=L.webnnIsGraphOutput;if(Z!=="string"&&xe&&We){let _e=L.UTF8ToString(P);if(xe(z,_e)||We(z,_e)){let Lt=Jt(Z);F=er(Lt,se),j="ml-tensor";let Nt=L.webnnCreateTemporaryTensor,Rr=L.webnnUploadTensor;if(!Nt||!Rr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Jr=await Nt(z,Lt,se);Rr(Jr,new Uint8Array(qe.buffer,qe.byteOffset,qe.byteLength)),$e=Jr}else F=qe.byteLength,$e=L._malloc(F),A.push($e),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,F),$e)}else F=qe.byteLength,$e=L._malloc(F),A.push($e),L.HEAPU8.set(new Uint8Array(qe.buffer,qe.byteOffset,F),$e)}}let oe=L.stackSave(),_t=L.stackAlloc(4*se.length);try{se.forEach((xe,We)=>L.setValue(_t+We*V,xe,V===4?"i32":"i64"));let qe=L._OrtCreateTensor(Jt(Z),$e,F,_t,se.length,Ln(j));qe===0&&Re(`Can't create tensor for input/output. session=${z}, index=${G}.`),$.push(qe)}finally{L.stackRestore(oe)}},H=async(y,$,A,z,P,G)=>{let N=ze(),L=N.PTR_SIZE,V=xr.get(y);if(!V)throw new Error(`cannot run inference. invalid session id: ${y}`);let Z=V[0],se=V[1],J=V[2],j=V[3],$e=V[4];V[5];let F=$.length,oe=z.length,_t=0,qe=[],xe=[],We=[],_e=[],Lt=[],Nt=N.stackSave(),Rr=N.stackAlloc(F*L),Jr=N.stackAlloc(F*L),Zn=N.stackAlloc(oe*L),Os=N.stackAlloc(oe*L);try{[_t,qe]=ws(G),me("wasm prepareInputOutputTensor");for(let He=0;He<F;He++)await Er(A[He],xe,_e,y,se[$[He]],$[He],$e);for(let He=0;He<oe;He++)await Er(P[He],We,_e,y,J[z[He]],F+z[He],$e);Fe("wasm prepareInputOutputTensor");for(let He=0;He<F;He++)N.setValue(Rr+He*L,xe[He],"*"),N.setValue(Jr+He*L,se[$[He]],"*");for(let He=0;He<oe;He++)N.setValue(Zn+He*L,We[He],"*"),N.setValue(Os+He*L,J[z[He]],"*");N.jsepOnRunStart?.(Z),N.webnnOnRunStart?.(Z);let Tt;Tt=await N._OrtRun(Z,Jr,Rr,F,Os,oe,Zn,_t),Tt!==0&&Re("failed to call OrtRun().");let nr=[],zs=[];me("wasm ProcessOutputTensor");for(let He=0;He<oe;He++){let rr=Number(N.getValue(Zn+He*L,"*"));if(rr===We[He]||Lt.includes(We[He])){nr.push(P[He]),rr!==We[He]&&N._OrtReleaseTensor(rr)!==0&&Re("Can't release tensor.");continue}let ci=N.stackSave(),mr=N.stackAlloc(4*L),xn=!1,Rt,Wt=0;try{N._OrtGetTensorData(rr,mr,mr+L,mr+2*L,mr+3*L)!==0&&Re(`Can't access output tensor data on index ${He}.`);let es=L===4?"i32":"i64",En=Number(N.getValue(mr,es));Wt=N.getValue(mr+L,"*");let Ds=N.getValue(mr+L*2,"*"),hi=Number(N.getValue(mr+L*3,es)),zt=[];for(let At=0;At<hi;At++)zt.push(Number(N.getValue(Ds+At*L,es)));N._OrtFree(Ds)!==0&&Re("Can't free memory for tensor dims.");let gr=zt.reduce((At,$t)=>At*$t,1);Rt=Zt(En);let Zr=j?.outputPreferredLocations[z[He]];if(Rt==="string"){if(Zr==="gpu-buffer"||Zr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let At=[];for(let $t=0;$t<gr;$t++){let sr=N.getValue(Wt+$t*L,"*"),pi=N.getValue(Wt+($t+1)*L,"*"),fi=$t===gr-1?void 0:pi-sr;At.push(N.UTF8ToString(sr,fi))}nr.push([Rt,zt,At,"cpu"])}else if(Zr==="gpu-buffer"&&gr>0){let At=N.jsepGetBuffer;if(!At)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let $t=At(Wt),sr=er(En,gr);if(sr===void 0||!vn(Rt))throw new Error(`Unsupported data type: ${Rt}`);xn=!0,nr.push([Rt,zt,{gpuBuffer:$t,download:N.jsepCreateDownloader($t,sr,Rt),dispose:()=>{N._OrtReleaseTensor(rr)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(Zr==="ml-tensor"&&gr>0){let At=N.webnnEnsureTensor,$t=N.webnnIsGraphInputOutputTypeSupported;if(!At||!$t)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(er(En,gr)===void 0||!bn(Rt))throw new Error(`Unsupported data type: ${Rt}`);if(!$t(y,Rt,!1))throw new Error(`preferredLocation "ml-tensor" for ${Rt} output is not supported by current WebNN Context.`);let sr=await At(y,Wt,En,zt,!1);xn=!0,nr.push([Rt,zt,{mlTensor:sr,download:N.webnnCreateMLTensorDownloader(Wt,Rt),dispose:()=>{N.webnnReleaseTensorId(Wt),N._OrtReleaseTensor(rr)}},"ml-tensor"])}else if(Zr==="ml-tensor-cpu-output"&&gr>0){let At=N.webnnCreateMLTensorDownloader(Wt,Rt)(),$t=nr.length;xn=!0,zs.push((async()=>{let sr=[$t,await At];return N.webnnReleaseTensorId(Wt),N._OrtReleaseTensor(rr),sr})()),nr.push([Rt,zt,[],"cpu"])}else{let At=yn(Rt),$t=new At(gr);new Uint8Array($t.buffer,$t.byteOffset,$t.byteLength).set(N.HEAPU8.subarray(Wt,Wt+$t.byteLength)),nr.push([Rt,zt,$t,"cpu"])}}finally{N.stackRestore(ci),Rt==="string"&&Wt&&N._free(Wt),xn||N._OrtReleaseTensor(rr)}}j&&!$e&&(N._OrtClearBoundOutputs(j.handle)!==0&&Re("Can't clear bound outputs."),xr.set(y,[Z,se,J,j,$e,!1]));for(let[He,rr]of await Promise.all(zs))nr[He][2]=rr;return Fe("wasm ProcessOutputTensor"),nr}finally{N.webnnOnRunEnd?.(Z),N.stackRestore(Nt),xe.forEach(Tt=>N._OrtReleaseTensor(Tt)),We.forEach(Tt=>N._OrtReleaseTensor(Tt)),_e.forEach(Tt=>N._free(Tt)),_t!==0&&N._OrtReleaseRunOptions(_t),qe.forEach(Tt=>N._free(Tt))}},Kr=y=>{let $=ze(),A=xr.get(y);if(!A)throw new Error("invalid session id");let z=A[0],P=$._OrtEndProfiling(z);P===0&&Re("Can't get an profile file name."),$._OrtFree(P)},Gn=y=>{let $=[];for(let A of y){let z=A[2];!Array.isArray(z)&&"buffer"in z&&$.push(z.buffer)}return $}}),pr,Ae,Cr,Qr,Br,Xr,Sn,Tn,fr,kr,qn,Wn,Hn,Cs,ks,ui,Yr,Rs,As=b(()=>{Ot(),Es(),Yt(),hn(),pr=()=>!!ge.wasm.proxy&&typeof document<"u",Cr=!1,Qr=!1,Br=!1,Tn=new Map,fr=(y,$)=>{let A=Tn.get(y);A?A.push($):Tn.set(y,[$])},kr=()=>{if(Cr||!Qr||Br||!Ae)throw new Error("worker not ready")},qn=y=>{switch(y.data.type){case"init-wasm":Cr=!1,y.data.err?(Br=!0,Sn[1](y.data.err)):(Qr=!0,Sn[0]()),Xr&&(URL.revokeObjectURL(Xr),Xr=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let $=Tn.get(y.data.type);y.data.err?$.shift()[1](y.data.err):$.shift()[0](y.data.out);break}}},Wn=async()=>{if(!Qr){if(Cr)throw new Error("multiple calls to 'initWasm()' detected.");if(Br)throw new Error("previous call to 'initWasm()' failed.");if(Cr=!0,pr())return new Promise((y,$)=>{Ae?.terminate(),ps().then(([A,z])=>{try{Ae=z,Ae.onerror=G=>$(G),Ae.onmessage=qn,Sn=[y,$];let P={type:"init-wasm",in:ge};if(!P.in.wasm.wasmPaths&&A){let G=ln();G&&(P.in.wasm.wasmPaths=G)}Ae.postMessage(P),Xr=A}catch(P){$(P)}},$)});try{await mn(ge.wasm),await Bn(ge),Qr=!0}catch(y){throw Br=!0,y}finally{Cr=!1}}},Hn=async y=>{if(pr())return kr(),new Promise(($,A)=>{fr("init-ep",[$,A]);let z={type:"init-ep",in:{epName:y,env:ge}};Ae.postMessage(z)});await Nn(ge,y)},Cs=async y=>pr()?(kr(),new Promise(($,A)=>{fr("copy-from",[$,A]);let z={type:"copy-from",in:{buffer:y}};Ae.postMessage(z,[y.buffer])})):Je(y),ks=async(y,$)=>{if(pr()){if($?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return kr(),new Promise((A,z)=>{fr("create",[A,z]);let P={type:"create",in:{model:y,options:{...$}}},G=[];y instanceof Uint8Array&&G.push(y.buffer),Ae.postMessage(P,G)})}else return tr(y,$)},ui=async y=>{if(pr())return kr(),new Promise(($,A)=>{fr("release",[$,A]);let z={type:"release",in:y};Ae.postMessage(z)});Vn(y)},Yr=async(y,$,A,z,P,G)=>{if(pr()){if(A.some(N=>N[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(P.some(N=>N))throw new Error("pre-allocated output tensor is not supported for proxy.");return kr(),new Promise((N,L)=>{fr("run",[N,L]);let V=A,Z={type:"run",in:{sessionId:y,inputIndices:$,inputs:V,outputIndices:z,options:G}};Ae.postMessage(Z,Gn(V))})}else return H(y,$,A,z,P,G)},Rs=async y=>{if(pr())return kr(),new Promise(($,A)=>{fr("end-profiling",[$,A]);let z={type:"end-profiling",in:y};Ae.postMessage(z)});Kr(y)}}),Ms,jn,Kn,Qn=b(()=>{Ot(),As(),Pe(),sn(),$s(),Ms=(y,$)=>{switch(y.location){case"cpu":return[y.type,y.dims,y.data,"cpu"];case"gpu-buffer":return[y.type,y.dims,{gpuBuffer:y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[y.type,y.dims,{mlTensor:y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${y.location} for ${$()}`)}},jn=y=>{switch(y[3]){case"cpu":return new vt(y[0],y[2],y[1]);case"gpu-buffer":{let $=y[0];if(!vn($))throw new Error(`not supported data type: ${$} for deserializing GPU tensor`);let{gpuBuffer:A,download:z,dispose:P}=y[2];return vt.fromGpuBuffer(A,{dataType:$,dims:y[1],download:z,dispose:P})}case"ml-tensor":{let $=y[0];if(!bn($))throw new Error(`not supported data type: ${$} for deserializing MLTensor tensor`);let{mlTensor:A,download:z,dispose:P}=y[2];return vt.fromMLTensor(A,{dataType:$,dims:y[1],download:z,dispose:P})}default:throw new Error(`invalid data location: ${y[3]}`)}},Kn=class{async fetchModelAndCopyToWasmMemory(y){return Cs(await _n(y))}async loadModel(y,$){dt();let A;typeof y=="string"?A=await this.fetchModelAndCopyToWasmMemory(y):A=y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ks(A,$),ct()}async dispose(){return ui(this.sessionId)}async run(y,$,A){dt();let z=[],P=[];Object.entries(y).forEach(J=>{let j=J[0],$e=J[1],F=this.inputNames.indexOf(j);if(F===-1)throw new Error(`invalid input '${j}'`);z.push($e),P.push(F)});let G=[],N=[];Object.entries($).forEach(J=>{let j=J[0],$e=J[1],F=this.outputNames.indexOf(j);if(F===-1)throw new Error(`invalid output '${j}'`);G.push($e),N.push(F)});let L=z.map((J,j)=>Ms(J,()=>`input "${this.inputNames[P[j]]}"`)),V=G.map((J,j)=>J?Ms(J,()=>`output "${this.outputNames[N[j]]}"`):null),Z=await Yr(this.sessionId,P,L,N,V,A),se={};for(let J=0;J<Z.length;J++)se[this.outputNames[N[J]]]=G[J]??jn(Z[J]);return ct(),se}startProfiling(){}endProfiling(){Rs(this.sessionId)}}}),$n={};U($n,{OnnxruntimeWebAssemblyBackend:()=>Yn,initializeFlags:()=>Xn,wasmBackend:()=>Jn});var Xn,Yn,Jn,Is=b(()=>{Ot(),As(),Qn(),Xn=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let y=ge.wasm.simd;if(typeof y!="boolean"&&y!==void 0&&y!=="fixed"&&y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${y}". Reset it to \`false\` and ignore SIMD feature checking.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let $=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil(($||1)/2))}},Yn=class{async init(y){Xn(),await Wn(),await Hn(y)}async createInferenceSessionHandler(y,$){let A=new Kn;return await A.loadModel(y,$),A}},Jn=new Yn}),Ps={};U(Ps,{InferenceSession:()=>dr,TRACE:()=>Ue,TRACE_EVENT_BEGIN:()=>me,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>dt,TRACE_FUNC_END:()=>ct,Tensor:()=>vt,default:()=>Xi,env:()=>ge,registerBackend:()=>ie}),Ot(),Ot(),Ot();var di="1.24.3",Xi=is;{let y=(Is(),te($n)).wasmBackend;ie("cpu",y,10),ie("wasm",y,10)}return Object.defineProperty(ge.versions,"web",{value:di,enumerable:!0}),te(Ps)})();c.exports=n})(oo)),oo.exports}var Lp;function ky(){return Lp||(Lp=1,(function(c){var r=Gr&&Gr.__createBinding||(Object.create?(function(he,re,de,pe){pe===void 0&&(pe=de);var Ie=Object.getOwnPropertyDescriptor(re,de);(!Ie||("get"in Ie?!re.__esModule:Ie.writable||Ie.configurable))&&(Ie={enumerable:!0,get:function(){return re[de]}}),Object.defineProperty(he,pe,Ie)}):(function(he,re,de,pe){pe===void 0&&(pe=de),he[pe]=re[de]})),n=Gr&&Gr.__setModuleDefault||(Object.create?(function(he,re){Object.defineProperty(he,"default",{enumerable:!0,value:re})}):function(he,re){he.default=re}),a=Gr&&Gr.__importStar||function(he){if(he&&he.__esModule)return he;var re={};if(he!=null)for(var de in he)de!=="default"&&Object.prototype.hasOwnProperty.call(he,de)&&r(re,he,de);return n(re,he),re};Object.defineProperty(c,"__esModule",{value:!0}),c.MicVAD=c.getDefaultRealTimeVADOptions=c.ort=c.DEFAULT_MODEL=void 0;const f=a(Cy()),v=Ao(),C=Mo(),R=oi(),b=Fi(),U=ff(),B=mf();c.DEFAULT_MODEL="legacy",c.ort=f;const te="vad.worklet.bundle.min.js",X="silero_vad_v5.onnx",ee="silero_vad_legacy.onnx",ie=he=>({...C.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{R.log.debug("VAD misfire")},onSpeechStart:()=>{R.log.debug("Detected speech start")},onSpeechEnd:()=>{R.log.debug("Detected speech end")},onSpeechRealStart:()=>{R.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:he,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async re=>{re.getTracks().forEach(de=>{de.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:re=>{re.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});c.getDefaultRealTimeVADOptions=ie;const ce=he=>"audioWorklet"in he&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function ue(he,re,de,pe,Ie){await de.audioWorklet.addModule(he),re.processorOptions={...re.processorOptions??{},frameSamples:pe};const ge=new AudioWorkletNode(de,"vad-helper-worklet",re);return ge.port.onmessage=async ut=>{const Qe=ut.data;if(!(typeof Qe=="object"&&Qe&&"message"in Qe)){console.error("Invalid message event",Qe);return}switch(Qe.message){case b.Message.AudioFrame:{if(!("data"in Qe&&Qe.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const ft=new Float32Array(Qe.data);await Ie(ft);break}}},ge}async function Be(he,re,de){const pe=new B.Resampler({nativeSampleRate:he.sampleRate,targetSampleRate:16e3,targetFrameSize:re});R.log.debug("using script processor");const ge=he.createScriptProcessor(4096,1,1);let ut=!1;return ge.onaudioprocess=async Qe=>{if(!ut){ut=!0;try{const ft=Qe.inputBuffer.getChannelData(0);Qe.outputBuffer.getChannelData(0).fill(0);const Xe=pe.process(ft);for(const mt of Xe)await de(mt)}catch(ft){console.error("Error processing audio:",ft)}finally{ut=!1}}},ge.connect(he.destination),ge}class ke{constructor(re,de,pe,Ie,ge=!1,ut=null,Qe=null,ft=null,Ne=null,Xe=null,mt=null,yt="uninitialized",ot=!1){this.options=re,this.frameProcessor=de,this.model=pe,this.frameSamples=Ie,this.listening=ge,this.errored=ut,this._stream=Qe,this._audioContext=ft,this._vadNode=Ne,this._mediaStreamAudioSourceNode=Xe,this._audioProcessorAdapterType=mt,this.initializationState=yt,this.ownsAudioContext=ot,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=Ye=>{this.initializationState="errored",this.errored=Ye},this.start=async()=>{switch(this.initializationState){case"uninitialized":{R.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ye){throw Ye instanceof Error?this.setErrored(Ye.message):this.setErrored(String(Ye)),Ye}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?ce(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await ue(this.options.baseAssetPath+te,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await Be(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),R.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{R.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:Ye,audioContext:Le,vadNode:rt}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ye);const Ze=new MediaStreamAudioSourceNode(Le,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Ze,Ze.connect(rt);break}case"destroyed":{R.log.warn("start called after destroyed");break}case"errored":{R.log.error("start called after errored");break}default:{R.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ye,mediaStreamAudioSourceNode:Le}=this.getAudioInstances();await this.options.pauseStream(Ye),Le.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{R.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ye}=this.getAudioInstances();Ye instanceof AudioWorkletNode&&Ye.port.postMessage(b.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await this._audioContext?.close()},this.setOptions=Ye=>{this.frameProcessor.setOptions(Ye)},this.processFrame=async Ye=>{await this.frameProcessor.process(Ye,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ye=>{switch(Ye.msg){case b.Message.FrameProcessed:this.options.onFrameProcessed(Ye.probs,Ye.frame);break;case b.Message.SpeechStart:this.options.onSpeechStart();break;case b.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case b.Message.VADMisfire:this.options.onVADMisfire();break;case b.Message.SpeechEnd:this.options.onSpeechEnd(Ye.audio);break}}}static async new(re={}){const de={...(0,c.getDefaultRealTimeVADOptions)(re.model??c.DEFAULT_MODEL),...re};(0,C.validateOptions)(de),c.ort.env.wasm.wasmPaths=de.onnxWASMBasePath,de.ortConfig!==void 0&&de.ortConfig(c.ort);const pe=de.model==="v5"?X:ee,Ie=de.baseAssetPath+pe,ge=de.model==="v5"?U.SileroV5.new:U.SileroLegacy.new;let ut;try{ut=await ge(c.ort,()=>(0,v.defaultModelFetcher)(Ie))}catch(mt){throw console.error(`Encountered an error while loading model file ${Ie}`),mt}const Qe=de.model==="v5"?512:1536,ft=Qe/16,Ne=new C.FrameProcessor(ut.process,ut.reset_state,{positiveSpeechThreshold:de.positiveSpeechThreshold,negativeSpeechThreshold:de.negativeSpeechThreshold,redemptionMs:de.redemptionMs,preSpeechPadMs:de.preSpeechPadMs,minSpeechMs:de.minSpeechMs,submitUserSpeechOnPause:de.submitUserSpeechOnPause},ft),Xe=new ke(de,Ne,ut,Qe);if(de.startOnLoad)try{await Xe.start()}catch(mt){throw console.error("Error starting micVad",mt),mt}return Xe}}c.MicVAD=ke})(Gr)),Gr}var Bp;function Np(){return Bp||(Bp=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.getDefaultRealTimeVADOptions=c.MicVAD=c.DEFAULT_MODEL=c.utils=c.NonRealTimeVAD=c.Message=c.FrameProcessor=c.defaultModelFetcher=c.baseAssetPath=void 0;var r=cf();Object.defineProperty(c,"baseAssetPath",{enumerable:!0,get:function(){return r.baseAssetPath}});var n=Ao();Object.defineProperty(c,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var a=Mo();Object.defineProperty(c,"FrameProcessor",{enumerable:!0,get:function(){return a.FrameProcessor}});var f=Fi();Object.defineProperty(c,"Message",{enumerable:!0,get:function(){return f.Message}});var v=xy();Object.defineProperty(c,"NonRealTimeVAD",{enumerable:!0,get:function(){return v.NonRealTimeVAD}});const C=Ey();c.utils={audioFileToArray:C.audioFileToArray,minFramesForTargetMS:C.minFramesForTargetMS,arrayBufferToBase64:C.arrayBufferToBase64,encodeWAV:C.encodeWAV};var R=ky();Object.defineProperty(c,"DEFAULT_MODEL",{enumerable:!0,get:function(){return R.DEFAULT_MODEL}}),Object.defineProperty(c,"MicVAD",{enumerable:!0,get:function(){return R.MicVAD}}),Object.defineProperty(c,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return R.getDefaultRealTimeVADOptions}})})(so)),so}var Up;function Ry(){return Up||(Up=1,(function(c){Object.defineProperty(c,"__esModule",{value:!0}),c.useMicVAD=c.getDefaultReactRealTimeVADOptions=c.utils=void 0;const r=Np(),n=le;var a=Np();Object.defineProperty(c,"utils",{enumerable:!0,get:function(){return a.utils}});const f={userSpeakingThreshold:.6},v=b=>({...(0,r.getDefaultRealTimeVADOptions)(b),...f});c.getDefaultReactRealTimeVADOptions=v;function C(b){const U=b.model??r.DEFAULT_MODEL,B={...(0,c.getDefaultReactRealTimeVADOptions)(U),...b},te={userSpeakingThreshold:B.userSpeakingThreshold},X={positiveSpeechThreshold:B.positiveSpeechThreshold,negativeSpeechThreshold:B.negativeSpeechThreshold,redemptionMs:B.redemptionMs,preSpeechPadMs:B.preSpeechPadMs,minSpeechMs:B.minSpeechMs,submitUserSpeechOnPause:B.submitUserSpeechOnPause,onFrameProcessed:B.onFrameProcessed,onVADMisfire:B.onVADMisfire,onSpeechStart:B.onSpeechStart,onSpeechEnd:B.onSpeechEnd,onSpeechRealStart:B.onSpeechRealStart,baseAssetPath:B.baseAssetPath,onnxWASMBasePath:B.onnxWASMBasePath,model:B.model,workletOptions:B.workletOptions,getStream:B.getStream,pauseStream:B.pauseStream,resumeStream:B.resumeStream,startOnLoad:B.startOnLoad,processorType:B.processorType};return B.ortConfig&&(X.ortConfig=B.ortConfig),B.audioContext&&(X.audioContext=B.audioContext),[te,X]}function R(b){const[U,B]=C(b),te=b.model??r.DEFAULT_MODEL,[X,ee]=(0,n.useState)(!1),[ie,ce]=(0,n.useState)(!0),[ue,Be]=(0,n.useState)(!1),[ke,he]=(0,n.useState)(!1),[re,de]=(0,n.useState)(null),pe=(0,n.useRef)(B.onFrameProcessed),Ie=(0,n.useRef)(B.onSpeechEnd),ge=(0,n.useRef)(B.onSpeechStart),ut=(0,n.useRef)(B.onSpeechRealStart),Qe=(0,n.useRef)(B.onVADMisfire),ft=(0,n.useRef)(B.getStream);(0,n.useEffect)(()=>{pe.current=B.onFrameProcessed,Ie.current=B.onSpeechEnd,ge.current=B.onSpeechStart,ut.current=B.onSpeechRealStart,Qe.current=B.onVADMisfire},[B.onFrameProcessed,B.onSpeechEnd,B.onSpeechStart,B.onSpeechRealStart,B.onVADMisfire]),(0,n.useEffect)(()=>{ft.current=B.getStream},[B.getStream]);const Ne=B.getStream.toString();(0,n.useEffect)(()=>{let ot=null,Ye=!1;return(async()=>{try{ce(!0),Be(!1);const rt={...B,onFrameProcessed:(Ze,Q)=>{const Me=Ze.isSpeech>U.userSpeakingThreshold;ee(Me),pe.current(Ze,Q)},onSpeechEnd:Ze=>{Ie.current(Ze)},onSpeechStart:()=>{ge.current()},onSpeechRealStart:()=>{ut.current()},onVADMisfire:()=>{Qe.current()},getStream:()=>ft.current()};if(ot=await r.MicVAD.new(rt),Ye){await ot.destroy();return}de(ot),B.startOnLoad&&(await ot.start(),he(!0)),ce(!1)}catch(rt){ce(!1),rt instanceof Error?Be(rt.message):Be(String(rt))}})().catch(()=>{}),function(){Ye=!0,ot&&ot.destroy(),!ie&&!ue&&he(!1)}},[Ne,te]);const Xe=(0,n.useCallback)(async()=>{!ie&&!ue&&(await re?.pause(),he(!1))},[ie,ue,re]),mt=(0,n.useCallback)(async()=>{!ie&&!ue&&(await re?.start(),he(!0))},[ie,ue,re]),yt=(0,n.useCallback)(async()=>{ke?await Xe():await mt()},[ke,Xe,mt]);return{listening:ke,errored:ue,loading:ie,userSpeaking:X,pause:Xe,start:mt,toggle:yt}}c.useMicVAD=R})(no)),no}var Ay=Ry();df();const Fp={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Di=16e3,yf=512,wf=700,My=300,Iy=yf/Di*1e3,Py=Math.ceil(wf/Iy);function Oy(c={}){const{onAudioChunk:r,onAudioEnd:n,onSpeechStart:a,onSpeechEnd:f,onVADMisfire:v,onError:C,interruptOnSpeechStart:R=!0,forceAudioMp4:b=!1}=c,{sendAudioChunk:U,endAudioStream:B,interrupt:te}=Hr(),[X,ee]=le.useState(!1),[ie,ce]=le.useState(null),ue=le.useRef(null),Be=le.useRef(null),ke=le.useRef(null),he=le.useRef(!1),re=le.useRef(null),de=le.useRef([]),pe=le.useCallback(()=>{if(!(typeof window>"u")){if(!ke.current){const Le=window.AudioContext||window.webkitAudioContext;if(!Le)return;ke.current=new Le({sampleRate:Di})}ke.current.state==="suspended"&&ke.current.resume().catch(()=>{})}},[]);le.useEffect(()=>{typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia||navigator.mediaDevices.getUserMedia({audio:Fp}).then(Le=>{ue.current=Le,ce(null)}).catch(Le=>{ce("permission_denied"),C?.(Le)})},[C]);const Ie=le.useCallback(async()=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone APIs are unavailable in this browser");if(ue.current&&ue.current.getTracks()[0]?.readyState==="live")return ue.current;const Le=await navigator.mediaDevices.getUserMedia({audio:Fp});return ue.current=Le,ce(null),Le},[]),ge=le.useCallback(async Le=>{Le.getTracks().forEach(rt=>{rt.enabled=!1})},[]),ut=le.useCallback(async()=>ue.current&&ue.current.getTracks()[0]?.readyState==="live"?(ue.current.getTracks().forEach(Le=>{Le.enabled=!0}),ue.current):Ie(),[Ie]),Qe=le.useCallback(()=>{const Le=de.current;if(!Le.length)return{samples:new Float32Array(0),duration:0};const rt=Le.reduce((Me,et)=>Me+et.length,0),Ze=new Float32Array(rt);let Q=0;for(const Me of Le)Ze.set(Me,Q),Q+=Me.length;return{samples:Ze,duration:rt/Di}},[]),ft=le.useCallback(()=>{const Le=ue.current,rt=ke.current;if(!Le||!rt||Be.current)return;const{samples:Ze,duration:Q}=Qe();de.current=[];const Me=!b&&MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/mp4")?"audio/mp4":"";try{const et=rt.createMediaStreamDestination();if(Ze.length>0){const Ct=rt.createBuffer(1,Ze.length,Di);Ct.getChannelData(0).set(Ze);const lt=rt.createBufferSource();lt.buffer=Ct,lt.connect(et),lt.start(0)}const gt=rt.createMediaStreamSource(Le);if(Q>0){const Ct=rt.createDelay(Q+.1);Ct.delayTime.value=Q,gt.connect(Ct).connect(et)}else gt.connect(et);const Gt=new MediaRecorder(et.stream,Me?{mimeType:Me}:{});Gt.ondataavailable=async Ct=>{if(!Ct.data||Ct.data.size<=0)return;const lt=await Ct.data.arrayBuffer();r?r(lt):U(lt)},Be.current=Gt,Gt.start(100)}catch(et){C?.(et)}},[Qe,b,r,C,U]),Ne=le.useCallback(()=>{const Le=Be.current;if(Le){if(Be.current=null,Le.state==="inactive"){n?n():B();return}Le.onstop=()=>{n?n():B()},Le.stop()}},[B,n]),Xe=le.useCallback(()=>{const Le=Be.current;if(Le&&(Be.current=null,Le.state!=="inactive"))try{Le.stop()}catch{}},[]),mt=le.useCallback(()=>{ke.current&&(ke.current.close().catch(()=>{}),ke.current=null)},[]),yt=le.useCallback(()=>{ue.current&&(ue.current.getTracks().forEach(Le=>Le.stop()),ue.current=null)},[]),ot=Ay.useMicVAD({model:"v5",startOnLoad:!1,processorType:"auto",positiveSpeechThreshold:.5,negativeSpeechThreshold:.3,redemptionMs:800,preSpeechPadMs:wf,minSpeechMs:150,submitUserSpeechOnPause:!1,userSpeakingThreshold:.7,workletOptions:{processorOptions:{frameSamples:yf}},baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.30/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.24.1/dist/",ortConfig:Le=>{Le.env.wasm.numThreads=1,Le.env.logLevel="error"},getStream:Ie,pauseStream:ge,resumeStream:ut,onFrameProcessed:(Le,rt)=>{if(!rt)return;const Ze=de.current;Ze.push(new Float32Array(rt)),Ze.length>Py&&Ze.shift()},onSpeechStart:()=>{he.current||(re.current&&(clearTimeout(re.current),re.current=null),ee(!0),R&&te(),ft(),a?.())},onSpeechEnd:()=>{re.current=setTimeout(()=>{ee(!1),Ne(),he.current=!0,setTimeout(()=>{he.current=!1},300),f?.()},My)},onVADMisfire:()=>{re.current&&(clearTimeout(re.current),re.current=null),ee(!1),Xe(),v?.()}}),Ye=le.useCallback(()=>{pe(),ot.listening&&Be.current&&(re.current&&(clearTimeout(re.current),re.current=null),ee(!1),Ne()),ot.toggle()},[Ne,pe,ot]);return le.useEffect(()=>()=>{re.current&&clearTimeout(re.current),Xe(),mt(),yt()},[mt,yt,Xe]),{isListening:ot.listening,isLoading:ot.loading,isSpeaking:X,micError:ie,toggle:Ye,start:ot.start,pause:ot.pause,userSpeaking:ot.userSpeaking}}const zy=()=>Hr(),vf=()=>{const{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:b,terminateSession:U,interrupt:B,refreshSessionActivity:te,clearSessionHistory:X,changeSessionLanguage:ee}=Hr();return{connectionState:c,isConnected:r,isSessionReady:n,error:a,reconnectAttempt:f,session:v,initializeSession:C,joinDesktopSession:R,disconnect:b,terminateSession:U,interrupt:B,refreshSessionActivity:te,clearSessionHistory:X,changeSessionLanguage:ee}},Dy=()=>{const{messages:c,sendTextMessage:r,clearMessages:n}=Hr();return{messages:c,sendTextMessage:r,clearMessages:n}},Ly=()=>{const{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}=Hr();return{sendAudioChunk:c,endAudioStream:r,isAudioPlaying:n,transcript:a,partialTranscript:f,interrupt:v,resumeAudioPlayback:C,attachAudioElement:R}},bf=()=>{const{session:c,isAvatarSpeaking:r,cloudStream:n,setCloudStreamState:a}=Hr(),f=n?.state||Qt.IDLE;return{streamingUrl:c.streamingUrl,isAvatarSpeaking:r,speakingSource:"avatar_events",isCloudAvatar:c.agentType===qr.CLOUD_AVATAR,isDesktopAvatar:c.agentType===qr.DESKTOP_AVATAR,cloudStreamState:f,cloudStreamError:n?.error||null,isCloudStreamConnected:f===Qt.CONNECTED,isCloudStreamLoading:f===Qt.CONNECTING||f===Qt.LOADING,setCloudStreamState:a}},By=c=>{const{attachAudioElement:r,resumeAudioPlayback:n}=Hr();le.useEffect(()=>{if(!c?.current)return;r(c.current);const a=()=>{n()},f=c.current;return f.addEventListener("click",a),f.addEventListener("touchstart",a),()=>{f.removeEventListener("click",a),f.removeEventListener("touchstart",a),r(null)}},[r,c,n])};function Ny({connect:c=!0,session:r,onError:n,onInitialized:a,children:f}){const{initializeSession:v,joinDesktopSession:C,disconnect:R}=vf(),b=le.useRef(!1);return le.useEffect(()=>{if(!c||b.current)return;let U=!1;return b.current=!0,(async()=>{try{if(r?.mode==="join_desktop"){const X=await C({uniqueId:r.uniqueId});U||a?.(X);return}const te=await v({apiKey:r?.apiKey,publicChatId:r?.publicChatId,agentId:r?.agentId,language:r?.language||"en"});U||a?.(te)}catch(te){U||n?.(te)}})(),()=>{U=!0,R(),b.current=!1}},[c,R,v,C,n,a,r]),f}function Uy({children:c,wsUrl:r,restUrl:n,session:a,connect:f=!0,reconnectOptions:v,enableAudio:C=!0,pcmOptions:R,debug:b=!1,onError:U,onInitialized:B}){return ar.jsx(uf,{wsUrl:r,restUrl:n,reconnectOptions:v,enableAudio:C,pcmOptions:R,debug:b,children:ar.jsx(Ny,{connect:f,session:a,onError:U,onInitialized:B,children:c})})}var lo={exports:{}},Vp;function Fy(){return Vp||(Vp=1,(function(c){const r={};r.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},r.localCName=r.generateIdentifier(),r.splitLines=function(n){return n.trim().split(`
|
|
2859
2859
|
`).map(a=>a.trim())},r.splitSections=function(n){return n.split(`
|
|
2860
2860
|
m=`).map((f,v)=>(v>0?"m="+f:f).trim()+`\r
|
|
2861
2861
|
`)},r.getDescription=function(n){const a=r.splitSections(n);return a&&a[0]},r.getMediaSections=function(n){const a=r.splitSections(n);return a.shift(),a},r.matchPrefix=function(n,a){return r.splitLines(n).filter(f=>f.indexOf(a)===0)},r.parseCandidate=function(n){let a;n.indexOf("a=candidate:")===0?a=n.substring(12).split(" "):a=n.substring(10).split(" ");const f={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let v=8;v<a.length;v+=2)switch(a[v]){case"raddr":f.relatedAddress=a[v+1];break;case"rport":f.relatedPort=parseInt(a[v+1],10);break;case"tcptype":f.tcpType=a[v+1];break;case"ufrag":f.ufrag=a[v+1],f.usernameFragment=a[v+1];break;default:f[a[v]]===void 0&&(f[a[v]]=a[v+1]);break}return f},r.writeCandidate=function(n){const a=[];a.push(n.foundation);const f=n.component;f==="rtp"?a.push(1):f==="rtcp"?a.push(2):a.push(f),a.push(n.protocol.toUpperCase()),a.push(n.priority),a.push(n.address||n.ip),a.push(n.port);const v=n.type;return a.push("typ"),a.push(v),v!=="host"&&n.relatedAddress&&n.relatedPort&&(a.push("raddr"),a.push(n.relatedAddress),a.push("rport"),a.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(a.push("tcptype"),a.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(a.push("ufrag"),a.push(n.usernameFragment||n.ufrag)),"candidate:"+a.join(" ")},r.parseIceOptions=function(n){return n.substring(14).split(" ")},r.parseRtpMap=function(n){let a=n.substring(9).split(" ");const f={payloadType:parseInt(a.shift(),10)};return a=a[0].split("/"),f.name=a[0],f.clockRate=parseInt(a[1],10),f.channels=a.length===3?parseInt(a[2],10):1,f.numChannels=f.channels,f},r.writeRtpMap=function(n){let a=n.payloadType;n.preferredPayloadType!==void 0&&(a=n.preferredPayloadType);const f=n.channels||n.numChannels||1;return"a=rtpmap:"+a+" "+n.name+"/"+n.clockRate+(f!==1?"/"+f:"")+`\r
|
|
@@ -2886,7 +2886,7 @@ a=ice-pwd:`+n.password+`\r
|
|
|
2886
2886
|
o=`+(f||"thisisadapterortc")+" "+v+" "+C+` IN IP4 127.0.0.1\r
|
|
2887
2887
|
s=-\r
|
|
2888
2888
|
t=0 0\r
|
|
2889
|
-
`},r.getDirection=function(n,a){const f=r.splitLines(n);for(let v=0;v<f.length;v++)switch(f[v]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[v].substring(2)}return a?r.getDirection(a):"sendrecv"},r.getKind=function(n){return r.splitLines(n)[0].split(" ")[0].substring(2)},r.isRejected=function(n){return n.split(" ",2)[1]==="0"},r.parseMLine=function(n){const f=r.splitLines(n)[0].substring(2).split(" ");return{kind:f[0],port:parseInt(f[1],10),protocol:f[2],fmt:f.slice(3).join(" ")}},r.parseOLine=function(n){const f=r.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:f[0],sessionId:f[1],sessionVersion:parseInt(f[2],10),netType:f[3],addressType:f[4],address:f[5]}},r.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const a=r.splitLines(n);for(let f=0;f<a.length;f++)if(a[f].length<2||a[f].charAt(1)!=="=")return!1;return!0},c.exports=r})(lo)),lo.exports}var Gp=Fy(),$r,
|
|
2889
|
+
`},r.getDirection=function(n,a){const f=r.splitLines(n);for(let v=0;v<f.length;v++)switch(f[v]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return f[v].substring(2)}return a?r.getDirection(a):"sendrecv"},r.getKind=function(n){return r.splitLines(n)[0].split(" ")[0].substring(2)},r.isRejected=function(n){return n.split(" ",2)[1]==="0"},r.parseMLine=function(n){const f=r.splitLines(n)[0].substring(2).split(" ");return{kind:f[0],port:parseInt(f[1],10),protocol:f[2],fmt:f.slice(3).join(" ")}},r.parseOLine=function(n){const f=r.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:f[0],sessionId:f[1],sessionVersion:parseInt(f[2],10),netType:f[3],addressType:f[4],address:f[5]}},r.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const a=r.splitLines(n);for(let f=0;f<a.length;f++)if(a[f].length<2||a[f].charAt(1)!=="=")return!1;return!0},c.exports=r})(lo)),lo.exports}var Gp=Fy(),$r,Pt,Li={d:(c,r)=>{for(var n in r)Li.o(r,n)&&!Li.o(c,n)&&Object.defineProperty(c,n,{enumerable:!0,get:r[n]})},o:(c,r)=>Object.prototype.hasOwnProperty.call(c,r)},Se={};Li.d(Se,{Dz:()=>nm,g$:()=>Ef,Lt:()=>$f,Q9:()=>xf,qf:()=>_o,hV:()=>lm,z$:()=>Ow,J0:()=>To,De:()=>ow,$C:()=>Dn,al:()=>zf,_W:()=>Df,Gv:()=>Xf,m:()=>Yf,tz:()=>Of,Nu:()=>am,zg:()=>cm,vp:()=>rm,vU:()=>K,wF:()=>Wf,rv:()=>sm,Nh:()=>im,ss:()=>dm,qW:()=>Jf,QL:()=>Qf,cf:()=>pm,eM:()=>qf,Yd:()=>T,Tk:()=>Te,iM:()=>_f,qy:()=>jr,ce:()=>Yy,sK:()=>we,Ok:()=>St,q5:()=>om,g:()=>Pw,xl:()=>Vf,I:()=>Gf,bx:()=>So,dD:()=>em,Ib:()=>li,Az:()=>It,Iw:()=>Ir,qY:()=>bo,db:()=>Tf,mR:()=>ai,Tn:()=>vo,rV:()=>Hf,gh:()=>Bf,Mi:()=>Nf,j:()=>Uf,YB:()=>Ff,Yt:()=>Kf,i5:()=>jf,x_:()=>Wr,Am:()=>$o,eR:()=>Cf,r8:()=>Lf,u3:()=>hm,vd:()=>Rf,iV:()=>Mf,jZ:()=>Af,SW:()=>Pf,ZH:()=>If,Ni:()=>fm,lh:()=>kf,ZP:()=>tm,bq:()=>Sf,$f:()=>mm,eu:()=>Zf,Ax:()=>rw,Mc:()=>tw});class T{static GetStackTrace(){const r=new Error;let n="No Stack Available for this browser";return r.stack&&(n=r.stack.toString().replace(/Error/g,"")),n}static SetLoggerVerbosity(r){this.verboseLogLevel!=null&&(this.verboseLogLevel=r)}static Log(r,n,a){if(a>this.verboseLogLevel)return;const f=`Level: Log
|
|
2890
2890
|
Msg: ${n}
|
|
2891
2891
|
Caller: ${r}`;console.log(f)}static Info(r,n,a){if(a>this.verboseLogLevel)return;const f=`Level: Info
|
|
2892
2892
|
Msg: ${n}`;console.info(f)}static Error(r,n){const a=`Level: Error
|
|
@@ -2895,8 +2895,8 @@ Caller: ${r}`;console.error(a)}static Warning(r,n){const a=`Level: Warning
|
|
|
2895
2895
|
Caller: ${r}
|
|
2896
2896
|
Msg: ${n}`;console.warn(a)}}T.verboseLogLevel=5,(function(c){c.LIST_STREAMERS="listStreamers",c.SUBSCRIBE="subscribe",c.UNSUBSCRIBE="unsubscribe",c.ICE_CANDIDATE="iceCandidate",c.OFFER="offer",c.ANSWER="answer",c.DATACHANNELREQUEST="dataChannelRequest",c.SFURECVDATACHANNELREADY="peerDataChannelsReady",c.PONG="pong"})($r||($r={}));class jr{sendFilter(r,n){return n}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2897
2897
|
`+JSON.stringify(this,this.sendFilter,4),6),JSON.stringify(this,this.sendFilter)}}class Vy extends jr{constructor(){super(),this.type=$r.LIST_STREAMERS}}class Gy extends jr{constructor(r){super(),this.type=$r.SUBSCRIBE,this.streamerId=r}}class qy extends jr{constructor(){super(),this.type=$r.UNSUBSCRIBE}}class Wy extends jr{constructor(r){super(),this.type=$r.PONG,this.time=r}}class Hy extends jr{constructor(r,n){super(),this.type=$r.OFFER,this.minBitrate=0,this.maxBitrate=0,r&&(this.type=r.type,this.sdp=r.sdp,this.minBitrate=n.minBitrateBps,this.maxBitrate=n.maxBitrateBps)}sendFilter(r,n){if(r!="minBitrate"&&r!="maxBitrate"||!(n<=0))return n}}class jy extends jr{constructor(r,n){super(),this.type=$r.ANSWER,this.minBitrate=0,this.maxBitrate=0,r&&(this.type=r.type,this.sdp=r.sdp,this.minBitrate=n.minBitrateBps,this.maxBitrate=n.maxBitrateBps)}sendFilter(r,n){if(r!="minBitrate"&&r!="maxBitrate"||!(n<=0))return n}}class Ky extends jr{constructor(){super(),this.type=$r.DATACHANNELREQUEST}}class Qy extends jr{constructor(){super(),this.type=$r.SFURECVDATACHANNELREADY}}class Xy{constructor(r){this.type=$r.ICE_CANDIDATE,this.candidate=r}payload(){return T.Log(T.GetStackTrace(),`Sending =>
|
|
2898
|
-
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(c){c.CONFIG="config",c.STREAMER_LIST="streamerList",c.STREAMER_ID_CHANGED="streamerIDChanged",c.PLAYER_COUNT="playerCount",c.OFFER="offer",c.ANSWER="answer",c.ICE_CANDIDATE="iceCandidate",c.PEER_DATA_CHANNELS="peerDataChannels",c.PING="ping",c.WARNING="warning"})(
|
|
2899
|
-
`+JSON.stringify(JSON.parse(r.data),void 0,4),6),this.signallingProtocol.handleMessage(n.type,r.data)}handleOnOpen(r){T.Log(T.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){T.Error(T.GetStackTrace(),"WebSocket error")}handleOnClose(r){T.Log(T.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(r.code)+" - "+r.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:r}))}requestStreamerList(){const r=new Vy;this.webSocket.send(r.payload())}sendSubscribe(r){const n=new Gy(r);this.webSocket.send(n.payload())}sendUnsubscribe(){const r=new qy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,n){const a=new Hy(r,n);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,n){const a=new jy(r,n);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Ky;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Qy;this.webSocket.send(r.payload())}sendIceCandidate(r){if(T.Log(T.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const n=new Xy(r);this.webSocket.send(n.payload())}}close(){var r;(r=this.webSocket)===null||r===void 0||r.close()}onConfig(r){}onStreamerList(r){}onStreamerIDChanged(r){}onIceCandidate(r){}onWebRtcAnswer(r){}onWebRtcOffer(r){}onWebRtcPeerDataChannels(r){}onPlayerCount(r){}}class Jy{constructor(r){this.videoElementProvider=r,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(r){if(T.Log(T.GetStackTrace(),"handleOnTrack "+JSON.stringify(r.streams),6),r.track.id=="probator")return;const n=this.videoElementProvider.getVideoElement();if(r.track&&T.Log(T.GetStackTrace(),"Got track - "+r.track.kind+" id="+r.track.id+" readyState="+r.track.readyState,6),r.track.kind!="audio")return r.track.kind=="video"&&n.srcObject!==r.streams[0]?(n.srcObject=r.streams[0],void T.Log(T.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(r.streams[0])}CreateAudioTrack(r){const n=this.videoElementProvider.getVideoElement();n.srcObject!=r&&n.srcObject&&n.srcObject!==r&&(this.audioElement.srcObject=r,T.Log(T.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class Zy{constructor(r){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=r,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(r){const n=btoa(r.reduce(((a,f)=>a+String.fromCharCode(f)),""));this.imageElement.src="data:image/jpeg;base64,"+n}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let r=0,n=0,a=0,f=0;const v=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;v<C?(r=this.rootDiv.clientWidth,n=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-n)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),n=this.rootDiv.clientHeight,a=0,f=Math.floor(.5*(this.rootDiv.clientWidth-r))),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=r+"px",this.imageElement.style.height=n+"px",this.imageElement.style.left=f+"px",this.imageElement.style.top=a+"px"}}}class ew{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Zy(r)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(r,n){this.freezeFrame.updateImageElementSource(r),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),n()}}processFreezeFrameMessage(r,n){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(r.slice(1,5).buffer).getInt32(0,!0);const a=r.slice(5);if(this.jpeg){const f=new Uint8Array(this.jpeg.length+a.length);f.set(this.jpeg,0),f.set(a,this.jpeg.length),this.jpeg=f}else this.jpeg=a,this.receiving=!0,T.Log(T.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,T.Log(T.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,n)):this.jpeg.length>this.size&&(T.Error(T.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class li{constructor(r,n,a,f,v=(()=>{})){this.onChange=v,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=n,this.value=f}set label(r){this._label=r,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(r){this._value=r,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class At extends li{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const b=this.getUrlParamFlag();this.flag=b}else this.flag=f;this.useUrlParams=v}getUrlParamFlag(){const r=new URLSearchParams(window.location.search);return!!r.has(this.id)&&r.get(this.id)!=="false"&&r.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);this.flag===!0?r.set(this.id,"true"):r.set(this.id,"false"),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(r){this.value=r}}class Ir extends li{constructor(r,n,a,f,v,C,R,b=(()=>{})){super(r,n,a,C,b),this._min=f,this._max=v;const U=new URLSearchParams(window.location.search);if(R&&U.has(this.id)){const B=Number.parseFloat(U.get(this.id));this.number=Number.isNaN(B)?C:B}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class Tf extends li{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const b=this.getUrlParamText();this.text=b}else this.text=f;this.useUrlParams=v}getUrlParamText(){var r;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(r=n.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.text),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}get text(){return this.value}set text(r){this.value=r}}class bo extends li{constructor(r,n,a,f,v,C,R=(()=>{})){super(r,n,a,f,R),this.options=v;const b=new URLSearchParams(window.location.search),U=C&&b.has(this.id)?this.getUrlParamText():f;this.selected=U,this.useUrlParams=C}getUrlParamText(){var r;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(r=n.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.selected),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}addOnChangedListener(r){this.onChange=r}get options(){return this._options}set options(r){this._options=r,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(r){let n=this.options.filter((a=>a.indexOf(r)!==-1));n.length?this.value=n[0]:(n=this.options.filter((a=>a.indexOf(r.split(" ")[0])!==-1)),n.length&&(this.value=n[0]))}}class $f extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class _o extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class xf extends Event{constructor(){super("afkWarningDeactivate")}}class Ef extends Event{constructor(){super("afkTimedOut")}}class Cf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class kf extends Event{constructor(){super("webRtcSdp")}}class Rf extends Event{constructor(){super("webRtcAutoConnect")}}class Af extends Event{constructor(){super("webRtcConnecting")}}class Mf extends Event{constructor(){super("webRtcConnected")}}class If extends Event{constructor(){super("webRtcFailed")}}class Pf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Of extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class zf extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Df extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Lf extends Event{constructor(){super("videoInitialized")}}class Bf extends Event{constructor(){super("streamLoading")}}class Nf extends Event{constructor(){super("streamConnect")}}class Uf extends Event{constructor(){super("streamDisconnect")}}class Ff extends Event{constructor(){super("streamReconnect")}}class Vf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Gf extends Event{constructor(){super("playStream")}}class So extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class qf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Wf extends Event{constructor(){super("hideFreezeFrame")}}class Hf extends Event{constructor(r){super("statsReceived"),this.data=r}}class jf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Kf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class Qf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Xf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Yf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Jf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ai extends Event{constructor(r){super("settingsChanged"),this.data=r}}class tw extends Event{constructor(){super("xrSessionStarted")}}class rw extends Event{constructor(){super("xrSessionEnded")}}class Zf extends Event{constructor(r){super("xrFrame"),this.data=r}}class em extends Event{constructor(r){super("playerCount"),this.data=r}}class tm extends Event{constructor(){super("webRtcTCPRelayDetected")}}class rm extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,n){super.addEventListener(r,n)}removeEventListener(r,n){super.removeEventListener(r,n)}}class K{}K.AutoConnect="AutoConnect",K.AutoPlayVideo="AutoPlayVideo",K.AFKDetection="TimeoutIfIdle",K.BrowserSendOffer="OfferToReceive",K.HoveringMouseMode="HoveringMouse",K.ForceMonoAudio="ForceMonoAudio",K.ForceTURN="ForceTURN",K.FakeMouseWithTouches="FakeMouseWithTouches",K.IsQualityController="ControlsQuality",K.MatchViewportResolution="MatchViewportRes",K.StartVideoMuted="StartVideoMuted",K.SuppressBrowserKeys="SuppressBrowserKeys",K.UseMic="UseMic",K.KeyboardInput="KeyboardInput",K.MouseInput="MouseInput",K.TouchInput="TouchInput",K.GamepadInput="GamepadInput",K.XRControllerInput="XRControllerInput",K.WaitForStreamer="WaitForStreamer",K.HideUI="HideUI";const nw=c=>Object.getOwnPropertyNames(K).some((r=>K[r]===c));class we{}we.AFKTimeoutSecs="AFKTimeout",we.AFKCountdownSecs="AFKCountdown",we.MinQP="MinQP",we.MaxQP="MaxQP",we.WebRTCFPS="WebRTCFPS",we.WebRTCMinBitrate="WebRTCMinBitrate",we.WebRTCMaxBitrate="WebRTCMaxBitrate",we.MaxReconnectAttempts="MaxReconnectAttempts",we.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const sw=c=>Object.getOwnPropertyNames(we).some((r=>we[r]===c));class Wr{}Wr.SignallingServerUrl="ss";const iw=c=>Object.getOwnPropertyNames(Wr).some((r=>Wr[r]===c));class St{}St.PreferredCodec="PreferredCodec",St.StreamerId="StreamerId";const aw=c=>Object.getOwnPropertyNames(St).some((r=>St[r]===c));class ow{constructor(r={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:n,useUrlParams:a}=r;this._useUrlParams=!!a,this.populateDefaultSettings(this._useUrlParams,n)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(r,n){this.textParameters.set(Wr.SignallingServerUrl,new Tf(Wr.SignallingServerUrl,"Signalling url","Url of the signalling server",n&&n.hasOwnProperty(Wr.SignallingServerUrl)?n[Wr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(St.StreamerId,new bo(St.StreamerId,"Streamer ID","The ID of the streamer to stream.",n&&n.hasOwnProperty(St.StreamerId)?n[St.StreamerId]:"",[],r)),this.optionParameters.set(St.PreferredCodec,new bo(St.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",n&&n.hasOwnProperty(St.PreferredCodec)?[n[St.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((v=>{const C=v.mimeType.split("/")[1]+" "+(v.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(K.AutoConnect,new At(K.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!n||!n.hasOwnProperty(K.AutoConnect))&&n[K.AutoConnect],r)),this.flags.set(K.AutoPlayVideo,new At(K.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!n||!n.hasOwnProperty(K.AutoPlayVideo)||n[K.AutoPlayVideo],r)),this.flags.set(K.BrowserSendOffer,new At(K.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!n||!n.hasOwnProperty(K.BrowserSendOffer))&&n[K.BrowserSendOffer],r)),this.flags.set(K.UseMic,new At(K.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!n||!n.hasOwnProperty(K.UseMic))&&n[K.UseMic],r)),this.flags.set(K.StartVideoMuted,new At(K.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!n||!n.hasOwnProperty(K.StartVideoMuted))&&n[K.StartVideoMuted],r)),this.flags.set(K.SuppressBrowserKeys,new At(K.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!n||!n.hasOwnProperty(K.SuppressBrowserKeys)||n[K.SuppressBrowserKeys],r)),this.flags.set(K.IsQualityController,new At(K.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!n||!n.hasOwnProperty(K.IsQualityController)||n[K.IsQualityController],r)),this.flags.set(K.ForceMonoAudio,new At(K.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!n||!n.hasOwnProperty(K.ForceMonoAudio))&&n[K.ForceMonoAudio],r)),this.flags.set(K.ForceTURN,new At(K.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!n||!n.hasOwnProperty(K.ForceTURN))&&n[K.ForceTURN],r)),this.flags.set(K.AFKDetection,new At(K.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!n||!n.hasOwnProperty(K.AFKDetection))&&n[K.AFKDetection],r)),this.flags.set(K.MatchViewportResolution,new At(K.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!n||!n.hasOwnProperty(K.MatchViewportResolution))&&n[K.MatchViewportResolution],r)),this.flags.set(K.HoveringMouseMode,new At(K.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!n||!n.hasOwnProperty(K.HoveringMouseMode))&&n[K.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(K.FakeMouseWithTouches,new At(K.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!n||!n.hasOwnProperty(K.FakeMouseWithTouches))&&n[K.FakeMouseWithTouches],r)),this.flags.set(K.KeyboardInput,new At(K.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!n||!n.hasOwnProperty(K.KeyboardInput)||n[K.KeyboardInput],r)),this.flags.set(K.MouseInput,new At(K.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!n||!n.hasOwnProperty(K.MouseInput)||n[K.MouseInput],r)),this.flags.set(K.TouchInput,new At(K.TouchInput,"Touch input","If enabled, send touch events to streamer",!n||!n.hasOwnProperty(K.TouchInput)||n[K.TouchInput],r)),this.flags.set(K.GamepadInput,new At(K.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!n||!n.hasOwnProperty(K.GamepadInput)||n[K.GamepadInput],r)),this.flags.set(K.XRControllerInput,new At(K.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!n||!n.hasOwnProperty(K.XRControllerInput)||n[K.XRControllerInput],r)),this.flags.set(K.WaitForStreamer,new At(K.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!n||!n.hasOwnProperty(K.WaitForStreamer)||n[K.WaitForStreamer],r)),this.flags.set(K.HideUI,new At(K.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!n||!n.hasOwnProperty(K.HideUI))&&n[K.HideUI],r)),this.numericParameters.set(we.AFKTimeoutSecs,new Ir(we.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,n&&n.hasOwnProperty(we.AFKTimeoutSecs)?n[we.AFKTimeoutSecs]:120,r)),this.numericParameters.set(we.AFKCountdownSecs,new Ir(we.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,r)),this.numericParameters.set(we.MaxReconnectAttempts,new Ir(we.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,n&&n.hasOwnProperty(we.MaxReconnectAttempts)?n[we.MaxReconnectAttempts]:3,r)),this.numericParameters.set(we.MinQP,new Ir(we.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(we.MinQP)?n[we.MinQP]:0,r)),this.numericParameters.set(we.MaxQP,new Ir(we.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(we.MaxQP)?n[we.MaxQP]:51,r)),this.numericParameters.set(we.WebRTCFPS,new Ir(we.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,n&&n.hasOwnProperty(we.WebRTCFPS)?n[we.WebRTCFPS]:60,r)),this.numericParameters.set(we.WebRTCMinBitrate,new Ir(we.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(we.WebRTCMinBitrate)?n[we.WebRTCMinBitrate]:0,r)),this.numericParameters.set(we.WebRTCMaxBitrate,new Ir(we.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(we.WebRTCMaxBitrate)?n[we.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(we.StreamerAutoJoinInterval,new Ir(we.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,n&&n.hasOwnProperty(we.StreamerAutoJoinInterval)?n[we.StreamerAutoJoinInterval]:3e3,r))}_addOnNumericSettingChangedListener(r,n){this.numericParameters.has(r)&&this.numericParameters.get(r).addOnChangedListener(n)}_addOnOptionSettingChangedListener(r,n){this.optionParameters.has(r)&&this.optionParameters.get(r).addOnChangedListener(n)}getNumericSettingValue(r){if(this.numericParameters.has(r))return this.numericParameters.get(r).number;throw new Error(`There is no numeric setting with the id of ${r}`)}getTextSettingValue(r){if(this.textParameters.has(r))return this.textParameters.get(r).value;throw new Error(`There is no numeric setting with the id of ${r}`)}setNumericSetting(r,n){if(!this.numericParameters.has(r))throw new Error(`There is no numeric setting with the id of ${r}`);this.numericParameters.get(r).number=n}_addOnSettingChangedListener(r,n){this.flags.has(r)&&(this.flags.get(r).onChange=n)}_addOnTextSettingChangedListener(r,n){this.textParameters.has(r)&&(this.textParameters.get(r).onChange=n)}getSettingOption(r){return this.optionParameters.get(r)}isFlagEnabled(r){return this.flags.get(r).flag}setFlagEnabled(r,n){this.flags.has(r)?this.flags.get(r).flag=n:T.Warning(T.GetStackTrace(),`Cannot toggle flag called ${r} - it does not exist in the Config.flags map.`)}setTextSetting(r,n){this.textParameters.has(r)?this.textParameters.get(r).text=n:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(r,n){this.optionParameters.has(r)?this.optionParameters.get(r).options=n:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(r,n){if(this.optionParameters.has(r)){const a=this.optionParameters.get(r),f=a.options;f.includes(n)||(f.push(n),a.options=f),a.selected=n}else T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(r,n){this.flags.has(r)?this.flags.get(r).label=n:T.Warning(T.GetStackTrace(),`Cannot set label for flag called ${r} - it does not exist in the Config.flags map.`)}setSettings(r){for(const n of Object.keys(r))nw(n)?this.setFlagEnabled(n,r[n]):sw(n)?this.setNumericSetting(n,r[n]):iw(n)?this.setTextSetting(n,r[n]):aw(n)&&this.setOptionSettingValue(n,r[n])}getSettings(){const r={};for(const[n,a]of this.flags.entries())r[n]=a.flag;for(const[n,a]of this.numericParameters.entries())r[n]=a.number;for(const[n,a]of this.textParameters.entries())r[n]=a.text;for(const[n,a]of this.optionParameters.entries())r[n]=a.selected;return r}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(r){for(const n of this.flags.keys()){const a=this.flags.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"flag",value:f,target:a})))}for(const n of this.numericParameters.keys()){const a=this.numericParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"number",value:f,target:a})))}for(const n of this.textParameters.keys()){const a=this.textParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"text",value:f,target:a})))}for(const n of this.optionParameters.keys()){const a=this.optionParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"option",value:f,target:a})))}}}var Dn;(function(c){c[c.LockedMouse=0]="LockedMouse",c[c.HoveringMouse=1]="HoveringMouse"})(Dn||(Dn={}));class nm{constructor(r,n,a){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=r,this.pixelStreaming=n,this.onDismissAfk=a,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new xf))}startAfkWarningTimer(){this.config.getNumericSettingValue(we.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(K.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(K.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(we.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new $f({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(we.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new _o({countDown:this.countDown})),this.config.isFlagEnabled(K.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new Ef),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new _o({countDown:this.countDown}))}),1e3)}}class qp{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(r,n,a){this.peerConnection=r,this.label=n,this.datachannelOptions=a,a==null&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=r=>this.handleOnOpen(r),this.dataChannel.onclose=r=>this.handleOnClose(r),this.dataChannel.onmessage=r=>this.handleOnMessage(r),this.dataChannel.onerror=r=>this.handleOnError(r)}handleOnOpen(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}handleOnClose(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}handleOnMessage(r){T.Log(T.GetStackTrace(),`Data Channel (${this.label}) message: ${r}`,8)}handleOnError(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) error: ${r}`,7),this.onError((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}onOpen(r,n){}onClose(r,n){}onError(r,n){}}class sm{}class im{}class am{}class To{}class om{}class lw{}class uw{}class lm{constructor(){this.inboundVideoStats=new im,this.inboundAudioStats=new sm,this.DataChannelStats=new am,this.outBoundVideoStats=new om,this.sessionStats=new lw,this.streamStats=new uw,this.codecs=new Map}processStats(r){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,r.forEach((n=>{switch(n.type){case"candidate-pair":this.handleCandidatePair(n);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(n);break;case"data-channel":this.handleDataChannel(n);break;case"inbound-rtp":this.handleInBoundRTP(n);break;case"local-candidate":this.handleLocalCandidate(n);break;case"remote-candidate":this.handleRemoteCandidate(n);break;case"remote-outbound-rtp":this.handleRemoteOutBound(n);break;case"track":this.handleTrack(n);break;case"transport":this.handleTransport(n);break;case"stream":this.handleStream(n);break;default:T.Error(T.GetStackTrace(),"unhandled Stat Type"),T.Log(T.GetStackTrace(),n)}}))}handleStream(r){this.streamStats=r}handleCandidatePair(r){this.candidatePairs.push(r)}handleDataChannel(r){this.DataChannelStats.bytesReceived=r.bytesReceived,this.DataChannelStats.bytesSent=r.bytesSent,this.DataChannelStats.dataChannelIdentifier=r.dataChannelIdentifier,this.DataChannelStats.id=r.id,this.DataChannelStats.label=r.label,this.DataChannelStats.messagesReceived=r.messagesReceived,this.DataChannelStats.messagesSent=r.messagesSent,this.DataChannelStats.protocol=r.protocol,this.DataChannelStats.state=r.state,this.DataChannelStats.timestamp=r.timestamp}handleLocalCandidate(r){const n=new To;n.label="local-candidate",n.address=r.address,n.port=r.port,n.protocol=r.protocol,n.candidateType=r.candidateType,n.id=r.id,n.relayProtocol=r.relayProtocol,n.transportId=r.transportId,this.localCandidates.push(n)}handleRemoteCandidate(r){const n=new To;n.label="remote-candidate",n.address=r.address,n.port=r.port,n.protocol=r.protocol,n.id=r.id,n.candidateType=r.candidateType,n.relayProtocol=r.relayProtocol,n.transportId=r.transportId,this.remoteCandidates.push(n)}handleInBoundRTP(r){switch(r.kind){case"video":this.inboundVideoStats=r,this.lastVideoStats!=null&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=r,this.lastAudioStats!=null&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:T.Log(T.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(r){r.kind==="video"&&(this.outBoundVideoStats.bytesSent=r.bytesSent,this.outBoundVideoStats.id=r.id,this.outBoundVideoStats.localId=r.localId,this.outBoundVideoStats.packetsSent=r.packetsSent,this.outBoundVideoStats.remoteTimestamp=r.remoteTimestamp,this.outBoundVideoStats.timestamp=r.timestamp)}handleTrack(r){r.type!=="track"||r.trackIdentifier!=="video_label"&&r.kind!=="video"||(this.inboundVideoStats.framesDropped=r.framesDropped,this.inboundVideoStats.framesReceived=r.framesReceived,this.inboundVideoStats.frameHeight=r.frameHeight,this.inboundVideoStats.frameWidth=r.frameWidth)}handleTransport(r){this.transportStats=r}handleCodec(r){const n=r.id,a=`${r.mimeType.replace("video/","").replace("audio/","")}${r.sdpFmtpLine?` ${r.sdpFmtpLine}`:""}`;this.codecs.set(n,a)}handleSessionStatistics(r,n,a){const f=Date.now()-r;this.sessionStats.runTime=new Date(f).toISOString().substr(11,8).toString();const v=n===null?"Not sent yet":n?"true":"false";this.sessionStats.controlsStreamInput=v,this.sessionStats.videoEncoderAvgQP=a}isNumber(r){return typeof r=="number"&&isFinite(r)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((r=>r.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((r=>r.selected),null)}}const Wp=(Hp={parseRtpParameters:()=>Gp.parseRtpParameters,splitSections:()=>Gp.splitSections},uo={},Li.d(uo,Hp),uo);var Hp,uo;class um{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var rs,Te,co=function(c,r,n,a){return new(n||(n=Promise))((function(f,v){function C(U){try{b(a.next(U))}catch(B){v(B)}}function R(U){try{b(a.throw(U))}catch(B){v(B)}}function b(U){var B;U.done?f(U.value):(B=U.value,B instanceof n?B:new n((function(te){te(B)}))).then(C,R)}b((a=a.apply(c,[])).next())}))};class dw{constructor(r,n,a){this.config=n,this.createPeerConnection(r,a)}createPeerConnection(r,n){this.config.isFlagEnabled(K.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new lm,this.preferredCodec=n,this.updateCodecSelection=!0}createOffer(r,n){return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",f=location.protocol==="https:";let v=n.isFlagEnabled(K.UseMic);!v||a||f||(v=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(v).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var b;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,v),(b=this.peerConnection)===null||b===void 0||b.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,n){var a;return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",v=location.protocol==="https:";let C=n.isFlagEnabled(K.UseMic);!C||f||v||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(St.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((b=>{var U;return b.sdp=this.mungeSDP(b.sdp,C),(U=this.peerConnection)===null||U===void 0?void 0:U.setLocalDescription(b)})).then((()=>{var b;this.onSendWebRTCAnswer((b=this.peerConnection)===null||b===void 0?void 0:b.currentLocalDescription)})).catch((()=>{T.Error(T.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(r){var n;(n=this.peerConnection)===null||n===void 0||n.setRemoteDescription(r),this.config.setOptionSettingOptions(St.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r))}generateStats(){var r;(r=this.peerConnection)===null||r===void 0||r.getStats(null).then((n=>{this.aggregatedStats.processStats(n),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(St.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(r,n){let a=r.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
2898
|
+
`+JSON.stringify(this,void 0,4),6),JSON.stringify(this)}}(function(c){c.CONFIG="config",c.STREAMER_LIST="streamerList",c.STREAMER_ID_CHANGED="streamerIDChanged",c.PLAYER_COUNT="playerCount",c.OFFER="offer",c.ANSWER="answer",c.ICE_CANDIDATE="iceCandidate",c.PEER_DATA_CHANNELS="peerDataChannels",c.PING="ping",c.WARNING="warning"})(Pt||(Pt={}));class _f{}class Yy extends _f{}class vo{constructor(){this.FromUEMessageHandlers=new Map}addMessageHandler(r,n){this.FromUEMessageHandlers.set(r,n)}handleMessage(r,n){this.FromUEMessageHandlers.has(r)?this.FromUEMessageHandlers.get(r)(n):T.Error(T.GetStackTrace(),`Message type of ${r} does not have a message handler registered on the frontend - ignoring message.`)}static setupDefaultHandlers(r){r.signallingProtocol.addMessageHandler(Pt.PING,(n=>{const a=new Wy(new Date().getTime()).payload();T.Log(T.GetStackTrace(),Pt.PING+": "+n,6),r.webSocket.send(a)})),r.signallingProtocol.addMessageHandler(Pt.CONFIG,(n=>{T.Log(T.GetStackTrace(),Pt.CONFIG,6);const a=JSON.parse(n);r.onConfig(a)})),r.signallingProtocol.addMessageHandler(Pt.STREAMER_LIST,(n=>{T.Log(T.GetStackTrace(),Pt.STREAMER_LIST,6);const a=JSON.parse(n);r.onStreamerList(a)})),r.signallingProtocol.addMessageHandler(Pt.STREAMER_ID_CHANGED,(n=>{T.Log(T.GetStackTrace(),Pt.STREAMER_ID_CHANGED,6);const a=JSON.parse(n);r.onStreamerIDChanged(a)})),r.signallingProtocol.addMessageHandler(Pt.PLAYER_COUNT,(n=>{T.Log(T.GetStackTrace(),Pt.PLAYER_COUNT,6);const a=JSON.parse(n);T.Log(T.GetStackTrace(),"Player Count: "+a.count,6),r.onPlayerCount(a)})),r.signallingProtocol.addMessageHandler(Pt.ANSWER,(n=>{T.Log(T.GetStackTrace(),Pt.ANSWER,6);const a=JSON.parse(n);r.onWebRtcAnswer(a)})),r.signallingProtocol.addMessageHandler(Pt.OFFER,(n=>{T.Log(T.GetStackTrace(),Pt.OFFER,6);const a=JSON.parse(n);r.onWebRtcOffer(a)})),r.signallingProtocol.addMessageHandler(Pt.ICE_CANDIDATE,(n=>{T.Log(T.GetStackTrace(),Pt.ICE_CANDIDATE,6);const a=JSON.parse(n);r.onIceCandidate(a.candidate)})),r.signallingProtocol.addMessageHandler(Pt.WARNING,(n=>{T.Warning(T.GetStackTrace(),`Warning received: ${n}`)})),r.signallingProtocol.addMessageHandler(Pt.PEER_DATA_CHANNELS,(n=>{T.Log(T.GetStackTrace(),Pt.PEER_DATA_CHANNELS,6);const a=JSON.parse(n);r.onWebRtcPeerDataChannels(a)}))}}class Sf{constructor(){this.WS_OPEN_STATE=1,this.onOpen=new EventTarget,this.onClose=new EventTarget,this.signallingProtocol=new vo,vo.setupDefaultHandlers(this)}connect(r){T.Log(T.GetStackTrace(),r,6);try{return this.webSocket=new WebSocket(r),this.webSocket.onopen=n=>this.handleOnOpen(n),this.webSocket.onerror=()=>this.handleOnError(),this.webSocket.onclose=n=>this.handleOnClose(n),this.webSocket.onmessage=n=>this.handleOnMessage(n),this.webSocket.onmessagebinary=n=>this.handleOnMessageBinary(n),!0}catch(n){return T.Error(n,n),!1}}handleOnMessageBinary(r){r&&r.data&&r.data.text().then((n=>{const a=new MessageEvent("messageFromBinary",{data:n});this.handleOnMessage(a)})).catch((n=>{T.Error(T.GetStackTrace(),`Failed to parse binary blob from websocket, reason: ${n}`)}))}handleOnMessage(r){if(r.data&&r.data instanceof Blob)return void this.handleOnMessageBinary(r);const n=JSON.parse(r.data);T.Log(T.GetStackTrace(),`received =>
|
|
2899
|
+
`+JSON.stringify(JSON.parse(r.data),void 0,4),6),this.signallingProtocol.handleMessage(n.type,r.data)}handleOnOpen(r){T.Log(T.GetStackTrace(),"Connected to the signalling server via WebSocket",6),this.onOpen.dispatchEvent(new Event("open"))}handleOnError(){T.Error(T.GetStackTrace(),"WebSocket error")}handleOnClose(r){T.Log(T.GetStackTrace(),"Disconnected to the signalling server via WebSocket: "+JSON.stringify(r.code)+" - "+r.reason),this.onClose.dispatchEvent(new CustomEvent("close",{detail:r}))}requestStreamerList(){const r=new Vy;this.webSocket.send(r.payload())}sendSubscribe(r){const n=new Gy(r);this.webSocket.send(n.payload())}sendUnsubscribe(){const r=new qy;this.webSocket.send(r.payload())}sendWebRtcOffer(r,n){const a=new Hy(r,n);this.webSocket.send(a.payload())}sendWebRtcAnswer(r,n){const a=new jy(r,n);this.webSocket.send(a.payload())}sendWebRtcDatachannelRequest(){const r=new Ky;this.webSocket.send(r.payload())}sendSFURecvDataChannelReady(){const r=new Qy;this.webSocket.send(r.payload())}sendIceCandidate(r){if(T.Log(T.GetStackTrace(),"Sending Ice Candidate"),this.webSocket&&this.webSocket.readyState===this.WS_OPEN_STATE){const n=new Xy(r);this.webSocket.send(n.payload())}}close(){var r;(r=this.webSocket)===null||r===void 0||r.close()}onConfig(r){}onStreamerList(r){}onStreamerIDChanged(r){}onIceCandidate(r){}onWebRtcAnswer(r){}onWebRtcOffer(r){}onWebRtcPeerDataChannels(r){}onPlayerCount(r){}}class Jy{constructor(r){this.videoElementProvider=r,this.audioElement=document.createElement("Audio"),this.videoElementProvider.setAudioElement(this.audioElement)}handleOnTrack(r){if(T.Log(T.GetStackTrace(),"handleOnTrack "+JSON.stringify(r.streams),6),r.track.id=="probator")return;const n=this.videoElementProvider.getVideoElement();if(r.track&&T.Log(T.GetStackTrace(),"Got track - "+r.track.kind+" id="+r.track.id+" readyState="+r.track.readyState,6),r.track.kind!="audio")return r.track.kind=="video"&&n.srcObject!==r.streams[0]?(n.srcObject=r.streams[0],void T.Log(T.GetStackTrace(),"Set video source from video track ontrack.")):void 0;this.CreateAudioTrack(r.streams[0])}CreateAudioTrack(r){const n=this.videoElementProvider.getVideoElement();n.srcObject!=r&&n.srcObject&&n.srcObject!==r&&(this.audioElement.srcObject=r,T.Log(T.GetStackTrace(),"Created new audio element to play separate audio stream."))}}class Zy{constructor(r){this.freezeFrameHeight=0,this.freezeFrameWidth=0,this.rootDiv=r,this.rootElement=document.createElement("div"),this.rootElement.id="freezeFrame",this.rootElement.style.display="none",this.rootElement.style.pointerEvents="none",this.rootElement.style.position="absolute",this.rootElement.style.zIndex="20",this.imageElement=document.createElement("img"),this.imageElement.style.position="absolute",this.rootElement.appendChild(this.imageElement),this.rootDiv.appendChild(this.rootElement)}setElementForShow(){this.rootElement.style.display="block"}setElementForHide(){this.rootElement.style.display="none"}updateImageElementSource(r){const n=btoa(r.reduce(((a,f)=>a+String.fromCharCode(f)),""));this.imageElement.src="data:image/jpeg;base64,"+n}setDimensionsFromElementAndResize(){this.freezeFrameHeight=this.imageElement.naturalHeight,this.freezeFrameWidth=this.imageElement.naturalWidth,this.resize()}resize(){if(this.freezeFrameWidth!==0&&this.freezeFrameHeight!==0){let r=0,n=0,a=0,f=0;const v=this.rootDiv.clientWidth/this.rootDiv.clientHeight,C=this.freezeFrameWidth/this.freezeFrameHeight;v<C?(r=this.rootDiv.clientWidth,n=Math.floor(this.rootDiv.clientWidth/C),a=Math.floor(.5*(this.rootDiv.clientHeight-n)),f=0):(r=Math.floor(this.rootDiv.clientHeight*C),n=this.rootDiv.clientHeight,a=0,f=Math.floor(.5*(this.rootDiv.clientWidth-r))),this.rootElement.style.width=this.rootDiv.offsetWidth+"px",this.rootElement.style.height=this.rootDiv.offsetHeight+"px",this.rootElement.style.left="0px",this.rootElement.style.top="0px",this.imageElement.style.width=r+"px",this.imageElement.style.height=n+"px",this.imageElement.style.left=f+"px",this.imageElement.style.top=a+"px"}}}class ew{constructor(r){this.receiving=!1,this.size=0,this.jpeg=void 0,this.valid=!1,this.freezeFrameDelay=50,this.freezeFrame=new Zy(r)}showFreezeFrame(){this.valid&&this.freezeFrame.setElementForShow()}hideFreezeFrame(){this.valid=!1,this.freezeFrame.setElementForHide()}updateFreezeFrameAndShow(r,n){this.freezeFrame.updateImageElementSource(r),this.freezeFrame.imageElement.onload=()=>{this.freezeFrame.setDimensionsFromElementAndResize(),n()}}processFreezeFrameMessage(r,n){this.receiving||(this.receiving=!0,this.valid=!1,this.size=0,this.jpeg=void 0),this.size=new DataView(r.slice(1,5).buffer).getInt32(0,!0);const a=r.slice(5);if(this.jpeg){const f=new Uint8Array(this.jpeg.length+a.length);f.set(this.jpeg,0),f.set(a,this.jpeg.length),this.jpeg=f}else this.jpeg=a,this.receiving=!0,T.Log(T.GetStackTrace(),`received first chunk of freeze frame: ${this.jpeg.length}/${this.size}`,6);this.jpeg.length===this.size?(this.receiving=!1,this.valid=!0,T.Log(T.GetStackTrace(),`received complete freeze frame ${this.size}`,6),this.updateFreezeFrameAndShow(this.jpeg,n)):this.jpeg.length>this.size&&(T.Error(T.GetStackTrace(),`received bigger freeze frame than advertised: ${this.jpeg.length}/${this.size}`),this.jpeg=void 0,this.receiving=!1)}}class li{constructor(r,n,a,f,v=(()=>{})){this.onChange=v,this.onChangeEmit=()=>{},this.id=r,this.description=a,this.label=n,this.value=f}set label(r){this._label=r,this.onChangeEmit(this._value)}get label(){return this._label}get value(){return this._value}set value(r){this._value=r,this.onChange(this._value,this),this.onChangeEmit(this._value)}}class It extends li{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const b=this.getUrlParamFlag();this.flag=b}else this.flag=f;this.useUrlParams=v}getUrlParamFlag(){const r=new URLSearchParams(window.location.search);return!!r.has(this.id)&&r.get(this.id)!=="false"&&r.get(this.id)!=="False"}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);this.flag===!0?r.set(this.id,"true"):r.set(this.id,"false"),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}enable(){this.flag=!0}get flag(){return!!this.value}set flag(r){this.value=r}}class Ir extends li{constructor(r,n,a,f,v,C,R,b=(()=>{})){super(r,n,a,C,b),this._min=f,this._max=v;const U=new URLSearchParams(window.location.search);if(R&&U.has(this.id)){const B=Number.parseFloat(U.get(this.id));this.number=Number.isNaN(B)?C:B}else this.number=C;this.useUrlParams=R}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.number.toString()),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}set number(r){this.value=this.clamp(r)}get number(){return this.value}clamp(r){return this._min==null&&this._max==null?r:this._min==null?Math.min(this._max,r):this._max==null?Math.max(this._min,r):Math.max(Math.min(this._max,r),this._min)}get min(){return this._min}get max(){return this._max}addOnChangedListener(r){this.onChange=r}}class Tf extends li{constructor(r,n,a,f,v,C=(()=>{})){super(r,n,a,f,C);const R=new URLSearchParams(window.location.search);if(v&&R.has(this.id)){const b=this.getUrlParamText();this.text=b}else this.text=f;this.useUrlParams=v}getUrlParamText(){var r;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(r=n.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.text),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}get text(){return this.value}set text(r){this.value=r}}class bo extends li{constructor(r,n,a,f,v,C,R=(()=>{})){super(r,n,a,f,R),this.options=v;const b=new URLSearchParams(window.location.search),U=C&&b.has(this.id)?this.getUrlParamText():f;this.selected=U,this.useUrlParams=C}getUrlParamText(){var r;const n=new URLSearchParams(window.location.search);return n.has(this.id)&&(r=n.get(this.id))!==null&&r!==void 0?r:""}updateURLParams(){if(this.useUrlParams){const r=new URLSearchParams(window.location.search);r.set(this.id,this.selected),window.history.replaceState({},"",r.toString()!==""?`${location.pathname}?${r}`:`${location.pathname}`)}}addOnChangedListener(r){this.onChange=r}get options(){return this._options}set options(r){this._options=r,this.onChangeEmit(this.selected)}get selected(){return this.value}set selected(r){let n=this.options.filter((a=>a.indexOf(r)!==-1));n.length?this.value=n[0]:(n=this.options.filter((a=>a.indexOf(r.split(" ")[0])!==-1)),n.length&&(this.value=n[0]))}}class $f extends Event{constructor(r){super("afkWarningActivate"),this.data=r}}class _o extends Event{constructor(r){super("afkWarningUpdate"),this.data=r}}class xf extends Event{constructor(){super("afkWarningDeactivate")}}class Ef extends Event{constructor(){super("afkTimedOut")}}class Cf extends Event{constructor(r){super("videoEncoderAvgQP"),this.data=r}}class kf extends Event{constructor(){super("webRtcSdp")}}class Rf extends Event{constructor(){super("webRtcAutoConnect")}}class Af extends Event{constructor(){super("webRtcConnecting")}}class Mf extends Event{constructor(){super("webRtcConnected")}}class If extends Event{constructor(){super("webRtcFailed")}}class Pf extends Event{constructor(r){super("webRtcDisconnected"),this.data=r}}class Of extends Event{constructor(r){super("dataChannelOpen"),this.data=r}}class zf extends Event{constructor(r){super("dataChannelClose"),this.data=r}}class Df extends Event{constructor(r){super("dataChannelError"),this.data=r}}class Lf extends Event{constructor(){super("videoInitialized")}}class Bf extends Event{constructor(){super("streamLoading")}}class Nf extends Event{constructor(){super("streamConnect")}}class Uf extends Event{constructor(){super("streamDisconnect")}}class Ff extends Event{constructor(){super("streamReconnect")}}class Vf extends Event{constructor(r){super("playStreamError"),this.data=r}}class Gf extends Event{constructor(){super("playStream")}}class So extends Event{constructor(r){super("playStreamRejected"),this.data=r}}class qf extends Event{constructor(r){super("loadFreezeFrame"),this.data=r}}class Wf extends Event{constructor(){super("hideFreezeFrame")}}class Hf extends Event{constructor(r){super("statsReceived"),this.data=r}}class jf extends Event{constructor(r){super("streamerListMessage"),this.data=r}}class Kf extends Event{constructor(r){super("StreamerIDChangedMessage"),this.data=r}}class Qf extends Event{constructor(r){super("latencyTestResult"),this.data=r}}class Xf extends Event{constructor(r){super("dataChannelLatencyTestResponse"),this.data=r}}class Yf extends Event{constructor(r){super("dataChannelLatencyTestResult"),this.data=r}}class Jf extends Event{constructor(r){super("initialSettings"),this.data=r}}class ai extends Event{constructor(r){super("settingsChanged"),this.data=r}}class tw extends Event{constructor(){super("xrSessionStarted")}}class rw extends Event{constructor(){super("xrSessionEnded")}}class Zf extends Event{constructor(r){super("xrFrame"),this.data=r}}class em extends Event{constructor(r){super("playerCount"),this.data=r}}class tm extends Event{constructor(){super("webRtcTCPRelayDetected")}}class rm extends EventTarget{dispatchEvent(r){return super.dispatchEvent(r)}addEventListener(r,n){super.addEventListener(r,n)}removeEventListener(r,n){super.removeEventListener(r,n)}}class K{}K.AutoConnect="AutoConnect",K.AutoPlayVideo="AutoPlayVideo",K.AFKDetection="TimeoutIfIdle",K.BrowserSendOffer="OfferToReceive",K.HoveringMouseMode="HoveringMouse",K.ForceMonoAudio="ForceMonoAudio",K.ForceTURN="ForceTURN",K.FakeMouseWithTouches="FakeMouseWithTouches",K.IsQualityController="ControlsQuality",K.MatchViewportResolution="MatchViewportRes",K.StartVideoMuted="StartVideoMuted",K.SuppressBrowserKeys="SuppressBrowserKeys",K.UseMic="UseMic",K.KeyboardInput="KeyboardInput",K.MouseInput="MouseInput",K.TouchInput="TouchInput",K.GamepadInput="GamepadInput",K.XRControllerInput="XRControllerInput",K.WaitForStreamer="WaitForStreamer",K.HideUI="HideUI";const nw=c=>Object.getOwnPropertyNames(K).some((r=>K[r]===c));class we{}we.AFKTimeoutSecs="AFKTimeout",we.AFKCountdownSecs="AFKCountdown",we.MinQP="MinQP",we.MaxQP="MaxQP",we.WebRTCFPS="WebRTCFPS",we.WebRTCMinBitrate="WebRTCMinBitrate",we.WebRTCMaxBitrate="WebRTCMaxBitrate",we.MaxReconnectAttempts="MaxReconnectAttempts",we.StreamerAutoJoinInterval="StreamerAutoJoinInterval";const sw=c=>Object.getOwnPropertyNames(we).some((r=>we[r]===c));class Wr{}Wr.SignallingServerUrl="ss";const iw=c=>Object.getOwnPropertyNames(Wr).some((r=>Wr[r]===c));class St{}St.PreferredCodec="PreferredCodec",St.StreamerId="StreamerId";const aw=c=>Object.getOwnPropertyNames(St).some((r=>St[r]===c));class ow{constructor(r={}){this.flags=new Map,this.numericParameters=new Map,this.textParameters=new Map,this.optionParameters=new Map;const{initialSettings:n,useUrlParams:a}=r;this._useUrlParams=!!a,this.populateDefaultSettings(this._useUrlParams,n)}get useUrlParams(){return this._useUrlParams}populateDefaultSettings(r,n){this.textParameters.set(Wr.SignallingServerUrl,new Tf(Wr.SignallingServerUrl,"Signalling url","Url of the signalling server",n&&n.hasOwnProperty(Wr.SignallingServerUrl)?n[Wr.SignallingServerUrl]:(location.protocol==="https:"?"wss://":"ws://")+window.location.hostname+(window.location.port==="80"||window.location.port===""?"":`:${window.location.port}`),r)),this.optionParameters.set(St.StreamerId,new bo(St.StreamerId,"Streamer ID","The ID of the streamer to stream.",n&&n.hasOwnProperty(St.StreamerId)?n[St.StreamerId]:"",[],r)),this.optionParameters.set(St.PreferredCodec,new bo(St.PreferredCodec,"Preferred Codec","The preferred codec to be used during codec negotiation","H264 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",n&&n.hasOwnProperty(St.PreferredCodec)?[n[St.PreferredCodec]]:(function(){const a=[];if(!RTCRtpReceiver.getCapabilities)return a.push("Only available on Chrome"),a;const f=/(VP\d|H26\d|AV1).*/;return RTCRtpReceiver.getCapabilities("video").codecs.forEach((v=>{const C=v.mimeType.split("/")[1]+" "+(v.sdpFmtpLine||"");f.exec(C)!==null&&a.push(C)})),a})(),r)),this.flags.set(K.AutoConnect,new It(K.AutoConnect,"Auto connect to stream","Whether we should attempt to auto connect to the signalling server or show a click to start prompt.",!(!n||!n.hasOwnProperty(K.AutoConnect))&&n[K.AutoConnect],r)),this.flags.set(K.AutoPlayVideo,new It(K.AutoPlayVideo,"Auto play video","When video is ready automatically start playing it as opposed to showing a play button.",!n||!n.hasOwnProperty(K.AutoPlayVideo)||n[K.AutoPlayVideo],r)),this.flags.set(K.BrowserSendOffer,new It(K.BrowserSendOffer,"Browser send offer","Browser will initiate the WebRTC handshake by sending the offer to the streamer",!(!n||!n.hasOwnProperty(K.BrowserSendOffer))&&n[K.BrowserSendOffer],r)),this.flags.set(K.UseMic,new It(K.UseMic,"Use microphone","Make browser request microphone access and open an input audio track.",!(!n||!n.hasOwnProperty(K.UseMic))&&n[K.UseMic],r)),this.flags.set(K.StartVideoMuted,new It(K.StartVideoMuted,"Start video muted","Video will start muted if true.",!(!n||!n.hasOwnProperty(K.StartVideoMuted))&&n[K.StartVideoMuted],r)),this.flags.set(K.SuppressBrowserKeys,new It(K.SuppressBrowserKeys,"Suppress browser keys","Suppress certain browser keys that we use in UE, for example F5 to show shader complexity instead of refresh the page.",!n||!n.hasOwnProperty(K.SuppressBrowserKeys)||n[K.SuppressBrowserKeys],r)),this.flags.set(K.IsQualityController,new It(K.IsQualityController,"Is quality controller?","True if this peer controls stream quality",!n||!n.hasOwnProperty(K.IsQualityController)||n[K.IsQualityController],r)),this.flags.set(K.ForceMonoAudio,new It(K.ForceMonoAudio,"Force mono audio","Force browser to request mono audio in the SDP",!(!n||!n.hasOwnProperty(K.ForceMonoAudio))&&n[K.ForceMonoAudio],r)),this.flags.set(K.ForceTURN,new It(K.ForceTURN,"Force TURN","Only generate TURN/Relayed ICE candidates.",!(!n||!n.hasOwnProperty(K.ForceTURN))&&n[K.ForceTURN],r)),this.flags.set(K.AFKDetection,new It(K.AFKDetection,"AFK if idle","Timeout the experience if user is AFK for a period.",!(!n||!n.hasOwnProperty(K.AFKDetection))&&n[K.AFKDetection],r)),this.flags.set(K.MatchViewportResolution,new It(K.MatchViewportResolution,"Match viewport resolution","Pixel Streaming will be instructed to dynamically resize the video stream to match the size of the video element.",!(!n||!n.hasOwnProperty(K.MatchViewportResolution))&&n[K.MatchViewportResolution],r)),this.flags.set(K.HoveringMouseMode,new It(K.HoveringMouseMode,"Control Scheme: Locked Mouse","Either locked mouse, where the pointer is consumed by the video and locked to it, or hovering mouse, where the mouse is not consumed.",!(!n||!n.hasOwnProperty(K.HoveringMouseMode))&&n[K.HoveringMouseMode],r,((a,f)=>{f.label=`Control Scheme: ${a?"Hovering":"Locked"} Mouse`}))),this.flags.set(K.FakeMouseWithTouches,new It(K.FakeMouseWithTouches,"Fake mouse with touches","A single finger touch is converted into a mouse event. This allows a non-touch application to be controlled partially via a touch device.",!(!n||!n.hasOwnProperty(K.FakeMouseWithTouches))&&n[K.FakeMouseWithTouches],r)),this.flags.set(K.KeyboardInput,new It(K.KeyboardInput,"Keyboard input","If enabled, send keyboard events to streamer",!n||!n.hasOwnProperty(K.KeyboardInput)||n[K.KeyboardInput],r)),this.flags.set(K.MouseInput,new It(K.MouseInput,"Mouse input","If enabled, send mouse events to streamer",!n||!n.hasOwnProperty(K.MouseInput)||n[K.MouseInput],r)),this.flags.set(K.TouchInput,new It(K.TouchInput,"Touch input","If enabled, send touch events to streamer",!n||!n.hasOwnProperty(K.TouchInput)||n[K.TouchInput],r)),this.flags.set(K.GamepadInput,new It(K.GamepadInput,"Gamepad input","If enabled, send gamepad events to streamer",!n||!n.hasOwnProperty(K.GamepadInput)||n[K.GamepadInput],r)),this.flags.set(K.XRControllerInput,new It(K.XRControllerInput,"XR controller input","If enabled, send XR controller events to streamer",!n||!n.hasOwnProperty(K.XRControllerInput)||n[K.XRControllerInput],r)),this.flags.set(K.WaitForStreamer,new It(K.WaitForStreamer,"Wait for streamer","Will continue trying to connect to the first streamer available.",!n||!n.hasOwnProperty(K.WaitForStreamer)||n[K.WaitForStreamer],r)),this.flags.set(K.HideUI,new It(K.HideUI,"Hide the UI overlay","Will hide all UI overlay details",!(!n||!n.hasOwnProperty(K.HideUI))&&n[K.HideUI],r)),this.numericParameters.set(we.AFKTimeoutSecs,new Ir(we.AFKTimeoutSecs,"AFK timeout","The time (in seconds) it takes for the application to time out if AFK timeout is enabled.",0,null,n&&n.hasOwnProperty(we.AFKTimeoutSecs)?n[we.AFKTimeoutSecs]:120,r)),this.numericParameters.set(we.AFKCountdownSecs,new Ir(we.AFKCountdownSecs,"AFK countdown","The time (in seconds) for a user to respond before the stream is ended after an AFK timeout.",10,null,10,r)),this.numericParameters.set(we.MaxReconnectAttempts,new Ir(we.MaxReconnectAttempts,"Max Reconnects","Maximum number of reconnects the application will attempt when a streamer disconnects.",0,999,n&&n.hasOwnProperty(we.MaxReconnectAttempts)?n[we.MaxReconnectAttempts]:3,r)),this.numericParameters.set(we.MinQP,new Ir(we.MinQP,"Min QP","The lower bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(we.MinQP)?n[we.MinQP]:0,r)),this.numericParameters.set(we.MaxQP,new Ir(we.MaxQP,"Max QP","The upper bound for the quantization parameter (QP) of the encoder. 0 = Best quality, 51 = worst quality.",0,51,n&&n.hasOwnProperty(we.MaxQP)?n[we.MaxQP]:51,r)),this.numericParameters.set(we.WebRTCFPS,new Ir(we.WebRTCFPS,"Max FPS","The maximum FPS that WebRTC will try to transmit frames at.",1,999,n&&n.hasOwnProperty(we.WebRTCFPS)?n[we.WebRTCFPS]:60,r)),this.numericParameters.set(we.WebRTCMinBitrate,new Ir(we.WebRTCMinBitrate,"Min Bitrate (kbps)","The minimum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(we.WebRTCMinBitrate)?n[we.WebRTCMinBitrate]:0,r)),this.numericParameters.set(we.WebRTCMaxBitrate,new Ir(we.WebRTCMaxBitrate,"Max Bitrate (kbps)","The maximum bitrate that WebRTC should use.",0,5e5,n&&n.hasOwnProperty(we.WebRTCMaxBitrate)?n[we.WebRTCMaxBitrate]:0,r)),this.numericParameters.set(we.StreamerAutoJoinInterval,new Ir(we.StreamerAutoJoinInterval,"Streamer Auto Join Interval (ms)","Delay between retries when waiting for an available streamer.",500,9e5,n&&n.hasOwnProperty(we.StreamerAutoJoinInterval)?n[we.StreamerAutoJoinInterval]:3e3,r))}_addOnNumericSettingChangedListener(r,n){this.numericParameters.has(r)&&this.numericParameters.get(r).addOnChangedListener(n)}_addOnOptionSettingChangedListener(r,n){this.optionParameters.has(r)&&this.optionParameters.get(r).addOnChangedListener(n)}getNumericSettingValue(r){if(this.numericParameters.has(r))return this.numericParameters.get(r).number;throw new Error(`There is no numeric setting with the id of ${r}`)}getTextSettingValue(r){if(this.textParameters.has(r))return this.textParameters.get(r).value;throw new Error(`There is no numeric setting with the id of ${r}`)}setNumericSetting(r,n){if(!this.numericParameters.has(r))throw new Error(`There is no numeric setting with the id of ${r}`);this.numericParameters.get(r).number=n}_addOnSettingChangedListener(r,n){this.flags.has(r)&&(this.flags.get(r).onChange=n)}_addOnTextSettingChangedListener(r,n){this.textParameters.has(r)&&(this.textParameters.get(r).onChange=n)}getSettingOption(r){return this.optionParameters.get(r)}isFlagEnabled(r){return this.flags.get(r).flag}setFlagEnabled(r,n){this.flags.has(r)?this.flags.get(r).flag=n:T.Warning(T.GetStackTrace(),`Cannot toggle flag called ${r} - it does not exist in the Config.flags map.`)}setTextSetting(r,n){this.textParameters.has(r)?this.textParameters.get(r).text=n:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.textParameters map.`)}setOptionSettingOptions(r,n){this.optionParameters.has(r)?this.optionParameters.get(r).options=n:T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.optionParameters map.`)}setOptionSettingValue(r,n){if(this.optionParameters.has(r)){const a=this.optionParameters.get(r),f=a.options;f.includes(n)||(f.push(n),a.options=f),a.selected=n}else T.Warning(T.GetStackTrace(),`Cannot set text setting called ${r} - it does not exist in the Config.enumParameters map.`)}setFlagLabel(r,n){this.flags.has(r)?this.flags.get(r).label=n:T.Warning(T.GetStackTrace(),`Cannot set label for flag called ${r} - it does not exist in the Config.flags map.`)}setSettings(r){for(const n of Object.keys(r))nw(n)?this.setFlagEnabled(n,r[n]):sw(n)?this.setNumericSetting(n,r[n]):iw(n)?this.setTextSetting(n,r[n]):aw(n)&&this.setOptionSettingValue(n,r[n])}getSettings(){const r={};for(const[n,a]of this.flags.entries())r[n]=a.flag;for(const[n,a]of this.numericParameters.entries())r[n]=a.number;for(const[n,a]of this.textParameters.entries())r[n]=a.text;for(const[n,a]of this.optionParameters.entries())r[n]=a.selected;return r}getFlags(){return Array.from(this.flags.values())}getTextSettings(){return Array.from(this.textParameters.values())}getNumericSettings(){return Array.from(this.numericParameters.values())}getOptionSettings(){return Array.from(this.optionParameters.values())}_registerOnChangeEvents(r){for(const n of this.flags.keys()){const a=this.flags.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"flag",value:f,target:a})))}for(const n of this.numericParameters.keys()){const a=this.numericParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"number",value:f,target:a})))}for(const n of this.textParameters.keys()){const a=this.textParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"text",value:f,target:a})))}for(const n of this.optionParameters.keys()){const a=this.optionParameters.get(n);a&&(a.onChangeEmit=f=>r.dispatchEvent(new ai({id:a.id,type:"option",value:f,target:a})))}}}var Dn;(function(c){c[c.LockedMouse=0]="LockedMouse",c[c.HoveringMouse=1]="HoveringMouse"})(Dn||(Dn={}));class nm{constructor(r,n,a){this.active=!1,this.countdownActive=!1,this.warnTimer=void 0,this.countDown=0,this.countDownTimer=void 0,this.config=r,this.pixelStreaming=n,this.onDismissAfk=a,this.onAFKTimedOutCallback=()=>{console.log("AFK timed out, did you want to override this callback?")}}onAfkClick(){clearInterval(this.countDownTimer),(this.active||this.countdownActive)&&(this.startAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new xf))}startAfkWarningTimer(){this.config.getNumericSettingValue(we.AFKTimeoutSecs)>0&&this.config.isFlagEnabled(K.AFKDetection)?this.active=!0:this.active=!1,this.resetAfkWarningTimer()}stopAfkWarningTimer(){this.active=!1,this.countdownActive=!1,clearTimeout(this.warnTimer),clearInterval(this.countDownTimer)}pauseAfkWarningTimer(){this.active=!1}resetAfkWarningTimer(){this.active&&this.config.isFlagEnabled(K.AFKDetection)&&(clearTimeout(this.warnTimer),this.warnTimer=setTimeout((()=>this.activateAfkEvent()),1e3*this.config.getNumericSettingValue(we.AFKTimeoutSecs)))}activateAfkEvent(){this.pauseAfkWarningTimer(),this.pixelStreaming.dispatchEvent(new $f({countDown:this.countDown,dismissAfk:this.onDismissAfk})),this.countDown=this.config.getNumericSettingValue(we.AFKCountdownSecs),this.countdownActive=!0,this.pixelStreaming.dispatchEvent(new _o({countDown:this.countDown})),this.config.isFlagEnabled(K.HoveringMouseMode)||document.exitPointerLock&&document.exitPointerLock(),this.countDownTimer=setInterval((()=>{this.countDown--,this.countDown==0?(this.pixelStreaming.dispatchEvent(new Ef),this.onAFKTimedOutCallback(),T.Log(T.GetStackTrace(),"You have been disconnected due to inactivity"),this.stopAfkWarningTimer()):this.pixelStreaming.dispatchEvent(new _o({countDown:this.countDown}))}),1e3)}}class qp{constructor(){this.isReceivingFreezeFrame=!1}getDataChannelInstance(){return this}createDataChannel(r,n,a){this.peerConnection=r,this.label=n,this.datachannelOptions=a,a==null&&(this.datachannelOptions={},this.datachannelOptions.ordered=!0),this.dataChannel=this.peerConnection.createDataChannel(this.label,this.datachannelOptions),this.setupDataChannel()}setupDataChannel(){this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=r=>this.handleOnOpen(r),this.dataChannel.onclose=r=>this.handleOnClose(r),this.dataChannel.onmessage=r=>this.handleOnMessage(r),this.dataChannel.onerror=r=>this.handleOnError(r)}handleOnOpen(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) opened.`,7),this.onOpen((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}handleOnClose(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) closed.`,7),this.onClose((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}handleOnMessage(r){T.Log(T.GetStackTrace(),`Data Channel (${this.label}) message: ${r}`,8)}handleOnError(r){var n;T.Log(T.GetStackTrace(),`Data Channel (${this.label}) error: ${r}`,7),this.onError((n=this.dataChannel)===null||n===void 0?void 0:n.label,r)}onOpen(r,n){}onClose(r,n){}onError(r,n){}}class sm{}class im{}class am{}class To{}class om{}class lw{}class uw{}class lm{constructor(){this.inboundVideoStats=new im,this.inboundAudioStats=new sm,this.DataChannelStats=new am,this.outBoundVideoStats=new om,this.sessionStats=new lw,this.streamStats=new uw,this.codecs=new Map}processStats(r){this.localCandidates=new Array,this.remoteCandidates=new Array,this.candidatePairs=new Array,r.forEach((n=>{switch(n.type){case"candidate-pair":this.handleCandidatePair(n);break;case"certificate":case"media-source":case"media-playout":case"outbound-rtp":case"peer-connection":case"remote-inbound-rtp":break;case"codec":this.handleCodec(n);break;case"data-channel":this.handleDataChannel(n);break;case"inbound-rtp":this.handleInBoundRTP(n);break;case"local-candidate":this.handleLocalCandidate(n);break;case"remote-candidate":this.handleRemoteCandidate(n);break;case"remote-outbound-rtp":this.handleRemoteOutBound(n);break;case"track":this.handleTrack(n);break;case"transport":this.handleTransport(n);break;case"stream":this.handleStream(n);break;default:T.Error(T.GetStackTrace(),"unhandled Stat Type"),T.Log(T.GetStackTrace(),n)}}))}handleStream(r){this.streamStats=r}handleCandidatePair(r){this.candidatePairs.push(r)}handleDataChannel(r){this.DataChannelStats.bytesReceived=r.bytesReceived,this.DataChannelStats.bytesSent=r.bytesSent,this.DataChannelStats.dataChannelIdentifier=r.dataChannelIdentifier,this.DataChannelStats.id=r.id,this.DataChannelStats.label=r.label,this.DataChannelStats.messagesReceived=r.messagesReceived,this.DataChannelStats.messagesSent=r.messagesSent,this.DataChannelStats.protocol=r.protocol,this.DataChannelStats.state=r.state,this.DataChannelStats.timestamp=r.timestamp}handleLocalCandidate(r){const n=new To;n.label="local-candidate",n.address=r.address,n.port=r.port,n.protocol=r.protocol,n.candidateType=r.candidateType,n.id=r.id,n.relayProtocol=r.relayProtocol,n.transportId=r.transportId,this.localCandidates.push(n)}handleRemoteCandidate(r){const n=new To;n.label="remote-candidate",n.address=r.address,n.port=r.port,n.protocol=r.protocol,n.id=r.id,n.candidateType=r.candidateType,n.relayProtocol=r.relayProtocol,n.transportId=r.transportId,this.remoteCandidates.push(n)}handleInBoundRTP(r){switch(r.kind){case"video":this.inboundVideoStats=r,this.lastVideoStats!=null&&(this.inboundVideoStats.bitrate=8*(this.inboundVideoStats.bytesReceived-this.lastVideoStats.bytesReceived)/(this.inboundVideoStats.timestamp-this.lastVideoStats.timestamp),this.inboundVideoStats.bitrate=Math.floor(this.inboundVideoStats.bitrate)),this.lastVideoStats=Object.assign({},this.inboundVideoStats);break;case"audio":this.inboundAudioStats=r,this.lastAudioStats!=null&&(this.inboundAudioStats.bitrate=8*(this.inboundAudioStats.bytesReceived-this.lastAudioStats.bytesReceived)/(this.inboundAudioStats.timestamp-this.lastAudioStats.timestamp),this.inboundAudioStats.bitrate=Math.floor(this.inboundAudioStats.bitrate)),this.lastAudioStats=Object.assign({},this.inboundAudioStats);break;default:T.Log(T.GetStackTrace(),"Kind is not handled")}}handleRemoteOutBound(r){r.kind==="video"&&(this.outBoundVideoStats.bytesSent=r.bytesSent,this.outBoundVideoStats.id=r.id,this.outBoundVideoStats.localId=r.localId,this.outBoundVideoStats.packetsSent=r.packetsSent,this.outBoundVideoStats.remoteTimestamp=r.remoteTimestamp,this.outBoundVideoStats.timestamp=r.timestamp)}handleTrack(r){r.type!=="track"||r.trackIdentifier!=="video_label"&&r.kind!=="video"||(this.inboundVideoStats.framesDropped=r.framesDropped,this.inboundVideoStats.framesReceived=r.framesReceived,this.inboundVideoStats.frameHeight=r.frameHeight,this.inboundVideoStats.frameWidth=r.frameWidth)}handleTransport(r){this.transportStats=r}handleCodec(r){const n=r.id,a=`${r.mimeType.replace("video/","").replace("audio/","")}${r.sdpFmtpLine?` ${r.sdpFmtpLine}`:""}`;this.codecs.set(n,a)}handleSessionStatistics(r,n,a){const f=Date.now()-r;this.sessionStats.runTime=new Date(f).toISOString().substr(11,8).toString();const v=n===null?"Not sent yet":n?"true":"false";this.sessionStats.controlsStreamInput=v,this.sessionStats.videoEncoderAvgQP=a}isNumber(r){return typeof r=="number"&&isFinite(r)}getActiveCandidatePair(){return this.transportStats?this.candidatePairs.find((r=>r.id===this.transportStats.selectedCandidatePairId),null):this.candidatePairs.find((r=>r.selected),null)}}const Wp=(Hp={parseRtpParameters:()=>Gp.parseRtpParameters,splitSections:()=>Gp.splitSections},uo={},Li.d(uo,Hp),uo);var Hp,uo;class um{static isVideoTransciever(r){return this.canTransceiverReceiveVideo(r)||this.canTransceiverSendVideo(r)}static canTransceiverReceiveVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="video"}static canTransceiverSendVideo(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="video"}static isAudioTransciever(r){return this.canTransceiverReceiveAudio(r)||this.canTransceiverSendAudio(r)}static canTransceiverReceiveAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="recvonly")&&r.receiver&&r.receiver.track&&r.receiver.track.kind==="audio"}static canTransceiverSendAudio(r){return!!r&&(r.direction==="sendrecv"||r.direction==="sendonly")&&r.sender&&r.sender.track&&r.sender.track.kind==="audio"}}var rs,Te,co=function(c,r,n,a){return new(n||(n=Promise))((function(f,v){function C(U){try{b(a.next(U))}catch(B){v(B)}}function R(U){try{b(a.throw(U))}catch(B){v(B)}}function b(U){var B;U.done?f(U.value):(B=U.value,B instanceof n?B:new n((function(te){te(B)}))).then(C,R)}b((a=a.apply(c,[])).next())}))};class dw{constructor(r,n,a){this.config=n,this.createPeerConnection(r,a)}createPeerConnection(r,n){this.config.isFlagEnabled(K.ForceTURN)&&(r.iceTransportPolicy="relay",T.Log(T.GetStackTrace(),"Forcing TURN usage by setting ICE Transport Policy in peer connection config.")),this.peerConnection=new RTCPeerConnection(r),this.peerConnection.onsignalingstatechange=a=>this.handleSignalStateChange(a),this.peerConnection.oniceconnectionstatechange=a=>this.handleIceConnectionStateChange(a),this.peerConnection.onicegatheringstatechange=a=>this.handleIceGatheringStateChange(a),this.peerConnection.ontrack=a=>this.handleOnTrack(a),this.peerConnection.onicecandidate=a=>this.handleIceCandidate(a),this.peerConnection.ondatachannel=a=>this.handleDataChannel(a),this.aggregatedStats=new lm,this.preferredCodec=n,this.updateCodecSelection=!0}createOffer(r,n){return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Create Offer",6);const a=location.hostname==="localhost"||location.hostname==="127.0.0.1",f=location.protocol==="https:";let v=n.isFlagEnabled(K.UseMic);!v||a||f||(v=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.setupTransceiversAsync(v).finally((()=>{var C;(C=this.peerConnection)===null||C===void 0||C.createOffer(r).then((R=>{var b;this.showTextOverlayConnecting(),R.sdp=this.mungeSDP(R.sdp,v),(b=this.peerConnection)===null||b===void 0||b.setLocalDescription(R),this.onSendWebRTCOffer(R)})).catch((()=>{this.showTextOverlaySetupFailure()}))}))}))}receiveOffer(r,n){var a;return co(this,void 0,void 0,(function*(){T.Log(T.GetStackTrace(),"Receive Offer",6),(a=this.peerConnection)===null||a===void 0||a.setRemoteDescription(r).then((()=>{const f=location.hostname==="localhost"||location.hostname==="127.0.0.1",v=location.protocol==="https:";let C=n.isFlagEnabled(K.UseMic);!C||f||v||(C=!1,T.Error(T.GetStackTrace(),"Microphone access in the browser will not work if you are not on HTTPS or localhost. Disabling mic access."),T.Error(T.GetStackTrace(),"For testing you can enable HTTP microphone access Chrome by visiting chrome://flags/ and enabling 'unsafely-treat-insecure-origin-as-secure'")),this.config.setOptionSettingOptions(St.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r)),this.setupTransceiversAsync(C).finally((()=>{var R;(R=this.peerConnection)===null||R===void 0||R.createAnswer().then((b=>{var U;return b.sdp=this.mungeSDP(b.sdp,C),(U=this.peerConnection)===null||U===void 0?void 0:U.setLocalDescription(b)})).then((()=>{var b;this.onSendWebRTCAnswer((b=this.peerConnection)===null||b===void 0?void 0:b.currentLocalDescription)})).catch((()=>{T.Error(T.GetStackTrace(),"createAnswer() failed")}))}))}))}))}receiveAnswer(r){var n;(n=this.peerConnection)===null||n===void 0||n.setRemoteDescription(r),this.config.setOptionSettingOptions(St.PreferredCodec,this.fuzzyIntersectUEAndBrowserCodecs(r))}generateStats(){var r;(r=this.peerConnection)===null||r===void 0||r.getStats(null).then((n=>{this.aggregatedStats.processStats(n),this.onVideoStats(this.aggregatedStats),this.updateCodecSelection&&this.aggregatedStats.inboundVideoStats.codecId&&this.config.setOptionSettingValue(St.PreferredCodec,this.aggregatedStats.codecs.get(this.aggregatedStats.inboundVideoStats.codecId))}))}close(){this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null)}mungeSDP(r,n){let a=r.replace(/(a=fmtp:\d+ .*level-asymmetry-allowed=.*)\r\n/gm,`$1;x-google-start-bitrate=10000;x-google-max-bitrate=100000\r
|
|
2900
2900
|
`),f="maxaveragebitrate=510000;";return n&&(f+="sprop-maxcapturerate=48000;"),f+=this.config.isFlagEnabled(K.ForceMonoAudio)?"stereo=0;":"stereo=1;",f+="useinbandfec=1",a=a.replace("useinbandfec=1",f),a}handleOnIce(r){var n;T.Log(T.GetStackTrace(),"peerconnection handleOnIce",6),this.config.isFlagEnabled(K.ForceTURN)&&r.candidate.indexOf("relay")<0?T.Info(T.GetStackTrace(),`Dropping candidate because it was not TURN relay. | Type= ${r.type} | Protocol= ${r.protocol} | Address=${r.address} | Port=${r.port} |`,6):(n=this.peerConnection)===null||n===void 0||n.addIceCandidate(r)}handleSignalStateChange(r){T.Log(T.GetStackTrace(),"signaling state change: "+r,6)}handleIceConnectionStateChange(r){T.Log(T.GetStackTrace(),"ice connection state change: "+r,6),this.onIceConnectionStateChange(r)}handleIceGatheringStateChange(r){T.Log(T.GetStackTrace(),"ice gathering state change: "+JSON.stringify(r),6)}handleOnTrack(r){this.onTrack(r)}handleIceCandidate(r){this.onPeerIceCandidate(r)}handleDataChannel(r){this.onDataChannel(r)}onTrack(r){}onIceConnectionStateChange(r){}onPeerIceCandidate(r){}onDataChannel(r){}fuzzyIntersectUEAndBrowserCodecs(r){const n=new Array,a=this.parseAvailableCodecs(r),f=this.config.getSettingOption(St.PreferredCodec).options;for(const v of a)if(f.includes(v))n.push(v);else{const C=v.split(" ")[0];for(const R of f)if(R.includes(C)){n.push(R);break}}return n}setupTransceiversAsync(r){var n,a,f,v,C,R,b,U,B,te,X,ee;return co(this,void 0,void 0,(function*(){let ie=!1;for(const ue of(a=(n=this.peerConnection)===null||n===void 0?void 0:n.getTransceivers())!==null&&a!==void 0?a:[])if(ue&&ue.receiver&&ue.receiver.track&&ue.receiver.track.kind==="video"){ie=!0;break}if(ie||(f=this.peerConnection)===null||f===void 0||f.addTransceiver("video",{direction:"recvonly"}),RTCRtpReceiver.getCapabilities&&this.preferredCodec!=""){for(const ue of(C=(v=this.peerConnection)===null||v===void 0?void 0:v.getTransceivers())!==null&&C!==void 0?C:[])if(ue&&ue.receiver&&ue.receiver.track&&ue.receiver.track.kind==="video"&&ue.setCodecPreferences){const Be=this.preferredCodec.split(" "),ke={mimeType:"video/"+Be[0],clockRate:9e4,sdpFmtpLine:Be[1]?Be[1]:""},he=[ke];RTCRtpReceiver.getCapabilities("video").codecs.forEach((re=>{(re.mimeType!=ke.mimeType||re?.sdpFmtpLine!=ke?.sdpFmtpLine)&&he.push(re)}));for(const re of he)re?.sdpFmtpLine!==void 0&&re.sdpFmtpLine!==""||delete re.sdpFmtpLine;ue.setCodecPreferences(he)}}let ce=!1;for(const ue of(b=(R=this.peerConnection)===null||R===void 0?void 0:R.getTransceivers())!==null&&b!==void 0?b:[])if(ue&&ue.receiver&&ue.receiver.track&&ue.receiver.track.kind==="audio"){ce=!0;break}if(r){const ue={video:!1,audio:{autoGainControl:!1,channelCount:1,echoCancellation:!1,latency:0,noiseSuppression:!1,sampleRate:48e3,sampleSize:16,volume:1}},Be=yield navigator.mediaDevices.getUserMedia(ue);if(Be)if(ce){for(const ke of(te=(B=this.peerConnection)===null||B===void 0?void 0:B.getTransceivers())!==null&&te!==void 0?te:[])if(um.canTransceiverReceiveAudio(ke))for(const he of Be.getTracks())he.kind&&he.kind=="audio"&&(ke.sender.replaceTrack(he),ke.direction="sendrecv")}else for(const ke of Be.getTracks())ke.kind&&ke.kind=="audio"&&((X=this.peerConnection)===null||X===void 0||X.addTransceiver(ke,{direction:"sendrecv"}));else ce||(ee=this.peerConnection)===null||ee===void 0||ee.addTransceiver("audio",{direction:"recvonly"})}else ce||(U=this.peerConnection)===null||U===void 0||U.addTransceiver("audio",{direction:"recvonly"})}))}onVideoStats(r){}onSendWebRTCOffer(r){}onSendWebRTCAnswer(r){}showTextOverlayConnecting(){}showTextOverlaySetupFailure(){}parseAvailableCodecs(r){if(!RTCRtpReceiver.getCapabilities)return["Only available on Chrome"];const n=[],a=(0,Wp.splitSections)(r.sdp);return a.shift(),a.forEach((f=>{const{codecs:v}=(0,Wp.parseRtpParameters)(f),C=/(VP\d|H26\d|AV1).*/;v.forEach((R=>{const b=R.name+" "+Object.keys(R.parameters||{}).map((U=>U+"="+R.parameters[U])).join(";");if(C.exec(b)!==null){R.name=="VP9"&&(R.parameters={"profile-id":"0"});const U=R.name+" "+Object.keys(R.parameters||{}).map((B=>B+"="+R.parameters[B])).join(";");n.push(U)}}))})),n}}class dm{constructor(){this.PixelStreamingSettings=new cw,this.EncoderSettings=new cm,this.WebRTCSettings=new hm}ueCompatible(){this.WebRTCSettings.MaxFPS!=null&&(this.WebRTCSettings.FPS=this.WebRTCSettings.MaxFPS)}}class cw{}class cm{}class hm{}class pm{constructor(){this.ReceiptTimeMs=null,this.TransmissionTimeMs=null,this.PreCaptureTimeMs=null,this.PostCaptureTimeMs=null,this.PreEncodeTimeMs=null,this.PostEncodeTimeMs=null,this.EncodeMs=null,this.CaptureToSendMs=null,this.testStartTimeMs=0,this.browserReceiptTimeMs=0,this.latencyExcludingDecode=0,this.testDuration=0,this.networkLatency=0,this.browserSendLatency=0,this.frameDisplayDeltaTimeMs=0,this.endToEndLatency=0,this.encodeLatency=0}setFrameDisplayDeltaTime(r){this.frameDisplayDeltaTimeMs==0&&(this.frameDisplayDeltaTimeMs=Math.round(r))}processFields(){this.EncodeMs!=null||this.PreEncodeTimeMs==null&&this.PostEncodeTimeMs==null||(T.Log(T.GetStackTrace(),`Setting Encode Ms
|
|
2901
2901
|
${this.PostEncodeTimeMs}
|
|
2902
2902
|
${this.PreEncodeTimeMs}`,6),this.EncodeMs=this.PostEncodeTimeMs-this.PreEncodeTimeMs),this.CaptureToSendMs!=null||this.PreCaptureTimeMs==null&&this.PostCaptureTimeMs==null||(T.Log(T.GetStackTrace(),`Setting CaptureToSendMs Ms
|