qt-human 4.1.2 → 4.2.0

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.
@@ -0,0 +1 @@
1
+ import{m as e,E as t}from"./shared-DSeGIn3o.js";import{L as i,T as n}from"./render-wURaNhSy.js";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function a(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var i=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})})),i}var o={exports:{}};var c,l={exports:{}},h=a(Object.freeze({__proto__:null,default:{}}));function d(){return c||(c=1,l.exports=function(){var e=e||function(e,t){var i;if("undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&void 0!==r&&r.crypto&&(i=r.crypto),!i)try{i=h}catch(e){}var n=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},s=Object.create||function(){function e(){}return function(t){var i;return e.prototype=t,i=new e,e.prototype=null,i}}(),a={},o=a.lib={},c=o.Base={extend:function(e){var t=s(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},l=o.WordArray=c.extend({init:function(e,i){e=this.words=e||[],this.sigBytes=i!=t?i:4*e.length},toString:function(e){return(e||u).stringify(this)},concat:function(e){var t=this.words,i=e.words,n=this.sigBytes,r=e.sigBytes;if(this.clamp(),n%4)for(var s=0;s<r;s++){var a=i[s>>>2]>>>24-s%4*8&255;t[n+s>>>2]|=a<<24-(n+s)%4*8}else for(var o=0;o<r;o+=4)t[n+o>>>2]=i[o>>>2];return this.sigBytes+=r,this},clamp:function(){var t=this.words,i=this.sigBytes;t[i>>>2]&=4294967295<<32-i%4*8,t.length=e.ceil(i/4)},clone:function(){var e=c.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],i=0;i<e;i+=4)t.push(n());return new l.init(t,e)}}),d=a.enc={},u=d.Hex={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r++){var s=t[r>>>2]>>>24-r%4*8&255;n.push((s>>>4).toString(16)),n.push((15&s).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,i=[],n=0;n<t;n+=2)i[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new l.init(i,t/2)}},f=d.Latin1={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r++){var s=t[r>>>2]>>>24-r%4*8&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var t=e.length,i=[],n=0;n<t;n++)i[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new l.init(i,t)}},p=d.Utf8={stringify:function(e){try{return decodeURIComponent(escape(f.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return f.parse(unescape(encodeURIComponent(e)))}},m=o.BufferedBlockAlgorithm=c.extend({reset:function(){this._data=new l.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=p.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var i,n=this._data,r=n.words,s=n.sigBytes,a=this.blockSize,o=s/(4*a),c=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,h=e.min(4*c,s);if(c){for(var d=0;d<c;d+=a)this._doProcessBlock(r,d);i=r.splice(0,c),n.sigBytes-=h}return new l.init(i,h)},clone:function(){var e=c.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});o.Hasher=m.extend({cfg:c.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){m.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,i){return new e.init(i).finalize(t)}},_createHmacHelper:function(e){return function(t,i){return new g.HMAC.init(e,i).finalize(t)}}});var g=a.algo={};return a}(Math);return e}()),l.exports}var u,f={exports:{}};function p(){return u||(u=1,f.exports=function(e){return n=(i=e).lib,r=n.Base,s=n.WordArray,(a=i.x64={}).Word=r.extend({init:function(e,t){this.high=e,this.low=t}}),a.WordArray=r.extend({init:function(e,i){e=this.words=e||[],this.sigBytes=i!=t?i:8*e.length},toX32:function(){for(var e=this.words,t=e.length,i=[],n=0;n<t;n++){var r=e[n];i.push(r.high),i.push(r.low)}return s.create(i,this.sigBytes)},clone:function(){for(var e=r.clone.call(this),t=e.words=this.words.slice(0),i=t.length,n=0;n<i;n++)t[n]=t[n].clone();return e}}),e;var t,i,n,r,s,a}(d())),f.exports}var m,g={exports:{}};function _(){return m||(m=1,g.exports=function(e){return function(){if("function"==typeof ArrayBuffer){var t=e.lib.WordArray,i=t.init,n=t.init=function(e){if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),(e instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array)&&(e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),e instanceof Uint8Array){for(var t=e.byteLength,n=[],r=0;r<t;r++)n[r>>>2]|=e[r]<<24-r%4*8;i.call(this,n,t)}else i.apply(this,arguments)};n.prototype=t}}(),e.lib.WordArray}(d())),g.exports}var y,T={exports:{}};function w(){return y||(y=1,T.exports=function(e){return function(){var t=e,i=t.lib.WordArray,n=t.enc;function r(e){return e<<8&4278255360|e>>>8&16711935}n.Utf16=n.Utf16BE={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],r=0;r<i;r+=2){var s=t[r>>>2]>>>16-r%4*8&65535;n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r<t;r++)n[r>>>1]|=e.charCodeAt(r)<<16-r%2*16;return i.create(n,2*t)}},n.Utf16LE={stringify:function(e){for(var t=e.words,i=e.sigBytes,n=[],s=0;s<i;s+=2){var a=r(t[s>>>2]>>>16-s%4*8&65535);n.push(String.fromCharCode(a))}return n.join("")},parse:function(e){for(var t=e.length,n=[],s=0;s<t;s++)n[s>>>1]|=r(e.charCodeAt(s)<<16-s%2*16);return i.create(n,2*t)}}}(),e.enc.Utf16}(d())),T.exports}var b,S={exports:{}};function v(){return b||(b=1,S.exports=function(e){return function(){var t=e,i=t.lib.WordArray;function n(e,t,n){for(var r=[],s=0,a=0;a<t;a++)if(a%4){var o=n[e.charCodeAt(a-1)]<<a%4*2|n[e.charCodeAt(a)]>>>6-a%4*2;r[s>>>2]|=o<<24-s%4*8,s++}return i.create(r,s)}t.enc.Base64={stringify:function(e){var t=e.words,i=e.sigBytes,n=this._map;e.clamp();for(var r=[],s=0;s<i;s+=3)for(var a=(t[s>>>2]>>>24-s%4*8&255)<<16|(t[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|t[s+2>>>2]>>>24-(s+2)%4*8&255,o=0;o<4&&s+.75*o<i;o++)r.push(n.charAt(a>>>6*(3-o)&63));var c=n.charAt(64);if(c)for(;r.length%4;)r.push(c);return r.join("")},parse:function(e){var t=e.length,i=this._map,r=this._reverseMap;if(!r){r=this._reverseMap=[];for(var s=0;s<i.length;s++)r[i.charCodeAt(s)]=s}var a=i.charAt(64);if(a){var o=e.indexOf(a);-1!==o&&(t=o)}return n(e,t,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.enc.Base64}(d())),S.exports}var A,E={exports:{}};function R(){return A||(A=1,E.exports=function(e){return function(){var t=e,i=t.lib.WordArray;function n(e,t,n){for(var r=[],s=0,a=0;a<t;a++)if(a%4){var o=n[e.charCodeAt(a-1)]<<a%4*2|n[e.charCodeAt(a)]>>>6-a%4*2;r[s>>>2]|=o<<24-s%4*8,s++}return i.create(r,s)}t.enc.Base64url={stringify:function(e,t){void 0===t&&(t=!0);var i=e.words,n=e.sigBytes,r=t?this._safe_map:this._map;e.clamp();for(var s=[],a=0;a<n;a+=3)for(var o=(i[a>>>2]>>>24-a%4*8&255)<<16|(i[a+1>>>2]>>>24-(a+1)%4*8&255)<<8|i[a+2>>>2]>>>24-(a+2)%4*8&255,c=0;c<4&&a+.75*c<n;c++)s.push(r.charAt(o>>>6*(3-c)&63));var l=r.charAt(64);if(l)for(;s.length%4;)s.push(l);return s.join("")},parse:function(e,t){void 0===t&&(t=!0);var i=e.length,r=t?this._safe_map:this._map,s=this._reverseMap;if(!s){s=this._reverseMap=[];for(var a=0;a<r.length;a++)s[r.charCodeAt(a)]=a}var o=r.charAt(64);if(o){var c=e.indexOf(o);-1!==c&&(i=c)}return n(e,i,s)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"}}(),e.enc.Base64url}(d())),E.exports}var k,x={exports:{}};function C(){return k||(k=1,x.exports=function(e){return function(t){var i=e,n=i.lib,r=n.WordArray,s=n.Hasher,a=i.algo,o=[];!function(){for(var e=0;e<64;e++)o[e]=4294967296*t.abs(t.sin(e+1))|0}();var c=a.MD5=s.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var i=0;i<16;i++){var n=t+i,r=e[n];e[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8)}var s=this._hash.words,a=e[t+0],c=e[t+1],f=e[t+2],p=e[t+3],m=e[t+4],g=e[t+5],_=e[t+6],y=e[t+7],T=e[t+8],w=e[t+9],b=e[t+10],S=e[t+11],v=e[t+12],A=e[t+13],E=e[t+14],R=e[t+15],k=s[0],x=s[1],C=s[2],I=s[3];k=l(k,x,C,I,a,7,o[0]),I=l(I,k,x,C,c,12,o[1]),C=l(C,I,k,x,f,17,o[2]),x=l(x,C,I,k,p,22,o[3]),k=l(k,x,C,I,m,7,o[4]),I=l(I,k,x,C,g,12,o[5]),C=l(C,I,k,x,_,17,o[6]),x=l(x,C,I,k,y,22,o[7]),k=l(k,x,C,I,T,7,o[8]),I=l(I,k,x,C,w,12,o[9]),C=l(C,I,k,x,b,17,o[10]),x=l(x,C,I,k,S,22,o[11]),k=l(k,x,C,I,v,7,o[12]),I=l(I,k,x,C,A,12,o[13]),C=l(C,I,k,x,E,17,o[14]),k=h(k,x=l(x,C,I,k,R,22,o[15]),C,I,c,5,o[16]),I=h(I,k,x,C,_,9,o[17]),C=h(C,I,k,x,S,14,o[18]),x=h(x,C,I,k,a,20,o[19]),k=h(k,x,C,I,g,5,o[20]),I=h(I,k,x,C,b,9,o[21]),C=h(C,I,k,x,R,14,o[22]),x=h(x,C,I,k,m,20,o[23]),k=h(k,x,C,I,w,5,o[24]),I=h(I,k,x,C,E,9,o[25]),C=h(C,I,k,x,p,14,o[26]),x=h(x,C,I,k,T,20,o[27]),k=h(k,x,C,I,A,5,o[28]),I=h(I,k,x,C,f,9,o[29]),C=h(C,I,k,x,y,14,o[30]),k=d(k,x=h(x,C,I,k,v,20,o[31]),C,I,g,4,o[32]),I=d(I,k,x,C,T,11,o[33]),C=d(C,I,k,x,S,16,o[34]),x=d(x,C,I,k,E,23,o[35]),k=d(k,x,C,I,c,4,o[36]),I=d(I,k,x,C,m,11,o[37]),C=d(C,I,k,x,y,16,o[38]),x=d(x,C,I,k,b,23,o[39]),k=d(k,x,C,I,A,4,o[40]),I=d(I,k,x,C,a,11,o[41]),C=d(C,I,k,x,p,16,o[42]),x=d(x,C,I,k,_,23,o[43]),k=d(k,x,C,I,w,4,o[44]),I=d(I,k,x,C,v,11,o[45]),C=d(C,I,k,x,R,16,o[46]),k=u(k,x=d(x,C,I,k,f,23,o[47]),C,I,a,6,o[48]),I=u(I,k,x,C,y,10,o[49]),C=u(C,I,k,x,E,15,o[50]),x=u(x,C,I,k,g,21,o[51]),k=u(k,x,C,I,v,6,o[52]),I=u(I,k,x,C,p,10,o[53]),C=u(C,I,k,x,b,15,o[54]),x=u(x,C,I,k,c,21,o[55]),k=u(k,x,C,I,T,6,o[56]),I=u(I,k,x,C,R,10,o[57]),C=u(C,I,k,x,_,15,o[58]),x=u(x,C,I,k,A,21,o[59]),k=u(k,x,C,I,m,6,o[60]),I=u(I,k,x,C,S,10,o[61]),C=u(C,I,k,x,f,15,o[62]),x=u(x,C,I,k,w,21,o[63]),s[0]=s[0]+k|0,s[1]=s[1]+x|0,s[2]=s[2]+C|0,s[3]=s[3]+I|0},_doFinalize:function(){var e=this._data,i=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;i[r>>>5]|=128<<24-r%32;var s=t.floor(n/4294967296),a=n;i[15+(r+64>>>9<<4)]=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),i[14+(r+64>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),e.sigBytes=4*(i.length+1),this._process();for(var o=this._hash,c=o.words,l=0;l<4;l++){var h=c[l];c[l]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return o},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function l(e,t,i,n,r,s,a){var o=e+(t&i|~t&n)+r+a;return(o<<s|o>>>32-s)+t}function h(e,t,i,n,r,s,a){var o=e+(t&n|i&~n)+r+a;return(o<<s|o>>>32-s)+t}function d(e,t,i,n,r,s,a){var o=e+(t^i^n)+r+a;return(o<<s|o>>>32-s)+t}function u(e,t,i,n,r,s,a){var o=e+(i^(t|~n))+r+a;return(o<<s|o>>>32-s)+t}i.MD5=s._createHelper(c),i.HmacMD5=s._createHmacHelper(c)}(Math),e.MD5}(d())),x.exports}var I,P={exports:{}};function D(){return I||(I=1,P.exports=function(e){return i=(t=e).lib,n=i.WordArray,r=i.Hasher,s=t.algo,a=[],o=s.SHA1=r.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],o=i[3],c=i[4],l=0;l<80;l++){if(l<16)a[l]=0|e[t+l];else{var h=a[l-3]^a[l-8]^a[l-14]^a[l-16];a[l]=h<<1|h>>>31}var d=(n<<5|n>>>27)+c+a[l];d+=l<20?1518500249+(r&s|~r&o):l<40?1859775393+(r^s^o):l<60?(r&s|r&o|s&o)-1894007588:(r^s^o)-899497514,c=o,o=s,s=r<<30|r>>>2,r=n,n=d}i[0]=i[0]+n|0,i[1]=i[1]+r|0,i[2]=i[2]+s|0,i[3]=i[3]+o|0,i[4]=i[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=Math.floor(i/4294967296),t[15+(n+64>>>9<<4)]=i,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA1=r._createHelper(o),t.HmacSHA1=r._createHmacHelper(o),e.SHA1;var t,i,n,r,s,a,o}(d())),P.exports}var O,L={exports:{}};function M(){return O||(O=1,L.exports=function(e){return function(t){var i=e,n=i.lib,r=n.WordArray,s=n.Hasher,a=i.algo,o=[],c=[];!function(){function e(e){for(var i=t.sqrt(e),n=2;n<=i;n++)if(!(e%n))return!1;return!0}function i(e){return 4294967296*(e-(0|e))|0}for(var n=2,r=0;r<64;)e(n)&&(r<8&&(o[r]=i(t.pow(n,.5))),c[r]=i(t.pow(n,1/3)),r++),n++}();var l=[],h=a.SHA256=s.extend({_doReset:function(){this._hash=new r.init(o.slice(0))},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],a=i[3],o=i[4],h=i[5],d=i[6],u=i[7],f=0;f<64;f++){if(f<16)l[f]=0|e[t+f];else{var p=l[f-15],m=(p<<25|p>>>7)^(p<<14|p>>>18)^p>>>3,g=l[f-2],_=(g<<15|g>>>17)^(g<<13|g>>>19)^g>>>10;l[f]=m+l[f-7]+_+l[f-16]}var y=n&r^n&s^r&s,T=(n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22),w=u+((o<<26|o>>>6)^(o<<21|o>>>11)^(o<<7|o>>>25))+(o&h^~o&d)+c[f]+l[f];u=d,d=h,h=o,o=a+w|0,a=s,s=r,r=n,n=w+(T+y)|0}i[0]=i[0]+n|0,i[1]=i[1]+r|0,i[2]=i[2]+s|0,i[3]=i[3]+a|0,i[4]=i[4]+o|0,i[5]=i[5]+h|0,i[6]=i[6]+d|0,i[7]=i[7]+u|0},_doFinalize:function(){var e=this._data,i=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return i[r>>>5]|=128<<24-r%32,i[14+(r+64>>>9<<4)]=t.floor(n/4294967296),i[15+(r+64>>>9<<4)]=n,e.sigBytes=4*i.length,this._process(),this._hash},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});i.SHA256=s._createHelper(h),i.HmacSHA256=s._createHmacHelper(h)}(Math),e.SHA256}(d())),L.exports}var B,N={exports:{}};var F,W={exports:{}};function U(){return F||(F=1,W.exports=function(e){return function(){var t=e,i=t.lib.Hasher,n=t.x64,r=n.Word,s=n.WordArray,a=t.algo;function o(){return r.create.apply(r,arguments)}var c=[o(1116352408,3609767458),o(1899447441,602891725),o(3049323471,3964484399),o(3921009573,2173295548),o(961987163,4081628472),o(1508970993,3053834265),o(2453635748,2937671579),o(2870763221,3664609560),o(3624381080,2734883394),o(310598401,1164996542),o(607225278,1323610764),o(1426881987,3590304994),o(1925078388,4068182383),o(2162078206,991336113),o(2614888103,633803317),o(3248222580,3479774868),o(3835390401,2666613458),o(4022224774,944711139),o(264347078,2341262773),o(604807628,2007800933),o(770255983,1495990901),o(1249150122,1856431235),o(1555081692,3175218132),o(1996064986,2198950837),o(2554220882,3999719339),o(2821834349,766784016),o(2952996808,2566594879),o(3210313671,3203337956),o(3336571891,1034457026),o(3584528711,2466948901),o(113926993,3758326383),o(338241895,168717936),o(666307205,1188179964),o(773529912,1546045734),o(1294757372,1522805485),o(1396182291,2643833823),o(1695183700,2343527390),o(1986661051,1014477480),o(2177026350,1206759142),o(2456956037,344077627),o(2730485921,1290863460),o(2820302411,3158454273),o(3259730800,3505952657),o(3345764771,106217008),o(3516065817,3606008344),o(3600352804,1432725776),o(4094571909,1467031594),o(275423344,851169720),o(430227734,3100823752),o(506948616,1363258195),o(659060556,3750685593),o(883997877,3785050280),o(958139571,3318307427),o(1322822218,3812723403),o(1537002063,2003034995),o(1747873779,3602036899),o(1955562222,1575990012),o(2024104815,1125592928),o(2227730452,2716904306),o(2361852424,442776044),o(2428436474,593698344),o(2756734187,3733110249),o(3204031479,2999351573),o(3329325298,3815920427),o(3391569614,3928383900),o(3515267271,566280711),o(3940187606,3454069534),o(4118630271,4000239992),o(116418474,1914138554),o(174292421,2731055270),o(289380356,3203993006),o(460393269,320620315),o(685471733,587496836),o(852142971,1086792851),o(1017036298,365543100),o(1126000580,2618297676),o(1288033470,3409855158),o(1501505948,4234509866),o(1607167915,987167468),o(1816402316,1246189591)],l=[];!function(){for(var e=0;e<80;e++)l[e]=o()}();var h=a.SHA512=i.extend({_doReset:function(){this._hash=new s.init([new r.init(1779033703,4089235720),new r.init(3144134277,2227873595),new r.init(1013904242,4271175723),new r.init(2773480762,1595750129),new r.init(1359893119,2917565137),new r.init(2600822924,725511199),new r.init(528734635,4215389547),new r.init(1541459225,327033209)])},_doProcessBlock:function(e,t){for(var i=this._hash.words,n=i[0],r=i[1],s=i[2],a=i[3],o=i[4],h=i[5],d=i[6],u=i[7],f=n.high,p=n.low,m=r.high,g=r.low,_=s.high,y=s.low,T=a.high,w=a.low,b=o.high,S=o.low,v=h.high,A=h.low,E=d.high,R=d.low,k=u.high,x=u.low,C=f,I=p,P=m,D=g,O=_,L=y,M=T,B=w,N=b,F=S,W=v,U=A,G=E,H=R,z=k,j=x,V=0;V<80;V++){var q,Y,K=l[V];if(V<16)Y=K.high=0|e[t+2*V],q=K.low=0|e[t+2*V+1];else{var X=l[V-15],$=X.high,Z=X.low,J=($>>>1|Z<<31)^($>>>8|Z<<24)^$>>>7,Q=(Z>>>1|$<<31)^(Z>>>8|$<<24)^(Z>>>7|$<<25),ee=l[V-2],te=ee.high,ie=ee.low,ne=(te>>>19|ie<<13)^(te<<3|ie>>>29)^te>>>6,re=(ie>>>19|te<<13)^(ie<<3|te>>>29)^(ie>>>6|te<<26),se=l[V-7],ae=se.high,oe=se.low,ce=l[V-16],le=ce.high,he=ce.low;Y=(Y=(Y=J+ae+((q=Q+oe)>>>0<Q>>>0?1:0))+ne+((q+=re)>>>0<re>>>0?1:0))+le+((q+=he)>>>0<he>>>0?1:0),K.high=Y,K.low=q}var de,ue=N&W^~N&G,fe=F&U^~F&H,pe=C&P^C&O^P&O,me=I&D^I&L^D&L,ge=(C>>>28|I<<4)^(C<<30|I>>>2)^(C<<25|I>>>7),_e=(I>>>28|C<<4)^(I<<30|C>>>2)^(I<<25|C>>>7),ye=(N>>>14|F<<18)^(N>>>18|F<<14)^(N<<23|F>>>9),Te=(F>>>14|N<<18)^(F>>>18|N<<14)^(F<<23|N>>>9),we=c[V],be=we.high,Se=we.low,ve=z+ye+((de=j+Te)>>>0<j>>>0?1:0),Ae=_e+me;z=G,j=H,G=W,H=U,W=N,U=F,N=M+(ve=(ve=(ve=ve+ue+((de+=fe)>>>0<fe>>>0?1:0))+be+((de+=Se)>>>0<Se>>>0?1:0))+Y+((de+=q)>>>0<q>>>0?1:0))+((F=B+de|0)>>>0<B>>>0?1:0)|0,M=O,B=L,O=P,L=D,P=C,D=I,C=ve+(ge+pe+(Ae>>>0<_e>>>0?1:0))+((I=de+Ae|0)>>>0<de>>>0?1:0)|0}p=n.low=p+I,n.high=f+C+(p>>>0<I>>>0?1:0),g=r.low=g+D,r.high=m+P+(g>>>0<D>>>0?1:0),y=s.low=y+L,s.high=_+O+(y>>>0<L>>>0?1:0),w=a.low=w+B,a.high=T+M+(w>>>0<B>>>0?1:0),S=o.low=S+F,o.high=b+N+(S>>>0<F>>>0?1:0),A=h.low=A+U,h.high=v+W+(A>>>0<U>>>0?1:0),R=d.low=R+H,d.high=E+G+(R>>>0<H>>>0?1:0),x=u.low=x+j,u.high=k+z+(x>>>0<j>>>0?1:0)},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[30+(n+128>>>10<<5)]=Math.floor(i/4294967296),t[31+(n+128>>>10<<5)]=i,e.sigBytes=4*t.length,this._process(),this._hash.toX32()},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e},blockSize:32});t.SHA512=i._createHelper(h),t.HmacSHA512=i._createHmacHelper(h)}(),e.SHA512}(d(),p())),W.exports}var G,H={exports:{}};var z,j={exports:{}};function V(){return z||(z=1,j.exports=function(e){return function(t){var i=e,n=i.lib,r=n.WordArray,s=n.Hasher,a=i.x64.Word,o=i.algo,c=[],l=[],h=[];!function(){for(var e=1,t=0,i=0;i<24;i++){c[e+5*t]=(i+1)*(i+2)/2%64;var n=(2*e+3*t)%5;e=t%5,t=n}for(e=0;e<5;e++)for(t=0;t<5;t++)l[e+5*t]=t+(2*e+3*t)%5*5;for(var r=1,s=0;s<24;s++){for(var o=0,d=0,u=0;u<7;u++){if(1&r){var f=(1<<u)-1;f<32?d^=1<<f:o^=1<<f-32}128&r?r=r<<1^113:r<<=1}h[s]=a.create(o,d)}}();var d=[];!function(){for(var e=0;e<25;e++)d[e]=a.create()}();var u=o.SHA3=s.extend({cfg:s.cfg.extend({outputLength:512}),_doReset:function(){for(var e=this._state=[],t=0;t<25;t++)e[t]=new a.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(e,t){for(var i=this._state,n=this.blockSize/2,r=0;r<n;r++){var s=e[t+2*r],a=e[t+2*r+1];s=16711935&(s<<8|s>>>24)|4278255360&(s<<24|s>>>8),a=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),(x=i[r]).high^=a,x.low^=s}for(var o=0;o<24;o++){for(var u=0;u<5;u++){for(var f=0,p=0,m=0;m<5;m++)f^=(x=i[u+5*m]).high,p^=x.low;var g=d[u];g.high=f,g.low=p}for(u=0;u<5;u++){var _=d[(u+4)%5],y=d[(u+1)%5],T=y.high,w=y.low;for(f=_.high^(T<<1|w>>>31),p=_.low^(w<<1|T>>>31),m=0;m<5;m++)(x=i[u+5*m]).high^=f,x.low^=p}for(var b=1;b<25;b++){var S=(x=i[b]).high,v=x.low,A=c[b];A<32?(f=S<<A|v>>>32-A,p=v<<A|S>>>32-A):(f=v<<A-32|S>>>64-A,p=S<<A-32|v>>>64-A);var E=d[l[b]];E.high=f,E.low=p}var R=d[0],k=i[0];for(R.high=k.high,R.low=k.low,u=0;u<5;u++)for(m=0;m<5;m++){var x=i[b=u+5*m],C=d[b],I=d[(u+1)%5+5*m],P=d[(u+2)%5+5*m];x.high=C.high^~I.high&P.high,x.low=C.low^~I.low&P.low}x=i[0];var D=h[o];x.high^=D.high,x.low^=D.low}},_doFinalize:function(){var e=this._data,i=e.words;this._nDataBytes;var n=8*e.sigBytes,s=32*this.blockSize;i[n>>>5]|=1<<24-n%32,i[(t.ceil((n+1)/s)*s>>>5)-1]|=128,e.sigBytes=4*i.length,this._process();for(var a=this._state,o=this.cfg.outputLength/8,c=o/8,l=[],h=0;h<c;h++){var d=a[h],u=d.high,f=d.low;u=16711935&(u<<8|u>>>24)|4278255360&(u<<24|u>>>8),f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),l.push(f),l.push(u)}return new r.init(l,o)},clone:function(){for(var e=s.clone.call(this),t=e._state=this._state.slice(0),i=0;i<25;i++)t[i]=t[i].clone();return e}});i.SHA3=s._createHelper(u),i.HmacSHA3=s._createHmacHelper(u)}(Math),e.SHA3}(d(),p())),j.exports}var q,Y={exports:{}};var K,X={exports:{}};function $(){return K||(K=1,X.exports=function(e){var t,i,n;i=(t=e).lib.Base,n=t.enc.Utf8,t.algo.HMAC=i.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=n.parse(t));var i=e.blockSize,r=4*i;t.sigBytes>r&&(t=e.finalize(t)),t.clamp();for(var s=this._oKey=t.clone(),a=this._iKey=t.clone(),o=s.words,c=a.words,l=0;l<i;l++)o[l]^=1549556828,c[l]^=909522486;s.sigBytes=a.sigBytes=r,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher,i=t.finalize(e);return t.reset(),t.finalize(this._oKey.clone().concat(i))}})}(d())),X.exports}var Z,J={exports:{}};var Q,ee={exports:{}};function te(){return Q||(Q=1,ee.exports=function(e){return i=(t=e).lib,n=i.Base,r=i.WordArray,s=t.algo,a=s.MD5,o=s.EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:a,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var i,n=this.cfg,s=n.hasher.create(),a=r.create(),o=a.words,c=n.keySize,l=n.iterations;o.length<c;){i&&s.update(i),i=s.update(e).finalize(t),s.reset();for(var h=1;h<l;h++)i=s.finalize(i),s.reset();a.concat(i)}return a.sigBytes=4*c,a}}),t.EvpKDF=function(e,t,i){return o.create(i).compute(e,t)},e.EvpKDF;var t,i,n,r,s,a,o}(d(),D(),$())),ee.exports}var ie,ne={exports:{}};function re(){return ie||(ie=1,ne.exports=function(e){e.lib.Cipher||function(t){var i=e,n=i.lib,r=n.Base,s=n.WordArray,a=n.BufferedBlockAlgorithm,o=i.enc;o.Utf8;var c=o.Base64,l=i.algo.EvpKDF,h=n.Cipher=a.extend({cfg:r.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,i){this.cfg=this.cfg.extend(i),this._xformMode=e,this._key=t,this.reset()},reset:function(){a.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function e(e){return"string"==typeof e?T:_}return function(t){return{encrypt:function(i,n,r){return e(n).encrypt(t,i,n,r)},decrypt:function(i,n,r){return e(n).decrypt(t,i,n,r)}}}}()});n.StreamCipher=h.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var d=i.mode={},u=n.BlockCipherMode=r.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}}),f=d.CBC=function(){var e=u.extend();function i(e,i,n){var r,s=this._iv;s?(r=s,this._iv=t):r=this._prevBlock;for(var a=0;a<n;a++)e[i+a]^=r[a]}return e.Encryptor=e.extend({processBlock:function(e,t){var n=this._cipher,r=n.blockSize;i.call(this,e,t,r),n.encryptBlock(e,t),this._prevBlock=e.slice(t,t+r)}}),e.Decryptor=e.extend({processBlock:function(e,t){var n=this._cipher,r=n.blockSize,s=e.slice(t,t+r);n.decryptBlock(e,t),i.call(this,e,t,r),this._prevBlock=s}}),e}(),p=(i.pad={}).Pkcs7={pad:function(e,t){for(var i=4*t,n=i-e.sigBytes%i,r=n<<24|n<<16|n<<8|n,a=[],o=0;o<n;o+=4)a.push(r);var c=s.create(a,n);e.concat(c)},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}};n.BlockCipher=h.extend({cfg:h.cfg.extend({mode:f,padding:p}),reset:function(){var e;h.reset.call(this);var t=this.cfg,i=t.iv,n=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=n.createEncryptor:(e=n.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,i&&i.words):(this._mode=e.call(n,this,i&&i.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var m=n.CipherParams=r.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),g=(i.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,i=e.salt;return(i?s.create([1398893684,1701076831]).concat(i).concat(t):t).toString(c)},parse:function(e){var t,i=c.parse(e),n=i.words;return 1398893684==n[0]&&1701076831==n[1]&&(t=s.create(n.slice(2,4)),n.splice(0,4),i.sigBytes-=16),m.create({ciphertext:i,salt:t})}},_=n.SerializableCipher=r.extend({cfg:r.extend({format:g}),encrypt:function(e,t,i,n){n=this.cfg.extend(n);var r=e.createEncryptor(i,n),s=r.finalize(t),a=r.cfg;return m.create({ciphertext:s,key:i,iv:a.iv,algorithm:e,mode:a.mode,padding:a.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,i,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(i,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),y=(i.kdf={}).OpenSSL={execute:function(e,t,i,n,r){if(n||(n=s.random(8)),r)a=l.create({keySize:t+i,hasher:r}).compute(e,n);else var a=l.create({keySize:t+i}).compute(e,n);var o=s.create(a.words.slice(t),4*i);return a.sigBytes=4*t,m.create({key:a,iv:o,salt:n})}},T=n.PasswordBasedCipher=_.extend({cfg:_.cfg.extend({kdf:y}),encrypt:function(e,t,i,n){var r=(n=this.cfg.extend(n)).kdf.execute(i,e.keySize,e.ivSize,n.salt,n.hasher);n.iv=r.iv;var s=_.encrypt.call(this,e,t,r.key,n);return s.mixIn(r),s},decrypt:function(e,t,i,n){n=this.cfg.extend(n),t=this._parse(t,n.format);var r=n.kdf.execute(i,e.keySize,e.ivSize,t.salt,n.hasher);return n.iv=r.iv,_.decrypt.call(this,e,t,r.key,n)}})}()}(d(),te())),ne.exports}var se,ae={exports:{}};function oe(){return se||(se=1,ae.exports=function(e){return e.mode.CFB=function(){var t=e.lib.BlockCipherMode.extend();function i(e,t,i,n){var r,s=this._iv;s?(r=s.slice(0),this._iv=void 0):r=this._prevBlock,n.encryptBlock(r,0);for(var a=0;a<i;a++)e[t+a]^=r[a]}return t.Encryptor=t.extend({processBlock:function(e,t){var n=this._cipher,r=n.blockSize;i.call(this,e,t,r,n),this._prevBlock=e.slice(t,t+r)}}),t.Decryptor=t.extend({processBlock:function(e,t){var n=this._cipher,r=n.blockSize,s=e.slice(t,t+r);i.call(this,e,t,r,n),this._prevBlock=s}}),t}(),e.mode.CFB}(d(),re())),ae.exports}var ce,le={exports:{}};function he(){return ce||(ce=1,le.exports=function(e){return e.mode.CTR=(t=e.lib.BlockCipherMode.extend(),i=t.Encryptor=t.extend({processBlock:function(e,t){var i=this._cipher,n=i.blockSize,r=this._iv,s=this._counter;r&&(s=this._counter=r.slice(0),this._iv=void 0);var a=s.slice(0);i.encryptBlock(a,0),s[n-1]=s[n-1]+1|0;for(var o=0;o<n;o++)e[t+o]^=a[o]}}),t.Decryptor=i,t),e.mode.CTR;var t,i}(d(),re())),le.exports}var de,ue={exports:{}};function fe(){return de||(de=1,ue.exports=function(e){return e.mode.CTRGladman=function(){var t=e.lib.BlockCipherMode.extend();function i(e){if(255&~(e>>24))e+=1<<24;else{var t=e>>16&255,i=e>>8&255,n=255&e;255===t?(t=0,255===i?(i=0,255===n?n=0:++n):++i):++t,e=0,e+=t<<16,e+=i<<8,e+=n}return e}function n(e){return 0===(e[0]=i(e[0]))&&(e[1]=i(e[1])),e}var r=t.Encryptor=t.extend({processBlock:function(e,t){var i=this._cipher,r=i.blockSize,s=this._iv,a=this._counter;s&&(a=this._counter=s.slice(0),this._iv=void 0),n(a);var o=a.slice(0);i.encryptBlock(o,0);for(var c=0;c<r;c++)e[t+c]^=o[c]}});return t.Decryptor=r,t}(),e.mode.CTRGladman}(d(),re())),ue.exports}var pe,me={exports:{}};function ge(){return pe||(pe=1,me.exports=function(e){return e.mode.OFB=(t=e.lib.BlockCipherMode.extend(),i=t.Encryptor=t.extend({processBlock:function(e,t){var i=this._cipher,n=i.blockSize,r=this._iv,s=this._keystream;r&&(s=this._keystream=r.slice(0),this._iv=void 0),i.encryptBlock(s,0);for(var a=0;a<n;a++)e[t+a]^=s[a]}}),t.Decryptor=i,t),e.mode.OFB;var t,i}(d(),re())),me.exports}var _e,ye={exports:{}};var Te,we={exports:{}};var be,Se={exports:{}};var ve,Ae={exports:{}};var Ee,Re={exports:{}};var ke,xe={exports:{}};var Ce,Ie={exports:{}};var Pe,De={exports:{}};var Oe,Le={exports:{}};function Me(){return Oe||(Oe=1,Le.exports=function(e){return function(){var t=e,i=t.lib,n=i.WordArray,r=i.BlockCipher,s=t.algo,a=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],o=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],c=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],h=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],d=s.DES=r.extend({_doReset:function(){for(var e=this._key.words,t=[],i=0;i<56;i++){var n=a[i]-1;t[i]=e[n>>>5]>>>31-n%32&1}for(var r=this._subKeys=[],s=0;s<16;s++){var l=r[s]=[],h=c[s];for(i=0;i<24;i++)l[i/6|0]|=t[(o[i]-1+h)%28]<<31-i%6,l[4+(i/6|0)]|=t[28+(o[i+24]-1+h)%28]<<31-i%6;for(l[0]=l[0]<<1|l[0]>>>31,i=1;i<7;i++)l[i]=l[i]>>>4*(i-1)+3;l[7]=l[7]<<5|l[7]>>>27}var d=this._invSubKeys=[];for(i=0;i<16;i++)d[i]=r[15-i]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._subKeys)},decryptBlock:function(e,t){this._doCryptBlock(e,t,this._invSubKeys)},_doCryptBlock:function(e,t,i){this._lBlock=e[t],this._rBlock=e[t+1],u.call(this,4,252645135),u.call(this,16,65535),f.call(this,2,858993459),f.call(this,8,16711935),u.call(this,1,1431655765);for(var n=0;n<16;n++){for(var r=i[n],s=this._lBlock,a=this._rBlock,o=0,c=0;c<8;c++)o|=l[c][((a^r[c])&h[c])>>>0];this._lBlock=a,this._rBlock=s^o}var d=this._lBlock;this._lBlock=this._rBlock,this._rBlock=d,u.call(this,1,1431655765),f.call(this,8,16711935),f.call(this,2,858993459),u.call(this,16,65535),u.call(this,4,252645135),e[t]=this._lBlock,e[t+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});function u(e,t){var i=(this._lBlock>>>e^this._rBlock)&t;this._rBlock^=i,this._lBlock^=i<<e}function f(e,t){var i=(this._rBlock>>>e^this._lBlock)&t;this._lBlock^=i,this._rBlock^=i<<e}t.DES=r._createHelper(d);var p=s.TripleDES=r.extend({_doReset:function(){var e=this._key.words;if(2!==e.length&&4!==e.length&&e.length<6)throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192.");var t=e.slice(0,2),i=e.length<4?e.slice(0,2):e.slice(2,4),r=e.length<6?e.slice(0,2):e.slice(4,6);this._des1=d.createEncryptor(n.create(t)),this._des2=d.createEncryptor(n.create(i)),this._des3=d.createEncryptor(n.create(r))},encryptBlock:function(e,t){this._des1.encryptBlock(e,t),this._des2.decryptBlock(e,t),this._des3.encryptBlock(e,t)},decryptBlock:function(e,t){this._des3.decryptBlock(e,t),this._des2.encryptBlock(e,t),this._des1.decryptBlock(e,t)},keySize:6,ivSize:2,blockSize:2});t.TripleDES=r._createHelper(p)}(),e.TripleDES}(d(),v(),C(),te(),re())),Le.exports}var Be,Ne={exports:{}};var Fe,We={exports:{}};var Ue,Ge={exports:{}};var He,ze={exports:{}};function je(){return He||(He=1,ze.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,n=t.algo;const r=16,s=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],a=[[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946],[1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055],[3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504],[976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462]];var o={pbox:[],sbox:[]};function c(e,t){let i=t>>24&255,n=t>>16&255,r=t>>8&255,s=255&t,a=e.sbox[0][i]+e.sbox[1][n];return a^=e.sbox[2][r],a+=e.sbox[3][s],a}function l(e,t,i){let n,s=t,a=i;for(let t=0;t<r;++t)s^=e.pbox[t],a=c(e,s)^a,n=s,s=a,a=n;return n=s,s=a,a=n,a^=e.pbox[r],s^=e.pbox[r+1],{left:s,right:a}}function h(e,t,i){let n,s=t,a=i;for(let t=r+1;t>1;--t)s^=e.pbox[t],a=c(e,s)^a,n=s,s=a,a=n;return n=s,s=a,a=n,a^=e.pbox[1],s^=e.pbox[0],{left:s,right:a}}function d(e,t,i){for(let t=0;t<4;t++){e.sbox[t]=[];for(let i=0;i<256;i++)e.sbox[t][i]=a[t][i]}let n=0;for(let a=0;a<r+2;a++)e.pbox[a]=s[a]^t[n],n++,n>=i&&(n=0);let o=0,c=0,h=0;for(let t=0;t<r+2;t+=2)h=l(e,o,c),o=h.left,c=h.right,e.pbox[t]=o,e.pbox[t+1]=c;for(let t=0;t<4;t++)for(let i=0;i<256;i+=2)h=l(e,o,c),o=h.left,c=h.right,e.sbox[t][i]=o,e.sbox[t][i+1]=c;return!0}var u=n.Blowfish=i.extend({_doReset:function(){if(this._keyPriorReset!==this._key){var e=this._keyPriorReset=this._key,t=e.words,i=e.sigBytes/4;d(o,t,i)}},encryptBlock:function(e,t){var i=l(o,e[t],e[t+1]);e[t]=i.left,e[t+1]=i.right},decryptBlock:function(e,t){var i=h(o,e[t],e[t+1]);e[t]=i.left,e[t+1]=i.right},blockSize:2,keySize:4,ivSize:2});t.Blowfish=i._createHelper(u)}(),e.Blowfish}(d(),v(),C(),te(),re())),ze.exports}o.exports=function(e){return e}(d(),p(),_(),w(),v(),R(),C(),D(),M(),B||(B=1,N.exports=function(e){return i=(t=e).lib.WordArray,n=t.algo,r=n.SHA256,s=n.SHA224=r.extend({_doReset:function(){this._hash=new i.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var e=r._doFinalize.call(this);return e.sigBytes-=4,e}}),t.SHA224=r._createHelper(s),t.HmacSHA224=r._createHmacHelper(s),e.SHA224;var t,i,n,r,s}(d(),M())),U(),G||(G=1,H.exports=function(e){return i=(t=e).x64,n=i.Word,r=i.WordArray,s=t.algo,a=s.SHA512,o=s.SHA384=a.extend({_doReset:function(){this._hash=new r.init([new n.init(3418070365,3238371032),new n.init(1654270250,914150663),new n.init(2438529370,812702999),new n.init(355462360,4144912697),new n.init(1731405415,4290775857),new n.init(2394180231,1750603025),new n.init(3675008525,1694076839),new n.init(1203062813,3204075428)])},_doFinalize:function(){var e=a._doFinalize.call(this);return e.sigBytes-=16,e}}),t.SHA384=a._createHelper(o),t.HmacSHA384=a._createHmacHelper(o),e.SHA384;var t,i,n,r,s,a,o}(d(),p(),U())),V(),q||(q=1,Y.exports=function(e){return function(t){var i=e,n=i.lib,r=n.WordArray,s=n.Hasher,a=i.algo,o=r.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),c=r.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),l=r.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),h=r.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),d=r.create([0,1518500249,1859775393,2400959708,2840853838]),u=r.create([1352829926,1548603684,1836072691,2053994217,0]),f=a.RIPEMD160=s.extend({_doReset:function(){this._hash=r.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var i=0;i<16;i++){var n=t+i,r=e[n];e[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8)}var s,a,f,w,b,S,v,A,E,R,k,x=this._hash.words,C=d.words,I=u.words,P=o.words,D=c.words,O=l.words,L=h.words;for(S=s=x[0],v=a=x[1],A=f=x[2],E=w=x[3],R=b=x[4],i=0;i<80;i+=1)k=s+e[t+P[i]]|0,k+=i<16?p(a,f,w)+C[0]:i<32?m(a,f,w)+C[1]:i<48?g(a,f,w)+C[2]:i<64?_(a,f,w)+C[3]:y(a,f,w)+C[4],k=(k=T(k|=0,O[i]))+b|0,s=b,b=w,w=T(f,10),f=a,a=k,k=S+e[t+D[i]]|0,k+=i<16?y(v,A,E)+I[0]:i<32?_(v,A,E)+I[1]:i<48?g(v,A,E)+I[2]:i<64?m(v,A,E)+I[3]:p(v,A,E)+I[4],k=(k=T(k|=0,L[i]))+R|0,S=R,R=E,E=T(A,10),A=v,v=k;k=x[1]+f+E|0,x[1]=x[2]+w+R|0,x[2]=x[3]+b+S|0,x[3]=x[4]+s+v|0,x[4]=x[0]+a+A|0,x[0]=k},_doFinalize:function(){var e=this._data,t=e.words,i=8*this._nDataBytes,n=8*e.sigBytes;t[n>>>5]|=128<<24-n%32,t[14+(n+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),e.sigBytes=4*(t.length+1),this._process();for(var r=this._hash,s=r.words,a=0;a<5;a++){var o=s[a];s[a]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}return r},clone:function(){var e=s.clone.call(this);return e._hash=this._hash.clone(),e}});function p(e,t,i){return e^t^i}function m(e,t,i){return e&t|~e&i}function g(e,t,i){return(e|~t)^i}function _(e,t,i){return e&i|t&~i}function y(e,t,i){return e^(t|~i)}function T(e,t){return e<<t|e>>>32-t}i.RIPEMD160=s._createHelper(f),i.HmacRIPEMD160=s._createHmacHelper(f)}(),e.RIPEMD160}(d())),$(),Z||(Z=1,J.exports=function(e){return n=(i=(t=e).lib).Base,r=i.WordArray,a=(s=t.algo).SHA256,o=s.HMAC,c=s.PBKDF2=n.extend({cfg:n.extend({keySize:4,hasher:a,iterations:25e4}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var i=this.cfg,n=o.create(i.hasher,e),s=r.create(),a=r.create([1]),c=s.words,l=a.words,h=i.keySize,d=i.iterations;c.length<h;){var u=n.update(t).finalize(a);n.reset();for(var f=u.words,p=f.length,m=u,g=1;g<d;g++){m=n.finalize(m),n.reset();for(var _=m.words,y=0;y<p;y++)f[y]^=_[y]}s.concat(u),l[0]++}return s.sigBytes=4*h,s}}),t.PBKDF2=function(e,t,i){return c.create(i).compute(e,t)},e.PBKDF2;var t,i,n,r,s,a,o,c}(d(),M(),$())),te(),re(),oe(),he(),fe(),ge(),_e||(_e=1,ye.exports=function(e){return e.mode.ECB=((t=e.lib.BlockCipherMode.extend()).Encryptor=t.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),t.Decryptor=t.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),t),e.mode.ECB;var t}(d(),re())),Te||(Te=1,we.exports=function(e){return e.pad.AnsiX923={pad:function(e,t){var i=e.sigBytes,n=4*t,r=n-i%n,s=i+r-1;e.clamp(),e.words[s>>>2]|=r<<24-s%4*8,e.sigBytes+=r},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},e.pad.Ansix923}(d(),re())),be||(be=1,Se.exports=function(e){return e.pad.Iso10126={pad:function(t,i){var n=4*i,r=n-t.sigBytes%n;t.concat(e.lib.WordArray.random(r-1)).concat(e.lib.WordArray.create([r<<24],1))},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},e.pad.Iso10126}(d(),re())),ve||(ve=1,Ae.exports=function(e){return e.pad.Iso97971={pad:function(t,i){t.concat(e.lib.WordArray.create([2147483648],1)),e.pad.ZeroPadding.pad(t,i)},unpad:function(t){e.pad.ZeroPadding.unpad(t),t.sigBytes--}},e.pad.Iso97971}(d(),re())),Ee||(Ee=1,Re.exports=function(e){return e.pad.ZeroPadding={pad:function(e,t){var i=4*t;e.clamp(),e.sigBytes+=i-(e.sigBytes%i||i)},unpad:function(e){var t=e.words,i=e.sigBytes-1;for(i=e.sigBytes-1;i>=0;i--)if(t[i>>>2]>>>24-i%4*8&255){e.sigBytes=i+1;break}}},e.pad.ZeroPadding}(d(),re())),ke||(ke=1,xe.exports=function(e){return e.pad.NoPadding={pad:function(){},unpad:function(){}},e.pad.NoPadding}(d(),re())),Ce||(Ce=1,Ie.exports=function(e){return i=(t=e).lib.CipherParams,n=t.enc.Hex,t.format.Hex={stringify:function(e){return e.ciphertext.toString(n)},parse:function(e){var t=n.parse(e);return i.create({ciphertext:t})}},e.format.Hex;var t,i,n}(d(),re())),Pe||(Pe=1,De.exports=function(e){return function(){var t=e,i=t.lib.BlockCipher,n=t.algo,r=[],s=[],a=[],o=[],c=[],l=[],h=[],d=[],u=[],f=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var i=0,n=0;for(t=0;t<256;t++){var p=n^n<<1^n<<2^n<<3^n<<4;p=p>>>8^255&p^99,r[i]=p,s[p]=i;var m=e[i],g=e[m],_=e[g],y=257*e[p]^16843008*p;a[i]=y<<24|y>>>8,o[i]=y<<16|y>>>16,c[i]=y<<8|y>>>24,l[i]=y,y=16843009*_^65537*g^257*m^16843008*i,h[p]=y<<24|y>>>8,d[p]=y<<16|y>>>16,u[p]=y<<8|y>>>24,f[p]=y,i?(i=m^e[e[e[_^m]]],n^=e[e[n]]):i=n=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],m=n.AES=i.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,i=e.sigBytes/4,n=4*((this._nRounds=i+6)+1),s=this._keySchedule=[],a=0;a<n;a++)a<i?s[a]=t[a]:(l=s[a-1],a%i?i>6&&a%i==4&&(l=r[l>>>24]<<24|r[l>>>16&255]<<16|r[l>>>8&255]<<8|r[255&l]):(l=r[(l=l<<8|l>>>24)>>>24]<<24|r[l>>>16&255]<<16|r[l>>>8&255]<<8|r[255&l],l^=p[a/i|0]<<24),s[a]=s[a-i]^l);for(var o=this._invKeySchedule=[],c=0;c<n;c++){if(a=n-c,c%4)var l=s[a];else l=s[a-4];o[c]=c<4||a<=4?l:h[r[l>>>24]]^d[r[l>>>16&255]]^u[r[l>>>8&255]]^f[r[255&l]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,a,o,c,l,r)},decryptBlock:function(e,t){var i=e[t+1];e[t+1]=e[t+3],e[t+3]=i,this._doCryptBlock(e,t,this._invKeySchedule,h,d,u,f,s),i=e[t+1],e[t+1]=e[t+3],e[t+3]=i},_doCryptBlock:function(e,t,i,n,r,s,a,o){for(var c=this._nRounds,l=e[t]^i[0],h=e[t+1]^i[1],d=e[t+2]^i[2],u=e[t+3]^i[3],f=4,p=1;p<c;p++){var m=n[l>>>24]^r[h>>>16&255]^s[d>>>8&255]^a[255&u]^i[f++],g=n[h>>>24]^r[d>>>16&255]^s[u>>>8&255]^a[255&l]^i[f++],_=n[d>>>24]^r[u>>>16&255]^s[l>>>8&255]^a[255&h]^i[f++],y=n[u>>>24]^r[l>>>16&255]^s[h>>>8&255]^a[255&d]^i[f++];l=m,h=g,d=_,u=y}m=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^i[f++],g=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^i[f++],_=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^i[f++],y=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^i[f++],e[t]=m,e[t+1]=g,e[t+2]=_,e[t+3]=y},keySize:8});t.AES=i._createHelper(m)}(),e.AES}(d(),v(),C(),te(),re())),Me(),Be||(Be=1,Ne.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,n=t.algo,r=n.RC4=i.extend({_doReset:function(){for(var e=this._key,t=e.words,i=e.sigBytes,n=this._S=[],r=0;r<256;r++)n[r]=r;r=0;for(var s=0;r<256;r++){var a=r%i,o=t[a>>>2]>>>24-a%4*8&255;s=(s+n[r]+o)%256;var c=n[r];n[r]=n[s],n[s]=c}this._i=this._j=0},_doProcessBlock:function(e,t){e[t]^=s.call(this)},keySize:8,ivSize:0});function s(){for(var e=this._S,t=this._i,i=this._j,n=0,r=0;r<4;r++){i=(i+e[t=(t+1)%256])%256;var s=e[t];e[t]=e[i],e[i]=s,n|=e[(e[t]+e[i])%256]<<24-8*r}return this._i=t,this._j=i,n}t.RC4=i._createHelper(r);var a=n.RC4Drop=r.extend({cfg:r.cfg.extend({drop:192}),_doReset:function(){r._doReset.call(this);for(var e=this.cfg.drop;e>0;e--)s.call(this)}});t.RC4Drop=i._createHelper(a)}(),e.RC4}(d(),v(),C(),te(),re())),Fe||(Fe=1,We.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,n=t.algo,r=[],s=[],a=[],o=n.Rabbit=i.extend({_doReset:function(){for(var e=this._key.words,t=this.cfg.iv,i=0;i<4;i++)e[i]=16711935&(e[i]<<8|e[i]>>>24)|4278255360&(e[i]<<24|e[i]>>>8);var n=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],r=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];for(this._b=0,i=0;i<4;i++)c.call(this);for(i=0;i<8;i++)r[i]^=n[i+4&7];if(t){var s=t.words,a=s[0],o=s[1],l=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),h=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),d=l>>>16|4294901760&h,u=h<<16|65535&l;for(r[0]^=l,r[1]^=d,r[2]^=h,r[3]^=u,r[4]^=l,r[5]^=d,r[6]^=h,r[7]^=u,i=0;i<4;i++)c.call(this)}},_doProcessBlock:function(e,t){var i=this._X;c.call(this),r[0]=i[0]^i[5]>>>16^i[3]<<16,r[1]=i[2]^i[7]>>>16^i[5]<<16,r[2]=i[4]^i[1]>>>16^i[7]<<16,r[3]=i[6]^i[3]>>>16^i[1]<<16;for(var n=0;n<4;n++)r[n]=16711935&(r[n]<<8|r[n]>>>24)|4278255360&(r[n]<<24|r[n]>>>8),e[t+n]^=r[n]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,i=0;i<8;i++)s[i]=t[i];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0<s[0]>>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0<s[1]>>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0<s[2]>>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0<s[3]>>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0<s[4]>>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0<s[5]>>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0<s[6]>>>0?1:0)|0,this._b=t[7]>>>0<s[7]>>>0?1:0,i=0;i<8;i++){var n=e[i]+t[i],r=65535&n,o=n>>>16,c=((r*r>>>17)+r*o>>>15)+o*o,l=((4294901760&n)*n|0)+((65535&n)*n|0);a[i]=c^l}e[0]=a[0]+(a[7]<<16|a[7]>>>16)+(a[6]<<16|a[6]>>>16)|0,e[1]=a[1]+(a[0]<<8|a[0]>>>24)+a[7]|0,e[2]=a[2]+(a[1]<<16|a[1]>>>16)+(a[0]<<16|a[0]>>>16)|0,e[3]=a[3]+(a[2]<<8|a[2]>>>24)+a[1]|0,e[4]=a[4]+(a[3]<<16|a[3]>>>16)+(a[2]<<16|a[2]>>>16)|0,e[5]=a[5]+(a[4]<<8|a[4]>>>24)+a[3]|0,e[6]=a[6]+(a[5]<<16|a[5]>>>16)+(a[4]<<16|a[4]>>>16)|0,e[7]=a[7]+(a[6]<<8|a[6]>>>24)+a[5]|0}t.Rabbit=i._createHelper(o)}(),e.Rabbit}(d(),v(),C(),te(),re())),Ue||(Ue=1,Ge.exports=function(e){return function(){var t=e,i=t.lib.StreamCipher,n=t.algo,r=[],s=[],a=[],o=n.RabbitLegacy=i.extend({_doReset:function(){var e=this._key.words,t=this.cfg.iv,i=this._X=[e[0],e[3]<<16|e[2]>>>16,e[1],e[0]<<16|e[3]>>>16,e[2],e[1]<<16|e[0]>>>16,e[3],e[2]<<16|e[1]>>>16],n=this._C=[e[2]<<16|e[2]>>>16,4294901760&e[0]|65535&e[1],e[3]<<16|e[3]>>>16,4294901760&e[1]|65535&e[2],e[0]<<16|e[0]>>>16,4294901760&e[2]|65535&e[3],e[1]<<16|e[1]>>>16,4294901760&e[3]|65535&e[0]];this._b=0;for(var r=0;r<4;r++)c.call(this);for(r=0;r<8;r++)n[r]^=i[r+4&7];if(t){var s=t.words,a=s[0],o=s[1],l=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),h=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),d=l>>>16|4294901760&h,u=h<<16|65535&l;for(n[0]^=l,n[1]^=d,n[2]^=h,n[3]^=u,n[4]^=l,n[5]^=d,n[6]^=h,n[7]^=u,r=0;r<4;r++)c.call(this)}},_doProcessBlock:function(e,t){var i=this._X;c.call(this),r[0]=i[0]^i[5]>>>16^i[3]<<16,r[1]=i[2]^i[7]>>>16^i[5]<<16,r[2]=i[4]^i[1]>>>16^i[7]<<16,r[3]=i[6]^i[3]>>>16^i[1]<<16;for(var n=0;n<4;n++)r[n]=16711935&(r[n]<<8|r[n]>>>24)|4278255360&(r[n]<<24|r[n]>>>8),e[t+n]^=r[n]},blockSize:4,ivSize:2});function c(){for(var e=this._X,t=this._C,i=0;i<8;i++)s[i]=t[i];for(t[0]=t[0]+1295307597+this._b|0,t[1]=t[1]+3545052371+(t[0]>>>0<s[0]>>>0?1:0)|0,t[2]=t[2]+886263092+(t[1]>>>0<s[1]>>>0?1:0)|0,t[3]=t[3]+1295307597+(t[2]>>>0<s[2]>>>0?1:0)|0,t[4]=t[4]+3545052371+(t[3]>>>0<s[3]>>>0?1:0)|0,t[5]=t[5]+886263092+(t[4]>>>0<s[4]>>>0?1:0)|0,t[6]=t[6]+1295307597+(t[5]>>>0<s[5]>>>0?1:0)|0,t[7]=t[7]+3545052371+(t[6]>>>0<s[6]>>>0?1:0)|0,this._b=t[7]>>>0<s[7]>>>0?1:0,i=0;i<8;i++){var n=e[i]+t[i],r=65535&n,o=n>>>16,c=((r*r>>>17)+r*o>>>15)+o*o,l=((4294901760&n)*n|0)+((65535&n)*n|0);a[i]=c^l}e[0]=a[0]+(a[7]<<16|a[7]>>>16)+(a[6]<<16|a[6]>>>16)|0,e[1]=a[1]+(a[0]<<8|a[0]>>>24)+a[7]|0,e[2]=a[2]+(a[1]<<16|a[1]>>>16)+(a[0]<<16|a[0]>>>16)|0,e[3]=a[3]+(a[2]<<8|a[2]>>>24)+a[1]|0,e[4]=a[4]+(a[3]<<16|a[3]>>>16)+(a[2]<<16|a[2]>>>16)|0,e[5]=a[5]+(a[4]<<8|a[4]>>>24)+a[3]|0,e[6]=a[6]+(a[5]<<16|a[5]>>>16)+(a[4]<<16|a[4]>>>16)|0,e[7]=a[7]+(a[6]<<8|a[6]>>>24)+a[5]|0}t.RabbitLegacy=i._createHelper(o)}(),e.RabbitLegacy}(d(),v(),C(),te(),re())),je());var Ve=s(o.exports),qe={salt:"muRcN7xuzLM8vQRw",iv:"WiUWpE647DRVN5rE"};function Ye(e){let t=e.length;for(;--t>=0;)e[t]=0}const Ke=256,Xe=286,$e=30,Ze=15,Je=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),Qe=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),et=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),tt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),it=new Array(576);Ye(it);const nt=new Array(60);Ye(nt);const rt=new Array(512);Ye(rt);const st=new Array(256);Ye(st);const at=new Array(29);Ye(at);const ot=new Array($e);function ct(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}let lt,ht,dt;function ut(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}Ye(ot);const ft=e=>e<256?rt[e]:rt[256+(e>>>7)],pt=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},mt=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,pt(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)},gt=(e,t,i)=>{mt(e,i[2*t],i[2*t+1])},_t=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},yt=(e,t,i)=>{const n=new Array(16);let r,s,a=0;for(r=1;r<=Ze;r++)a=a+i[r-1]<<1,n[r]=a;for(s=0;s<=t;s++){let t=e[2*s+1];0!==t&&(e[2*s]=_t(n[t]++,t))}},Tt=e=>{let t;for(t=0;t<Xe;t++)e.dyn_ltree[2*t]=0;for(t=0;t<$e;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},wt=e=>{e.bi_valid>8?pt(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},bt=(e,t,i,n)=>{const r=2*t,s=2*i;return e[r]<e[s]||e[r]===e[s]&&n[t]<=n[i]},St=(e,t,i)=>{const n=e.heap[i];let r=i<<1;for(;r<=e.heap_len&&(r<e.heap_len&&bt(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!bt(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n},vt=(e,t,i)=>{let n,r,s,a,o=0;if(0!==e.sym_next)do{n=255&e.pending_buf[e.sym_buf+o++],n+=(255&e.pending_buf[e.sym_buf+o++])<<8,r=e.pending_buf[e.sym_buf+o++],0===n?gt(e,r,t):(s=st[r],gt(e,s+Ke+1,t),a=Je[s],0!==a&&(r-=at[s],mt(e,r,a)),n--,s=ft(n),gt(e,s,i),a=Qe[s],0!==a&&(n-=ot[s],mt(e,n,a)))}while(o<e.sym_next);gt(e,256,t)},At=(e,t)=>{const i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,s=t.stat_desc.elems;let a,o,c,l=-1;for(e.heap_len=0,e.heap_max=573,a=0;a<s;a++)0!==i[2*a]?(e.heap[++e.heap_len]=l=a,e.depth[a]=0):i[2*a+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=l<2?++l:0,i[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=n[2*c+1]);for(t.max_code=l,a=e.heap_len>>1;a>=1;a--)St(e,i,a);c=s;do{a=e.heap[1],e.heap[1]=e.heap[e.heap_len--],St(e,i,1),o=e.heap[1],e.heap[--e.heap_max]=a,e.heap[--e.heap_max]=o,i[2*c]=i[2*a]+i[2*o],e.depth[c]=(e.depth[a]>=e.depth[o]?e.depth[a]:e.depth[o])+1,i[2*a+1]=i[2*o+1]=c,e.heap[1]=c++,St(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,a=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let l,h,d,u,f,p,m=0;for(u=0;u<=Ze;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)h=e.heap[l],u=i[2*i[2*h+1]+1]+1,u>c&&(u=c,m++),i[2*h+1]=u,h>n||(e.bl_count[u]++,f=0,h>=o&&(f=a[h-o]),p=i[2*h],e.opt_len+=p*(u+f),s&&(e.static_len+=p*(r[2*h+1]+f)));if(0!==m){do{for(u=c-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[c]--,m-=2}while(m>0);for(u=c;0!==u;u--)for(h=e.bl_count[u];0!==h;)d=e.heap[--l],d>n||(i[2*d+1]!==u&&(e.opt_len+=(u-i[2*d+1])*i[2*d],i[2*d+1]=u),h--)}})(e,t),yt(i,l,e.bl_count)},Et=(e,t,i)=>{let n,r,s=-1,a=t[1],o=0,c=7,l=4;for(0===a&&(c=138,l=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)r=a,a=t[2*(n+1)+1],++o<c&&r===a||(o<l?e.bl_tree[2*r]+=o:0!==r?(r!==s&&e.bl_tree[2*r]++,e.bl_tree[32]++):o<=10?e.bl_tree[34]++:e.bl_tree[36]++,o=0,s=r,0===a?(c=138,l=3):r===a?(c=6,l=3):(c=7,l=4))},Rt=(e,t,i)=>{let n,r,s=-1,a=t[1],o=0,c=7,l=4;for(0===a&&(c=138,l=3),n=0;n<=i;n++)if(r=a,a=t[2*(n+1)+1],!(++o<c&&r===a)){if(o<l)do{gt(e,r,e.bl_tree)}while(0!=--o);else 0!==r?(r!==s&&(gt(e,r,e.bl_tree),o--),gt(e,16,e.bl_tree),mt(e,o-3,2)):o<=10?(gt(e,17,e.bl_tree),mt(e,o-3,3)):(gt(e,18,e.bl_tree),mt(e,o-11,7));o=0,s=r,0===a?(c=138,l=3):r===a?(c=6,l=3):(c=7,l=4)}};let kt=!1;const xt=(e,t,i,n)=>{mt(e,0+(n?1:0),3),wt(e),pt(e,i),pt(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var Ct=(e,t,i,n)=>{let r,s,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<Ke;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),At(e,e.l_desc),At(e,e.d_desc),a=(e=>{let t;for(Et(e,e.dyn_ltree,e.l_desc.max_code),Et(e,e.dyn_dtree,e.d_desc.max_code),At(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*tt[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,s=e.static_len+3+7>>>3,s<=r&&(r=s)):r=s=i+5,i+4<=r&&-1!==t?xt(e,t,i,n):4===e.strategy||s===r?(mt(e,2+(n?1:0),3),vt(e,it,nt)):(mt(e,4+(n?1:0),3),((e,t,i,n)=>{let r;for(mt(e,t-257,5),mt(e,i-1,5),mt(e,n-4,4),r=0;r<n;r++)mt(e,e.bl_tree[2*tt[r]+1],3);Rt(e,e.dyn_ltree,t-1),Rt(e,e.dyn_dtree,i-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),vt(e,e.dyn_ltree,e.dyn_dtree)),Tt(e),n&&wt(e)},It={_tr_init:e=>{kt||((()=>{let e,t,i,n,r;const s=new Array(16);for(i=0,n=0;n<28;n++)for(at[n]=i,e=0;e<1<<Je[n];e++)st[i++]=n;for(st[i-1]=n,r=0,n=0;n<16;n++)for(ot[n]=r,e=0;e<1<<Qe[n];e++)rt[r++]=n;for(r>>=7;n<$e;n++)for(ot[n]=r<<7,e=0;e<1<<Qe[n]-7;e++)rt[256+r++]=n;for(t=0;t<=Ze;t++)s[t]=0;for(e=0;e<=143;)it[2*e+1]=8,e++,s[8]++;for(;e<=255;)it[2*e+1]=9,e++,s[9]++;for(;e<=279;)it[2*e+1]=7,e++,s[7]++;for(;e<=287;)it[2*e+1]=8,e++,s[8]++;for(yt(it,287,s),e=0;e<$e;e++)nt[2*e+1]=5,nt[2*e]=_t(e,5);lt=new ct(it,Je,257,Xe,Ze),ht=new ct(nt,Qe,0,$e,Ze),dt=new ct(new Array(0),et,0,19,7)})(),kt=!0),e.l_desc=new ut(e.dyn_ltree,lt),e.d_desc=new ut(e.dyn_dtree,ht),e.bl_desc=new ut(e.bl_tree,dt),e.bi_buf=0,e.bi_valid=0,Tt(e)},_tr_stored_block:xt,_tr_flush_block:Ct,_tr_tally:(e,t,i)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(st[i]+Ke+1)]++,e.dyn_dtree[2*ft(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{mt(e,2,3),gt(e,256,it),(e=>{16===e.bi_valid?(pt(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}};var Pt=(e,t,i,n)=>{let r=65535&e,s=e>>>16&65535,a=0;for(;0!==i;){a=i>2e3?2e3:i,i-=a;do{r=r+t[n++]|0,s=s+r|0}while(--a);r%=65521,s%=65521}return r|s<<16};const Dt=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var Ot=(e,t,i,n)=>{const r=Dt,s=n+i;e^=-1;for(let i=n;i<s;i++)e=e>>>8^r[255&(e^t[i])];return~e},Lt={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},Mt={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:Bt,_tr_stored_block:Nt,_tr_flush_block:Ft,_tr_tally:Wt,_tr_align:Ut}=It,{Z_NO_FLUSH:Gt,Z_PARTIAL_FLUSH:Ht,Z_FULL_FLUSH:zt,Z_FINISH:jt,Z_BLOCK:Vt,Z_OK:qt,Z_STREAM_END:Yt,Z_STREAM_ERROR:Kt,Z_DATA_ERROR:Xt,Z_BUF_ERROR:$t,Z_DEFAULT_COMPRESSION:Zt,Z_FILTERED:Jt,Z_HUFFMAN_ONLY:Qt,Z_RLE:ei,Z_FIXED:ti,Z_DEFAULT_STRATEGY:ii,Z_UNKNOWN:ni,Z_DEFLATED:ri}=Mt,si=258,ai=262,oi=42,ci=113,li=666,hi=(e,t)=>(e.msg=Lt[t],t),di=e=>2*e-(e>4?9:0),ui=e=>{let t=e.length;for(;--t>=0;)e[t]=0},fi=e=>{let t,i,n,r=e.w_size;t=e.hash_size,n=t;do{i=e.head[--n],e.head[n]=i>=r?i-r:0}while(--t);t=r,n=t;do{i=e.prev[--n],e.prev[n]=i>=r?i-r:0}while(--t)};let pi=(e,t,i)=>(t<<e.hash_shift^i)&e.hash_mask;const mi=e=>{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},gi=(e,t)=>{Ft(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,mi(e.strm)},_i=(e,t)=>{e.pending_buf[e.pending++]=t},yi=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ti=(e,t,i,n)=>{let r=e.avail_in;return r>n&&(r=n),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=Pt(e.adler,t,r,i):2===e.state.wrap&&(e.adler=Ot(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},wi=(e,t)=>{let i,n,r=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match;const c=e.strstart>e.w_size-ai?e.strstart-(e.w_size-ai):0,l=e.window,h=e.w_mask,d=e.prev,u=e.strstart+si;let f=l[s+a-1],p=l[s+a];e.prev_length>=e.good_match&&(r>>=2),o>e.lookahead&&(o=e.lookahead);do{if(i=t,l[i+a]===p&&l[i+a-1]===f&&l[i]===l[s]&&l[++i]===l[s+1]){s+=2,i++;do{}while(l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&l[++s]===l[++i]&&s<u);if(n=si-(u-s),s=u-si,n>a){if(e.match_start=t,a=n,n>=o)break;f=l[s+a-1],p=l[s+a]}}}while((t=d[t&h])>c&&0!=--r);return a<=e.lookahead?a:e.lookahead},bi=e=>{const t=e.w_size;let i,n,r;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-ai)&&(e.window.set(e.window.subarray(t,t+t-n),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),fi(e),n+=t),0===e.strm.avail_in)break;if(i=Ti(e.strm,e.window,e.strstart+e.lookahead,n),e.lookahead+=i,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=pi(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=pi(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<ai&&0!==e.strm.avail_in)},Si=(e,t)=>{let i,n,r,s=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,a=0,o=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,n=e.strstart-e.block_start,i>n+e.strm.avail_in&&(i=n+e.strm.avail_in),i>r&&(i=r),i<s&&(0===i&&t!==jt||t===Gt||i!==n+e.strm.avail_in))break;a=t===jt&&i===n+e.strm.avail_in?1:0,Nt(e,0,0,a),e.pending_buf[e.pending-4]=i,e.pending_buf[e.pending-3]=i>>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,mi(e.strm),n&&(n>i&&(n=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+n),e.strm.next_out),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n,e.block_start+=n,i-=n),i&&(Ti(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===a);return o-=e.strm.avail_in,o&&(o>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=o&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-o,e.strm.next_in),e.strstart),e.strstart+=o,e.insert+=o>e.w_size-e.insert?e.w_size-e.insert:o),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),a?4:t!==Gt&&t!==jt&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(Ti(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,s=r>e.w_size?e.w_size:r,n=e.strstart-e.block_start,(n>=s||(n||t===jt)&&t!==Gt&&0===e.strm.avail_in&&n<=r)&&(i=n>r?r:n,a=t===jt&&0===e.strm.avail_in&&i===n?1:0,Nt(e,e.block_start,i,a),e.block_start+=i,mi(e.strm)),a?3:1)},vi=(e,t)=>{let i,n;for(;;){if(e.lookahead<ai){if(bi(e),e.lookahead<ai&&t===Gt)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=pi(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-ai&&(e.match_length=wi(e,i)),e.match_length>=3)if(n=Wt(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=pi(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=pi(e,e.ins_h,e.window[e.strstart+1]);else n=Wt(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(gi(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===jt?(gi(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(gi(e,!1),0===e.strm.avail_out)?1:2},Ai=(e,t)=>{let i,n,r;for(;;){if(e.lookahead<ai){if(bi(e),e.lookahead<ai&&t===Gt)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=pi(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-ai&&(e.match_length=wi(e,i),e.match_length<=5&&(e.strategy===Jt||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,n=Wt(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=pi(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(gi(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(n=Wt(e,0,e.window[e.strstart-1]),n&&gi(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=Wt(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===jt?(gi(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(gi(e,!1),0===e.strm.avail_out)?1:2};function Ei(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}const Ri=[new Ei(0,0,0,0,Si),new Ei(4,4,8,4,vi),new Ei(4,5,16,8,vi),new Ei(4,6,32,32,vi),new Ei(4,4,16,16,Ai),new Ei(8,16,32,32,Ai),new Ei(8,16,128,128,Ai),new Ei(8,32,128,256,Ai),new Ei(32,128,258,1024,Ai),new Ei(32,258,258,4096,Ai)];function ki(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ri,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),ui(this.dyn_ltree),ui(this.dyn_dtree),ui(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),ui(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),ui(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const xi=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==oi&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==ci&&t.status!==li?1:0},Ci=e=>{if(xi(e))return hi(e,Kt);e.total_in=e.total_out=0,e.data_type=ni;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?oi:ci,e.adler=2===t.wrap?0:1,t.last_flush=-2,Bt(t),qt},Ii=e=>{const t=Ci(e);var i;return t===qt&&((i=e.state).window_size=2*i.w_size,ui(i.head),i.max_lazy_match=Ri[i.level].max_lazy,i.good_match=Ri[i.level].good_length,i.nice_match=Ri[i.level].nice_length,i.max_chain_length=Ri[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},Pi=(e,t,i,n,r,s)=>{if(!e)return Kt;let a=1;if(t===Zt&&(t=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),r<1||r>9||i!==ri||n<8||n>15||t<0||t>9||s<0||s>ti||8===n&&1!==a)return hi(e,Kt);8===n&&(n=9);const o=new ki;return e.state=o,o.strm=e,o.status=oi,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=t,o.strategy=s,o.method=i,Ii(e)};var Di={deflateInit:(e,t)=>Pi(e,t,ri,15,8,ii),deflateInit2:Pi,deflateReset:Ii,deflateResetKeep:Ci,deflateSetHeader:(e,t)=>xi(e)||2!==e.state.wrap?Kt:(e.state.gzhead=t,qt),deflate:(e,t)=>{if(xi(e)||t>Vt||t<0)return e?hi(e,Kt):Kt;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===li&&t!==jt)return hi(e,0===e.avail_out?$t:Kt);const n=i.last_flush;if(i.last_flush=t,0!==i.pending){if(mi(e),0===e.avail_out)return i.last_flush=-1,qt}else if(0===e.avail_in&&di(t)<=di(n)&&t!==jt)return hi(e,$t);if(i.status===li&&0!==e.avail_in)return hi(e,$t);if(i.status===oi&&0===i.wrap&&(i.status=ci),i.status===oi){let t=ri+(i.w_bits-8<<4)<<8,n=-1;if(n=i.strategy>=Qt||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=n<<6,0!==i.strstart&&(t|=32),t+=31-t%31,yi(i,t),0!==i.strstart&&(yi(i,e.adler>>>16),yi(i,65535&e.adler)),e.adler=1,i.status=ci,mi(e),0!==i.pending)return i.last_flush=-1,qt}if(57===i.status)if(e.adler=0,_i(i,31),_i(i,139),_i(i,8),i.gzhead)_i(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),_i(i,255&i.gzhead.time),_i(i,i.gzhead.time>>8&255),_i(i,i.gzhead.time>>16&255),_i(i,i.gzhead.time>>24&255),_i(i,9===i.level?2:i.strategy>=Qt||i.level<2?4:0),_i(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(_i(i,255&i.gzhead.extra.length),_i(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=Ot(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(_i(i,0),_i(i,0),_i(i,0),_i(i,0),_i(i,0),_i(i,9===i.level?2:i.strategy>=Qt||i.level<2?4:0),_i(i,3),i.status=ci,mi(e),0!==i.pending)return i.last_flush=-1,qt;if(69===i.status){if(i.gzhead.extra){let t=i.pending,n=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+n>i.pending_buf_size;){let r=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=Ot(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=r,mi(e),0!==i.pending)return i.last_flush=-1,qt;t=0,n-=r}let r=new Uint8Array(i.gzhead.extra);i.pending_buf.set(r.subarray(i.gzindex,i.gzindex+n),i.pending),i.pending+=n,i.gzhead.hcrc&&i.pending>t&&(e.adler=Ot(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ot(e.adler,i.pending_buf,i.pending-n,n)),mi(e),0!==i.pending)return i.last_flush=-1,qt;n=0}t=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,_i(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Ot(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,n=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>n&&(e.adler=Ot(e.adler,i.pending_buf,i.pending-n,n)),mi(e),0!==i.pending)return i.last_flush=-1,qt;n=0}t=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,_i(i,t)}while(0!==t);i.gzhead.hcrc&&i.pending>n&&(e.adler=Ot(e.adler,i.pending_buf,i.pending-n,n))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(mi(e),0!==i.pending))return i.last_flush=-1,qt;_i(i,255&e.adler),_i(i,e.adler>>8&255),e.adler=0}if(i.status=ci,mi(e),0!==i.pending)return i.last_flush=-1,qt}if(0!==e.avail_in||0!==i.lookahead||t!==Gt&&i.status!==li){let n=0===i.level?Si(i,t):i.strategy===Qt?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(bi(e),0===e.lookahead)){if(t===Gt)return 1;break}if(e.match_length=0,i=Wt(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(gi(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===jt?(gi(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(gi(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===ei?((e,t)=>{let i,n,r,s;const a=e.window;for(;;){if(e.lookahead<=si){if(bi(e),e.lookahead<=si&&t===Gt)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,n=a[r],n===a[++r]&&n===a[++r]&&n===a[++r])){s=e.strstart+si;do{}while(n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&n===a[++r]&&r<s);e.match_length=si-(s-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=Wt(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=Wt(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(gi(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===jt?(gi(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(gi(e,!1),0===e.strm.avail_out)?1:2})(i,t):Ri[i.level].func(i,t);if(3!==n&&4!==n||(i.status=li),1===n||3===n)return 0===e.avail_out&&(i.last_flush=-1),qt;if(2===n&&(t===Ht?Ut(i):t!==Vt&&(Nt(i,0,0,!1),t===zt&&(ui(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),mi(e),0===e.avail_out))return i.last_flush=-1,qt}return t!==jt?qt:i.wrap<=0?Yt:(2===i.wrap?(_i(i,255&e.adler),_i(i,e.adler>>8&255),_i(i,e.adler>>16&255),_i(i,e.adler>>24&255),_i(i,255&e.total_in),_i(i,e.total_in>>8&255),_i(i,e.total_in>>16&255),_i(i,e.total_in>>24&255)):(yi(i,e.adler>>>16),yi(i,65535&e.adler)),mi(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?qt:Yt)},deflateEnd:e=>{if(xi(e))return Kt;const t=e.state.status;return e.state=null,t===ci?hi(e,Xt):qt},deflateSetDictionary:(e,t)=>{let i=t.length;if(xi(e))return Kt;const n=e.state,r=n.wrap;if(2===r||1===r&&n.status!==oi||n.lookahead)return Kt;if(1===r&&(e.adler=Pt(e.adler,t,i,0)),n.wrap=0,i>=n.w_size){0===r&&(ui(n.head),n.strstart=0,n.block_start=0,n.insert=0);let e=new Uint8Array(n.w_size);e.set(t.subarray(i-n.w_size,i),0),t=e,i=n.w_size}const s=e.avail_in,a=e.next_in,o=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,bi(n);n.lookahead>=3;){let e=n.strstart,t=n.lookahead-2;do{n.ins_h=pi(n,n.ins_h,n.window[e+3-1]),n.prev[e&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=e,e++}while(--t);n.strstart=e,n.lookahead=2,bi(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,e.next_in=a,e.input=o,e.avail_in=s,n.wrap=r,qt},deflateInfo:"pako deflate (from Nodeca project)"};const Oi=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var Li={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)Oi(i,t)&&(e[t]=i[t])}}return e},flattenChunks:e=>{let t=0;for(let i=0,n=e.length;i<n;i++)t+=e[i].length;const i=new Uint8Array(t);for(let t=0,n=0,r=e.length;t<r;t++){let r=e[t];i.set(r,n),n+=r.length}return i}};let Mi=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){Mi=!1}const Bi=new Uint8Array(256);for(let e=0;e<256;e++)Bi[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;Bi[254]=Bi[254]=1;var Ni={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,n,r,s,a=e.length,o=0;for(r=0;r<a;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<a&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Uint8Array(o),s=0,r=0;s<o;r++)i=e.charCodeAt(r),55296==(64512&i)&&r+1<a&&(n=e.charCodeAt(r+1),56320==(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[s++]=i:i<2048?(t[s++]=192|i>>>6,t[s++]=128|63&i):i<65536?(t[s++]=224|i>>>12,t[s++]=128|i>>>6&63,t[s++]=128|63&i):(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63,t[s++]=128|i>>>6&63,t[s++]=128|63&i);return t},buf2string:(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let n,r;const s=new Array(2*i);for(r=0,n=0;n<i;){let t=e[n++];if(t<128){s[r++]=t;continue}let a=Bi[t];if(a>4)s[r++]=65533,n+=a-1;else{for(t&=2===a?31:3===a?15:7;a>1&&n<i;)t=t<<6|63&e[n++],a--;a>1?s[r++]=65533:t<65536?s[r++]=t:(t-=65536,s[r++]=55296|t>>10&1023,s[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&Mi)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i})(s,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Bi[e[i]]>t?i:t}};var Fi=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const Wi=Object.prototype.toString,{Z_NO_FLUSH:Ui,Z_SYNC_FLUSH:Gi,Z_FULL_FLUSH:Hi,Z_FINISH:zi,Z_OK:ji,Z_STREAM_END:Vi,Z_DEFAULT_COMPRESSION:qi,Z_DEFAULT_STRATEGY:Yi,Z_DEFLATED:Ki}=Mt;function Xi(e){this.options=Li.assign({level:qi,method:Ki,chunkSize:16384,windowBits:15,memLevel:8,strategy:Yi},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Fi,this.strm.avail_out=0;let i=Di.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==ji)throw new Error(Lt[i]);if(t.header&&Di.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?Ni.string2buf(t.dictionary):"[object ArrayBuffer]"===Wi.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=Di.deflateSetDictionary(this.strm,e),i!==ji)throw new Error(Lt[i]);this._dict_set=!0}}function $i(e,t){const i=new Xi(t);if(i.push(e,!0),i.err)throw i.msg||Lt[i.err];return i.result}Xi.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize;let r,s;if(this.ended)return!1;for(s=t===~~t?t:!0===t?zi:Ui,"string"==typeof e?i.input=Ni.string2buf(e):"[object ArrayBuffer]"===Wi.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(s===Gi||s===Hi)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=Di.deflate(i,s),r===Vi)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=Di.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===ji;if(0!==i.avail_out){if(s>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Xi.prototype.onData=function(e){this.chunks.push(e)},Xi.prototype.onEnd=function(e){e===ji&&(this.result=Li.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Zi={Deflate:Xi,deflate:$i,deflateRaw:function(e,t){return(t=t||{}).raw=!0,$i(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,$i(e,t)},constants:Mt};const Ji=16209;var Qi=function(e,t){let i,n,r,s,a,o,c,l,h,d,u,f,p,m,g,_,y,T,w,b,S,v,A,E;const R=e.state;i=e.next_in,A=e.input,n=i+(e.avail_in-5),r=e.next_out,E=e.output,s=r-(t-e.avail_out),a=r+(e.avail_out-257),o=R.dmax,c=R.wsize,l=R.whave,h=R.wnext,d=R.window,u=R.hold,f=R.bits,p=R.lencode,m=R.distcode,g=(1<<R.lenbits)-1,_=(1<<R.distbits)-1;e:do{f<15&&(u+=A[i++]<<f,f+=8,u+=A[i++]<<f,f+=8),y=p[u&g];t:for(;;){if(T=y>>>24,u>>>=T,f-=T,T=y>>>16&255,0===T)E[r++]=65535&y;else{if(!(16&T)){if(64&T){if(32&T){R.mode=16191;break e}e.msg="invalid literal/length code",R.mode=Ji;break e}y=p[(65535&y)+(u&(1<<T)-1)];continue t}for(w=65535&y,T&=15,T&&(f<T&&(u+=A[i++]<<f,f+=8),w+=u&(1<<T)-1,u>>>=T,f-=T),f<15&&(u+=A[i++]<<f,f+=8,u+=A[i++]<<f,f+=8),y=m[u&_];;){if(T=y>>>24,u>>>=T,f-=T,T=y>>>16&255,16&T){if(b=65535&y,T&=15,f<T&&(u+=A[i++]<<f,f+=8,f<T&&(u+=A[i++]<<f,f+=8)),b+=u&(1<<T)-1,b>o){e.msg="invalid distance too far back",R.mode=Ji;break e}if(u>>>=T,f-=T,T=r-s,b>T){if(T=b-T,T>l&&R.sane){e.msg="invalid distance too far back",R.mode=Ji;break e}if(S=0,v=d,0===h){if(S+=c-T,T<w){w-=T;do{E[r++]=d[S++]}while(--T);S=r-b,v=E}}else if(h<T){if(S+=c+h-T,T-=h,T<w){w-=T;do{E[r++]=d[S++]}while(--T);if(S=0,h<w){T=h,w-=T;do{E[r++]=d[S++]}while(--T);S=r-b,v=E}}}else if(S+=h-T,T<w){w-=T;do{E[r++]=d[S++]}while(--T);S=r-b,v=E}for(;w>2;)E[r++]=v[S++],E[r++]=v[S++],E[r++]=v[S++],w-=3;w&&(E[r++]=v[S++],w>1&&(E[r++]=v[S++]))}else{S=r-b;do{E[r++]=E[S++],E[r++]=E[S++],E[r++]=E[S++],w-=3}while(w>2);w&&(E[r++]=E[S++],w>1&&(E[r++]=E[S++]))}break}if(64&T){e.msg="invalid distance code",R.mode=Ji;break e}y=m[(65535&y)+(u&(1<<T)-1)]}}break}}while(i<n&&r<a);w=f>>3,i-=w,f-=w<<3,u&=(1<<f)-1,e.next_in=i,e.next_out=r,e.avail_in=i<n?n-i+5:5-(i-n),e.avail_out=r<a?a-r+257:257-(r-a),R.hold=u,R.bits=f};const en=15,tn=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),nn=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),rn=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),sn=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var an=(e,t,i,n,r,s,a,o)=>{const c=o.bits;let l,h,d,u,f,p,m=0,g=0,_=0,y=0,T=0,w=0,b=0,S=0,v=0,A=0,E=null;const R=new Uint16Array(16),k=new Uint16Array(16);let x,C,I,P=null;for(m=0;m<=en;m++)R[m]=0;for(g=0;g<n;g++)R[t[i+g]]++;for(T=c,y=en;y>=1&&0===R[y];y--);if(T>y&&(T=y),0===y)return r[s++]=20971520,r[s++]=20971520,o.bits=1,0;for(_=1;_<y&&0===R[_];_++);for(T<_&&(T=_),S=1,m=1;m<=en;m++)if(S<<=1,S-=R[m],S<0)return-1;if(S>0&&(0===e||1!==y))return-1;for(k[1]=0,m=1;m<en;m++)k[m+1]=k[m]+R[m];for(g=0;g<n;g++)0!==t[i+g]&&(a[k[t[i+g]]++]=g);if(0===e?(E=P=a,p=20):1===e?(E=tn,P=nn,p=257):(E=rn,P=sn,p=0),A=0,g=0,m=_,f=s,w=T,b=0,d=-1,v=1<<T,u=v-1,1===e&&v>852||2===e&&v>592)return 1;for(;;){x=m-b,a[g]+1<p?(C=0,I=a[g]):a[g]>=p?(C=P[a[g]-p],I=E[a[g]-p]):(C=96,I=0),l=1<<m-b,h=1<<w,_=h;do{h-=l,r[f+(A>>b)+h]=x<<24|C<<16|I}while(0!==h);for(l=1<<m-1;A&l;)l>>=1;if(0!==l?(A&=l-1,A+=l):A=0,g++,0==--R[m]){if(m===y)break;m=t[i+a[g]]}if(m>T&&(A&u)!==d){for(0===b&&(b=T),f+=_,w=m-b,S=1<<w;w+b<y&&(S-=R[w+b],!(S<=0));)w++,S<<=1;if(v+=1<<w,1===e&&v>852||2===e&&v>592)return 1;d=A&u,r[d]=T<<24|w<<16|f-s}}return 0!==A&&(r[f+A]=m-b<<24|64<<16),o.bits=T,0};const{Z_FINISH:on,Z_BLOCK:cn,Z_TREES:ln,Z_OK:hn,Z_STREAM_END:dn,Z_NEED_DICT:un,Z_STREAM_ERROR:fn,Z_DATA_ERROR:pn,Z_MEM_ERROR:mn,Z_BUF_ERROR:gn,Z_DEFLATED:_n}=Mt,yn=16180,Tn=16190,wn=16191,bn=16192,Sn=16194,vn=16199,An=16200,En=16206,Rn=16209,kn=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function xn(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Cn=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<yn||t.mode>16211?1:0},In=e=>{if(Cn(e))return fn;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=yn,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,hn},Pn=e=>{if(Cn(e))return fn;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,In(e)},Dn=(e,t)=>{let i;if(Cn(e))return fn;const n=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?fn:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,Pn(e))},On=(e,t)=>{if(!e)return fn;const i=new xn;e.state=i,i.strm=e,i.window=null,i.mode=yn;const n=Dn(e,t);return n!==hn&&(e.state=null),n};let Ln,Mn,Bn=!0;const Nn=e=>{if(Bn){Ln=new Int32Array(512),Mn=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(an(1,e.lens,0,288,Ln,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;an(2,e.lens,0,32,Mn,0,e.work,{bits:5}),Bn=!1}e.lencode=Ln,e.lenbits=9,e.distcode=Mn,e.distbits=5},Fn=(e,t,i,n)=>{let r;const s=e.state;return null===s.window&&(s.wsize=1<<s.wbits,s.wnext=0,s.whave=0,s.window=new Uint8Array(s.wsize)),n>=s.wsize?(s.window.set(t.subarray(i-s.wsize,i),0),s.wnext=0,s.whave=s.wsize):(r=s.wsize-s.wnext,r>n&&(r=n),s.window.set(t.subarray(i-n,i-n+r),s.wnext),(n-=r)?(s.window.set(t.subarray(i-n,i),0),s.wnext=n,s.whave=s.wsize):(s.wnext+=r,s.wnext===s.wsize&&(s.wnext=0),s.whave<s.wsize&&(s.whave+=r))),0};var Wn=(e,t)=>{let i,n,r,s,a,o,c,l,h,d,u,f,p,m,g,_,y,T,w,b,S,v,A=0;const E=new Uint8Array(4);let R,k;const x=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Cn(e)||!e.output||!e.input&&0!==e.avail_in)return fn;i=e.state,i.mode===wn&&(i.mode=bn),a=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,l=i.hold,h=i.bits,d=o,u=c,v=hn;e:for(;;)switch(i.mode){case yn:if(0===i.wrap){i.mode=bn;break}for(;h<16;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(2&i.wrap&&35615===l){0===i.wbits&&(i.wbits=15),i.check=0,E[0]=255&l,E[1]=l>>>8&255,i.check=Ot(i.check,E,2,0),l=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=Rn;break}if((15&l)!==_n){e.msg="unknown compression method",i.mode=Rn;break}if(l>>>=4,h-=4,S=8+(15&l),0===i.wbits&&(i.wbits=S),S>15||S>i.wbits){e.msg="invalid window size",i.mode=Rn;break}i.dmax=1<<i.wbits,i.flags=0,e.adler=i.check=1,i.mode=512&l?16189:wn,l=0,h=0;break;case 16181:for(;h<16;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(i.flags=l,(255&i.flags)!==_n){e.msg="unknown compression method",i.mode=Rn;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=Rn;break}i.head&&(i.head.text=l>>8&1),512&i.flags&&4&i.wrap&&(E[0]=255&l,E[1]=l>>>8&255,i.check=Ot(i.check,E,2,0)),l=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}i.head&&(i.head.time=l),512&i.flags&&4&i.wrap&&(E[0]=255&l,E[1]=l>>>8&255,E[2]=l>>>16&255,E[3]=l>>>24&255,i.check=Ot(i.check,E,4,0)),l=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}i.head&&(i.head.xflags=255&l,i.head.os=l>>8),512&i.flags&&4&i.wrap&&(E[0]=255&l,E[1]=l>>>8&255,i.check=Ot(i.check,E,2,0)),l=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}i.length=l,i.head&&(i.head.extra_len=l),512&i.flags&&4&i.wrap&&(E[0]=255&l,E[1]=l>>>8&255,i.check=Ot(i.check,E,2,0)),l=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(f=i.length,f>o&&(f=o),f&&(i.head&&(S=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(s,s+f),S)),512&i.flags&&4&i.wrap&&(i.check=Ot(i.check,n,f,s)),o-=f,s+=f,i.length-=f),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===o)break e;f=0;do{S=n[s+f++],i.head&&S&&i.length<65536&&(i.head.name+=String.fromCharCode(S))}while(S&&f<o);if(512&i.flags&&4&i.wrap&&(i.check=Ot(i.check,n,f,s)),o-=f,s+=f,S)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=16187;case 16187:if(4096&i.flags){if(0===o)break e;f=0;do{S=n[s+f++],i.head&&S&&i.length<65536&&(i.head.comment+=String.fromCharCode(S))}while(S&&f<o);if(512&i.flags&&4&i.wrap&&(i.check=Ot(i.check,n,f,s)),o-=f,s+=f,S)break e}else i.head&&(i.head.comment=null);i.mode=16188;case 16188:if(512&i.flags){for(;h<16;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(4&i.wrap&&l!==(65535&i.check)){e.msg="header crc mismatch",i.mode=Rn;break}l=0,h=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=wn;break;case 16189:for(;h<32;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}e.adler=i.check=kn(l),l=0,h=0,i.mode=Tn;case Tn:if(0===i.havedict)return e.next_out=a,e.avail_out=c,e.next_in=s,e.avail_in=o,i.hold=l,i.bits=h,un;e.adler=i.check=1,i.mode=wn;case wn:if(t===cn||t===ln)break e;case bn:if(i.last){l>>>=7&h,h-=7&h,i.mode=En;break}for(;h<3;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}switch(i.last=1&l,l>>>=1,h-=1,3&l){case 0:i.mode=16193;break;case 1:if(Nn(i),i.mode=vn,t===ln){l>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Rn}l>>>=2,h-=2;break;case 16193:for(l>>>=7&h,h-=7&h;h<32;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if((65535&l)!=(l>>>16^65535)){e.msg="invalid stored block lengths",i.mode=Rn;break}if(i.length=65535&l,l=0,h=0,i.mode=Sn,t===ln)break e;case Sn:i.mode=16195;case 16195:if(f=i.length,f){if(f>o&&(f=o),f>c&&(f=c),0===f)break e;r.set(n.subarray(s,s+f),a),o-=f,s+=f,c-=f,a+=f,i.length-=f;break}i.mode=wn;break;case 16196:for(;h<14;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(i.nlen=257+(31&l),l>>>=5,h-=5,i.ndist=1+(31&l),l>>>=5,h-=5,i.ncode=4+(15&l),l>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Rn;break}i.have=0,i.mode=16197;case 16197:for(;i.have<i.ncode;){for(;h<3;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}i.lens[x[i.have++]]=7&l,l>>>=3,h-=3}for(;i.have<19;)i.lens[x[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,R={bits:i.lenbits},v=an(0,i.lens,0,19,i.lencode,0,i.work,R),i.lenbits=R.bits,v){e.msg="invalid code lengths set",i.mode=Rn;break}i.have=0,i.mode=16198;case 16198:for(;i.have<i.nlen+i.ndist;){for(;A=i.lencode[l&(1<<i.lenbits)-1],g=A>>>24,_=A>>>16&255,y=65535&A,!(g<=h);){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(y<16)l>>>=g,h-=g,i.lens[i.have++]=y;else{if(16===y){for(k=g+2;h<k;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(l>>>=g,h-=g,0===i.have){e.msg="invalid bit length repeat",i.mode=Rn;break}S=i.lens[i.have-1],f=3+(3&l),l>>>=2,h-=2}else if(17===y){for(k=g+3;h<k;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}l>>>=g,h-=g,S=0,f=3+(7&l),l>>>=3,h-=3}else{for(k=g+7;h<k;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}l>>>=g,h-=g,S=0,f=11+(127&l),l>>>=7,h-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Rn;break}for(;f--;)i.lens[i.have++]=S}}if(i.mode===Rn)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Rn;break}if(i.lenbits=9,R={bits:i.lenbits},v=an(1,i.lens,0,i.nlen,i.lencode,0,i.work,R),i.lenbits=R.bits,v){e.msg="invalid literal/lengths set",i.mode=Rn;break}if(i.distbits=6,i.distcode=i.distdyn,R={bits:i.distbits},v=an(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,R),i.distbits=R.bits,v){e.msg="invalid distances set",i.mode=Rn;break}if(i.mode=vn,t===ln)break e;case vn:i.mode=An;case An:if(o>=6&&c>=258){e.next_out=a,e.avail_out=c,e.next_in=s,e.avail_in=o,i.hold=l,i.bits=h,Qi(e,u),a=e.next_out,r=e.output,c=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,l=i.hold,h=i.bits,i.mode===wn&&(i.back=-1);break}for(i.back=0;A=i.lencode[l&(1<<i.lenbits)-1],g=A>>>24,_=A>>>16&255,y=65535&A,!(g<=h);){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(_&&!(240&_)){for(T=g,w=_,b=y;A=i.lencode[b+((l&(1<<T+w)-1)>>T)],g=A>>>24,_=A>>>16&255,y=65535&A,!(T+g<=h);){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}l>>>=T,h-=T,i.back+=T}if(l>>>=g,h-=g,i.back+=g,i.length=y,0===_){i.mode=16205;break}if(32&_){i.back=-1,i.mode=wn;break}if(64&_){e.msg="invalid literal/length code",i.mode=Rn;break}i.extra=15&_,i.mode=16201;case 16201:if(i.extra){for(k=i.extra;h<k;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}i.length+=l&(1<<i.extra)-1,l>>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;A=i.distcode[l&(1<<i.distbits)-1],g=A>>>24,_=A>>>16&255,y=65535&A,!(g<=h);){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(!(240&_)){for(T=g,w=_,b=y;A=i.distcode[b+((l&(1<<T+w)-1)>>T)],g=A>>>24,_=A>>>16&255,y=65535&A,!(T+g<=h);){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}l>>>=T,h-=T,i.back+=T}if(l>>>=g,h-=g,i.back+=g,64&_){e.msg="invalid distance code",i.mode=Rn;break}i.offset=y,i.extra=15&_,i.mode=16203;case 16203:if(i.extra){for(k=i.extra;h<k;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}i.offset+=l&(1<<i.extra)-1,l>>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Rn;break}i.mode=16204;case 16204:if(0===c)break e;if(f=u-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Rn;break}f>i.wnext?(f-=i.wnext,p=i.wsize-f):p=i.wnext-f,f>i.length&&(f=i.length),m=i.window}else m=r,p=a-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do{r[a++]=m[p++]}while(--f);0===i.length&&(i.mode=An);break;case 16205:if(0===c)break e;r[a++]=i.length,c--,i.mode=An;break;case En:if(i.wrap){for(;h<32;){if(0===o)break e;o--,l|=n[s++]<<h,h+=8}if(u-=c,e.total_out+=u,i.total+=u,4&i.wrap&&u&&(e.adler=i.check=i.flags?Ot(i.check,r,u,a-u):Pt(i.check,r,u,a-u)),u=c,4&i.wrap&&(i.flags?l:kn(l))!==i.check){e.msg="incorrect data check",i.mode=Rn;break}l=0,h=0}i.mode=16207;case 16207:if(i.wrap&&i.flags){for(;h<32;){if(0===o)break e;o--,l+=n[s++]<<h,h+=8}if(4&i.wrap&&l!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=Rn;break}l=0,h=0}i.mode=16208;case 16208:v=dn;break e;case Rn:v=pn;break e;case 16210:return mn;default:return fn}return e.next_out=a,e.avail_out=c,e.next_in=s,e.avail_in=o,i.hold=l,i.bits=h,(i.wsize||u!==e.avail_out&&i.mode<Rn&&(i.mode<En||t!==on))&&Fn(e,e.output,e.next_out,u-e.avail_out),d-=e.avail_in,u-=e.avail_out,e.total_in+=d,e.total_out+=u,i.total+=u,4&i.wrap&&u&&(e.adler=i.check=i.flags?Ot(i.check,r,u,e.next_out-u):Pt(i.check,r,u,e.next_out-u)),e.data_type=i.bits+(i.last?64:0)+(i.mode===wn?128:0)+(i.mode===vn||i.mode===Sn?256:0),(0===d&&0===u||t===on)&&v===hn&&(v=gn),v},Un={inflateReset:Pn,inflateReset2:Dn,inflateResetKeep:In,inflateInit:e=>On(e,15),inflateInit2:On,inflate:Wn,inflateEnd:e=>{if(Cn(e))return fn;let t=e.state;return t.window&&(t.window=null),e.state=null,hn},inflateGetHeader:(e,t)=>{if(Cn(e))return fn;const i=e.state;return 2&i.wrap?(i.head=t,t.done=!1,hn):fn},inflateSetDictionary:(e,t)=>{const i=t.length;let n,r,s;return Cn(e)?fn:(n=e.state,0!==n.wrap&&n.mode!==Tn?fn:n.mode===Tn&&(r=1,r=Pt(r,t,i,0),r!==n.check)?pn:(s=Fn(e,t,i,i),s?(n.mode=16210,mn):(n.havedict=1,hn)))},inflateInfo:"pako inflate (from Nodeca project)"};var Gn=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const Hn=Object.prototype.toString,{Z_NO_FLUSH:zn,Z_FINISH:jn,Z_OK:Vn,Z_STREAM_END:qn,Z_NEED_DICT:Yn,Z_STREAM_ERROR:Kn,Z_DATA_ERROR:Xn,Z_MEM_ERROR:$n}=Mt;function Zn(e){this.options=Li.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Fi,this.strm.avail_out=0;let i=Un.inflateInit2(this.strm,t.windowBits);if(i!==Vn)throw new Error(Lt[i]);if(this.header=new Gn,Un.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Ni.string2buf(t.dictionary):"[object ArrayBuffer]"===Hn.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Un.inflateSetDictionary(this.strm,t.dictionary),i!==Vn)))throw new Error(Lt[i])}function Jn(e,t){const i=new Zn(t);if(i.push(e),i.err)throw i.msg||Lt[i.err];return i.result}Zn.prototype.push=function(e,t){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let s,a,o;if(this.ended)return!1;for(a=t===~~t?t:!0===t?jn:zn,"[object ArrayBuffer]"===Hn.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),s=Un.inflate(i,a),s===Yn&&r&&(s=Un.inflateSetDictionary(i,r),s===Vn?s=Un.inflate(i,a):s===Xn&&(s=Yn));i.avail_in>0&&s===qn&&i.state.wrap>0&&0!==e[i.next_in];)Un.inflateReset(i),s=Un.inflate(i,a);switch(s){case Kn:case Xn:case Yn:case $n:return this.onEnd(s),this.ended=!0,!1}if(o=i.avail_out,i.next_out&&(0===i.avail_out||s===qn))if("string"===this.options.to){let e=Ni.utf8border(i.output,i.next_out),t=i.next_out-e,r=Ni.buf2string(i.output,e);i.next_out=t,i.avail_out=n-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(r)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(s!==Vn||0!==o){if(s===qn)return s=Un.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},Zn.prototype.onData=function(e){this.chunks.push(e)},Zn.prototype.onEnd=function(e){e===Vn&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Li.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Qn={Inflate:Zn,inflate:Jn,inflateRaw:function(e,t){return(t=t||{}).raw=!0,Jn(e,t)},ungzip:Jn,constants:Mt};const{Deflate:er,deflate:tr,deflateRaw:ir,gzip:nr}=Zi,{Inflate:rr,inflate:sr,inflateRaw:ar,ungzip:or}=Qn;var cr={Deflate:er,deflate:tr,deflateRaw:ir,gzip:nr,Inflate:rr,inflate:sr,inflateRaw:ar,ungzip:or,constants:Mt};async function lr(e,t){const i=Ve.lib.WordArray.create(e.slice(0,16)),n=function(e){const t=[];let i=0;const n=e.length;for(;i<n;)t.push(e[i++]<<24|e[i++]<<16|e[i++]<<8|e[i++]);return Ve.lib.WordArray.create(t,n)}(e.slice(16)),r=function(e){return Ve.enc.Hex.parse(Ve.SHA256(e).toString())}(t),s=function(e){const t=e.sigBytes,i=new Uint8Array(t);let n=0;const r=e.words;for(let e=0;e<t;e++)i[e]=r[n>>>2]>>>24-n%4*8&255,n++;return i}(Ve.AES.decrypt({ciphertext:n},r,{iv:i,mode:Ve.mode.CBC,padding:Ve.pad.Pkcs7}));return cr.inflate(s)}Ve.enc.Utf8.parse(qe.salt),Ve.enc.Utf8.parse(qe.iv);var hr="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},dr=[],ur=[],fr="undefined"!=typeof Uint8Array?Uint8Array:Array,pr=!1;function mr(){pr=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)dr[t]=e[t],ur[e.charCodeAt(t)]=t;ur["-".charCodeAt(0)]=62,ur["_".charCodeAt(0)]=63}function gr(e,t,i){for(var n,r,s=[],a=t;a<i;a+=3)n=(e[a]<<16)+(e[a+1]<<8)+e[a+2],s.push(dr[(r=n)>>18&63]+dr[r>>12&63]+dr[r>>6&63]+dr[63&r]);return s.join("")}function _r(e){var t;pr||mr();for(var i=e.length,n=i%3,r="",s=[],a=16383,o=0,c=i-n;o<c;o+=a)s.push(gr(e,o,o+a>c?c:o+a));return 1===n?(t=e[i-1],r+=dr[t>>2],r+=dr[t<<4&63],r+="=="):2===n&&(t=(e[i-2]<<8)+e[i-1],r+=dr[t>>10],r+=dr[t>>4&63],r+=dr[t<<2&63],r+="="),s.push(r),s.join("")}function yr(e,t,i,n,r){var s,a,o=8*r-n-1,c=(1<<o)-1,l=c>>1,h=-7,d=i?r-1:0,u=i?-1:1,f=e[t+d];for(d+=u,s=f&(1<<-h)-1,f>>=-h,h+=o;h>0;s=256*s+e[t+d],d+=u,h-=8);for(a=s&(1<<-h)-1,s>>=-h,h+=n;h>0;a=256*a+e[t+d],d+=u,h-=8);if(0===s)s=1-l;else{if(s===c)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=l}return(f?-1:1)*a*Math.pow(2,s-n)}function Tr(e,t,i,n,r,s){var a,o,c,l=8*s-r-1,h=(1<<l)-1,d=h>>1,u=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,p=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,a=h):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+d>=1?u/c:u*Math.pow(2,1-d))*c>=2&&(a++,c/=2),a+d>=h?(o=0,a=h):a+d>=1?(o=(t*c-1)*Math.pow(2,r),a+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,r),a=0));r>=8;e[i+f]=255&o,f+=p,o/=256,r-=8);for(a=a<<r|o,l+=r;l>0;e[i+f]=255&a,f+=p,a/=256,l-=8);e[i+f-p]|=128*m}var wr={}.toString,br=Array.isArray||function(e){return"[object Array]"==wr.call(e)};function Sr(){return Ar.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function vr(e,t){if(Sr()<t)throw new RangeError("Invalid typed array length");return Ar.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=Ar.prototype:(null===e&&(e=new Ar(t)),e.length=t),e}function Ar(e,t,i){if(!(Ar.TYPED_ARRAY_SUPPORT||this instanceof Ar))return new Ar(e,t,i);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return kr(this,e)}return Er(this,e,t,i)}function Er(e,t,i,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,i,n){if(t.byteLength,i<0||t.byteLength<i)throw new RangeError("'offset' is out of bounds");if(t.byteLength<i+(n||0))throw new RangeError("'length' is out of bounds");t=void 0===i&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,i):new Uint8Array(t,i,n);Ar.TYPED_ARRAY_SUPPORT?(e=t).__proto__=Ar.prototype:e=xr(e,t);return e}(e,t,i,n):"string"==typeof t?function(e,t,i){"string"==typeof i&&""!==i||(i="utf8");if(!Ar.isEncoding(i))throw new TypeError('"encoding" must be a valid string encoding');var n=0|Pr(t,i);e=vr(e,n);var r=e.write(t,i);r!==n&&(e=e.slice(0,r));return e}(e,t,i):function(e,t){if(Ir(t)){var i=0|Cr(t.length);return 0===(e=vr(e,i)).length||t.copy(e,0,0,i),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(n=t.length)!=n?vr(e,0):xr(e,t);if("Buffer"===t.type&&br(t.data))return xr(e,t.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function Rr(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function kr(e,t){if(Rr(t),e=vr(e,t<0?0:0|Cr(t)),!Ar.TYPED_ARRAY_SUPPORT)for(var i=0;i<t;++i)e[i]=0;return e}function xr(e,t){var i=t.length<0?0:0|Cr(t.length);e=vr(e,i);for(var n=0;n<i;n+=1)e[n]=255&t[n];return e}function Cr(e){if(e>=Sr())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Sr().toString(16)+" bytes");return 0|e}function Ir(e){return!(null==e||!e._isBuffer)}function Pr(e,t){if(Ir(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var i=e.length;if(0===i)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":case void 0:return rs(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return ss(e).length;default:if(n)return rs(e).length;t=(""+t).toLowerCase(),n=!0}}function Dr(e,t,i){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Yr(this,t,i);case"utf8":case"utf-8":return zr(this,t,i);case"ascii":return Vr(this,t,i);case"latin1":case"binary":return qr(this,t,i);case"base64":return Hr(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Kr(this,t,i);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function Or(e,t,i){var n=e[t];e[t]=e[i],e[i]=n}function Lr(e,t,i,n,r){if(0===e.length)return-1;if("string"==typeof i?(n=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),i=+i,isNaN(i)&&(i=r?0:e.length-1),i<0&&(i=e.length+i),i>=e.length){if(r)return-1;i=e.length-1}else if(i<0){if(!r)return-1;i=0}if("string"==typeof t&&(t=Ar.from(t,n)),Ir(t))return 0===t.length?-1:Mr(e,t,i,n,r);if("number"==typeof t)return t&=255,Ar.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,i):Uint8Array.prototype.lastIndexOf.call(e,t,i):Mr(e,[t],i,n,r);throw new TypeError("val must be string, number or Buffer")}function Mr(e,t,i,n,r){var s,a=1,o=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,o/=2,c/=2,i/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(r){var h=-1;for(s=i;s<o;s++)if(l(e,s)===l(t,-1===h?0:s-h)){if(-1===h&&(h=s),s-h+1===c)return h*a}else-1!==h&&(s-=s-h),h=-1}else for(i+c>o&&(i=o-c),s=i;s>=0;s--){for(var d=!0,u=0;u<c;u++)if(l(e,s+u)!==l(t,u)){d=!1;break}if(d)return s}return-1}function Br(e,t,i,n){i=Number(i)||0;var r=e.length-i;n?(n=Number(n))>r&&(n=r):n=r;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");n>s/2&&(n=s/2);for(var a=0;a<n;++a){var o=parseInt(t.substr(2*a,2),16);if(isNaN(o))return a;e[i+a]=o}return a}function Nr(e,t,i,n){return as(rs(t,e.length-i),e,i,n)}function Fr(e,t,i,n){return as(function(e){for(var t=[],i=0;i<e.length;++i)t.push(255&e.charCodeAt(i));return t}(t),e,i,n)}function Wr(e,t,i,n){return Fr(e,t,i,n)}function Ur(e,t,i,n){return as(ss(t),e,i,n)}function Gr(e,t,i,n){return as(function(e,t){for(var i,n,r,s=[],a=0;a<e.length&&!((t-=2)<0);++a)n=(i=e.charCodeAt(a))>>8,r=i%256,s.push(r),s.push(n);return s}(t,e.length-i),e,i,n)}function Hr(e,t,i){return 0===t&&i===e.length?_r(e):_r(e.slice(t,i))}function zr(e,t,i){i=Math.min(e.length,i);for(var n=[],r=t;r<i;){var s,a,o,c,l=e[r],h=null,d=l>239?4:l>223?3:l>191?2:1;if(r+d<=i)switch(d){case 1:l<128&&(h=l);break;case 2:128==(192&(s=e[r+1]))&&(c=(31&l)<<6|63&s)>127&&(h=c);break;case 3:s=e[r+1],a=e[r+2],128==(192&s)&&128==(192&a)&&(c=(15&l)<<12|(63&s)<<6|63&a)>2047&&(c<55296||c>57343)&&(h=c);break;case 4:s=e[r+1],a=e[r+2],o=e[r+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(c=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&o)>65535&&c<1114112&&(h=c)}null===h?(h=65533,d=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),r+=d}return function(e){var t=e.length;if(t<=jr)return String.fromCharCode.apply(String,e);var i="",n=0;for(;n<t;)i+=String.fromCharCode.apply(String,e.slice(n,n+=jr));return i}(n)}Ar.TYPED_ARRAY_SUPPORT=void 0===hr.TYPED_ARRAY_SUPPORT||hr.TYPED_ARRAY_SUPPORT,Sr(),Ar.poolSize=8192,Ar._augment=function(e){return e.__proto__=Ar.prototype,e},Ar.from=function(e,t,i){return Er(null,e,t,i)},Ar.TYPED_ARRAY_SUPPORT&&(Ar.prototype.__proto__=Uint8Array.prototype,Ar.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Ar[Symbol.species]),Ar.alloc=function(e,t,i){return function(e,t,i,n){return Rr(t),t<=0?vr(e,t):void 0!==i?"string"==typeof n?vr(e,t).fill(i,n):vr(e,t).fill(i):vr(e,t)}(null,e,t,i)},Ar.allocUnsafe=function(e){return kr(null,e)},Ar.allocUnsafeSlow=function(e){return kr(null,e)},Ar.isBuffer=function(e){return null!=e&&(!!e._isBuffer||os(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&os(e.slice(0,0))}(e))},Ar.compare=function(e,t){if(!Ir(e)||!Ir(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var i=e.length,n=t.length,r=0,s=Math.min(i,n);r<s;++r)if(e[r]!==t[r]){i=e[r],n=t[r];break}return i<n?-1:n<i?1:0},Ar.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Ar.concat=function(e,t){if(!br(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return Ar.alloc(0);var i;if(void 0===t)for(t=0,i=0;i<e.length;++i)t+=e[i].length;var n=Ar.allocUnsafe(t),r=0;for(i=0;i<e.length;++i){var s=e[i];if(!Ir(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,r),r+=s.length}return n},Ar.byteLength=Pr,Ar.prototype._isBuffer=!0,Ar.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Or(this,t,t+1);return this},Ar.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Or(this,t,t+3),Or(this,t+1,t+2);return this},Ar.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Or(this,t,t+7),Or(this,t+1,t+6),Or(this,t+2,t+5),Or(this,t+3,t+4);return this},Ar.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?zr(this,0,e):Dr.apply(this,arguments)},Ar.prototype.equals=function(e){if(!Ir(e))throw new TypeError("Argument must be a Buffer");return this===e||0===Ar.compare(this,e)},Ar.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},Ar.prototype.compare=function(e,t,i,n,r){if(!Ir(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===i&&(i=e?e.length:0),void 0===n&&(n=0),void 0===r&&(r=this.length),t<0||i>e.length||n<0||r>this.length)throw new RangeError("out of range index");if(n>=r&&t>=i)return 0;if(n>=r)return-1;if(t>=i)return 1;if(this===e)return 0;for(var s=(r>>>=0)-(n>>>=0),a=(i>>>=0)-(t>>>=0),o=Math.min(s,a),c=this.slice(n,r),l=e.slice(t,i),h=0;h<o;++h)if(c[h]!==l[h]){s=c[h],a=l[h];break}return s<a?-1:a<s?1:0},Ar.prototype.includes=function(e,t,i){return-1!==this.indexOf(e,t,i)},Ar.prototype.indexOf=function(e,t,i){return Lr(this,e,t,i,!0)},Ar.prototype.lastIndexOf=function(e,t,i){return Lr(this,e,t,i,!1)},Ar.prototype.write=function(e,t,i,n){if(void 0===t)n="utf8",i=this.length,t=0;else if(void 0===i&&"string"==typeof t)n=t,i=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(i)?(i|=0,void 0===n&&(n="utf8")):(n=i,i=void 0)}var r=this.length-t;if((void 0===i||i>r)&&(i=r),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var s=!1;;)switch(n){case"hex":return Br(this,e,t,i);case"utf8":case"utf-8":return Nr(this,e,t,i);case"ascii":return Fr(this,e,t,i);case"latin1":case"binary":return Wr(this,e,t,i);case"base64":return Ur(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Gr(this,e,t,i);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},Ar.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var jr=4096;function Vr(e,t,i){var n="";i=Math.min(e.length,i);for(var r=t;r<i;++r)n+=String.fromCharCode(127&e[r]);return n}function qr(e,t,i){var n="";i=Math.min(e.length,i);for(var r=t;r<i;++r)n+=String.fromCharCode(e[r]);return n}function Yr(e,t,i){var n=e.length;(!t||t<0)&&(t=0),(!i||i<0||i>n)&&(i=n);for(var r="",s=t;s<i;++s)r+=ns(e[s]);return r}function Kr(e,t,i){for(var n=e.slice(t,i),r="",s=0;s<n.length;s+=2)r+=String.fromCharCode(n[s]+256*n[s+1]);return r}function Xr(e,t,i){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>i)throw new RangeError("Trying to access beyond buffer length")}function $r(e,t,i,n,r,s){if(!Ir(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||t<s)throw new RangeError('"value" argument is out of bounds');if(i+n>e.length)throw new RangeError("Index out of range")}function Zr(e,t,i,n){t<0&&(t=65535+t+1);for(var r=0,s=Math.min(e.length-i,2);r<s;++r)e[i+r]=(t&255<<8*(n?r:1-r))>>>8*(n?r:1-r)}function Jr(e,t,i,n){t<0&&(t=4294967295+t+1);for(var r=0,s=Math.min(e.length-i,4);r<s;++r)e[i+r]=t>>>8*(n?r:3-r)&255}function Qr(e,t,i,n,r,s){if(i+n>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function es(e,t,i,n,r){return r||Qr(e,0,i,4),Tr(e,t,i,n,23,4),i+4}function ts(e,t,i,n,r){return r||Qr(e,0,i,8),Tr(e,t,i,n,52,8),i+8}Ar.prototype.slice=function(e,t){var i,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e),Ar.TYPED_ARRAY_SUPPORT)(i=this.subarray(e,t)).__proto__=Ar.prototype;else{var r=t-e;i=new Ar(r,void 0);for(var s=0;s<r;++s)i[s]=this[s+e]}return i},Ar.prototype.readUIntLE=function(e,t,i){e|=0,t|=0,i||Xr(e,t,this.length);for(var n=this[e],r=1,s=0;++s<t&&(r*=256);)n+=this[e+s]*r;return n},Ar.prototype.readUIntBE=function(e,t,i){e|=0,t|=0,i||Xr(e,t,this.length);for(var n=this[e+--t],r=1;t>0&&(r*=256);)n+=this[e+--t]*r;return n},Ar.prototype.readUInt8=function(e,t){return t||Xr(e,1,this.length),this[e]},Ar.prototype.readUInt16LE=function(e,t){return t||Xr(e,2,this.length),this[e]|this[e+1]<<8},Ar.prototype.readUInt16BE=function(e,t){return t||Xr(e,2,this.length),this[e]<<8|this[e+1]},Ar.prototype.readUInt32LE=function(e,t){return t||Xr(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Ar.prototype.readUInt32BE=function(e,t){return t||Xr(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Ar.prototype.readIntLE=function(e,t,i){e|=0,t|=0,i||Xr(e,t,this.length);for(var n=this[e],r=1,s=0;++s<t&&(r*=256);)n+=this[e+s]*r;return n>=(r*=128)&&(n-=Math.pow(2,8*t)),n},Ar.prototype.readIntBE=function(e,t,i){e|=0,t|=0,i||Xr(e,t,this.length);for(var n=t,r=1,s=this[e+--n];n>0&&(r*=256);)s+=this[e+--n]*r;return s>=(r*=128)&&(s-=Math.pow(2,8*t)),s},Ar.prototype.readInt8=function(e,t){return t||Xr(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Ar.prototype.readInt16LE=function(e,t){t||Xr(e,2,this.length);var i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},Ar.prototype.readInt16BE=function(e,t){t||Xr(e,2,this.length);var i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},Ar.prototype.readInt32LE=function(e,t){return t||Xr(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Ar.prototype.readInt32BE=function(e,t){return t||Xr(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Ar.prototype.readFloatLE=function(e,t){return t||Xr(e,4,this.length),yr(this,e,!0,23,4)},Ar.prototype.readFloatBE=function(e,t){return t||Xr(e,4,this.length),yr(this,e,!1,23,4)},Ar.prototype.readDoubleLE=function(e,t){return t||Xr(e,8,this.length),yr(this,e,!0,52,8)},Ar.prototype.readDoubleBE=function(e,t){return t||Xr(e,8,this.length),yr(this,e,!1,52,8)},Ar.prototype.writeUIntLE=function(e,t,i,n){(e=+e,t|=0,i|=0,n)||$r(this,e,t,i,Math.pow(2,8*i)-1,0);var r=1,s=0;for(this[t]=255&e;++s<i&&(r*=256);)this[t+s]=e/r&255;return t+i},Ar.prototype.writeUIntBE=function(e,t,i,n){(e=+e,t|=0,i|=0,n)||$r(this,e,t,i,Math.pow(2,8*i)-1,0);var r=i-1,s=1;for(this[t+r]=255&e;--r>=0&&(s*=256);)this[t+r]=e/s&255;return t+i},Ar.prototype.writeUInt8=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,1,255,0),Ar.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Ar.prototype.writeUInt16LE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,2,65535,0),Ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Zr(this,e,t,!0),t+2},Ar.prototype.writeUInt16BE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,2,65535,0),Ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Zr(this,e,t,!1),t+2},Ar.prototype.writeUInt32LE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,4,4294967295,0),Ar.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Jr(this,e,t,!0),t+4},Ar.prototype.writeUInt32BE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,4,4294967295,0),Ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Jr(this,e,t,!1),t+4},Ar.prototype.writeIntLE=function(e,t,i,n){if(e=+e,t|=0,!n){var r=Math.pow(2,8*i-1);$r(this,e,t,i,r-1,-r)}var s=0,a=1,o=0;for(this[t]=255&e;++s<i&&(a*=256);)e<0&&0===o&&0!==this[t+s-1]&&(o=1),this[t+s]=(e/a|0)-o&255;return t+i},Ar.prototype.writeIntBE=function(e,t,i,n){if(e=+e,t|=0,!n){var r=Math.pow(2,8*i-1);$r(this,e,t,i,r-1,-r)}var s=i-1,a=1,o=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===o&&0!==this[t+s+1]&&(o=1),this[t+s]=(e/a|0)-o&255;return t+i},Ar.prototype.writeInt8=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,1,127,-128),Ar.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Ar.prototype.writeInt16LE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,2,32767,-32768),Ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Zr(this,e,t,!0),t+2},Ar.prototype.writeInt16BE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,2,32767,-32768),Ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Zr(this,e,t,!1),t+2},Ar.prototype.writeInt32LE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,4,2147483647,-2147483648),Ar.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Jr(this,e,t,!0),t+4},Ar.prototype.writeInt32BE=function(e,t,i){return e=+e,t|=0,i||$r(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Ar.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Jr(this,e,t,!1),t+4},Ar.prototype.writeFloatLE=function(e,t,i){return es(this,e,t,!0,i)},Ar.prototype.writeFloatBE=function(e,t,i){return es(this,e,t,!1,i)},Ar.prototype.writeDoubleLE=function(e,t,i){return ts(this,e,t,!0,i)},Ar.prototype.writeDoubleBE=function(e,t,i){return ts(this,e,t,!1,i)},Ar.prototype.copy=function(e,t,i,n){if(i||(i=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<i&&(n=i),n===i)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-i&&(n=e.length-t+i);var r,s=n-i;if(this===e&&i<t&&t<n)for(r=s-1;r>=0;--r)e[r+t]=this[r+i];else if(s<1e3||!Ar.TYPED_ARRAY_SUPPORT)for(r=0;r<s;++r)e[r+t]=this[r+i];else Uint8Array.prototype.set.call(e,this.subarray(i,i+s),t);return s},Ar.prototype.fill=function(e,t,i,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,i=this.length):"string"==typeof i&&(n=i,i=this.length),1===e.length){var r=e.charCodeAt(0);r<256&&(e=r)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!Ar.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<i)throw new RangeError("Out of range index");if(i<=t)return this;var s;if(t>>>=0,i=void 0===i?this.length:i>>>0,e||(e=0),"number"==typeof e)for(s=t;s<i;++s)this[s]=e;else{var a=Ir(e)?e:rs(new Ar(e,n).toString()),o=a.length;for(s=0;s<i-t;++s)this[s+t]=a[s%o]}return this};var is=/[^+\/0-9A-Za-z-_]/g;function ns(e){return e<16?"0"+e.toString(16):e.toString(16)}function rs(e,t){var i;t=t||1/0;for(var n=e.length,r=null,s=[],a=0;a<n;++a){if((i=e.charCodeAt(a))>55295&&i<57344){if(!r){if(i>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&s.push(239,191,189);continue}r=i;continue}if(i<56320){(t-=3)>-1&&s.push(239,191,189),r=i;continue}i=65536+(r-55296<<10|i-56320)}else r&&(t-=3)>-1&&s.push(239,191,189);if(r=null,i<128){if((t-=1)<0)break;s.push(i)}else if(i<2048){if((t-=2)<0)break;s.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;s.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return s}function ss(e){return function(e){var t,i,n,r,s,a;pr||mr();var o=e.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===e[o-2]?2:"="===e[o-1]?1:0,a=new fr(3*o/4-s),n=s>0?o-4:o;var c=0;for(t=0,i=0;t<n;t+=4,i+=3)r=ur[e.charCodeAt(t)]<<18|ur[e.charCodeAt(t+1)]<<12|ur[e.charCodeAt(t+2)]<<6|ur[e.charCodeAt(t+3)],a[c++]=r>>16&255,a[c++]=r>>8&255,a[c++]=255&r;return 2===s?(r=ur[e.charCodeAt(t)]<<2|ur[e.charCodeAt(t+1)]>>4,a[c++]=255&r):1===s&&(r=ur[e.charCodeAt(t)]<<10|ur[e.charCodeAt(t+1)]<<4|ur[e.charCodeAt(t+2)]>>2,a[c++]=r>>8&255,a[c++]=255&r),a}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(is,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function as(e,t,i,n){for(var r=0;r<n&&!(r+i>=t.length||r>=e.length);++r)t[r+i]=e[r];return r}function os(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}const cs=new class{dbName="LargeFileCacheDB";storeName="files";db;constructor(){this.init()}async init(){return new Promise(((e,t)=>{const i=indexedDB.open(this.dbName,1);i.onupgradeneeded=()=>{const e=i.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)},i.onsuccess=()=>{this.db=i.result,e()},i.onerror=()=>t(i.error)}))}async set(e,t){return new Promise(((i,n)=>{if(!this.db)return n("indexedDB 还未初始化");const r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName),s=new Blob([t]),a=r.put(s,e);a.onsuccess=()=>i(),a.onerror=()=>n(a.error)}))}async get(e){return new Promise((t=>{if(!this.db)return t(null);const i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(e);i.onsuccess=()=>t(i.result||null)}))}},ls=async e=>{const{model:t,onProgress:i}=e,n=await async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:(e,t,i)=>{};if(!e)throw new Error("url is required");const i=await cs.get(e);if(i)return t(e,100,100),await i.arrayBuffer();const n=await fetch(e),r=n.body.getReader(),s=+n.headers.get("content-length");let a=0,o=[];for(;;){const{done:i,value:n}=await r.read();if(i)break;o.push(n),a+=n.length,t&&t(e,a,s)}const c=new Uint8Array(o.reduce(((e,t)=>e+t.length),0));let l=0;for(let e of o)c.set(e,l),l+=e.length;const h=c.buffer;return await cs.set(e,h),h}(t.bundle,i),r=Ar.from(n),s=t.key??t.bundle.replace(/^.*\/(.*?).bundle/,"$1"),a=await lr(r,s);return{...t,buffer:a.buffer}},hs=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e=>{};const i=[],n={},r=function(){let i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;n[i]={url:i,progress:r,total:s};let a=0,o=0;e.forEach((e=>{let{bundle:t}=e;a+=n[t].total,o+=n[t].progress}));const c=Math.floor(o/a*100);t(c)};return e.forEach((e=>{n[e.bundle]={url:e.bundle,progress:0,total:0},i.push(ls({model:e,onProgress:r}))})),Promise.all(i)};var ds;!function(e){e.HUMAN_READY="human.ready",e.HUMAN_ERROR="human.error",e.HUMAN_ACTION_PENDING="human.action.pending",e.HUMAN_LOAD_PROGRESS="human.load.progress",e.CORE_BUNDLES_LOADED="core.bundles.loaded",e.AUDIO_PLAY="audio.play",e.AUDIO_PAUSE="audio.pause",e.AUDIO_MUTE="audio.mute",e.RECORDER_MESSAGE="recorder.message",e.RECORDER_START="recorder.start",e.RECORDER_STOP="recorder.stop",e.RECORDER_SENDING="recorder.sending",e.VOICE_SLEEP="voice.sleep",e.VOICE_WAKE="voice.wake",e.VOICE_INTERRUPT="voice.interrupt",e.VOICE_BARGE_IN="voice.barge_in",e.VOICE2TEXT="voice2text",e.WAKE_RECORDER_START="wake.record.start",e.WAKE_RECORDER_STOP="wake.record.stop",e.VOICE_INTERACTION_OPENED="voice.interaction.opened",e.VOICE_INTERACTION_CLOSED="voice.interaction.closed",e.VOICE_INTERACTION_WAKEUP="voice.interaction.wakeup",e.VOICE_INTERACTION_SLEEP="voice.interaction.sleep",e.VOICE_INTERACTION_WAKE_CONFIRM="voice.interaction.wake.confirm",e.VOICE_INTERACTION_EXIT_PROMPT="voice.interaction.exit.prompt",e.VOICE_INTERACTION_POST_EXIT_IDLE="voice.interaction.post_exit_idle",e.VOICE_INTERACTION_INTERRUPT="voice.interaction.interrupt",e.VOICE_INTERRUPT_HINT_SHOW="voice.interrupt.hint.show",e.VOICE_INTERRUPT_HINT_HIDE="voice.interrupt.hint.hide",e.VOICE_INTERRUPTED="voice.interrupted",e.VOICE_INTERACTION_AUDIO_START="voice.interaction.audio.start",e.VOICE_INTERACTION_AUDIO_STOP="voice.interaction.audio.stop",e.VOICE_INTERACTION_PLAY_START="voice.interaction.play.start",e.VOICE_INTERACTION_PLAY_END="voice.interaction.play.end",e.VOICE_INTERACTION_WEBRTC_STATE="voice.interaction.webrtc.state",e.WEBRTC_TTS_PLAY_START="webrtc.tts.play.start",e.WEBRTC_TTS_PLAY_END="webrtc.tts.play.end",e.CHAT_MESSAGE_BS_PLAY_START="chat.message.bs.play.start",e.CHAT_MESSAGE_BS_PLAY_END="chat.message.bs.play.end",e.TOOL_RESULT="tool.result",e.GATEWAY_CONNECTED="gateway.connected",e.GATEWAY_DISCONNECTED="gateway.disconnected",e.GATEWAY_RECONNECTING="gateway.reconnecting",e.GATEWAY_MESSAGE="gateway.message",e.GATEWAY_ERROR="gateway.error",e.GATEWAY_STATE_PUSH="gateway.state.push",e.CAMERA_PERSON_TEST_RESULT="camera.person.test.result",e.CAMERA_FACE_RECOGNITION_RESULT="camera.face.recognition.result",e.EXPRESSION_SMILE_DETECTED="expression.smile.detected",e.EXPRESSION_SMILE_STATE_CHANGED="expression.smile.state_changed",e.RENDER_READY="render.ready",e.RENDER_ERROR="render.error",e.MODEL_LOAD_PROGRESS="model.load.progress",e.MODEL_LOADED="model.loaded",e.MODEL_LOAD_FAILED="model.load.failed",e.ANIMATION_START="animation.start",e.ANIMATION_END="animation.end",e.ERROR="error"}(ds||(ds={}));const us="qt-human-degraded-notice";class fs{container;constructor(e){this.container="string"==typeof e?document.getElementById(e):e??null}syncWithToken(e){const t=function(e){try{const t=e.split(".")[1];if(!t)return null;const i=t.replace(/-/g,"+").replace(/_/g,"/"),n=decodeURIComponent(atob(i).split("").map((e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2))).join(""));return JSON.parse(n)}catch{return null}}(e);t&&!0===t.degraded?this.show():this.hide()}show(){if(!this.container||this.container.querySelector(`#${us}`))return;"static"===window.getComputedStyle(this.container).position&&(this.container.style.position="relative");const e=document.createElement("div");e.id=us,e.textContent="平台运行授权已到期,当前为降级体验;请联系服务方续期以恢复完整服务",Object.assign(e.style,{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"9",padding:"6px 12px",fontSize:"12px",lineHeight:"1.6",textAlign:"center",color:"#7a5b00",background:"rgba(255, 244, 206, 0.92)",borderTop:"1px solid rgba(214, 178, 70, 0.55)",pointerEvents:"none",fontFamily:'-apple-system, system-ui, "PingFang SC", sans-serif'}),this.container.appendChild(e),console.warn("[Human] 平台运行授权已到期(degraded),显示降级提示;续期后刷新 token 自动消失")}hide(){this.container?.querySelector(`#${us}`)?.remove()}destroy(){this.hide(),this.container=null}}var ps=new class{prefix;ttl;cache;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.prefix=e.prefix||"app_",this.ttl=e.ttl||0,this.cache=new Map}getKey(e){return`${this.prefix}${e}`}isExpired(e){return!!e.expiry&&Date.now()>e.expiry}setItem(e,t){const i={value:t,expiry:this.ttl?Date.now()+this.ttl:null};this.cache.set(this.getKey(e),i)}getItem(e){const t=this.getKey(e);if(this.cache.has(t)){const e=this.cache.get(t);if(!this.isExpired(e))return e.value;this.cache.delete(t)}return null}removeItem(e){const t=this.getKey(e);this.cache.delete(t)}clear(){this.cache.clear()}}({prefix:"quante_",ttl:12096e5});const ms="auth-token",gs="platform-base-api";function _s(){throw new Error("setTimeout has not been defined")}function ys(){throw new Error("clearTimeout has not been defined")}var Ts=_s,ws=ys;function bs(e){if(Ts===setTimeout)return setTimeout(e,0);if((Ts===_s||!Ts)&&setTimeout)return Ts=setTimeout,setTimeout(e,0);try{return Ts(e,0)}catch(t){try{return Ts.call(null,e,0)}catch(t){return Ts.call(this,e,0)}}}"function"==typeof hr.setTimeout&&(Ts=setTimeout),"function"==typeof hr.clearTimeout&&(ws=clearTimeout);var Ss,vs=[],As=!1,Es=-1;function Rs(){As&&Ss&&(As=!1,Ss.length?vs=Ss.concat(vs):Es=-1,vs.length&&ks())}function ks(){if(!As){var e=bs(Rs);As=!0;for(var t=vs.length;t;){for(Ss=vs,vs=[];++Es<t;)Ss&&Ss[Es].run();Es=-1,t=vs.length}Ss=null,As=!1,function(e){if(ws===clearTimeout)return clearTimeout(e);if((ws===ys||!ws)&&clearTimeout)return ws=clearTimeout,clearTimeout(e);try{return ws(e)}catch(t){try{return ws.call(null,e)}catch(t){return ws.call(this,e)}}}(e)}}function xs(e,t){this.fun=e,this.array=t}xs.prototype.run=function(){this.fun.apply(null,this.array)};function Cs(){}var Is=Cs,Ps=Cs,Ds=Cs,Os=Cs,Ls=Cs,Ms=Cs,Bs=Cs;var Ns=hr.performance||{},Fs=Ns.now||Ns.mozNow||Ns.msNow||Ns.oNow||Ns.webkitNow||function(){return(new Date).getTime()};var Ws=new Date;var Us={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var i=1;i<arguments.length;i++)t[i-1]=arguments[i];vs.push(new xs(e,t)),1!==vs.length||As||bs(ks)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Is,addListener:Ps,once:Ds,off:Os,removeListener:Ls,removeAllListeners:Ms,emit:Bs,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*Fs.call(Ns),i=Math.floor(t),n=Math.floor(t%1*1e9);return e&&(i-=e[0],(n-=e[1])<0&&(i--,n+=1e9)),[i,n]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Ws)/1e3}};function Gs(e,t){return function(){return e.apply(t,arguments)}}const{toString:Hs}=Object.prototype,{getPrototypeOf:zs}=Object,{iterator:js,toStringTag:Vs}=Symbol,qs=(Ys=Object.create(null),e=>{const t=Hs.call(e);return Ys[t]||(Ys[t]=t.slice(8,-1).toLowerCase())});var Ys;const Ks=e=>(e=e.toLowerCase(),t=>qs(t)===e),Xs=e=>t=>typeof t===e,{isArray:$s}=Array,Zs=Xs("undefined");function Js(e){return null!==e&&!Zs(e)&&null!==e.constructor&&!Zs(e.constructor)&&ta(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Qs=Ks("ArrayBuffer");const ea=Xs("string"),ta=Xs("function"),ia=Xs("number"),na=e=>null!==e&&"object"==typeof e,ra=e=>{if("object"!==qs(e))return!1;const t=zs(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Vs in e||js in e)},sa=Ks("Date"),aa=Ks("File"),oa=Ks("Blob"),ca=Ks("FileList");const la="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==hr?hr:{},ha=void 0!==la.FormData?la.FormData:void 0,da=Ks("URLSearchParams"),[ua,fa,pa,ma]=["ReadableStream","Request","Response","Headers"].map(Ks);function ga(e,t,{allOwnKeys:i=!1}={}){if(null==e)return;let n,r;if("object"!=typeof e&&(e=[e]),$s(e))for(n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else{if(Js(e))return;const r=i?Object.getOwnPropertyNames(e):Object.keys(e),s=r.length;let a;for(n=0;n<s;n++)a=r[n],t.call(null,e[a],a,e)}}function _a(e,t){if(Js(e))return null;t=t.toLowerCase();const i=Object.keys(e);let n,r=i.length;for(;r-- >0;)if(n=i[r],t===n.toLowerCase())return n;return null}const ya="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:hr,Ta=e=>!Zs(e)&&e!==ya;const wa=(ba="undefined"!=typeof Uint8Array&&zs(Uint8Array),e=>ba&&e instanceof ba);var ba;const Sa=Ks("HTMLFormElement"),va=(({hasOwnProperty:e})=>(t,i)=>e.call(t,i))(Object.prototype),{propertyIsEnumerable:Aa}=Object.prototype,Ea=Ks("RegExp"),Ra=(e,t)=>{const i=Object.getOwnPropertyDescriptors(e),n={};ga(i,((i,r)=>{let s;!1!==(s=t(i,r,e))&&(n[r]=s||i)})),Object.defineProperties(e,n)};const ka=Ks("AsyncFunction"),xa=(Ca="function"==typeof setImmediate,Ia=ta(ya.postMessage),Ca?setImmediate:Ia?(Pa=`axios@${Math.random()}`,Da=[],ya.addEventListener("message",(({source:e,data:t})=>{e===ya&&t===Pa&&Da.length&&Da.shift()()}),!1),e=>{Da.push(e),ya.postMessage(Pa,"*")}):e=>setTimeout(e));var Ca,Ia,Pa,Da;const Oa="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ya):void 0!==Us&&Us.nextTick||xa;var La={isArray:$s,isArrayBuffer:Qs,isBuffer:Js,isFormData:e=>{if(!e)return!1;if(ha&&e instanceof ha)return!0;const t=zs(e);if(!t||t===Object.prototype)return!1;if(!ta(e.append))return!1;const i=qs(e);return"formdata"===i||"object"===i&&ta(e.toString)&&"[object FormData]"===e.toString()},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Qs(e.buffer),t},isString:ea,isNumber:ia,isBoolean:e=>!0===e||!1===e,isObject:na,isPlainObject:ra,isEmptyObject:e=>{if(!na(e)||Js(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:ua,isRequest:fa,isResponse:pa,isHeaders:ma,isUndefined:Zs,isDate:sa,isFile:aa,isReactNativeBlob:e=>!(!e||void 0===e.uri),isReactNative:e=>e&&void 0!==e.getParts,isBlob:oa,isRegExp:Ea,isFunction:ta,isStream:e=>na(e)&&ta(e.pipe),isURLSearchParams:da,isTypedArray:wa,isFileList:ca,forEach:ga,merge:function e(...t){const{caseless:i,skipUndefined:n}=Ta(this)&&this||{},r={},s=(t,s)=>{if("__proto__"===s||"constructor"===s||"prototype"===s)return;const a=i&&"string"==typeof s&&_a(r,s)||s,o=va(r,a)?r[a]:void 0;ra(o)&&ra(t)?r[a]=e(o,t):ra(t)?r[a]=e({},t):$s(t)?r[a]=t.slice():n&&Zs(t)||(r[a]=t)};for(let e=0,i=t.length;e<i;e++){const i=t[e];if(!i||Js(i))continue;if(ga(i,s),"object"!=typeof i||$s(i))continue;const n=Object.getOwnPropertySymbols(i);for(let e=0;e<n.length;e++){const t=n[e];Aa.call(i,t)&&s(i[t],t)}}return r},extend:(e,t,i,{allOwnKeys:n}={})=>(ga(t,((t,n)=>{i&&ta(t)?Object.defineProperty(e,n,{__proto__:null,value:Gs(t,i),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,n,{__proto__:null,value:t,writable:!0,enumerable:!0,configurable:!0})}),{allOwnKeys:n}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,i,n)=>{e.prototype=Object.create(t.prototype,n),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),i&&Object.assign(e.prototype,i)},toFlatObject:(e,t,i,n)=>{let r,s,a;const o={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),s=r.length;s-- >0;)a=r[s],n&&!n(a,e,t)||o[a]||(t[a]=e[a],o[a]=!0);e=!1!==i&&zs(e)}while(e&&(!i||i(e,t))&&e!==Object.prototype);return t},kindOf:qs,kindOfTest:Ks,endsWith:(e,t,i)=>{e=String(e),(void 0===i||i>e.length)&&(i=e.length),i-=t.length;const n=e.indexOf(t,i);return-1!==n&&n===i},toArray:e=>{if(!e)return null;if($s(e))return e;let t=e.length;if(!ia(t))return null;const i=new Array(t);for(;t-- >0;)i[t]=e[t];return i},forEachEntry:(e,t)=>{const i=(e&&e[js]).call(e);let n;for(;(n=i.next())&&!n.done;){const i=n.value;t.call(e,i[0],i[1])}},matchAll:(e,t)=>{let i;const n=[];for(;null!==(i=e.exec(t));)n.push(i);return n},isHTMLForm:Sa,hasOwnProperty:va,hasOwnProp:va,reduceDescriptors:Ra,freezeMethods:e=>{Ra(e,((t,i)=>{if(ta(e)&&["arguments","caller","callee"].includes(i))return!1;const n=e[i];ta(n)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")}))}))},toObjectSet:(e,t)=>{const i={},n=e=>{e.forEach((e=>{i[e]=!0}))};return $s(e)?n(e):n(String(e).split(t)),i},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,i){return t.toUpperCase()+i})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:_a,global:ya,isContextDefined:Ta,isSpecCompliantForm:function(e){return!!(e&&ta(e.append)&&"FormData"===e[Vs]&&e[js])},toJSONObject:e=>{const t=new WeakSet,i=e=>{if(na(e)){if(t.has(e))return;if(Js(e))return e;if(!("toJSON"in e)){t.add(e);const n=$s(e)?[]:{};return ga(e,((e,t)=>{const r=i(e);!Zs(r)&&(n[t]=r)})),t.delete(e),n}}return e};return i(e)},isAsyncFn:ka,isThenable:e=>e&&(na(e)||ta(e))&&ta(e.then)&&ta(e.catch),setImmediate:xa,asap:Oa,isIterable:e=>null!=e&&ta(e[js])};const Ma=La.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Ba=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Na=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function Fa(e,t){return La.isArray(e)?e.map((e=>Fa(e,t))):function(e){let t=0,i=e.length;for(;t<i;){const i=e.charCodeAt(t);if(9!==i&&32!==i)break;t+=1}for(;i>t;){const t=e.charCodeAt(i-1);if(9!==t&&32!==t)break;i-=1}return 0===t&&i===e.length?e:e.slice(t,i)}(String(e).replace(t,""))}function Wa(e){const t=Object.create(null);return La.forEach(e.toJSON(),((e,i)=>{t[i]=(e=>Fa(e,Na))(e)})),t}const Ua=Symbol("internals");function Ga(e){return e&&String(e).trim().toLowerCase()}function Ha(e){return!1===e||null==e?e:La.isArray(e)?e.map(Ha):(e=>Fa(e,Ba))(String(e))}function za(e,t,i,n,r){return La.isFunction(n)?n.call(this,t,i):(r&&(t=i),La.isString(t)?La.isString(n)?-1!==t.indexOf(n):La.isRegExp(n)?n.test(t):void 0:void 0)}class ja{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function r(e,t,i){const r=Ga(t);if(!r)return;const s=La.findKey(n,r);(!s||void 0===n[s]||!0===i||void 0===i&&!1!==n[s])&&(n[s||t]=Ha(e))}const s=(e,t)=>La.forEach(e,((e,i)=>r(e,i,t)));if(La.isPlainObject(e)||e instanceof this.constructor)s(e,t);else if(La.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))s((e=>{const t={};let i,n,r;return e&&e.split("\n").forEach((function(e){r=e.indexOf(":"),i=e.substring(0,r).trim().toLowerCase(),n=e.substring(r+1).trim(),!i||t[i]&&Ma[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n)})),t})(e),t);else if(La.isObject(e)&&La.isIterable(e)){let i,n,r={};for(const t of e){if(!La.isArray(t))throw new TypeError("Object iterator must return a key-value pair");r[n=t[0]]=(i=r[n])?La.isArray(i)?[...i,t[1]]:[i,t[1]]:t[1]}s(r,t)}else null!=e&&r(t,e,i);return this}get(e,t){if(e=Ga(e)){const i=La.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t}(e);if(La.isFunction(t))return t.call(this,e,i);if(La.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ga(e)){const i=La.findKey(this,e);return!(!i||void 0===this[i]||t&&!za(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function r(e){if(e=Ga(e)){const r=La.findKey(i,e);!r||t&&!za(0,i[r],r,t)||(delete i[r],n=!0)}}return La.isArray(e)?e.forEach(r):r(e),n}clear(e){const t=Object.keys(this);let i=t.length,n=!1;for(;i--;){const r=t[i];e&&!za(0,this[r],r,e,!0)||(delete this[r],n=!0)}return n}normalize(e){const t=this,i={};return La.forEach(this,((n,r)=>{const s=La.findKey(i,r);if(s)return t[s]=Ha(n),void delete t[r];const a=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(r):String(r).trim();a!==r&&delete t[r],t[a]=Ha(n),i[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return La.forEach(this,((i,n)=>{null!=i&&!1!==i&&(t[n]=e&&La.isArray(i)?i.join(", "):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const i=new this(e);return t.forEach((e=>i.set(e))),i}static accessor(e){const t=(this[Ua]=this[Ua]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=Ga(e);t[n]||(!function(e,t){const i=La.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+i,{__proto__:null,value:function(e,i,r){return this[n].call(this,t,e,i,r)},configurable:!0})}))}(i,e),t[n]=!0)}return La.isArray(e)?e.forEach(n):n(e),this}}ja.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),La.reduceDescriptors(ja.prototype,(({value:e},t)=>{let i=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[i]=e}}})),La.freezeMethods(ja);function Va(e,t){const i=new Set(t.map((e=>String(e).toLowerCase()))),n=[],r=e=>{if(null===e||"object"!=typeof e)return e;if(La.isBuffer(e))return e;if(-1!==n.indexOf(e))return;let t;if(e instanceof ja&&(e=e.toJSON()),n.push(e),La.isArray(e))t=[],e.forEach(((e,i)=>{const n=r(e);La.isUndefined(n)||(t[i]=n)}));else{if(!La.isPlainObject(e)&&function(e){if(La.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(La.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}(e))return n.pop(),e;t=Object.create(null);for(const[n,s]of Object.entries(e)){const e=i.has(n.toLowerCase())?"[REDACTED ****]":r(s);La.isUndefined(e)||(t[n]=e)}}return n.pop(),t};return r(e)}class qa extends Error{static from(e,t,i,n,r,s){const a=new qa(e.message,t||e.code,i,n,r);return a.cause=e,a.name=e.name,null!=e.status&&null==a.status&&(a.status=e.status),s&&Object.assign(a,s),a}constructor(e,t,i,n,r){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r,this.status=r.status)}toJSON(){const e=this.config,t=e&&La.hasOwnProp(e,"redact")?e.redact:void 0,i=La.isArray(t)&&t.length>0?Va(e,t):La.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}}qa.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",qa.ERR_BAD_OPTION="ERR_BAD_OPTION",qa.ECONNABORTED="ECONNABORTED",qa.ETIMEDOUT="ETIMEDOUT",qa.ECONNREFUSED="ECONNREFUSED",qa.ERR_NETWORK="ERR_NETWORK",qa.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",qa.ERR_DEPRECATED="ERR_DEPRECATED",qa.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",qa.ERR_BAD_REQUEST="ERR_BAD_REQUEST",qa.ERR_CANCELED="ERR_CANCELED",qa.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",qa.ERR_INVALID_URL="ERR_INVALID_URL",qa.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";function Ya(e){return La.isPlainObject(e)||La.isArray(e)}function Ka(e){return La.endsWith(e,"[]")?e.slice(0,-2):e}function Xa(e,t,i){return e?e.concat(t).map((function(e,t){return e=Ka(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}const $a=La.toFlatObject(La,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Za(e,t,i){if(!La.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(i=La.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!La.isUndefined(t[e])}))).metaTokens,r=i.visitor||d,s=i.dots,a=i.indexes,o=i.Blob||"undefined"!=typeof Blob&&Blob,c=void 0===i.maxDepth?100:i.maxDepth,l=o&&La.isSpecCompliantForm(t);if(!La.isFunction(r))throw new TypeError("visitor must be a function");function h(e){if(null===e)return"";if(La.isDate(e))return e.toISOString();if(La.isBoolean(e))return e.toString();if(!l&&La.isBlob(e))throw new qa("Blob is not supported. Use a Buffer instead.");return La.isArrayBuffer(e)||La.isTypedArray(e)?l&&"function"==typeof Blob?new Blob([e]):Ar.from(e):e}function d(e,i,r){let o=e;if(La.isReactNative(t)&&La.isReactNativeBlob(e))return t.append(Xa(r,i,s),h(e)),!1;if(e&&!r&&"object"==typeof e)if(La.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(La.isArray(e)&&function(e){return La.isArray(e)&&!e.some(Ya)}(e)||(La.isFileList(e)||La.endsWith(i,"[]"))&&(o=La.toArray(e)))return i=Ka(i),o.forEach((function(e,n){!La.isUndefined(e)&&null!==e&&t.append(!0===a?Xa([i],n,s):null===a?i:i+"[]",h(e))})),!1;return!!Ya(e)||(t.append(Xa(r,i,s),h(e)),!1)}const u=[],f=Object.assign($a,{defaultVisitor:d,convertValue:h,isVisitable:Ya});if(!La.isObject(e))throw new TypeError("data must be an object");return function e(i,n,s=0){if(!La.isUndefined(i)){if(s>c)throw new qa("Object is too deeply nested ("+s+" levels). Max depth: "+c,qa.ERR_FORM_DATA_DEPTH_EXCEEDED);if(-1!==u.indexOf(i))throw new Error("Circular reference detected in "+n.join("."));u.push(i),La.forEach(i,(function(i,a){!0===(!(La.isUndefined(i)||null===i)&&r.call(t,i,La.isString(a)?a.trim():a,n,f))&&e(i,n?n.concat(a):[a],s+1)})),u.pop()}}(e),t}function Ja(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,(function(e){return t[e]}))}function Qa(e,t){this._pairs=[],e&&Za(e,this,t)}const eo=Qa.prototype;function to(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function io(e,t,i){if(!t)return e;const n=i&&i.encode||to,r=La.isFunction(i)?{serialize:i}:i,s=r&&r.serialize;let a;if(a=s?s(t,r):La.isURLSearchParams(t)?t.toString():new Qa(t,r).toString(n),a){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e}eo.append=function(e,t){this._pairs.push([e,t])},eo.toString=function(e){const t=e?function(t){return e.call(this,t,Ja)}:Ja;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class no{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){La.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var ro={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1},so={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Qa,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const ao="undefined"!=typeof window&&"undefined"!=typeof document,oo="object"==typeof navigator&&navigator||void 0,co=ao&&(!oo||["ReactNative","NativeScript","NS"].indexOf(oo.product)<0),lo="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,ho=ao&&window.location.href||"http://localhost";var uo={...Object.freeze({__proto__:null,hasBrowserEnv:ao,hasStandardBrowserEnv:co,hasStandardBrowserWebWorkerEnv:lo,navigator:oo,origin:ho}),...so};function fo(e){function t(e,i,n,r){let s=e[r++];if("__proto__"===s)return!0;const a=Number.isFinite(+s),o=r>=e.length;if(s=!s&&La.isArray(n)?n.length:s,o)return La.hasOwnProp(n,s)?n[s]=La.isArray(n[s])?n[s].concat(i):[n[s],i]:n[s]=i,!a;La.hasOwnProp(n,s)&&La.isObject(n[s])||(n[s]=[]);return t(e,i,n[s],r)&&La.isArray(n[s])&&(n[s]=function(e){const t={},i=Object.keys(e);let n;const r=i.length;let s;for(n=0;n<r;n++)s=i[n],t[s]=e[s];return t}(n[s])),!a}if(La.isFormData(e)&&La.isFunction(e.entries)){const i={};return La.forEachEntry(e,((e,n)=>{t(function(e){return La.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,i,0)})),i}return null}const po=(e,t)=>null!=e&&La.hasOwnProp(e,t)?e[t]:void 0;const mo={transitional:ro,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,r=La.isObject(e);r&&La.isHTMLForm(e)&&(e=new FormData(e));if(La.isFormData(e))return n?JSON.stringify(fo(e)):e;if(La.isArrayBuffer(e)||La.isBuffer(e)||La.isStream(e)||La.isFile(e)||La.isBlob(e)||La.isReadableStream(e))return e;if(La.isArrayBufferView(e))return e.buffer;if(La.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let s;if(r){const t=po(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Za(e,new uo.classes.URLSearchParams,{visitor:function(e,t,i,n){return uo.isNode&&La.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...t})}(e,t).toString();if((s=La.isFileList(e))||i.indexOf("multipart/form-data")>-1){const i=po(this,"env"),n=i&&i.FormData;return Za(s?{"files[]":e}:e,n&&new n,t)}}return r||n?(t.setContentType("application/json",!1),function(e,t,i){if(La.isString(e))try{return(t||JSON.parse)(e),La.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=po(this,"transitional")||mo.transitional,i=t&&t.forcedJSONParsing,n=po(this,"responseType"),r="json"===n;if(La.isResponse(e)||La.isReadableStream(e))return e;if(e&&La.isString(e)&&(i&&!n||r)){const i=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,po(this,"parseReviver"))}catch(e){if(i){if("SyntaxError"===e.name)throw qa.from(e,qa.ERR_BAD_RESPONSE,this,null,po(this,"response"));throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:uo.classes.FormData,Blob:uo.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};function go(e,t){const i=this||mo,n=t||i,r=ja.from(n.headers);let s=n.data;return La.forEach(e,(function(e){s=e.call(i,s,r.normalize(),t?t.status:void 0)})),r.normalize(),s}function _o(e){return!(!e||!e.__CANCEL__)}La.forEach(["delete","get","head","post","put","patch","query"],(e=>{mo.headers[e]={}}));class yo extends qa{constructor(e,t,i){super(null==e?"canceled":e,qa.ERR_CANCELED,t,i),this.name="CanceledError",this.__CANCEL__=!0}}function To(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new qa("Request failed with status code "+i.status,i.status>=400&&i.status<500?qa.ERR_BAD_REQUEST:qa.ERR_BAD_RESPONSE,i.config,i.request,i)):e(i)}const wo=(e,t,i=3)=>{let n=0;const r=function(e,t){e=e||10;const i=new Array(e),n=new Array(e);let r,s=0,a=0;return t=void 0!==t?t:1e3,function(o){const c=Date.now(),l=n[a];r||(r=c),i[s]=o,n[s]=c;let h=a,d=0;for(;h!==s;)d+=i[h++],h%=e;if(s=(s+1)%e,s===a&&(a=(a+1)%e),c-r<t)return;const u=l&&c-l;return u?Math.round(1e3*d/u):void 0}}(50,250);return function(e,t){let i,n,r=0,s=1e3/t;const a=(t,s=Date.now())=>{r=s,i=null,n&&(clearTimeout(n),n=null),e(...t)};return[(...e)=>{const t=Date.now(),o=t-r;o>=s?a(e,t):(i=e,n||(n=setTimeout((()=>{n=null,a(i)}),s-o)))},()=>i&&a(i)]}((i=>{if(!i||"number"!=typeof i.loaded)return;const s=i.loaded,a=i.lengthComputable?i.total:void 0,o=null!=a?Math.min(s,a):s,c=Math.max(0,o-n),l=r(c);n=Math.max(n,o);e({loaded:o,total:a,progress:a?o/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a?(a-o)/l:void 0,event:i,lengthComputable:null!=a,[t?"download":"upload"]:!0})}),i)},bo=(e,t)=>{const i=null!=e;return[n=>t[0]({lengthComputable:i,total:e,loaded:n}),t[1]]},So=e=>(...t)=>La.asap((()=>e(...t)));var vo=uo.hasStandardBrowserEnv?((e,t)=>i=>(i=new URL(i,uo.origin),e.protocol===i.protocol&&e.host===i.host&&(t||e.port===i.port)))(new URL(uo.origin),uo.navigator&&/(msie|trident)/i.test(uo.navigator.userAgent)):()=>!0,Ao=uo.hasStandardBrowserEnv?{write(e,t,i,n,r,s,a){if("undefined"==typeof document)return;const o=[`${e}=${encodeURIComponent(t)}`];La.isNumber(i)&&o.push(`expires=${new Date(i).toUTCString()}`),La.isString(n)&&o.push(`path=${n}`),La.isString(r)&&o.push(`domain=${r}`),!0===s&&o.push("secure"),La.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(let i=0;i<t.length;i++){const n=t[i].replace(/^\s+/,""),r=n.indexOf("=");if(-1!==r&&n.slice(0,r)===e)return decodeURIComponent(n.slice(r+1))}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function Eo(e,t,i){let n=!("string"==typeof(r=t)&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r));var r;return e&&(n||!1===i)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Ro=e=>e instanceof ja?{...e}:e;function ko(e,t){t=t||{};const i=Object.create(null);function n(e,t,i,n){return La.isPlainObject(e)&&La.isPlainObject(t)?La.merge.call({caseless:n},e,t):La.isPlainObject(t)?La.merge({},t):La.isArray(t)?t.slice():t}function r(e,t,i,r){return La.isUndefined(t)?La.isUndefined(e)?void 0:n(void 0,e,0,r):n(e,t,0,r)}function s(e,t){if(!La.isUndefined(t))return n(void 0,t)}function a(e,t){return La.isUndefined(t)?La.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(i,r,s){return La.hasOwnProp(t,s)?n(i,r):La.hasOwnProp(e,s)?n(void 0,i):void 0}Object.defineProperty(i,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});const c={url:s,method:s,data:s,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,allowedSocketPaths:a,responseEncoding:a,validateStatus:o,headers:(e,t,i)=>r(Ro(e),Ro(t),0,!0)};return La.forEach(Object.keys({...e,...t}),(function(n){if("__proto__"===n||"constructor"===n||"prototype"===n)return;const s=La.hasOwnProp(c,n)?c[n]:r,a=s(La.hasOwnProp(e,n)?e[n]:void 0,La.hasOwnProp(t,n)?t[n]:void 0,n);La.isUndefined(a)&&s!==o||(i[n]=a)})),i}const xo=["content-type","content-length"];function Co(e){const t=ko({},e),i=e=>La.hasOwnProp(t,e)?t[e]:void 0,n=i("data");let r=i("withXSRFToken");const s=i("xsrfHeaderName"),a=i("xsrfCookieName");let o=i("headers");const c=i("auth"),l=i("baseURL"),h=i("allowAbsoluteUrls"),d=i("url");var u;if(t.headers=o=ja.from(o),t.url=io(Eo(l,d,h),i("params"),i("paramsSerializer")),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?(u=c.password,encodeURIComponent(u).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16))))):""))),La.isFormData(n)&&(uo.hasStandardBrowserEnv||uo.hasStandardBrowserWebWorkerEnv||La.isReactNative(n)?o.setContentType(void 0):La.isFunction(n.getHeaders)&&function(e,t,i){"content-only"===i?Object.entries(t).forEach((([t,i])=>{xo.includes(t.toLowerCase())&&e.set(t,i)})):e.set(t)}(o,n.getHeaders(),i("formDataHeaderPolicy"))),uo.hasStandardBrowserEnv){La.isFunction(r)&&(r=r(t));if(!0===r||null==r&&vo(t.url)){const e=s&&a&&Ao.read(a);e&&o.set(s,e)}}return t}var Io="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,i){const n=Co(e);let r=n.data;const s=ja.from(n.headers).normalize();let a,o,c,l,h,{responseType:d,onUploadProgress:u,onDownloadProgress:f}=n;function p(){l&&l(),h&&h(),n.cancelToken&&n.cancelToken.unsubscribe(a),n.signal&&n.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=ja.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());To((function(e){t(e),p()}),(function(e){i(e),p()}),{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&m.responseURL.startsWith("file:"))&&setTimeout(g)},m.onabort=function(){m&&(i(new qa("Request aborted",qa.ECONNABORTED,e,m)),p(),m=null)},m.onerror=function(t){const n=t&&t.message?t.message:"Network Error",r=new qa(n,qa.ERR_NETWORK,e,m);r.event=t||null,i(r),p(),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const r=n.transitional||ro;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),i(new qa(t,r.clarifyTimeoutError?qa.ETIMEDOUT:qa.ECONNABORTED,e,m)),p(),m=null},void 0===r&&s.setContentType(null),"setRequestHeader"in m&&La.forEach(Wa(s),(function(e,t){m.setRequestHeader(t,e)})),La.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),f&&([c,h]=wo(f,!0),m.addEventListener("progress",c)),u&&m.upload&&([o,l]=wo(u),m.upload.addEventListener("progress",o),m.upload.addEventListener("loadend",l)),(n.cancelToken||n.signal)&&(a=t=>{m&&(i(!t||t.type?new yo(null,e,m):t),m.abort(),p(),m=null)},n.cancelToken&&n.cancelToken.subscribe(a),n.signal&&(n.signal.aborted?a():n.signal.addEventListener("abort",a)));const _=function(e){const t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}(n.url);!_||uo.protocols.includes(_)?m.send(r||null):i(new qa("Unsupported protocol "+_+":",qa.ERR_BAD_REQUEST,e))}))};const Po=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;const i=new AbortController;let n=!1;const r=function(e){if(!n){n=!0,a();const t=e instanceof Error?e:this.reason;i.abort(t instanceof qa?t:new yo(t instanceof Error?t.message:t))}};let s=t&&setTimeout((()=>{s=null,r(new qa(`timeout of ${t}ms exceeded`,qa.ETIMEDOUT))}),t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)})),e=null)};e.forEach((e=>e.addEventListener("abort",r)));const{signal:o}=i;return o.unsubscribe=()=>La.asap(a),o},Do=function*(e,t){let i=e.byteLength;if(i<t)return void(yield e);let n,r=0;for(;r<i;)n=r+t,yield e.slice(r,n),r=n},Oo=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:i}=await t.read();if(e)break;yield i}}finally{await t.cancel()}},Lo=(e,t,i,n)=>{const r=async function*(e,t){for await(const i of Oo(e))yield*Do(i,t)}(e,t);let s,a=0,o=e=>{s||(s=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await r.next();if(t)return o(),void e.close();let s=n.byteLength;if(i){let e=a+=s;i(e)}e.enqueue(new Uint8Array(n))}catch(e){throw o(e),e}},cancel:e=>(o(e),r.return())},{highWaterMark:2})};const Mo="1.17.0",{isFunction:Bo}=La,No=e=>{if(!La.isString(e))return e;try{return decodeURIComponent(e)}catch(t){return e}},Fo=(e,...t)=>{try{return!!e(...t)}catch(e){return!1}},Wo=e=>{const t=void 0!==La.global&&null!==La.global?La.global:globalThis,{ReadableStream:i,TextEncoder:n}=t;e=La.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e);const{fetch:r,Request:s,Response:a}=e,o=r?Bo(r):"function"==typeof fetch,c=Bo(s),l=Bo(a);if(!o)return!1;const h=o&&Bo(i),d=o&&("function"==typeof n?(u=new n,e=>u.encode(e)):async e=>new Uint8Array(await new s(e).arrayBuffer()));var u;const f=c&&h&&Fo((()=>{let e=!1;const t=new s(uo.origin,{body:new i,method:"POST",get duplex(){return e=!0,"half"}}),n=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!n})),p=l&&h&&Fo((()=>La.isReadableStream(new a("").body))),m={stream:p&&(e=>e.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!m[e]&&(m[e]=(t,i)=>{let n=t&&t[e];if(n)return n.call(t);throw new qa(`Response type '${e}' is not supported`,qa.ERR_NOT_SUPPORT,i)})}));const g=async(e,t)=>{const i=La.toFiniteNumber(e.getContentLength());return null==i?(async e=>{if(null==e)return 0;if(La.isBlob(e))return e.size;if(La.isSpecCompliantForm(e)){const t=new s(uo.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return La.isArrayBufferView(e)||La.isArrayBuffer(e)?e.byteLength:(La.isURLSearchParams(e)&&(e+=""),La.isString(e)?(await d(e)).byteLength:void 0)})(t):i};return async e=>{let{url:t,method:i,data:o,signal:l,cancelToken:h,timeout:d,onDownloadProgress:u,onUploadProgress:_,responseType:y,headers:T,withCredentials:w="same-origin",fetchOptions:b,maxContentLength:S,maxBodyLength:v}=Co(e);const A=La.isNumber(S)&&S>-1,E=La.isNumber(v)&&v>-1;let R=r||fetch;y=y?(y+"").toLowerCase():"text";let k=Po([l,h&&h.toAbortSignal()],d),x=null;const C=k&&k.unsubscribe&&(()=>{k.unsubscribe()});let I;try{let r;const l=(D="auth",La.hasOwnProp(e,D)?e[D]:void 0);if(l){const e=l.username||"";r={username:e,password:l.password||""}}if((e=>{const t=e.indexOf("://");let i=e;return-1!==t&&(i=i.slice(t+3)),i.includes("@")||i.includes(":")})(t)){const e=new URL(t,uo.origin);if(!r&&(e.username||e.password)){const t=No(e.username);r={username:t,password:No(e.password)}}(e.username||e.password)&&(e.username="",e.password="",t=e.href)}if(r&&(T.delete("authorization"),T.set("Authorization","Basic "+btoa((P=(r.username||"")+":"+(r.password||""),encodeURIComponent(P).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16)))))))),A&&"string"==typeof t&&t.startsWith("data:")){const i=function(e){if(!e||"string"!=typeof e)return 0;if(!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const i=e.slice(5,t),n=e.slice(t+1);if(/;base64/i.test(i)){let e=n.length;const t=n.length;for(let i=0;i<t;i++)if(37===n.charCodeAt(i)&&i+2<t){const t=n.charCodeAt(i+1),r=n.charCodeAt(i+2);(t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102)&&(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102)&&(e-=2,i+=2)}let i=0,r=t-1;const s=e=>e>=2&&37===n.charCodeAt(e-2)&&51===n.charCodeAt(e-1)&&(68===n.charCodeAt(e)||100===n.charCodeAt(e));r>=0&&(61===n.charCodeAt(r)?(i++,r--):s(r)&&(i++,r-=3)),1===i&&r>=0&&(61===n.charCodeAt(r)||s(r))&&i++;const a=3*Math.floor(e/4)-(i||0);return a>0?a:0}if(void 0!==Ar&&"function"==typeof Ar.byteLength)return Ar.byteLength(n,"utf8");let r=0;for(let e=0,t=n.length;e<t;e++){const i=n.charCodeAt(e);if(i<128)r+=1;else if(i<2048)r+=2;else if(i>=55296&&i<=56319&&e+1<t){const t=n.charCodeAt(e+1);t>=56320&&t<=57343?(r+=4,e++):r+=3}else r+=3}return r}(t);if(i>S)throw new qa("maxContentLength size of "+S+" exceeded",qa.ERR_BAD_RESPONSE,e,x)}if(E&&"get"!==i&&"head"!==i){const t=await g(T,o);if("number"==typeof t&&isFinite(t)&&t>v)throw new qa("Request body larger than maxBodyLength limit",qa.ERR_BAD_REQUEST,e,x)}if(_&&f&&"get"!==i&&"head"!==i&&0!==(I=await g(T,o))){let e,i=new s(t,{method:"POST",body:o,duplex:"half"});if(La.isFormData(o)&&(e=i.headers.get("content-type"))&&T.setContentType(e),i.body){const[e,t]=bo(I,wo(So(_)));o=Lo(i.body,65536,e,t)}}La.isString(w)||(w=w?"include":"omit");const h=c&&"credentials"in s.prototype;if(La.isFormData(o)){const e=T.getContentType();e&&/^multipart\/form-data/i.test(e)&&!/boundary=/i.test(e)&&T.delete("content-type")}T.set("User-Agent","axios/"+Mo,!1);const d={...b,signal:k,method:i.toUpperCase(),headers:Wa(T.normalize()),body:o,duplex:"half",credentials:h?w:void 0};x=c&&new s(t,d);let O=await(c?R(x,b):R(t,d));if(A){const t=La.toFiniteNumber(O.headers.get("content-length"));if(null!=t&&t>S)throw new qa("maxContentLength size of "+S+" exceeded",qa.ERR_BAD_RESPONSE,e,x)}const L=p&&("stream"===y||"response"===y);if(p&&O.body&&(u||A||L&&C)){const t={};["status","statusText","headers"].forEach((e=>{t[e]=O[e]}));const i=La.toFiniteNumber(O.headers.get("content-length")),[n,r]=u&&bo(i,wo(So(u),!0))||[];let s=0;const o=t=>{if(A&&(s=t,s>S))throw new qa("maxContentLength size of "+S+" exceeded",qa.ERR_BAD_RESPONSE,e,x);n&&n(t)};O=new a(Lo(O.body,65536,o,(()=>{r&&r(),C&&C()})),t)}y=y||"text";let M=await m[La.findKey(m,y)||"text"](O,e);if(A&&!p&&!L){let t;if(null!=M&&("number"==typeof M.byteLength?t=M.byteLength:"number"==typeof M.size?t=M.size:"string"==typeof M&&(t="function"==typeof n?(new n).encode(M).byteLength:M.length)),"number"==typeof t&&t>S)throw new qa("maxContentLength size of "+S+" exceeded",qa.ERR_BAD_RESPONSE,e,x)}return!L&&C&&C(),await new Promise(((t,i)=>{To(t,i,{data:M,headers:ja.from(O.headers),status:O.status,statusText:O.statusText,config:e,request:x})}))}catch(t){if(C&&C(),k&&k.aborted&&k.reason instanceof qa){const i=k.reason;throw i.config=e,x&&(i.request=x),t!==i&&(i.cause=t),i}if(t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message))throw Object.assign(new qa("Network Error",qa.ERR_NETWORK,e,x,t&&t.response),{cause:t.cause||t});throw qa.from(t,t&&t.code,e,x,t&&t.response)}var P,D}},Uo=new Map,Go=e=>{let t=e&&e.env||{};const{fetch:i,Request:n,Response:r}=t,s=[n,r,i];let a,o,c=s.length,l=Uo;for(;c--;)a=s[c],o=l.get(a),void 0===o&&l.set(a,o=c?new Map:Wo(t)),l=o;return o};Go();const Ho={http:null,xhr:Io,fetch:{get:Go}};La.forEach(Ho,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch(e){}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}}));const zo=e=>`- ${e}`,jo=e=>La.isFunction(e)||null===e||!1===e;var Vo={getAdapter:function(e,t){e=La.isArray(e)?e:[e];const{length:i}=e;let n,r;const s={};for(let a=0;a<i;a++){let i;if(n=e[a],r=n,!jo(n)&&(r=Ho[(i=String(n)).toLowerCase()],void 0===r))throw new qa(`Unknown adapter '${i}'`);if(r&&(La.isFunction(r)||(r=r.get(t))))break;s[i||"#"+a]=r}if(!r){const e=Object.entries(s).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));let t=i?e.length>1?"since :\n"+e.map(zo).join("\n"):" "+zo(e[0]):"as no adapter specified";throw new qa("There is no suitable adapter to dispatch the request "+t,"ERR_NOT_SUPPORT")}return r},adapters:Ho};function qo(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new yo(null,e)}function Yo(e){qo(e),e.headers=ja.from(e.headers),e.data=go.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Vo.getAdapter(e.adapter||mo.adapter,e)(e).then((function(t){qo(e),e.response=t;try{t.data=go.call(e,e.transformResponse,t)}finally{delete e.response}return t.headers=ja.from(t.headers),t}),(function(t){if(!_o(t)&&(qo(e),t&&t.response)){e.response=t.response;try{t.response.data=go.call(e,e.transformResponse,t.response)}finally{delete e.response}t.response.headers=ja.from(t.response.headers)}return Promise.reject(t)}))}const Ko={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Ko[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const Xo={};Ko.transitional=function(e,t,i){function n(e,t){return"[Axios v"+Mo+"] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,r,s)=>{if(!1===e)throw new qa(n(r," has been removed"+(t?" in "+t:"")),qa.ERR_DEPRECATED);return t&&!Xo[r]&&(Xo[r]=!0,console.warn(n(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,r,s)}},Ko.spelling=function(e){return(t,i)=>(console.warn(`${i} is likely a misspelling of ${e}`),!0)};var $o={assertOptions:function(e,t,i){if("object"!=typeof e)throw new qa("options must be an object",qa.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let r=n.length;for(;r-- >0;){const s=n[r],a=Object.prototype.hasOwnProperty.call(t,s)?t[s]:void 0;if(a){const t=e[s],i=void 0===t||a(t,s,e);if(!0!==i)throw new qa("option "+s+" must be "+i,qa.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new qa("Unknown option "+s,qa.ERR_BAD_OPTION)}},validators:Ko};const Zo=$o.validators;class Jo{constructor(e){this.defaults=e||{},this.interceptors={request:new no,response:new no}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const i=(()=>{if(!t.stack)return"";const e=t.stack.indexOf("\n");return-1===e?"":t.stack.slice(e+1)})();try{if(e.stack){if(i){const t=i.indexOf("\n"),n=-1===t?-1:i.indexOf("\n",t+1),r=-1===n?"":i.slice(n+1);String(e.stack).endsWith(r)||(e.stack+="\n"+i)}}else e.stack=i}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=ko(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:r}=t;void 0!==i&&$o.assertOptions(i,{silentJSONParsing:Zo.transitional(Zo.boolean),forcedJSONParsing:Zo.transitional(Zo.boolean),clarifyTimeoutError:Zo.transitional(Zo.boolean),legacyInterceptorReqResOrdering:Zo.transitional(Zo.boolean),advertiseZstdAcceptEncoding:Zo.transitional(Zo.boolean)},!1),null!=n&&(La.isFunction(n)?t.paramsSerializer={serialize:n}:$o.assertOptions(n,{encode:Zo.function,serialize:Zo.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),$o.assertOptions(t,{baseUrl:Zo.spelling("baseURL"),withXsrfToken:Zo.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=r&&La.merge(r.common,r[t.method]);r&&La.forEach(["delete","get","head","post","put","patch","query","common"],(e=>{delete r[e]})),t.headers=ja.concat(s,r);const a=[];let o=!0;this.interceptors.request.forEach((function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;o=o&&e.synchronous;const i=t.transitional||ro;i&&i.legacyInterceptorReqResOrdering?a.unshift(e.fulfilled,e.rejected):a.push(e.fulfilled,e.rejected)}));const c=[];let l;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let h,d=0;if(!o){const e=[Yo.bind(this),void 0];for(e.unshift(...a),e.push(...c),h=e.length,l=Promise.resolve(t);d<h;)l=l.then(e[d++],e[d++]);return l}h=a.length;let u=t;for(;d<h;){const e=a[d++],t=a[d++];try{u=e(u)}catch(e){t.call(this,e);break}}try{l=Yo.call(this,u)}catch(e){return Promise.reject(e)}for(d=0,h=c.length;d<h;)l=l.then(c[d++],c[d++]);return l}getUri(e){return io(Eo((e=ko(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}La.forEach(["delete","get","head","options"],(function(e){Jo.prototype[e]=function(t,i){return this.request(ko(i||{},{method:e,url:t,data:(i||{}).data}))}})),La.forEach(["post","put","patch","query"],(function(e){function t(t){return function(i,n,r){return this.request(ko(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}Jo.prototype[e]=t(),"query"!==e&&(Jo.prototype[e+"Form"]=t(!0))}));class Qo{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const i=this;this.promise.then((e=>{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,r){i.reason||(i.reason=new yo(e,n,r),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Qo((function(t){e=t})),cancel:e}}}const ec={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(ec).forEach((([e,t])=>{ec[t]=e}));const tc=function e(t){const i=new Jo(t),n=Gs(Jo.prototype.request,i);return La.extend(n,Jo.prototype,i,{allOwnKeys:!0}),La.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(ko(t,i))},n}(mo);tc.Axios=Jo,tc.CanceledError=yo,tc.CancelToken=Qo,tc.isCancel=_o,tc.VERSION=Mo,tc.toFormData=Za,tc.AxiosError=qa,tc.Cancel=tc.CanceledError,tc.all=function(e){return Promise.all(e)},tc.spread=function(e){return function(t){return e.apply(null,t)}},tc.isAxiosError=function(e){return La.isObject(e)&&!0===e.isAxiosError},tc.mergeConfig=ko,tc.AxiosHeaders=ja,tc.formToJSON=e=>fo(La.isHTMLForm(e)?new FormData(e):e),tc.getAdapter=Vo.getAdapter,tc.HttpStatusCode=ec,tc.default=tc;const ic={baseURL:process.env.ROLLUP_BASE_API,timeout:3e4,withCredentials:!0};var nc=new class{service;constructor(e){this.service=this.setConfig(e)}setConfig(t){const i=tc.create(e(ic,t));return i.interceptors.request.use((e=>{const t=ps.getItem(ms);return t&&e.headers&&"function"==typeof e.headers.set&&e.headers.set("Authorization","Bearer "+t),e}),(e=>Promise.reject(e))),i.interceptors.response.use((e=>{const{data:t,status:i}=e;return 401===i||t.code&&0!==t.code?Promise.reject(t):t}),(async e=>(-1!==e.message.indexOf("timeout")&&console.error("请求超时!请您稍后重试"),-1!==e.message.indexOf("Network Error")&&console.error("网络错误!请您稍后重试"),Promise.reject(e)))),this.service=i,i}get(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.service.get(e,{params:t,...i})}post(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.service.post(e,t,i)}download(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.service.post(e,t,{...i,responseType:"blob"})}template(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.service.get(e,{params:t,...i,responseType:"blob"})}upload(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.service.post(e,t,{...i,headers:{"Content-Type":"multipart/form-data"}})}}(ic);tc.CancelToken;let rc=null;const sc={fetchFloat32Array:[],apiText2Speech:[],apiAsk:[]},ac=async(t,i,n)=>{const r=ps.getItem(gs),s=ps.getItem(ms),a=await(async()=>(rc||(rc=import("./streaming-C91bzAdu.js").then((e=>{const t=e.SSE??e.default??e;if("function"!=typeof t)throw new Error("SSE constructor is unavailable");return t}))),rc))(),o=i.message[i.message.length-1].content;Reflect.deleteProperty(i,"message");const c=e({query:"",language:"",conversation_id:"",response_mode:"streaming",files:[],inputs:{}},{...i,query:o});try{sc.apiAsk.length>0&&sc.apiAsk.forEach((e=>{e.close()}));const e=`${r}/human-auth/characters/${t}/chat-messages`,i=new a(`${e}`,{method:"POST",headers:{responseType:"streaming"===c.response_mode?"stream":"json","Content-Type":"application/json",Authorization:`Bearer ${s}`},payload:JSON.stringify(c)});sc.apiAsk=[i],i.addEventListener("message",(e=>{const t={code:0,msg:"success",data:null};if("streaming"===c.response_mode)if(e.data)t.data=JSON.parse(e.data);else{const i=JSON.parse(e.source.xhr.responseText);t.code=i.code,t.data=i.data,t.msg=i.msg}else t.code=e.code,t.data=e.data,t.msg=e.msg;"message"!==t.data.event&&"message_end"!==t.data.event&&"error"!==t.data.event||n&&n(t)})),i.onerror=e=>{throw console.error("sse...onerror=",e),new Error(e)},i.onabort=e=>{},i.onreadystatechange=e=>{2===e.readyState&&(sc.apiAsk=[])}}catch(e){throw console.error("Fetch error:",e),new Error(e)}};function oc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var cc;!function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR",e[e.NONE=4]="NONE"}(cc||(cc={}));class lc{level=cc.WARN;prefix="[JSSDK]";enabled=!0;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.level=e.level??cc.WARN,this.prefix=e.prefix??"[JSSDK]",this.enabled=e.enabled??!0}configure(e){void 0!==e.level&&(this.level=e.level),void 0!==e.prefix&&(this.prefix=e.prefix),void 0!==e.enabled&&(this.enabled=e.enabled)}setLevel(e){this.level=e}setEnabled(e){this.enabled=e}debug(e){if(this.enabled&&this.level<=cc.DEBUG){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];this.prefix}}info(e){if(this.enabled&&this.level<=cc.INFO){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];this.prefix}}warn(e){if(this.enabled&&this.level<=cc.WARN){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];console.warn(`${this.prefix} [WARN]`,e,...i)}}error(e){if(this.enabled&&this.level<=cc.ERROR){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];console.error(`${this.prefix} [ERROR]`,e,...i)}}child(e){return new lc({level:this.level,prefix:`${this.prefix}:${e}`,enabled:this.enabled})}}function hc(e){if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack?.split("\n").slice(0,5).join("\n")};if("object"==typeof e&&null!==e)try{return JSON.stringify(e),e}catch{}return{name:"UnknownError",message:String(e)}}new lc;var dc,uc={};dc=uc,function(){var e=function(){this.init()};e.prototype={init:function(){var e=this||t;return e._counter=1e3,e._html5AudioPool=[],e.html5PoolSize=10,e._codecs={},e._howls=[],e._muted=!1,e._volume=1,e._canPlayEvent="canplaythrough",e._navigator="undefined"!=typeof window&&window.navigator?window.navigator:null,e.masterGain=null,e.noAudio=!1,e.usingWebAudio=!0,e.autoSuspend=!0,e.ctx=null,e.autoUnlock=!0,e._setup(),e},volume:function(e){var i=this||t;if(e=parseFloat(e),i.ctx||h(),void 0!==e&&e>=0&&e<=1){if(i._volume=e,i._muted)return i;i.usingWebAudio&&i.masterGain.gain.setValueAtTime(e,t.ctx.currentTime);for(var n=0;n<i._howls.length;n++)if(!i._howls[n]._webAudio)for(var r=i._howls[n]._getSoundIds(),s=0;s<r.length;s++){var a=i._howls[n]._soundById(r[s]);a&&a._node&&(a._node.volume=a._volume*e)}return i}return i._volume},mute:function(e){var i=this||t;i.ctx||h(),i._muted=e,i.usingWebAudio&&i.masterGain.gain.setValueAtTime(e?0:i._volume,t.ctx.currentTime);for(var n=0;n<i._howls.length;n++)if(!i._howls[n]._webAudio)for(var r=i._howls[n]._getSoundIds(),s=0;s<r.length;s++){var a=i._howls[n]._soundById(r[s]);a&&a._node&&(a._node.muted=!!e||a._muted)}return i},stop:function(){for(var e=this||t,i=0;i<e._howls.length;i++)e._howls[i].stop();return e},unload:function(){for(var e=this||t,i=e._howls.length-1;i>=0;i--)e._howls[i].unload();return e.usingWebAudio&&e.ctx&&void 0!==e.ctx.close&&(e.ctx.close(),e.ctx=null,h()),e},codecs:function(e){return(this||t)._codecs[e.replace(/^x-/,"")]},_setup:function(){var e=this||t;if(e.state=e.ctx&&e.ctx.state||"suspended",e._autoSuspend(),!e.usingWebAudio)if("undefined"!=typeof Audio)try{void 0===(new Audio).oncanplaythrough&&(e._canPlayEvent="canplay")}catch(t){e.noAudio=!0}else e.noAudio=!0;try{(new Audio).muted&&(e.noAudio=!0)}catch(e){}return e.noAudio||e._setupCodecs(),e},_setupCodecs:function(){var e=this||t,i=null;try{i="undefined"!=typeof Audio?new Audio:null}catch(t){return e}if(!i||"function"!=typeof i.canPlayType)return e;var n=i.canPlayType("audio/mpeg;").replace(/^no$/,""),r=e._navigator?e._navigator.userAgent:"",s=r.match(/OPR\/(\d+)/g),a=s&&parseInt(s[0].split("/")[1],10)<33,o=-1!==r.indexOf("Safari")&&-1===r.indexOf("Chrome"),c=r.match(/Version\/(.*?) /),l=o&&c&&parseInt(c[1],10)<15;return e._codecs={mp3:!(a||!n&&!i.canPlayType("audio/mp3;").replace(/^no$/,"")),mpeg:!!n,opus:!!i.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,""),ogg:!!i.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),oga:!!i.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),wav:!!(i.canPlayType('audio/wav; codecs="1"')||i.canPlayType("audio/wav")).replace(/^no$/,""),aac:!!i.canPlayType("audio/aac;").replace(/^no$/,""),caf:!!i.canPlayType("audio/x-caf;").replace(/^no$/,""),m4a:!!(i.canPlayType("audio/x-m4a;")||i.canPlayType("audio/m4a;")||i.canPlayType("audio/aac;")).replace(/^no$/,""),m4b:!!(i.canPlayType("audio/x-m4b;")||i.canPlayType("audio/m4b;")||i.canPlayType("audio/aac;")).replace(/^no$/,""),mp4:!!(i.canPlayType("audio/x-mp4;")||i.canPlayType("audio/mp4;")||i.canPlayType("audio/aac;")).replace(/^no$/,""),weba:!(l||!i.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),webm:!(l||!i.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")),dolby:!!i.canPlayType('audio/mp4; codecs="ec-3"').replace(/^no$/,""),flac:!!(i.canPlayType("audio/x-flac;")||i.canPlayType("audio/flac;")).replace(/^no$/,"")},e},_unlockAudio:function(){var e=this||t;if(!e._audioUnlocked&&e.ctx){e._audioUnlocked=!1,e.autoUnlock=!1,e._mobileUnloaded||44100===e.ctx.sampleRate||(e._mobileUnloaded=!0,e.unload()),e._scratchBuffer=e.ctx.createBuffer(1,1,22050);var i=function(t){for(;e._html5AudioPool.length<e.html5PoolSize;)try{var n=new Audio;n._unlocked=!0,e._releaseHtml5Audio(n)}catch(t){e.noAudio=!0;break}for(var r=0;r<e._howls.length;r++)if(!e._howls[r]._webAudio)for(var s=e._howls[r]._getSoundIds(),a=0;a<s.length;a++){var o=e._howls[r]._soundById(s[a]);o&&o._node&&!o._node._unlocked&&(o._node._unlocked=!0,o._node.load())}e._autoResume();var c=e.ctx.createBufferSource();c.buffer=e._scratchBuffer,c.connect(e.ctx.destination),void 0===c.start?c.noteOn(0):c.start(0),"function"==typeof e.ctx.resume&&e.ctx.resume(),c.onended=function(){c.disconnect(0),e._audioUnlocked=!0,document.removeEventListener("touchstart",i,!0),document.removeEventListener("touchend",i,!0),document.removeEventListener("click",i,!0),document.removeEventListener("keydown",i,!0);for(var t=0;t<e._howls.length;t++)e._howls[t]._emit("unlock")}};return document.addEventListener("touchstart",i,!0),document.addEventListener("touchend",i,!0),document.addEventListener("click",i,!0),document.addEventListener("keydown",i,!0),e}},_obtainHtml5Audio:function(){var e=this||t;if(e._html5AudioPool.length)return e._html5AudioPool.pop();var i=(new Audio).play();return i&&"undefined"!=typeof Promise&&(i instanceof Promise||"function"==typeof i.then)&&i.catch((function(){console.warn("HTML5 Audio pool exhausted, returning potentially locked audio object.")})),new Audio},_releaseHtml5Audio:function(e){var i=this||t;return e._unlocked&&i._html5AudioPool.push(e),i},_autoSuspend:function(){var e=this;if(e.autoSuspend&&e.ctx&&void 0!==e.ctx.suspend&&t.usingWebAudio){for(var i=0;i<e._howls.length;i++)if(e._howls[i]._webAudio)for(var n=0;n<e._howls[i]._sounds.length;n++)if(!e._howls[i]._sounds[n]._paused)return e;return e._suspendTimer&&clearTimeout(e._suspendTimer),e._suspendTimer=setTimeout((function(){if(e.autoSuspend){e._suspendTimer=null,e.state="suspending";var t=function(){e.state="suspended",e._resumeAfterSuspend&&(delete e._resumeAfterSuspend,e._autoResume())};e.ctx.suspend().then(t,t)}}),3e4),e}},_autoResume:function(){var e=this;if(e.ctx&&void 0!==e.ctx.resume&&t.usingWebAudio)return"running"===e.state&&"interrupted"!==e.ctx.state&&e._suspendTimer?(clearTimeout(e._suspendTimer),e._suspendTimer=null):"suspended"===e.state||"running"===e.state&&"interrupted"===e.ctx.state?(e.ctx.resume().then((function(){e.state="running";for(var t=0;t<e._howls.length;t++)e._howls[t]._emit("resume")})),e._suspendTimer&&(clearTimeout(e._suspendTimer),e._suspendTimer=null)):"suspending"===e.state&&(e._resumeAfterSuspend=!0),e}};var t=new e,i=function(e){e.src&&0!==e.src.length?this.init(e):console.error("An array of source files must be passed with any new Howl.")};i.prototype={init:function(e){var i=this;return t.ctx||h(),i._autoplay=e.autoplay||!1,i._format="string"!=typeof e.format?e.format:[e.format],i._html5=e.html5||!1,i._muted=e.mute||!1,i._loop=e.loop||!1,i._pool=e.pool||5,i._preload="boolean"!=typeof e.preload&&"metadata"!==e.preload||e.preload,i._rate=e.rate||1,i._sprite=e.sprite||{},i._src="string"!=typeof e.src?e.src:[e.src],i._volume=void 0!==e.volume?e.volume:1,i._xhr={method:e.xhr&&e.xhr.method?e.xhr.method:"GET",headers:e.xhr&&e.xhr.headers?e.xhr.headers:null,withCredentials:!(!e.xhr||!e.xhr.withCredentials)&&e.xhr.withCredentials},i._duration=0,i._state="unloaded",i._sounds=[],i._endTimers={},i._queue=[],i._playLock=!1,i._onend=e.onend?[{fn:e.onend}]:[],i._onfade=e.onfade?[{fn:e.onfade}]:[],i._onload=e.onload?[{fn:e.onload}]:[],i._onloaderror=e.onloaderror?[{fn:e.onloaderror}]:[],i._onplayerror=e.onplayerror?[{fn:e.onplayerror}]:[],i._onpause=e.onpause?[{fn:e.onpause}]:[],i._onplay=e.onplay?[{fn:e.onplay}]:[],i._onstop=e.onstop?[{fn:e.onstop}]:[],i._onmute=e.onmute?[{fn:e.onmute}]:[],i._onvolume=e.onvolume?[{fn:e.onvolume}]:[],i._onrate=e.onrate?[{fn:e.onrate}]:[],i._onseek=e.onseek?[{fn:e.onseek}]:[],i._onunlock=e.onunlock?[{fn:e.onunlock}]:[],i._onresume=[],i._webAudio=t.usingWebAudio&&!i._html5,void 0!==t.ctx&&t.ctx&&t.autoUnlock&&t._unlockAudio(),t._howls.push(i),i._autoplay&&i._queue.push({event:"play",action:function(){i.play()}}),i._preload&&"none"!==i._preload&&i.load(),i},load:function(){var e=this,i=null;if(t.noAudio)e._emit("loaderror",null,"No audio support.");else{"string"==typeof e._src&&(e._src=[e._src]);for(var r=0;r<e._src.length;r++){var s,o;if(e._format&&e._format[r])s=e._format[r];else{if("string"!=typeof(o=e._src[r])){e._emit("loaderror",null,"Non-string found in selected audio sources - ignoring.");continue}(s=/^data:audio\/([^;,]+);/i.exec(o))||(s=/\.([^.]+)$/.exec(o.split("?",1)[0])),s&&(s=s[1].toLowerCase())}if(s||console.warn('No file extension was found. Consider using the "format" property or specify an extension.'),s&&t.codecs(s)){i=e._src[r];break}}if(i)return e._src=i,e._state="loading","https:"===window.location.protocol&&"http:"===i.slice(0,5)&&(e._html5=!0,e._webAudio=!1),new n(e),e._webAudio&&a(e),e;e._emit("loaderror",null,"No codec support for selected audio sources.")}},play:function(e,i){var n=this,r=null;if("number"==typeof e)r=e,e=null;else{if("string"==typeof e&&"loaded"===n._state&&!n._sprite[e])return null;if(void 0===e&&(e="__default",!n._playLock)){for(var s=0,a=0;a<n._sounds.length;a++)n._sounds[a]._paused&&!n._sounds[a]._ended&&(s++,r=n._sounds[a]._id);1===s?e=null:r=null}}var o=r?n._soundById(r):n._inactiveSound();if(!o)return null;if(r&&!e&&(e=o._sprite||"__default"),"loaded"!==n._state){o._sprite=e,o._ended=!1;var c=o._id;return n._queue.push({event:"play",action:function(){n.play(c)}}),c}if(r&&!o._paused)return i||n._loadQueue("play"),o._id;n._webAudio&&t._autoResume();var l=Math.max(0,o._seek>0?o._seek:n._sprite[e][0]/1e3),h=Math.max(0,(n._sprite[e][0]+n._sprite[e][1])/1e3-l),d=1e3*h/Math.abs(o._rate),u=n._sprite[e][0]/1e3,f=(n._sprite[e][0]+n._sprite[e][1])/1e3;o._sprite=e,o._ended=!1;var p=function(){o._paused=!1,o._seek=l,o._start=u,o._stop=f,o._loop=!(!o._loop&&!n._sprite[e][2])};if(!(l>=f)){var m=o._node;if(n._webAudio){var g=function(){n._playLock=!1,p(),n._refreshBuffer(o);var e=o._muted||n._muted?0:o._volume;m.gain.setValueAtTime(e,t.ctx.currentTime),o._playStart=t.ctx.currentTime,void 0===m.bufferSource.start?o._loop?m.bufferSource.noteGrainOn(0,l,86400):m.bufferSource.noteGrainOn(0,l,h):o._loop?m.bufferSource.start(0,l,86400):m.bufferSource.start(0,l,h),d!==1/0&&(n._endTimers[o._id]=setTimeout(n._ended.bind(n,o),d)),i||setTimeout((function(){n._emit("play",o._id),n._loadQueue()}),0)};"running"===t.state&&"interrupted"!==t.ctx.state?g():(n._playLock=!0,n.once("resume",g),n._clearTimer(o._id))}else{var _=function(){m.currentTime=l,m.muted=o._muted||n._muted||t._muted||m.muted,m.volume=o._volume*t.volume(),m.playbackRate=o._rate;try{var r=m.play();if(r&&"undefined"!=typeof Promise&&(r instanceof Promise||"function"==typeof r.then)?(n._playLock=!0,p(),r.then((function(){n._playLock=!1,m._unlocked=!0,i?n._loadQueue():n._emit("play",o._id)})).catch((function(){n._playLock=!1,n._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction."),o._ended=!0,o._paused=!0}))):i||(n._playLock=!1,p(),n._emit("play",o._id)),m.playbackRate=o._rate,m.paused)return void n._emit("playerror",o._id,"Playback was unable to start. This is most commonly an issue on mobile devices and Chrome where playback was not within a user interaction.");"__default"!==e||o._loop?n._endTimers[o._id]=setTimeout(n._ended.bind(n,o),d):(n._endTimers[o._id]=function(){n._ended(o),m.removeEventListener("ended",n._endTimers[o._id],!1)},m.addEventListener("ended",n._endTimers[o._id],!1))}catch(e){n._emit("playerror",o._id,e)}};"data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"===m.src&&(m.src=n._src,m.load());var y=window&&window.ejecta||!m.readyState&&t._navigator.isCocoonJS;if(m.readyState>=3||y)_();else{n._playLock=!0,n._state="loading";var T=function(){n._state="loaded",_(),m.removeEventListener(t._canPlayEvent,T,!1)};m.addEventListener(t._canPlayEvent,T,!1),n._clearTimer(o._id)}}return o._id}n._ended(o)},pause:function(e){var t=this;if("loaded"!==t._state||t._playLock)return t._queue.push({event:"pause",action:function(){t.pause(e)}}),t;for(var i=t._getSoundIds(e),n=0;n<i.length;n++){t._clearTimer(i[n]);var r=t._soundById(i[n]);if(r&&!r._paused&&(r._seek=t.seek(i[n]),r._rateSeek=0,r._paused=!0,t._stopFade(i[n]),r._node))if(t._webAudio){if(!r._node.bufferSource)continue;void 0===r._node.bufferSource.stop?r._node.bufferSource.noteOff(0):r._node.bufferSource.stop(0),t._cleanBuffer(r._node)}else isNaN(r._node.duration)&&r._node.duration!==1/0||r._node.pause();arguments[1]||t._emit("pause",r?r._id:null)}return t},stop:function(e,t){var i=this;if("loaded"!==i._state||i._playLock)return i._queue.push({event:"stop",action:function(){i.stop(e)}}),i;for(var n=i._getSoundIds(e),r=0;r<n.length;r++){i._clearTimer(n[r]);var s=i._soundById(n[r]);s&&(s._seek=s._start||0,s._rateSeek=0,s._paused=!0,s._ended=!0,i._stopFade(n[r]),s._node&&(i._webAudio?s._node.bufferSource&&(void 0===s._node.bufferSource.stop?s._node.bufferSource.noteOff(0):s._node.bufferSource.stop(0),i._cleanBuffer(s._node)):isNaN(s._node.duration)&&s._node.duration!==1/0||(s._node.currentTime=s._start||0,s._node.pause(),s._node.duration===1/0&&i._clearSound(s._node))),t||i._emit("stop",s._id))}return i},mute:function(e,i){var n=this;if("loaded"!==n._state||n._playLock)return n._queue.push({event:"mute",action:function(){n.mute(e,i)}}),n;if(void 0===i){if("boolean"!=typeof e)return n._muted;n._muted=e}for(var r=n._getSoundIds(i),s=0;s<r.length;s++){var a=n._soundById(r[s]);a&&(a._muted=e,a._interval&&n._stopFade(a._id),n._webAudio&&a._node?a._node.gain.setValueAtTime(e?0:a._volume,t.ctx.currentTime):a._node&&(a._node.muted=!!t._muted||e),n._emit("mute",a._id))}return n},volume:function(){var e,i,n,r=this,s=arguments;if(0===s.length)return r._volume;if(1===s.length||2===s.length&&void 0===s[1]?r._getSoundIds().indexOf(s[0])>=0?i=parseInt(s[0],10):e=parseFloat(s[0]):s.length>=2&&(e=parseFloat(s[0]),i=parseInt(s[1],10)),!(void 0!==e&&e>=0&&e<=1))return(n=i?r._soundById(i):r._sounds[0])?n._volume:0;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"volume",action:function(){r.volume.apply(r,s)}}),r;void 0===i&&(r._volume=e),i=r._getSoundIds(i);for(var a=0;a<i.length;a++)(n=r._soundById(i[a]))&&(n._volume=e,s[2]||r._stopFade(i[a]),r._webAudio&&n._node&&!n._muted?n._node.gain.setValueAtTime(e,t.ctx.currentTime):n._node&&!n._muted&&(n._node.volume=e*t.volume()),r._emit("volume",n._id));return r},fade:function(e,i,n,r){var s=this;if("loaded"!==s._state||s._playLock)return s._queue.push({event:"fade",action:function(){s.fade(e,i,n,r)}}),s;e=Math.min(Math.max(0,parseFloat(e)),1),i=Math.min(Math.max(0,parseFloat(i)),1),n=parseFloat(n),s.volume(e,r);for(var a=s._getSoundIds(r),o=0;o<a.length;o++){var c=s._soundById(a[o]);if(c){if(r||s._stopFade(a[o]),s._webAudio&&!c._muted){var l=t.ctx.currentTime,h=l+n/1e3;c._volume=e,c._node.gain.setValueAtTime(e,l),c._node.gain.linearRampToValueAtTime(i,h)}s._startFadeInterval(c,e,i,n,a[o],void 0===r)}}return s},_startFadeInterval:function(e,t,i,n,r,s){var a=this,o=t,c=i-t,l=Math.abs(c/.01),h=Math.max(4,l>0?n/l:n),d=Date.now();e._fadeTo=i,e._interval=setInterval((function(){var r=(Date.now()-d)/n;d=Date.now(),o+=c*r,o=Math.round(100*o)/100,o=c<0?Math.max(i,o):Math.min(i,o),a._webAudio?e._volume=o:a.volume(o,e._id,!0),s&&(a._volume=o),(i<t&&o<=i||i>t&&o>=i)&&(clearInterval(e._interval),e._interval=null,e._fadeTo=null,a.volume(i,e._id),a._emit("fade",e._id))}),h)},_stopFade:function(e){var i=this,n=i._soundById(e);return n&&n._interval&&(i._webAudio&&n._node.gain.cancelScheduledValues(t.ctx.currentTime),clearInterval(n._interval),n._interval=null,i.volume(n._fadeTo,e),n._fadeTo=null,i._emit("fade",e)),i},loop:function(){var e,t,i,n=this,r=arguments;if(0===r.length)return n._loop;if(1===r.length){if("boolean"!=typeof r[0])return!!(i=n._soundById(parseInt(r[0],10)))&&i._loop;e=r[0],n._loop=e}else 2===r.length&&(e=r[0],t=parseInt(r[1],10));for(var s=n._getSoundIds(t),a=0;a<s.length;a++)(i=n._soundById(s[a]))&&(i._loop=e,n._webAudio&&i._node&&i._node.bufferSource&&(i._node.bufferSource.loop=e,e&&(i._node.bufferSource.loopStart=i._start||0,i._node.bufferSource.loopEnd=i._stop,n.playing(s[a])&&(n.pause(s[a],!0),n.play(s[a],!0)))));return n},rate:function(){var e,i,n,r=this,s=arguments;if(0===s.length?i=r._sounds[0]._id:1===s.length?r._getSoundIds().indexOf(s[0])>=0?i=parseInt(s[0],10):e=parseFloat(s[0]):2===s.length&&(e=parseFloat(s[0]),i=parseInt(s[1],10)),"number"!=typeof e)return(n=r._soundById(i))?n._rate:r._rate;if("loaded"!==r._state||r._playLock)return r._queue.push({event:"rate",action:function(){r.rate.apply(r,s)}}),r;void 0===i&&(r._rate=e),i=r._getSoundIds(i);for(var a=0;a<i.length;a++)if(n=r._soundById(i[a])){r.playing(i[a])&&(n._rateSeek=r.seek(i[a]),n._playStart=r._webAudio?t.ctx.currentTime:n._playStart),n._rate=e,r._webAudio&&n._node&&n._node.bufferSource?n._node.bufferSource.playbackRate.setValueAtTime(e,t.ctx.currentTime):n._node&&(n._node.playbackRate=e);var o=r.seek(i[a]),c=1e3*((r._sprite[n._sprite][0]+r._sprite[n._sprite][1])/1e3-o)/Math.abs(n._rate);!r._endTimers[i[a]]&&n._paused||(r._clearTimer(i[a]),r._endTimers[i[a]]=setTimeout(r._ended.bind(r,n),c)),r._emit("rate",n._id)}return r},seek:function(){var e,i,n=this,r=arguments;if(0===r.length?n._sounds.length&&(i=n._sounds[0]._id):1===r.length?n._getSoundIds().indexOf(r[0])>=0?i=parseInt(r[0],10):n._sounds.length&&(i=n._sounds[0]._id,e=parseFloat(r[0])):2===r.length&&(e=parseFloat(r[0]),i=parseInt(r[1],10)),void 0===i)return 0;if("number"==typeof e&&("loaded"!==n._state||n._playLock))return n._queue.push({event:"seek",action:function(){n.seek.apply(n,r)}}),n;var s=n._soundById(i);if(s){if(!("number"==typeof e&&e>=0)){if(n._webAudio){var a=n.playing(i)?t.ctx.currentTime-s._playStart:0,o=s._rateSeek?s._rateSeek-s._seek:0;return s._seek+(o+a*Math.abs(s._rate))}return s._node.currentTime}var c=n.playing(i);c&&n.pause(i,!0),s._seek=e,s._ended=!1,n._clearTimer(i),n._webAudio||!s._node||isNaN(s._node.duration)||(s._node.currentTime=e);var l=function(){c&&n.play(i,!0),n._emit("seek",i)};if(c&&!n._webAudio){var h=function(){n._playLock?setTimeout(h,0):l()};setTimeout(h,0)}else l()}return n},playing:function(e){var t=this;if("number"==typeof e){var i=t._soundById(e);return!!i&&!i._paused}for(var n=0;n<t._sounds.length;n++)if(!t._sounds[n]._paused)return!0;return!1},duration:function(e){var t=this,i=t._duration,n=t._soundById(e);return n&&(i=t._sprite[n._sprite][1]/1e3),i},state:function(){return this._state},unload:function(){for(var e=this,i=e._sounds,n=0;n<i.length;n++)i[n]._paused||e.stop(i[n]._id),e._webAudio||(e._clearSound(i[n]._node),i[n]._node.removeEventListener("error",i[n]._errorFn,!1),i[n]._node.removeEventListener(t._canPlayEvent,i[n]._loadFn,!1),i[n]._node.removeEventListener("ended",i[n]._endFn,!1),t._releaseHtml5Audio(i[n]._node)),delete i[n]._node,e._clearTimer(i[n]._id);var r=t._howls.indexOf(e);r>=0&&t._howls.splice(r,1);var a=!0;for(n=0;n<t._howls.length;n++)if(t._howls[n]._src===e._src||e._src.indexOf(t._howls[n]._src)>=0){a=!1;break}return s&&a&&delete s[e._src],t.noAudio=!1,e._state="unloaded",e._sounds=[],e=null,null},on:function(e,t,i,n){var r=this["_on"+e];return"function"==typeof t&&r.push(n?{id:i,fn:t,once:n}:{id:i,fn:t}),this},off:function(e,t,i){var n=this,r=n["_on"+e],s=0;if("number"==typeof t&&(i=t,t=null),t||i)for(s=0;s<r.length;s++){var a=i===r[s].id;if(t===r[s].fn&&a||!t&&a){r.splice(s,1);break}}else if(e)n["_on"+e]=[];else{var o=Object.keys(n);for(s=0;s<o.length;s++)0===o[s].indexOf("_on")&&Array.isArray(n[o[s]])&&(n[o[s]]=[])}return n},once:function(e,t,i){return this.on(e,t,i,1),this},_emit:function(e,t,i){for(var n=this,r=n["_on"+e],s=r.length-1;s>=0;s--)r[s].id&&r[s].id!==t&&"load"!==e||(setTimeout(function(e){e.call(this,t,i)}.bind(n,r[s].fn),0),r[s].once&&n.off(e,r[s].fn,r[s].id));return n._loadQueue(e),n},_loadQueue:function(e){var t=this;if(t._queue.length>0){var i=t._queue[0];i.event===e&&(t._queue.shift(),t._loadQueue()),e||i.action()}return t},_ended:function(e){var i=this,n=e._sprite;if(!i._webAudio&&e._node&&!e._node.paused&&!e._node.ended&&e._node.currentTime<e._stop)return setTimeout(i._ended.bind(i,e),100),i;var r=!(!e._loop&&!i._sprite[n][2]);if(i._emit("end",e._id),!i._webAudio&&r&&i.stop(e._id,!0).play(e._id),i._webAudio&&r){i._emit("play",e._id),e._seek=e._start||0,e._rateSeek=0,e._playStart=t.ctx.currentTime;var s=1e3*(e._stop-e._start)/Math.abs(e._rate);i._endTimers[e._id]=setTimeout(i._ended.bind(i,e),s)}return i._webAudio&&!r&&(e._paused=!0,e._ended=!0,e._seek=e._start||0,e._rateSeek=0,i._clearTimer(e._id),i._cleanBuffer(e._node),t._autoSuspend()),i._webAudio||r||i.stop(e._id,!0),i},_clearTimer:function(e){var t=this;if(t._endTimers[e]){if("function"!=typeof t._endTimers[e])clearTimeout(t._endTimers[e]);else{var i=t._soundById(e);i&&i._node&&i._node.removeEventListener("ended",t._endTimers[e],!1)}delete t._endTimers[e]}return t},_soundById:function(e){for(var t=this,i=0;i<t._sounds.length;i++)if(e===t._sounds[i]._id)return t._sounds[i];return null},_inactiveSound:function(){var e=this;e._drain();for(var t=0;t<e._sounds.length;t++)if(e._sounds[t]._ended)return e._sounds[t].reset();return new n(e)},_drain:function(){var e=this,t=e._pool,i=0,n=0;if(!(e._sounds.length<t)){for(n=0;n<e._sounds.length;n++)e._sounds[n]._ended&&i++;for(n=e._sounds.length-1;n>=0;n--){if(i<=t)return;e._sounds[n]._ended&&(e._webAudio&&e._sounds[n]._node&&e._sounds[n]._node.disconnect(0),e._sounds.splice(n,1),i--)}}},_getSoundIds:function(e){if(void 0===e){for(var t=[],i=0;i<this._sounds.length;i++)t.push(this._sounds[i]._id);return t}return[e]},_refreshBuffer:function(e){return e._node.bufferSource=t.ctx.createBufferSource(),e._node.bufferSource.buffer=s[this._src],e._panner?e._node.bufferSource.connect(e._panner):e._node.bufferSource.connect(e._node),e._node.bufferSource.loop=e._loop,e._loop&&(e._node.bufferSource.loopStart=e._start||0,e._node.bufferSource.loopEnd=e._stop||0),e._node.bufferSource.playbackRate.setValueAtTime(e._rate,t.ctx.currentTime),this},_cleanBuffer:function(e){var i=t._navigator&&t._navigator.vendor.indexOf("Apple")>=0;if(!e.bufferSource)return this;if(t._scratchBuffer&&e.bufferSource&&(e.bufferSource.onended=null,e.bufferSource.disconnect(0),i))try{e.bufferSource.buffer=t._scratchBuffer}catch(e){}return e.bufferSource=null,this},_clearSound:function(e){/MSIE |Trident\//.test(t._navigator&&t._navigator.userAgent)||(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA")}};var n=function(e){this._parent=e,this.init()};n.prototype={init:function(){var e=this,i=e._parent;return e._muted=i._muted,e._loop=i._loop,e._volume=i._volume,e._rate=i._rate,e._seek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,i._sounds.push(e),e.create(),e},create:function(){var e=this,i=e._parent,n=t._muted||e._muted||e._parent._muted?0:e._volume;return i._webAudio?(e._node=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),e._node.gain.setValueAtTime(n,t.ctx.currentTime),e._node.paused=!0,e._node.connect(t.masterGain)):t.noAudio||(e._node=t._obtainHtml5Audio(),e._errorFn=e._errorListener.bind(e),e._node.addEventListener("error",e._errorFn,!1),e._loadFn=e._loadListener.bind(e),e._node.addEventListener(t._canPlayEvent,e._loadFn,!1),e._endFn=e._endListener.bind(e),e._node.addEventListener("ended",e._endFn,!1),e._node.src=i._src,e._node.preload=!0===i._preload?"auto":i._preload,e._node.volume=n*t.volume(),e._node.load()),e},reset:function(){var e=this,i=e._parent;return e._muted=i._muted,e._loop=i._loop,e._volume=i._volume,e._rate=i._rate,e._seek=0,e._rateSeek=0,e._paused=!0,e._ended=!0,e._sprite="__default",e._id=++t._counter,e},_errorListener:function(){var e=this;e._parent._emit("loaderror",e._id,e._node.error?e._node.error.code:0),e._node.removeEventListener("error",e._errorFn,!1)},_loadListener:function(){var e=this,i=e._parent;i._duration=Math.ceil(10*e._node.duration)/10,0===Object.keys(i._sprite).length&&(i._sprite={__default:[0,1e3*i._duration]}),"loaded"!==i._state&&(i._state="loaded",i._emit("load"),i._loadQueue()),e._node.removeEventListener(t._canPlayEvent,e._loadFn,!1)},_endListener:function(){var e=this,t=e._parent;t._duration===1/0&&(t._duration=Math.ceil(10*e._node.duration)/10,t._sprite.__default[1]===1/0&&(t._sprite.__default[1]=1e3*t._duration),t._ended(e)),e._node.removeEventListener("ended",e._endFn,!1)}};var s={},a=function(e){var t=e._src;if(s[t])return e._duration=s[t].duration,void l(e);if(/^data:[^;]+;base64,/.test(t)){for(var i=atob(t.split(",")[1]),n=new Uint8Array(i.length),r=0;r<i.length;++r)n[r]=i.charCodeAt(r);c(n.buffer,e)}else{var a=new XMLHttpRequest;a.open(e._xhr.method,t,!0),a.withCredentials=e._xhr.withCredentials,a.responseType="arraybuffer",e._xhr.headers&&Object.keys(e._xhr.headers).forEach((function(t){a.setRequestHeader(t,e._xhr.headers[t])})),a.onload=function(){var t=(a.status+"")[0];"0"===t||"2"===t||"3"===t?c(a.response,e):e._emit("loaderror",null,"Failed loading audio file with status: "+a.status+".")},a.onerror=function(){e._webAudio&&(e._html5=!0,e._webAudio=!1,e._sounds=[],delete s[t],e.load())},o(a)}},o=function(e){try{e.send()}catch(t){e.onerror()}},c=function(e,i){var n=function(){i._emit("loaderror",null,"Decoding audio data failed.")},r=function(e){e&&i._sounds.length>0?(s[i._src]=e,l(i,e)):n()};"undefined"!=typeof Promise&&1===t.ctx.decodeAudioData.length?t.ctx.decodeAudioData(e).then(r).catch(n):t.ctx.decodeAudioData(e,r,n)},l=function(e,t){t&&!e._duration&&(e._duration=t.duration),0===Object.keys(e._sprite).length&&(e._sprite={__default:[0,1e3*e._duration]}),"loaded"!==e._state&&(e._state="loaded",e._emit("load"),e._loadQueue())},h=function(){if(t.usingWebAudio){try{"undefined"!=typeof AudioContext?t.ctx=new AudioContext:"undefined"!=typeof webkitAudioContext?t.ctx=new webkitAudioContext:t.usingWebAudio=!1}catch(e){t.usingWebAudio=!1}t.ctx||(t.usingWebAudio=!1);var e=/iP(hone|od|ad)/.test(t._navigator&&t._navigator.platform),i=t._navigator&&t._navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/),n=i?parseInt(i[1],10):null;if(e&&n&&n<9){var r=/safari/.test(t._navigator&&t._navigator.userAgent.toLowerCase());t._navigator&&!r&&(t.usingWebAudio=!1)}t.usingWebAudio&&(t.masterGain=void 0===t.ctx.createGain?t.ctx.createGainNode():t.ctx.createGain(),t.masterGain.gain.setValueAtTime(t._muted?0:t._volume,t.ctx.currentTime),t.masterGain.connect(t.ctx.destination)),t._setup()}};dc.Howler=t,dc.Howl=i,void 0!==r?(r.HowlerGlobal=e,r.Howler=t,r.Howl=i,r.Sound=n):"undefined"!=typeof window&&(window.HowlerGlobal=e,window.Howler=t,window.Howl=i,window.Sound=n)}(),function(){var e;HowlerGlobal.prototype._pos=[0,0,0],HowlerGlobal.prototype._orientation=[0,0,-1,0,1,0],HowlerGlobal.prototype.stereo=function(e){var t=this;if(!t.ctx||!t.ctx.listener)return t;for(var i=t._howls.length-1;i>=0;i--)t._howls[i].stereo(e);return t},HowlerGlobal.prototype.pos=function(e,t,i){var n=this;return n.ctx&&n.ctx.listener?(t="number"!=typeof t?n._pos[1]:t,i="number"!=typeof i?n._pos[2]:i,"number"!=typeof e?n._pos:(n._pos=[e,t,i],void 0!==n.ctx.listener.positionX?(n.ctx.listener.positionX.setTargetAtTime(n._pos[0],Howler.ctx.currentTime,.1),n.ctx.listener.positionY.setTargetAtTime(n._pos[1],Howler.ctx.currentTime,.1),n.ctx.listener.positionZ.setTargetAtTime(n._pos[2],Howler.ctx.currentTime,.1)):n.ctx.listener.setPosition(n._pos[0],n._pos[1],n._pos[2]),n)):n},HowlerGlobal.prototype.orientation=function(e,t,i,n,r,s){var a=this;if(!a.ctx||!a.ctx.listener)return a;var o=a._orientation;return t="number"!=typeof t?o[1]:t,i="number"!=typeof i?o[2]:i,n="number"!=typeof n?o[3]:n,r="number"!=typeof r?o[4]:r,s="number"!=typeof s?o[5]:s,"number"!=typeof e?o:(a._orientation=[e,t,i,n,r,s],void 0!==a.ctx.listener.forwardX?(a.ctx.listener.forwardX.setTargetAtTime(e,Howler.ctx.currentTime,.1),a.ctx.listener.forwardY.setTargetAtTime(t,Howler.ctx.currentTime,.1),a.ctx.listener.forwardZ.setTargetAtTime(i,Howler.ctx.currentTime,.1),a.ctx.listener.upX.setTargetAtTime(n,Howler.ctx.currentTime,.1),a.ctx.listener.upY.setTargetAtTime(r,Howler.ctx.currentTime,.1),a.ctx.listener.upZ.setTargetAtTime(s,Howler.ctx.currentTime,.1)):a.ctx.listener.setOrientation(e,t,i,n,r,s),a)},Howl.prototype.init=(e=Howl.prototype.init,function(t){var i=this;return i._orientation=t.orientation||[1,0,0],i._stereo=t.stereo||null,i._pos=t.pos||null,i._pannerAttr={coneInnerAngle:void 0!==t.coneInnerAngle?t.coneInnerAngle:360,coneOuterAngle:void 0!==t.coneOuterAngle?t.coneOuterAngle:360,coneOuterGain:void 0!==t.coneOuterGain?t.coneOuterGain:0,distanceModel:void 0!==t.distanceModel?t.distanceModel:"inverse",maxDistance:void 0!==t.maxDistance?t.maxDistance:1e4,panningModel:void 0!==t.panningModel?t.panningModel:"HRTF",refDistance:void 0!==t.refDistance?t.refDistance:1,rolloffFactor:void 0!==t.rolloffFactor?t.rolloffFactor:1},i._onstereo=t.onstereo?[{fn:t.onstereo}]:[],i._onpos=t.onpos?[{fn:t.onpos}]:[],i._onorientation=t.onorientation?[{fn:t.onorientation}]:[],e.call(this,t)}),Howl.prototype.stereo=function(e,i){var n=this;if(!n._webAudio)return n;if("loaded"!==n._state)return n._queue.push({event:"stereo",action:function(){n.stereo(e,i)}}),n;var r=void 0===Howler.ctx.createStereoPanner?"spatial":"stereo";if(void 0===i){if("number"!=typeof e)return n._stereo;n._stereo=e,n._pos=[e,0,0]}for(var s=n._getSoundIds(i),a=0;a<s.length;a++){var o=n._soundById(s[a]);if(o){if("number"!=typeof e)return o._stereo;o._stereo=e,o._pos=[e,0,0],o._node&&(o._pannerAttr.panningModel="equalpower",o._panner&&o._panner.pan||t(o,r),"spatial"===r?void 0!==o._panner.positionX?(o._panner.positionX.setValueAtTime(e,Howler.ctx.currentTime),o._panner.positionY.setValueAtTime(0,Howler.ctx.currentTime),o._panner.positionZ.setValueAtTime(0,Howler.ctx.currentTime)):o._panner.setPosition(e,0,0):o._panner.pan.setValueAtTime(e,Howler.ctx.currentTime)),n._emit("stereo",o._id)}}return n},Howl.prototype.pos=function(e,i,n,r){var s=this;if(!s._webAudio)return s;if("loaded"!==s._state)return s._queue.push({event:"pos",action:function(){s.pos(e,i,n,r)}}),s;if(i="number"!=typeof i?0:i,n="number"!=typeof n?-.5:n,void 0===r){if("number"!=typeof e)return s._pos;s._pos=[e,i,n]}for(var a=s._getSoundIds(r),o=0;o<a.length;o++){var c=s._soundById(a[o]);if(c){if("number"!=typeof e)return c._pos;c._pos=[e,i,n],c._node&&(c._panner&&!c._panner.pan||t(c,"spatial"),void 0!==c._panner.positionX?(c._panner.positionX.setValueAtTime(e,Howler.ctx.currentTime),c._panner.positionY.setValueAtTime(i,Howler.ctx.currentTime),c._panner.positionZ.setValueAtTime(n,Howler.ctx.currentTime)):c._panner.setPosition(e,i,n)),s._emit("pos",c._id)}}return s},Howl.prototype.orientation=function(e,i,n,r){var s=this;if(!s._webAudio)return s;if("loaded"!==s._state)return s._queue.push({event:"orientation",action:function(){s.orientation(e,i,n,r)}}),s;if(i="number"!=typeof i?s._orientation[1]:i,n="number"!=typeof n?s._orientation[2]:n,void 0===r){if("number"!=typeof e)return s._orientation;s._orientation=[e,i,n]}for(var a=s._getSoundIds(r),o=0;o<a.length;o++){var c=s._soundById(a[o]);if(c){if("number"!=typeof e)return c._orientation;c._orientation=[e,i,n],c._node&&(c._panner||(c._pos||(c._pos=s._pos||[0,0,-.5]),t(c,"spatial")),void 0!==c._panner.orientationX?(c._panner.orientationX.setValueAtTime(e,Howler.ctx.currentTime),c._panner.orientationY.setValueAtTime(i,Howler.ctx.currentTime),c._panner.orientationZ.setValueAtTime(n,Howler.ctx.currentTime)):c._panner.setOrientation(e,i,n)),s._emit("orientation",c._id)}}return s},Howl.prototype.pannerAttr=function(){var e,i,n,r=this,s=arguments;if(!r._webAudio)return r;if(0===s.length)return r._pannerAttr;if(1===s.length){if("object"!=typeof s[0])return(n=r._soundById(parseInt(s[0],10)))?n._pannerAttr:r._pannerAttr;e=s[0],void 0===i&&(e.pannerAttr||(e.pannerAttr={coneInnerAngle:e.coneInnerAngle,coneOuterAngle:e.coneOuterAngle,coneOuterGain:e.coneOuterGain,distanceModel:e.distanceModel,maxDistance:e.maxDistance,refDistance:e.refDistance,rolloffFactor:e.rolloffFactor,panningModel:e.panningModel}),r._pannerAttr={coneInnerAngle:void 0!==e.pannerAttr.coneInnerAngle?e.pannerAttr.coneInnerAngle:r._coneInnerAngle,coneOuterAngle:void 0!==e.pannerAttr.coneOuterAngle?e.pannerAttr.coneOuterAngle:r._coneOuterAngle,coneOuterGain:void 0!==e.pannerAttr.coneOuterGain?e.pannerAttr.coneOuterGain:r._coneOuterGain,distanceModel:void 0!==e.pannerAttr.distanceModel?e.pannerAttr.distanceModel:r._distanceModel,maxDistance:void 0!==e.pannerAttr.maxDistance?e.pannerAttr.maxDistance:r._maxDistance,refDistance:void 0!==e.pannerAttr.refDistance?e.pannerAttr.refDistance:r._refDistance,rolloffFactor:void 0!==e.pannerAttr.rolloffFactor?e.pannerAttr.rolloffFactor:r._rolloffFactor,panningModel:void 0!==e.pannerAttr.panningModel?e.pannerAttr.panningModel:r._panningModel})}else 2===s.length&&(e=s[0],i=parseInt(s[1],10));for(var a=r._getSoundIds(i),o=0;o<a.length;o++)if(n=r._soundById(a[o])){var c=n._pannerAttr;c={coneInnerAngle:void 0!==e.coneInnerAngle?e.coneInnerAngle:c.coneInnerAngle,coneOuterAngle:void 0!==e.coneOuterAngle?e.coneOuterAngle:c.coneOuterAngle,coneOuterGain:void 0!==e.coneOuterGain?e.coneOuterGain:c.coneOuterGain,distanceModel:void 0!==e.distanceModel?e.distanceModel:c.distanceModel,maxDistance:void 0!==e.maxDistance?e.maxDistance:c.maxDistance,refDistance:void 0!==e.refDistance?e.refDistance:c.refDistance,rolloffFactor:void 0!==e.rolloffFactor?e.rolloffFactor:c.rolloffFactor,panningModel:void 0!==e.panningModel?e.panningModel:c.panningModel};var l=n._panner;l||(n._pos||(n._pos=r._pos||[0,0,-.5]),t(n,"spatial"),l=n._panner),l.coneInnerAngle=c.coneInnerAngle,l.coneOuterAngle=c.coneOuterAngle,l.coneOuterGain=c.coneOuterGain,l.distanceModel=c.distanceModel,l.maxDistance=c.maxDistance,l.refDistance=c.refDistance,l.rolloffFactor=c.rolloffFactor,l.panningModel=c.panningModel}return r},Sound.prototype.init=function(e){return function(){var t=this,i=t._parent;t._orientation=i._orientation,t._stereo=i._stereo,t._pos=i._pos,t._pannerAttr=i._pannerAttr,e.call(this),t._stereo?i.stereo(t._stereo):t._pos&&i.pos(t._pos[0],t._pos[1],t._pos[2],t._id)}}(Sound.prototype.init),Sound.prototype.reset=function(e){return function(){var t=this,i=t._parent;return t._orientation=i._orientation,t._stereo=i._stereo,t._pos=i._pos,t._pannerAttr=i._pannerAttr,t._stereo?i.stereo(t._stereo):t._pos?i.pos(t._pos[0],t._pos[1],t._pos[2],t._id):t._panner&&(t._panner.disconnect(0),t._panner=void 0,i._refreshBuffer(t)),e.call(this)}}(Sound.prototype.reset);var t=function(e,t){"spatial"===(t=t||"spatial")?(e._panner=Howler.ctx.createPanner(),e._panner.coneInnerAngle=e._pannerAttr.coneInnerAngle,e._panner.coneOuterAngle=e._pannerAttr.coneOuterAngle,e._panner.coneOuterGain=e._pannerAttr.coneOuterGain,e._panner.distanceModel=e._pannerAttr.distanceModel,e._panner.maxDistance=e._pannerAttr.maxDistance,e._panner.refDistance=e._pannerAttr.refDistance,e._panner.rolloffFactor=e._pannerAttr.rolloffFactor,e._panner.panningModel=e._pannerAttr.panningModel,void 0!==e._panner.positionX?(e._panner.positionX.setValueAtTime(e._pos[0],Howler.ctx.currentTime),e._panner.positionY.setValueAtTime(e._pos[1],Howler.ctx.currentTime),e._panner.positionZ.setValueAtTime(e._pos[2],Howler.ctx.currentTime)):e._panner.setPosition(e._pos[0],e._pos[1],e._pos[2]),void 0!==e._panner.orientationX?(e._panner.orientationX.setValueAtTime(e._orientation[0],Howler.ctx.currentTime),e._panner.orientationY.setValueAtTime(e._orientation[1],Howler.ctx.currentTime),e._panner.orientationZ.setValueAtTime(e._orientation[2],Howler.ctx.currentTime)):e._panner.setOrientation(e._orientation[0],e._orientation[1],e._orientation[2])):(e._panner=Howler.ctx.createStereoPanner(),e._panner.pan.setValueAtTime(e._stereo,Howler.ctx.currentTime)),e._panner.connect(e._node),e._paused||e._parent.pause(e._id,!0).play(e._id,!0)}}();class fc extends t{url="";audio=null;static VOLUMN=1;static MUTED=!1;constructor(e){super(),e&&(this.url=e,this.setUrl(e))}async setUrl(e){return this.isPlaying()&&this.pause(),this.url=e,new Promise((t=>{const i=new uc.Howl({src:e,loop:!1,preload:!0,volume:fc.VOLUMN,format:["wav"],mute:fc.MUTED,onload:()=>{t(!0),this.emit("onload");const e=Howler.ctx;if(fc.VOLUMN>1){const t=e.createGain();i._sounds[0]._node.connect(t),t.connect(e.destination),i.gainNode=t,i.gainNode.gain.value=fc.VOLUMN}},onplay:()=>{this.emit("onplay")},onstop:()=>{this.emit("onstop")},onend:()=>{this.emit("onend")},onplayerror:(e,i)=>{t(!1),this.emit("onplayerror")}});this.audio=i}))}getUrl(){return this.url}async play(){return this.audio?.play(),Promise.resolve(!0)}async restart(){return this.reset(),this.play()}pause(){this.audio?.pause()}seek(e){this.audio?.seek(e)}load(){this.audio?.load()}reset(){this.audio?.seek(0)}isLoaded(){return"loaded"===this.audio?.state()}isPlaying(){return!!this.audio?.playing()}getDuration(){return this.audio.duration()}setVolume(e){fc.VOLUMN=e,this.audio?.volume(e)}getVolume(){return this.audio.volume()}destroy(){this.url="",this.audio?.pause()}mute(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.audio&&this.audio.mute(e)}}const pc=fc;var mc=new fc;var gc=function(){this.__data__=[],this.size=0};var _c=function(e,t){return e===t||e!=e&&t!=t},yc=_c;var Tc=function(e,t){for(var i=e.length;i--;)if(yc(e[i][0],t))return i;return-1},wc=Tc,bc=Array.prototype.splice;var Sc=Tc;var vc=Tc;var Ac=Tc;var Ec=gc,Rc=function(e){var t=this.__data__,i=wc(t,e);return!(i<0)&&(i==t.length-1?t.pop():bc.call(t,i,1),--this.size,!0)},kc=function(e){var t=this.__data__,i=Sc(t,e);return i<0?void 0:t[i][1]},xc=function(e){return vc(this.__data__,e)>-1},Cc=function(e,t){var i=this.__data__,n=Ac(i,e);return n<0?(++this.size,i.push([e,t])):i[n][1]=t,this};function Ic(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}Ic.prototype.clear=Ec,Ic.prototype.delete=Rc,Ic.prototype.get=kc,Ic.prototype.has=xc,Ic.prototype.set=Cc;var Pc=Ic,Dc=Pc;var Oc=function(){this.__data__=new Dc,this.size=0};var Lc=function(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i};var Mc=function(e){return this.__data__.get(e)};var Bc=function(e){return this.__data__.has(e)},Nc="object"==typeof r&&r&&r.Object===Object&&r,Fc=Nc,Wc="object"==typeof self&&self&&self.Object===Object&&self,Uc=Fc||Wc||Function("return this")(),Gc=Uc.Symbol,Hc=Gc,zc=Object.prototype,jc=zc.hasOwnProperty,Vc=zc.toString,qc=Hc?Hc.toStringTag:void 0;var Yc=function(e){var t=jc.call(e,qc),i=e[qc];try{e[qc]=void 0;var n=!0}catch(e){}var r=Vc.call(e);return n&&(t?e[qc]=i:delete e[qc]),r},Kc=Object.prototype.toString;var Xc=Yc,$c=function(e){return Kc.call(e)},Zc=Gc?Gc.toStringTag:void 0;var Jc=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Zc&&Zc in Object(e)?Xc(e):$c(e)};var Qc=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},el=Jc,tl=Qc;var il,nl=function(e){if(!tl(e))return!1;var t=el(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},rl=Uc["__core-js_shared__"],sl=(il=/[^.]+$/.exec(rl&&rl.keys&&rl.keys.IE_PROTO||""))?"Symbol(src)_1."+il:"";var al=function(e){return!!sl&&sl in e},ol=Function.prototype.toString;var cl=nl,ll=al,hl=Qc,dl=function(e){if(null!=e){try{return ol.call(e)}catch(e){}try{return e+""}catch(e){}}return""},ul=/^\[object .+?Constructor\]$/,fl=Function.prototype,pl=Object.prototype,ml=fl.toString,gl=pl.hasOwnProperty,_l=RegExp("^"+ml.call(gl).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var yl=function(e){return!(!hl(e)||ll(e))&&(cl(e)?_l:ul).test(dl(e))},Tl=function(e,t){return null==e?void 0:e[t]};var wl=function(e,t){var i=Tl(e,t);return yl(i)?i:void 0},bl=wl(Uc,"Map"),Sl=wl(Object,"create"),vl=Sl;var Al=function(){this.__data__=vl?vl(null):{},this.size=0};var El=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Rl=Sl,kl=Object.prototype.hasOwnProperty;var xl=function(e){var t=this.__data__;if(Rl){var i=t[e];return"__lodash_hash_undefined__"===i?void 0:i}return kl.call(t,e)?t[e]:void 0},Cl=Sl,Il=Object.prototype.hasOwnProperty;var Pl=Sl;var Dl=Al,Ol=El,Ll=xl,Ml=function(e){var t=this.__data__;return Cl?void 0!==t[e]:Il.call(t,e)},Bl=function(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=Pl&&void 0===t?"__lodash_hash_undefined__":t,this};function Nl(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}Nl.prototype.clear=Dl,Nl.prototype.delete=Ol,Nl.prototype.get=Ll,Nl.prototype.has=Ml,Nl.prototype.set=Bl;var Fl=Nl,Wl=Pc,Ul=bl;var Gl=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var Hl=function(e,t){var i=e.__data__;return Gl(t)?i["string"==typeof t?"string":"hash"]:i.map},zl=Hl;var jl=Hl;var Vl=Hl;var ql=Hl;var Yl=function(){this.size=0,this.__data__={hash:new Fl,map:new(Ul||Wl),string:new Fl}},Kl=function(e){var t=zl(this,e).delete(e);return this.size-=t?1:0,t},Xl=function(e){return jl(this,e).get(e)},$l=function(e){return Vl(this,e).has(e)},Zl=function(e,t){var i=ql(this,e),n=i.size;return i.set(e,t),this.size+=i.size==n?0:1,this};function Jl(e){var t=-1,i=null==e?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}Jl.prototype.clear=Yl,Jl.prototype.delete=Kl,Jl.prototype.get=Xl,Jl.prototype.has=$l,Jl.prototype.set=Zl;var Ql=Pc,eh=bl,th=Jl;var ih=Pc,nh=Oc,rh=Lc,sh=Mc,ah=Bc,oh=function(e,t){var i=this.__data__;if(i instanceof Ql){var n=i.__data__;if(!eh||n.length<199)return n.push([e,t]),this.size=++i.size,this;i=this.__data__=new th(n)}return i.set(e,t),this.size=i.size,this};function ch(e){var t=this.__data__=new ih(e);this.size=t.size}ch.prototype.clear=nh,ch.prototype.delete=rh,ch.prototype.get=sh,ch.prototype.has=ah,ch.prototype.set=oh;var lh=ch,hh=wl,dh=function(){try{var e=hh(Object,"defineProperty");return e({},"",{}),e}catch(e){}}(),uh=dh;var fh=function(e,t,i){"__proto__"==t&&uh?uh(e,t,{configurable:!0,enumerable:!0,value:i,writable:!0}):e[t]=i},ph=fh,mh=_c;var gh=function(e,t,i){(void 0!==i&&!mh(e[t],i)||void 0===i&&!(t in e))&&ph(e,t,i)};var _h=function(e){return function(t,i,n){for(var r=-1,s=Object(t),a=n(t),o=a.length;o--;){var c=a[e?o:++r];if(!1===i(s[c],c,s))break}return t}}(),yh={exports:{}};!function(e,t){var i=Uc,n=t&&!t.nodeType&&t,r=n&&e&&!e.nodeType&&e,s=r&&r.exports===n?i.Buffer:void 0,a=s?s.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var i=e.length,n=a?a(i):new e.constructor(i);return e.copy(n),n}}(yh,yh.exports);var Th=yh.exports,wh=Uc.Uint8Array;var bh=function(e){var t=new e.constructor(e.byteLength);return new wh(t).set(new wh(e)),t};var Sh=function(e,t){var i=t?bh(e.buffer):e.buffer;return new e.constructor(i,e.byteOffset,e.length)};var vh=function(e,t){var i=-1,n=e.length;for(t||(t=Array(n));++i<n;)t[i]=e[i];return t},Ah=Qc,Eh=Object.create,Rh=function(){function e(){}return function(t){if(!Ah(t))return{};if(Eh)return Eh(t);e.prototype=t;var i=new e;return e.prototype=void 0,i}}();var kh=function(e,t){return function(i){return e(t(i))}}(Object.getPrototypeOf,Object),xh=Object.prototype;var Ch=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||xh)},Ih=Rh,Ph=kh,Dh=Ch;var Oh=function(e){return"function"!=typeof e.constructor||Dh(e)?{}:Ih(Ph(e))};var Lh=function(e){return null!=e&&"object"==typeof e},Mh=Jc,Bh=Lh;var Nh=function(e){return Bh(e)&&"[object Arguments]"==Mh(e)},Fh=Lh,Wh=Object.prototype,Uh=Wh.hasOwnProperty,Gh=Wh.propertyIsEnumerable,Hh=Nh(function(){return arguments}())?Nh:function(e){return Fh(e)&&Uh.call(e,"callee")&&!Gh.call(e,"callee")},zh=Array.isArray;var jh=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},Vh=nl,qh=jh;var Yh=function(e){return null!=e&&qh(e.length)&&!Vh(e)},Kh=Yh,Xh=Lh;var $h=function(e){return Xh(e)&&Kh(e)},Zh={exports:{}};var Jh=function(){return!1};!function(e,t){var i=Uc,n=Jh,r=t&&!t.nodeType&&t,s=r&&e&&!e.nodeType&&e,a=s&&s.exports===r?i.Buffer:void 0,o=(a?a.isBuffer:void 0)||n;e.exports=o}(Zh,Zh.exports);var Qh=Zh.exports,ed=Jc,td=kh,id=Lh,nd=Function.prototype,rd=Object.prototype,sd=nd.toString,ad=rd.hasOwnProperty,od=sd.call(Object);var cd=function(e){if(!id(e)||"[object Object]"!=ed(e))return!1;var t=td(e);if(null===t)return!0;var i=ad.call(t,"constructor")&&t.constructor;return"function"==typeof i&&i instanceof i&&sd.call(i)==od},ld=Jc,hd=jh,dd=Lh,ud={};ud["[object Float32Array]"]=ud["[object Float64Array]"]=ud["[object Int8Array]"]=ud["[object Int16Array]"]=ud["[object Int32Array]"]=ud["[object Uint8Array]"]=ud["[object Uint8ClampedArray]"]=ud["[object Uint16Array]"]=ud["[object Uint32Array]"]=!0,ud["[object Arguments]"]=ud["[object Array]"]=ud["[object ArrayBuffer]"]=ud["[object Boolean]"]=ud["[object DataView]"]=ud["[object Date]"]=ud["[object Error]"]=ud["[object Function]"]=ud["[object Map]"]=ud["[object Number]"]=ud["[object Object]"]=ud["[object RegExp]"]=ud["[object Set]"]=ud["[object String]"]=ud["[object WeakMap]"]=!1;var fd=function(e){return dd(e)&&hd(e.length)&&!!ud[ld(e)]};var pd=function(e){return function(t){return e(t)}},md={exports:{}};!function(e,t){var i=Nc,n=t&&!t.nodeType&&t,r=n&&e&&!e.nodeType&&e,s=r&&r.exports===n&&i.process,a=function(){try{var e=r&&r.require&&r.require("util").types;return e||s&&s.binding&&s.binding("util")}catch(e){}}();e.exports=a}(md,md.exports);var gd=md.exports,_d=fd,yd=pd,Td=gd&&gd.isTypedArray,wd=Td?yd(Td):_d;var bd=function(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]},Sd=fh,vd=_c,Ad=Object.prototype.hasOwnProperty;var Ed=function(e,t,i){var n=e[t];Ad.call(e,t)&&vd(n,i)&&(void 0!==i||t in e)||Sd(e,t,i)},Rd=fh;var kd=function(e,t,i,n){var r=!i;i||(i={});for(var s=-1,a=t.length;++s<a;){var o=t[s],c=n?n(i[o],e[o],o,i,e):void 0;void 0===c&&(c=e[o]),r?Rd(i,o,c):Ed(i,o,c)}return i};var xd=/^(?:0|[1-9]\d*)$/;var Cd=function(e,t){var i=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==i||"symbol"!=i&&xd.test(e))&&e>-1&&e%1==0&&e<t},Id=function(e,t){for(var i=-1,n=Array(e);++i<e;)n[i]=t(i);return n},Pd=Hh,Dd=zh,Od=Qh,Ld=Cd,Md=wd,Bd=Object.prototype.hasOwnProperty;var Nd=function(e,t){var i=Dd(e),n=!i&&Pd(e),r=!i&&!n&&Od(e),s=!i&&!n&&!r&&Md(e),a=i||n||r||s,o=a?Id(e.length,String):[],c=o.length;for(var l in e)!t&&!Bd.call(e,l)||a&&("length"==l||r&&("offset"==l||"parent"==l)||s&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||Ld(l,c))||o.push(l);return o};var Fd=Qc,Wd=Ch,Ud=function(e){var t=[];if(null!=e)for(var i in Object(e))t.push(i);return t},Gd=Object.prototype.hasOwnProperty;var Hd=Nd,zd=function(e){if(!Fd(e))return Ud(e);var t=Wd(e),i=[];for(var n in e)("constructor"!=n||!t&&Gd.call(e,n))&&i.push(n);return i},jd=Yh;var Vd=function(e){return jd(e)?Hd(e,!0):zd(e)},qd=kd,Yd=Vd;var Kd=gh,Xd=Th,$d=Sh,Zd=vh,Jd=Oh,Qd=Hh,eu=zh,tu=$h,iu=Qh,nu=nl,ru=Qc,su=cd,au=wd,ou=bd,cu=function(e){return qd(e,Yd(e))};var lu=lh,hu=gh,du=_h,uu=function(e,t,i,n,r,s,a){var o=ou(e,i),c=ou(t,i),l=a.get(c);if(l)Kd(e,i,l);else{var h=s?s(o,c,i+"",e,t,a):void 0,d=void 0===h;if(d){var u=eu(c),f=!u&&iu(c),p=!u&&!f&&au(c);h=c,u||f||p?eu(o)?h=o:tu(o)?h=Zd(o):f?(d=!1,h=Xd(c,!0)):p?(d=!1,h=$d(c,!0)):h=[]:su(c)||Qd(c)?(h=o,Qd(o)?h=cu(o):ru(o)&&!nu(o)||(h=Jd(c))):d=!1}d&&(a.set(c,h),r(h,c,n,s,a),a.delete(c)),Kd(e,i,h)}},fu=Qc,pu=Vd,mu=bd;var gu=function e(t,i,n,r,s){t!==i&&du(i,(function(a,o){if(s||(s=new lu),fu(a))uu(t,i,o,n,e,r,s);else{var c=r?r(mu(t,o),a,o+"",t,i,s):void 0;void 0===c&&(c=a),hu(t,o,c)}}),pu)};var _u=function(e){return e};var yu=function(e,t,i){switch(i.length){case 0:return e.call(t);case 1:return e.call(t,i[0]);case 2:return e.call(t,i[0],i[1]);case 3:return e.call(t,i[0],i[1],i[2])}return e.apply(t,i)},Tu=Math.max;var wu=function(e,t,i){return t=Tu(void 0===t?e.length-1:t,0),function(){for(var n=arguments,r=-1,s=Tu(n.length-t,0),a=Array(s);++r<s;)a[r]=n[t+r];r=-1;for(var o=Array(t+1);++r<t;)o[r]=n[r];return o[t]=i(a),yu(e,this,o)}};var bu=function(e){return function(){return e}},Su=dh,vu=Su?function(e,t){return Su(e,"toString",{configurable:!0,enumerable:!1,value:bu(t),writable:!0})}:_u,Au=Date.now;var Eu=function(e){var t=0,i=0;return function(){var n=Au(),r=16-(n-i);if(i=n,r>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}(vu),Ru=_u,ku=wu,xu=Eu;var Cu=_c,Iu=Yh,Pu=Cd,Du=Qc;var Ou=function(e,t){return xu(ku(e,t,Ru),e+"")},Lu=function(e,t,i){if(!Du(i))return!1;var n=typeof t;return!!("number"==n?Iu(i)&&Pu(t,i.length):"string"==n&&t in i)&&Cu(i[t],e)};var Mu,Bu=gu,Nu=s(function(e){return Ou((function(t,i){var n=-1,r=i.length,s=r>1?i[r-1]:void 0,a=r>2?i[2]:void 0;for(s=e.length>3&&"function"==typeof s?(r--,s):void 0,a&&Lu(i[0],i[1],a)&&(s=r<3?void 0:s,r=1),t=Object(t);++n<r;){var o=i[n];o&&e(t,o,n,s)}return t}))}((function(e,t,i){Bu(e,t,i)})));!function(e){e.IDLE="idle",e.PLAYING="playing",e.PAUSED="paused",e.STOPPED="stopped"}(Mu||(Mu={}));class Fu{audioContext=null;audioWorkletNode=null;outputGainNode=null;aecGainNode=null;state=Mu.IDLE;config;isInitialized=!1;initializingPromise=null;mediaStreamDestination=null;audioElement=null;onPlaybackStartedHandler;onPlaybackEndedHandler;onPlaybackStoppedHandler;onBufferLowHandler;onErrorHandler;processorBlobUrl=null;onAudioWaiting=null;onAudioPlaying=null;jitterConfig={initialBuffer:200,minBuffer:100,maxBuffer:500,jitterMultiplier:3,shrinkRate:20};lastChunkArrivalTime=0;lastChunkTimestamp=0;jitterEstimate=0;totalSamplesReceived=0;chunkCount=0;chunkIntervals=[];maxChunkInterval=0;targetBufferMs=100;lastTargetUpdateTime=0;workletStats={actualBufferMs:0,underrunCount:0,minBufferMs:100};isMobile;isIOS;workletConfig;useAecOutput;outputGain=1;duckingTimer=null;isChangingRate=!1;resampleSequence=0;pendingResamples=new Map;nextSendSequence=0;isProcessingResample=!1;resampleLastSample=0;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.config={sampleRate:e.sampleRate||24e3,channels:e.channels||1,bufferSize:e.bufferSize||4096,...e};const t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),i="undefined"!=typeof window&&("1"===new URLSearchParams(window.location.search).get("forceMobileBuffer")||"1"===window.localStorage.getItem("forceMobileBuffer"));this.isMobile=t||i,this.isIOS=/iPhone|iPad|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,this.useAecOutput=!0,this.isIOS,this.isMobile?(this.jitterConfig={initialBuffer:350,minBuffer:200,maxBuffer:800,jitterMultiplier:3,shrinkRate:15},this.workletConfig={firstPlaybackBufferMs:650,maxWaitForDataSec:4}):this.workletConfig={firstPlaybackBufferMs:350,maxWaitForDataSec:2}}async setRate(e){if(this.config.sampleRate!==e||!this.isInitialized)if(this.isChangingRate)console.warn("[AudioManager] Rate change already in progress, skipping");else{this.isChangingRate=!0;try{this.config.sampleRate=e,await this.dispose(),this.resetJitterBuffer(),await this.initialize()}finally{this.isChangingRate=!1}}}setFirstPlaybackBuffer(e){let t;if(e<=0?t=this.isMobile?650:350:(t=e,this.isMobile),this.workletConfig.firstPlaybackBufferMs=t,this.audioWorkletNode&&this.audioContext){const e=this.audioContext.sampleRate,i=Math.floor(e*(t/1e3));this.audioWorkletNode.port.postMessage({type:"update-first-playback-buffer",payload:{firstPlaybackBuffer:i}})}}async setMuted(e){this.config.muted!==e&&(this.config.muted=e,this.isInitialized&&this.audioWorkletNode&&(e?(this.audioWorkletNode.disconnect(),this.outputGainNode?.disconnect(),this.aecGainNode?.disconnect(),this.audioElement&&this.audioElement.pause()):(this.audioContext&&(this.outputGainNode||(this.outputGainNode=this.audioContext.createGain()),this.outputGainNode.gain.value=this.outputGain,this.audioWorkletNode.connect(this.outputGainNode),this.outputGainNode.connect(this.audioContext.destination)),this.mediaStreamDestination&&(this.aecGainNode||(this.aecGainNode=this.audioContext.createGain()),this.aecGainNode.gain.value=1,this.audioWorkletNode.connect(this.aecGainNode),this.aecGainNode.connect(this.mediaStreamDestination)),this.audioElement&&this.audioElement.play().catch((e=>{console.warn("[AudioManager] AEC reference resume failed:",e)})))))}setOutputGain(e){const t=Math.max(0,Math.min(1,e));this.outputGain=t,this.outputGainNode&&(this.outputGainNode.gain.value=t)}duckOutput(e,t){this.setOutputGain(e),this.duckingTimer&&(clearTimeout(this.duckingTimer),this.duckingTimer=null),this.duckingTimer=window.setTimeout((()=>{this.duckingTimer=null,this.setOutputGain(1)}),t)}async setAecEnabled(e){}isAecEnabled(){return this.useAecOutput}isMobileDevice(){return this.isMobile}async initialize(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(!this.isInitialized)try{this.audioContext=new(window.AudioContext||window.webkitAudioContext);this.audioContext.sampleRate,this.config.sampleRate;if("suspended"===this.audioContext.state){if(!e)return void(this.isInitialized=!0);await this.audioContext.resume()}await this.completeInitialization()}catch(e){const t=e instanceof Error?e:new Error("Failed to initialize audio");throw this.onErrorHandler?.(t),t}}async completeInitialization(){if(!this.audioContext)throw new Error("AudioContext not created");const e=this.createProcessorBlobUrl();await this.audioContext.audioWorklet.addModule(e),this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"pcm-audio-processor",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[this.config.channels||1]}),this.audioWorkletNode.port.onmessage=e=>{this.handleWorkletMessage(e.data)},this.config.muted||(this.outputGainNode=this.audioContext.createGain(),this.outputGainNode.gain.value=this.outputGain,this.audioWorkletNode.connect(this.outputGainNode),this.outputGainNode.connect(this.audioContext.destination),this.isIOS||(this.aecGainNode=this.audioContext.createGain(),this.aecGainNode.gain.value=1,this.mediaStreamDestination=this.audioContext.createMediaStreamDestination(),this.audioWorkletNode.connect(this.aecGainNode),this.aecGainNode.connect(this.mediaStreamDestination),this.audioElement=new Audio,this.audioElement.srcObject=this.mediaStreamDestination.stream,this.audioElement.volume=.01,this.onAudioWaiting=()=>{this.audioElement,Date.now()},this.onAudioPlaying=()=>{this.audioElement,Date.now()},this.audioElement.addEventListener("waiting",this.onAudioWaiting),this.audioElement.addEventListener("playing",this.onAudioPlaying),this.audioElement.play().catch((e=>{console.warn("[AudioManager] AEC reference play failed:",e)})))),this.isInitialized=!0}async ensureFullyInitialized(){if(this.initializingPromise)await this.initializingPromise;else if(!this.audioWorkletNode||!this.audioContext||"running"!==this.audioContext.state){this.initializingPromise=this.doEnsureFullyInitialized();try{await this.initializingPromise}finally{this.initializingPromise=null}}}async doEnsureFullyInitialized(){if(this.audioContext){if("suspended"===this.audioContext.state)try{await this.audioContext.resume(),this.audioContext.state}catch(e){throw console.error("[AudioManager] ❌ AudioContext resume failed:",e),new Error("AudioContext could not be resumed. User interaction may be required.")}this.audioWorkletNode||await this.completeInitialization()}else await this.initialize(!0)}async playAudio(e){if(await this.ensureFullyInitialized(),!this.audioWorkletNode)throw new Error("AudioWorklet not initialized");const t=new Int16Array(e),i=new Float32Array(t.length);for(let e=0;e<t.length;e++)i[e]=t[e]/32768;this.audioWorkletNode.port.postMessage({type:"append-float32-data",payload:i.buffer},[i.buffer])}async appendAudio(e){if(await this.ensureFullyInitialized(),!this.audioWorkletNode||!this.audioContext)throw new Error("AudioWorklet not initialized");const t=performance.now(),i=this.config.sampleRate||24e3;this.audioContext.sampleRate;const n=e.byteLength/2;if(this.chunkCount>0){const e=t-this.lastChunkArrivalTime,n=e-(this.totalSamplesReceived-this.lastChunkTimestamp)/i*1e3;this.jitterEstimate=this.jitterEstimate+(Math.abs(n)-this.jitterEstimate)/16,this.chunkIntervals.push(e),this.chunkIntervals.length>50&&this.chunkIntervals.shift(),this.maxChunkInterval=Math.max(this.maxChunkInterval,e),this.updateTargetBuffer()}this.lastChunkArrivalTime=t,this.lastChunkTimestamp=this.totalSamplesReceived,this.totalSamplesReceived+=n,this.chunkCount++;const r=new Int16Array(e),s=new Float32Array(r.length);for(let e=0;e<r.length;e++)s[e]=r[e]/32768;this.audioWorkletNode.port.postMessage({type:"append-float32-data",payload:s.buffer},[s.buffer])}async resampleWithWebAudio(e,t,i){if(t===i)return e;const n=e.length,r=Math.round(n*i/t);try{const s=new OfflineAudioContext(1,r,i),a=s.createBuffer(1,n,t);a.copyToChannel(e,0);const o=s.createBufferSource();o.buffer=a,o.connect(s.destination),o.start();return(await s.startRendering()).getChannelData(0)}catch(n){return console.warn("[AudioManager] Web Audio resample failed, using fallback:",n),this.resampleLinear(e,t,i)}}resampleLinear(e,t,i){const n=t/i,r=Math.round(e.length/n),s=new Float32Array(r);for(let t=0;t<r;t++){const i=t*n,r=Math.floor(i),a=i-r,o=r<e.length?e[r]:0,c=r+1<e.length?e[r+1]:o;s[t]=o+(c-o)*a}return s}processResampleQueue(){if(!this.isProcessingResample){for(this.isProcessingResample=!0;this.pendingResamples.has(this.nextSendSequence);){const e=this.pendingResamples.get(this.nextSendSequence);if(this.pendingResamples.delete(this.nextSendSequence),this.nextSendSequence++,this.audioWorkletNode){const t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);this.audioWorkletNode.port.postMessage({type:"append-resampled-data",payload:t},[t])}}this.isProcessingResample=!1}}resetResampleState(){this.resampleSequence=0,this.pendingResamples.clear(),this.nextSendSequence=0,this.resampleLastSample=0}updateTargetBuffer(){const e=performance.now(),{initialBuffer:t,minBuffer:i,maxBuffer:n,jitterMultiplier:r,shrinkRate:s}=this.jitterConfig,a=t+r*this.jitterEstimate;if(a>this.targetBufferMs)this.targetBufferMs=a;else{const t=s*(e-this.lastTargetUpdateTime)/1e3;this.targetBufferMs=Math.max(a,this.targetBufferMs-t)}if(this.targetBufferMs=Math.max(i,Math.min(n,this.targetBufferMs)),this.lastTargetUpdateTime=e,this.audioWorkletNode&&this.audioContext){const e=this.audioContext.sampleRate,t=Math.floor(this.targetBufferMs/1e3*e);this.audioWorkletNode.port.postMessage({type:"update-min-buffer",payload:{minBufferSize:t}})}this.chunkCount%30==0&&(this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"get-stats"}),this.jitterEstimate.toFixed(1),this.targetBufferMs.toFixed(0),this.workletStats.actualBufferMs.toFixed(0),this.workletStats.underrunCount,this.chunkCount,this.getAverageChunkInterval().toFixed(0),this.maxChunkInterval.toFixed(0))}getAverageChunkInterval(){if(0===this.chunkIntervals.length)return 0;return this.chunkIntervals.reduce(((e,t)=>e+t),0)/this.chunkIntervals.length}getJitterBufferStats(){return this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"get-stats"}),{jitter:this.jitterEstimate,targetBuffer:this.targetBufferMs,actualBuffer:this.workletStats.actualBufferMs,underrunCount:this.workletStats.underrunCount,chunkCount:this.chunkCount,avgChunkInterval:this.getAverageChunkInterval(),maxChunkInterval:this.maxChunkInterval}}getChunkIntervalPercentiles(){if(0===this.chunkIntervals.length)return{p50:0,p95:0,p99:0};const e=[...this.chunkIntervals].sort(((e,t)=>e-t)),t=e.length,i=Math.floor(.5*t),n=Math.floor(.95*t),r=Math.floor(.99*t);return{p50:e[i]||0,p95:e[n]||e[t-1]||0,p99:e[r]||e[t-1]||0}}printJitterBufferReport(){const e=this.getJitterBufferStats(),t=this.getChunkIntervalPercentiles();e.jitter.toFixed(1),e.targetBuffer.toFixed(0),e.actualBuffer.toFixed(0),e.underrunCount,e.chunkCount,e.avgChunkInterval.toFixed(0),e.maxChunkInterval.toFixed(0),t.p50.toFixed(0),t.p95.toFixed(0),t.p99.toFixed(0)}resetJitterBuffer(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this.lastChunkArrivalTime=0,this.lastChunkTimestamp=0,this.totalSamplesReceived=0,this.chunkCount=0,this.chunkIntervals=[],this.maxChunkInterval=0,this.lastTargetUpdateTime=0,e&&this.jitterEstimate>0?(this.targetBufferMs=Math.min(this.jitterConfig.maxBuffer,this.jitterConfig.initialBuffer+this.jitterConfig.jitterMultiplier*this.jitterEstimate),this.jitterEstimate.toFixed(1),this.targetBufferMs.toFixed(0)):(this.jitterEstimate=0,this.targetBufferMs=this.jitterConfig.initialBuffer),this.resetResampleState(),this.audioWorkletNode&&this.audioContext){const e=this.audioContext.sampleRate,t=Math.floor(this.targetBufferMs/1e3*e);this.audioWorkletNode.port.postMessage({type:"update-min-buffer",payload:{minBufferSize:t}})}}stopPlayback(){this.audioWorkletNode&&(this.audioWorkletNode.port.postMessage({type:"stop"}),this.state=Mu.STOPPED)}clearBuffer(){this.audioWorkletNode&&(this.audioWorkletNode.port.postMessage({type:"clear"}),this.state=Mu.IDLE)}notifyStreamStarted(){this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"stream-started"})}notifyStreamEnded(){this.audioWorkletNode&&this.audioWorkletNode.port.postMessage({type:"stream-ended"})}async getStats(){return this.audioWorkletNode?new Promise((e=>{let t=!1;const i=setTimeout((()=>{t||(t=!0,this.audioWorkletNode?.port.removeEventListener("message",n),e(null))}),2e3),n=r=>{if("stats"===r.data.type){if(t)return;t=!0,clearTimeout(i),this.audioWorkletNode?.port.removeEventListener("message",n),e(r.data.payload)}};this.audioWorkletNode&&(this.audioWorkletNode.port.addEventListener("message",n),this.audioWorkletNode.port.postMessage({type:"get-stats"}))})):null}getState(){return this.state}isPlaying(){return this.state===Mu.PLAYING}async enableAudio(){this.audioContext?"suspended"===this.audioContext.state&&await this.audioContext.resume():await this.initialize(!0)}isAudioEnabled(){return"running"===this.audioContext?.state}async dispose(){this.stopPlayback(),this.duckingTimer&&(clearTimeout(this.duckingTimer),this.duckingTimer=null),this.audioElement&&(this.onAudioWaiting&&(this.audioElement.removeEventListener("waiting",this.onAudioWaiting),this.onAudioWaiting=null),this.onAudioPlaying&&(this.audioElement.removeEventListener("playing",this.onAudioPlaying),this.onAudioPlaying=null),this.audioElement.pause(),this.audioElement.srcObject=null,this.audioElement=null),this.mediaStreamDestination&&(this.mediaStreamDestination.disconnect(),this.mediaStreamDestination=null),this.outputGainNode&&(this.outputGainNode.disconnect(),this.outputGainNode=null),this.aecGainNode&&(this.aecGainNode.disconnect(),this.aecGainNode=null),this.audioWorkletNode&&(this.audioWorkletNode.disconnect(),this.audioWorkletNode=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.processorBlobUrl&&(URL.revokeObjectURL(this.processorBlobUrl),this.processorBlobUrl=null),this.initializingPromise=null,this.onPlaybackStartedHandler=void 0,this.onPlaybackEndedHandler=void 0,this.onPlaybackStoppedHandler=void 0,this.onBufferLowHandler=void 0,this.onErrorHandler=void 0,this.isInitialized=!1,this.state=Mu.IDLE}onPlaybackStarted(e){this.onPlaybackStartedHandler=e}onPlaybackEnded(e){this.onPlaybackEndedHandler=e}onPlaybackStopped(e){this.onPlaybackStoppedHandler=e}onBufferLow(e){this.onBufferLowHandler=e}onError(e){this.onErrorHandler=e}handleWorkletMessage(e){const{type:t,payload:i}=e;switch(t){case"playback-started":i?.isFirstPlayback?(i.requiredBufferMs?.toFixed(0),i.actualBufferMs?.toFixed(0),Date.now()):(i?.actualBufferMs?.toFixed(0),Date.now()),this.state=Mu.PLAYING,this.onPlaybackStartedHandler?.();break;case"playback-ended":this.state=Mu.IDLE,this.onPlaybackEndedHandler?.();break;case"playback-stopped":this.state=Mu.STOPPED,this.onPlaybackStoppedHandler?.();break;case"buffer-cleared":this.state=Mu.IDLE;break;case"buffer-low":this.onBufferLowHandler?.(i.remainingSamples);break;case"buffer-empty":console.warn("[AudioManager] ⚠️ Buffer empty (underrun):",{underrunCount:i.underrunCount,consecutiveUnderruns:i.consecutiveUnderruns,streamEnded:i.streamEnded,time:Date.now()}),this.workletStats.underrunCount=i.underrunCount;break;case"stats":i&&(this.workletStats={actualBufferMs:i.remainingDurationMs||0,underrunCount:i.underrunCount||0,minBufferMs:i.minBufferMs||100});break;case"init-info":i.outputSampleRate,i.inputSampleRate,i.needResample,i.resampleRatio?.toFixed(4),i.bufferCapacity;break;case"buffer-overflow":console.warn("[AudioManager] ⚠️ Buffer overflow, dropped samples:",i.droppedSamples);break;case"error":console.error("[AudioManager] ❌ Error:",i.message),this.onErrorHandler?.(new Error(i.message))}}createProcessorBlobUrl(){const e=this.getProcessorCode(),t=new Blob([e],{type:"application/javascript"});return this.processorBlobUrl&&URL.revokeObjectURL(this.processorBlobUrl),this.processorBlobUrl=URL.createObjectURL(t),this.processorBlobUrl}getProcessorCode(){return`\n// AudioWorklet processor for PCM audio playback\n// 使用环形缓冲区(Ring Buffer)实现,避免 GC 卡顿\nconst outputSampleRate = ${this.audioContext?.sampleRate||this.config.sampleRate||24e3}; // AudioContext 实际采样率\nconst inputSampleRate = ${this.config.sampleRate||24e3}; // TTS 数据采样率\nconst initialMinBufferMs = ${this.jitterConfig.initialBuffer};\nconst firstPlaybackBufferMs = ${this.workletConfig.firstPlaybackBufferMs};\nconst maxWaitForData = ${this.workletConfig.maxWaitForDataSec};\n\n// 是否需要重采样\nconst needResample = outputSampleRate !== inputSampleRate;\nconst resampleRatio = needResample ? inputSampleRate / outputSampleRate : 1.0;\n\nclass PCMAudioProcessor extends AudioWorkletProcessor {\n constructor() {\n super();\n\n // ========== 环形缓冲区(Ring Buffer)==========\n // 预分配固定大小的 Float32Array,避免运行时内存分配和 GC\n // 容量需要足够大以容纳完整的 TTS 响应:gRPC 传输速度 > 实时播放速度,\n // 长回复(30秒+)的音频数据会在短时间内全部到达并缓存\n const maxBufferSeconds = 60;\n this.bufferCapacity = outputSampleRate * maxBufferSeconds;\n this.ringBuffer = new Float32Array(this.bufferCapacity);\n this.writeIndex = 0; // 写入位置\n this.readIndex = 0; // 读取位置\n this.availableSamples = 0; // 可用样本数\n\n // ========== 重采样相关 ==========\n this.resampleBuffer = null; // 重采样临时缓冲区\n this.lastInputSample = 0; // 上一个输入样本(用于插值)\n this.resamplePhase = 0; // 重采样相位(跨 chunk 的小数部分)\n\n // ========== Jitter Buffer 配置 ==========\n this.minBufferSize = Math.floor(outputSampleRate * (initialMinBufferMs / 1000));\n this.lowBufferThreshold = Math.floor(this.minBufferSize * 0.5);\n this.firstPlaybackBuffer = Math.floor(outputSampleRate * (firstPlaybackBufferMs / 1000));\n this.hasStartedFirstPlayback = false;\n\n // ========== 播放状态 ==========\n this.isPlaying = false;\n this.shouldStop = false;\n this.streamEnded = false;\n this.bufferEmptyTime = 0;\n this.maxWaitForData = maxWaitForData;\n\n // ========== 统计信息 ==========\n this.underrunCount = 0;\n this.consecutiveUnderruns = 0;\n this.lastLowBufferWarning = 0;\n this.totalSamplesWritten = 0;\n this.totalSamplesRead = 0;\n\n this.port.onmessage = (event) => {\n this.handleMessage(event.data);\n };\n\n // 日志:初始化信息\n this.port.postMessage({\n type: 'init-info',\n payload: {\n outputSampleRate,\n inputSampleRate,\n needResample,\n resampleRatio,\n bufferCapacity: this.bufferCapacity\n }\n });\n }\n\n handleMessage(data) {\n const { type, payload } = data;\n\n switch (type) {\n case 'audio-data':\n this.addAudioData(payload, true);\n break;\n case 'append-audio-data':\n this.addAudioData(payload, false);\n break;\n case 'append-float32-data':\n // P1-4: 主线程已完成 Int16→Float32 转换,只需重采样\n this.addFloat32Data(payload);\n break;\n case 'append-resampled-data':\n // 主线程已完成高质量重采样,直接写入缓冲区\n this.addResampledData(payload);\n break;\n case 'play':\n this.startPlayback();\n break;\n case 'stop':\n this.stopPlayback();\n break;\n case 'clear':\n this.clearBuffer();\n break;\n case 'get-stats':\n this.sendStats();\n break;\n case 'stream-ended':\n this.streamEnded = true;\n break;\n case 'stream-started':\n this.streamEnded = false;\n this.bufferEmptyTime = 0;\n this.hasStartedFirstPlayback = false;\n break;\n case 'update-min-buffer':\n const newMinBuffer = payload.minBufferSize;\n if (newMinBuffer > 0 && newMinBuffer !== this.minBufferSize) {\n this.minBufferSize = newMinBuffer;\n this.lowBufferThreshold = Math.floor(newMinBuffer * 0.5);\n }\n break;\n case 'update-first-playback-buffer':\n const newFirstPlaybackBuffer = payload.firstPlaybackBuffer;\n if (newFirstPlaybackBuffer > 0) {\n this.firstPlaybackBuffer = newFirstPlaybackBuffer;\n }\n break;\n }\n }\n\n // 状态保持型线性插值重采样(正确处理 chunk 边界)\n // 支持任意采样率比率(如 24000→48000, 24000→44100 等)\n // 关键:使用 lastInputSample 和 resamplePhase 确保 chunk 之间的连续性\n resample(inputData) {\n if (!needResample) {\n if (inputData.length > 0) {\n this.lastInputSample = inputData[inputData.length - 1];\n }\n return inputData;\n }\n\n const inputLength = inputData.length;\n if (inputLength === 0) return inputData;\n\n // 使用实际的采样率比率计算输出长度\n // resampleRatio = inputSampleRate / outputSampleRate(如 24000/48000 = 0.5)\n // outputLength = inputLength / resampleRatio = inputLength * (outputSampleRate / inputSampleRate)\n const outputLength = Math.ceil(inputLength / resampleRatio);\n\n // 复用或创建重采样缓冲区\n if (!this.resampleBuffer || this.resampleBuffer.length < outputLength) {\n this.resampleBuffer = new Float32Array(outputLength);\n }\n\n // 状态保持型线性插值重采样:\n // 对于每个输出样本,计算其在输入序列中的位置,然后线性插值\n // resamplePhase 保存跨 chunk 的小数部分,确保边界连续\n let inputPos = this.resamplePhase || 0; // 从上次的位置继续\n let outputIdx = 0;\n\n while (outputIdx < outputLength && inputPos < inputLength) {\n const intPart = Math.floor(inputPos);\n const fracPart = inputPos - intPart;\n\n // 获取插值所需的两个样本\n const sample0 = (intPart === 0 && fracPart < 0.0001)\n ? this.lastInputSample // chunk 边界:使用上一个 chunk 的最后一个样本\n : (intPart > 0 ? inputData[intPart - 1] : this.lastInputSample);\n const sample1 = intPart < inputLength ? inputData[intPart] : inputData[inputLength - 1];\n\n // 线性插值\n this.resampleBuffer[outputIdx] = sample0 + (sample1 - sample0) * fracPart;\n\n outputIdx++;\n inputPos += resampleRatio; // 按比率前进(如 0.5 表示每输出 1 个样本消耗 0.5 个输入样本)\n }\n\n // 保存状态供下一个 chunk 使用\n this.lastInputSample = inputData[inputLength - 1];\n this.resamplePhase = inputPos - inputLength; // 保存小数部分\n\n return this.resampleBuffer.subarray(0, outputIdx);\n }\n\n addAudioData(pcmData, replaceBuffer = false) {\n // 1. 转换 Int16 PCM 到 Float32\n let audioData;\n if (pcmData instanceof ArrayBuffer) {\n const int16Array = new Int16Array(pcmData);\n audioData = new Float32Array(int16Array.length);\n for (let i = 0; i < int16Array.length; i++) {\n audioData[i] = int16Array[i] / 32768.0;\n }\n } else {\n audioData = new Float32Array(pcmData);\n }\n\n // 2. 重采样(如果需要)\n const processedData = this.resample(audioData);\n const length = processedData.length;\n\n // 3. 写入环形缓冲区\n if (replaceBuffer) {\n // 替换模式:清空缓冲区\n this.writeIndex = 0;\n this.readIndex = 0;\n this.availableSamples = 0;\n }\n\n // 检查是否有足够空间\n const freeSpace = this.bufferCapacity - this.availableSamples;\n if (length > freeSpace) {\n // 缓冲区溢出,丢弃最旧的数据\n const overflow = length - freeSpace;\n this.readIndex = (this.readIndex + overflow) % this.bufferCapacity;\n this.availableSamples -= overflow;\n // 通知主线程\n this.port.postMessage({\n type: 'buffer-overflow',\n payload: { droppedSamples: overflow }\n });\n }\n\n // 写入数据到环形缓冲区(使用 TypedArray.set() 批量写入,性能提升 10-100x)\n if (this.writeIndex + length <= this.bufferCapacity) {\n // 不需要环绕,直接批量写入\n this.ringBuffer.set(processedData, this.writeIndex);\n this.writeIndex += length;\n } else {\n // 需要环绕,分两段写入\n const firstPart = this.bufferCapacity - this.writeIndex;\n this.ringBuffer.set(processedData.subarray(0, firstPart), this.writeIndex);\n this.ringBuffer.set(processedData.subarray(firstPart), 0);\n this.writeIndex = length - firstPart;\n }\n this.availableSamples += length;\n this.totalSamplesWritten += length;\n\n // 自动开始播放\n const requiredBuffer = this.hasStartedFirstPlayback\n ? this.minBufferSize\n : this.firstPlaybackBuffer;\n\n if (!this.isPlaying && this.availableSamples >= requiredBuffer) {\n const isFirstPlayback = !this.hasStartedFirstPlayback;\n this.hasStartedFirstPlayback = true;\n this.startPlayback(isFirstPlayback, requiredBuffer);\n }\n\n // 重置缓冲区空时间\n if (this.isPlaying && this.bufferEmptyTime > 0) {\n this.bufferEmptyTime = 0;\n }\n }\n\n // P1-4: 添加已在主线程转换的 Float32 数据(跳过 Int16→Float32 转换,只需重采样)\n addFloat32Data(float32Buffer) {\n // 数据已经是 Float32 格式,直接从 ArrayBuffer 创建视图\n const audioData = new Float32Array(float32Buffer);\n\n // 重采样(如果需要)\n const processedData = this.resample(audioData);\n const length = processedData.length;\n\n // 检查是否有足够空间\n const freeSpace = this.bufferCapacity - this.availableSamples;\n if (length > freeSpace) {\n // 缓冲区溢出,丢弃最旧的数据\n const overflow = length - freeSpace;\n this.readIndex = (this.readIndex + overflow) % this.bufferCapacity;\n this.availableSamples -= overflow;\n // 通知主线程\n this.port.postMessage({\n type: 'buffer-overflow',\n payload: { droppedSamples: overflow }\n });\n }\n\n // 写入数据到环形缓冲区(使用 TypedArray.set() 批量写入)\n if (this.writeIndex + length <= this.bufferCapacity) {\n // 不需要环绕,直接批量写入\n this.ringBuffer.set(processedData, this.writeIndex);\n this.writeIndex += length;\n } else {\n // 需要环绕,分两段写入\n const firstPart = this.bufferCapacity - this.writeIndex;\n this.ringBuffer.set(processedData.subarray(0, firstPart), this.writeIndex);\n this.ringBuffer.set(processedData.subarray(firstPart), 0);\n this.writeIndex = length - firstPart;\n }\n this.availableSamples += length;\n this.totalSamplesWritten += length;\n\n // 自动开始播放\n const requiredBuffer = this.hasStartedFirstPlayback\n ? this.minBufferSize\n : this.firstPlaybackBuffer;\n\n if (!this.isPlaying && this.availableSamples >= requiredBuffer) {\n const isFirstPlayback = !this.hasStartedFirstPlayback;\n this.hasStartedFirstPlayback = true;\n this.startPlayback(isFirstPlayback, requiredBuffer);\n }\n\n // 重置缓冲区空时间\n if (this.isPlaying && this.bufferEmptyTime > 0) {\n this.bufferEmptyTime = 0;\n }\n }\n\n // 添加已在主线程重采样的数据(跳过重采样步骤)\n addResampledData(resampledBuffer) {\n // 数据已经是 Float32 格式,直接从 ArrayBuffer 创建视图\n const processedData = new Float32Array(resampledBuffer);\n const length = processedData.length;\n\n // 检查是否有足够空间\n const freeSpace = this.bufferCapacity - this.availableSamples;\n if (length > freeSpace) {\n // 缓冲区溢出,丢弃最旧的数据\n const overflow = length - freeSpace;\n this.readIndex = (this.readIndex + overflow) % this.bufferCapacity;\n this.availableSamples -= overflow;\n // 通知主线程\n this.port.postMessage({\n type: 'buffer-overflow',\n payload: { droppedSamples: overflow }\n });\n }\n\n // 写入数据到环形缓冲区(使用 TypedArray.set() 批量写入)\n if (this.writeIndex + length <= this.bufferCapacity) {\n // 不需要环绕,直接批量写入\n this.ringBuffer.set(processedData, this.writeIndex);\n this.writeIndex += length;\n } else {\n // 需要环绕,分两段写入\n const firstPart = this.bufferCapacity - this.writeIndex;\n this.ringBuffer.set(processedData.subarray(0, firstPart), this.writeIndex);\n this.ringBuffer.set(processedData.subarray(firstPart), 0);\n this.writeIndex = length - firstPart;\n }\n this.availableSamples += length;\n this.totalSamplesWritten += length;\n\n // 自动开始播放\n const requiredBuffer = this.hasStartedFirstPlayback\n ? this.minBufferSize\n : this.firstPlaybackBuffer;\n\n if (!this.isPlaying && this.availableSamples >= requiredBuffer) {\n const isFirstPlayback = !this.hasStartedFirstPlayback;\n this.hasStartedFirstPlayback = true;\n this.startPlayback(isFirstPlayback, requiredBuffer);\n }\n\n // 重置缓冲区空时间\n if (this.isPlaying && this.bufferEmptyTime > 0) {\n this.bufferEmptyTime = 0;\n }\n }\n\n startPlayback(isFirstPlayback = false, requiredBuffer = 0) {\n this.isPlaying = true;\n this.shouldStop = false;\n this.port.postMessage({\n type: 'playback-started',\n payload: {\n isFirstPlayback,\n requiredBufferMs: (requiredBuffer / outputSampleRate) * 1000,\n actualBufferMs: (this.availableSamples / outputSampleRate) * 1000\n }\n });\n }\n\n stopPlayback() {\n this.isPlaying = false;\n this.shouldStop = true;\n this.port.postMessage({ type: 'playback-stopped' });\n }\n\n clearBuffer() {\n // 重置环形缓冲区指针(O(1),不需要清空数组)\n this.writeIndex = 0;\n this.readIndex = 0;\n this.availableSamples = 0;\n this.isPlaying = false;\n this.shouldStop = true;\n this.hasStartedFirstPlayback = false;\n this.bufferEmptyTime = 0;\n this.lastInputSample = 0; // 重置重采样边界样本\n this.resamplePhase = 0; // 重置重采样相位\n this.port.postMessage({ type: 'buffer-cleared' });\n }\n\n sendStats() {\n const stats = {\n // 缓冲区状态\n availableSamples: this.availableSamples,\n bufferCapacity: this.bufferCapacity,\n bufferUsagePercent: ((this.availableSamples / this.bufferCapacity) * 100).toFixed(1) + '%',\n remainingDurationMs: (this.availableSamples / outputSampleRate) * 1000,\n // 播放状态\n isPlaying: this.isPlaying,\n streamEnded: this.streamEnded,\n hasStartedFirstPlayback: this.hasStartedFirstPlayback,\n // 统计信息\n underrunCount: this.underrunCount,\n consecutiveUnderruns: this.consecutiveUnderruns,\n totalSamplesWritten: this.totalSamplesWritten,\n totalSamplesRead: this.totalSamplesRead,\n // Jitter Buffer 配置\n minBufferSize: this.minBufferSize,\n minBufferMs: (this.minBufferSize / outputSampleRate) * 1000,\n firstPlaybackBufferMs: (this.firstPlaybackBuffer / outputSampleRate) * 1000,\n // 重采样信息\n needResample,\n resampleRatio,\n inputSampleRate,\n outputSampleRate\n };\n\n this.port.postMessage({ type: 'stats', payload: stats });\n }\n\n process(inputs, outputs, parameters) {\n const output = outputs[0];\n const outputChannel = output[0];\n const frameCount = outputChannel.length;\n\n // 非播放状态,输出静音\n if (!this.isPlaying || this.shouldStop) {\n outputChannel.fill(0);\n return true;\n }\n\n // 缓冲区完全为空\n if (this.availableSamples === 0) {\n outputChannel.fill(0);\n this.underrunCount++;\n this.consecutiveUnderruns++;\n\n if (this.bufferEmptyTime === 0) {\n this.bufferEmptyTime = currentTime;\n this.port.postMessage({\n type: 'buffer-empty',\n payload: {\n underrunCount: this.underrunCount,\n consecutiveUnderruns: this.consecutiveUnderruns,\n streamEnded: this.streamEnded\n }\n });\n }\n\n if (this.streamEnded) {\n this.isPlaying = false;\n this.port.postMessage({ type: 'playback-ended' });\n } else if (currentTime - this.bufferEmptyTime > this.maxWaitForData) {\n this.isPlaying = false;\n this.port.postMessage({ type: 'playback-ended' });\n }\n\n return true;\n }\n\n // 缓冲区低警告\n const now = currentTime;\n if (this.availableSamples < this.lowBufferThreshold && this.availableSamples > 0) {\n if (now - this.lastLowBufferWarning > 0.5) {\n this.lastLowBufferWarning = now;\n this.port.postMessage({\n type: 'buffer-low',\n payload: {\n remainingSamples: this.availableSamples,\n threshold: this.lowBufferThreshold\n }\n });\n }\n }\n\n // 从环形缓冲区批量读取数据(使用 TypedArray 操作,性能提升显著)\n // 重置连续 underrun 计数\n if (this.consecutiveUnderruns > 0) {\n this.consecutiveUnderruns = 0;\n }\n\n // 计算实际可读取的样本数\n const samplesToRead = Math.min(frameCount, this.availableSamples);\n\n if (samplesToRead > 0) {\n // 批量读取数据\n if (this.readIndex + samplesToRead <= this.bufferCapacity) {\n // 不需要环绕,直接批量复制\n outputChannel.set(\n this.ringBuffer.subarray(this.readIndex, this.readIndex + samplesToRead)\n );\n this.readIndex += samplesToRead;\n } else {\n // 需要环绕,分两段读取\n const firstPart = this.bufferCapacity - this.readIndex;\n outputChannel.set(\n this.ringBuffer.subarray(this.readIndex, this.bufferCapacity),\n 0\n );\n outputChannel.set(\n this.ringBuffer.subarray(0, samplesToRead - firstPart),\n firstPart\n );\n this.readIndex = samplesToRead - firstPart;\n }\n\n this.availableSamples -= samplesToRead;\n this.totalSamplesRead += samplesToRead;\n\n // 淡出处理(仅在流结束时且接近尾部)\n if (this.streamEnded) {\n const fadeThreshold = Math.floor(outputSampleRate * 0.05); // 50ms\n if (this.availableSamples < fadeThreshold) {\n // 对已读取的样本应用淡出\n const fadeStartSample = Math.max(0, samplesToRead - fadeThreshold);\n for (let i = fadeStartSample; i < samplesToRead; i++) {\n const fadeGain = (samplesToRead - i) / fadeThreshold;\n outputChannel[i] *= fadeGain;\n }\n }\n }\n }\n\n // 如果读取的样本不够,填充静音并记录 underrun\n if (samplesToRead < frameCount) {\n // 填充剩余部分为静音\n outputChannel.fill(0, samplesToRead);\n\n // 流已结束时,尾帧不足属于正常情况,不计为 underrun\n if (!this.streamEnded) {\n this.underrunCount++;\n this.consecutiveUnderruns++;\n\n if (now - this.lastLowBufferWarning > 0.5) {\n this.lastLowBufferWarning = now;\n this.port.postMessage({\n type: 'buffer-empty',\n payload: {\n underrunCount: this.underrunCount,\n consecutiveUnderruns: this.consecutiveUnderruns,\n streamEnded: this.streamEnded\n }\n });\n }\n }\n }\n\n // 检查是否应该结束播放\n if (this.availableSamples === 0) {\n if (this.streamEnded) {\n this.isPlaying = false;\n this.port.postMessage({ type: 'playback-ended' });\n } else {\n if (this.bufferEmptyTime === 0) {\n this.bufferEmptyTime = currentTime;\n }\n if (currentTime - this.bufferEmptyTime > this.maxWaitForData) {\n this.isPlaying = false;\n this.port.postMessage({ type: 'playback-ended' });\n }\n }\n } else {\n this.bufferEmptyTime = 0;\n }\n\n return true;\n }\n}\n\nregisterProcessor('pcm-audio-processor', PCMAudioProcessor);\n `}}const Wu=8,Uu=10,Gu=0,Hu=300,zu=3,ju=0,Vu=new Array(52).fill(0);class qu extends t{blendShapes=[];audioBuffer=[];audioBufferReadIndex=0;static AUDIO_BUFFER_CLEANUP_THRESHOLD=100;get unreadAudioCount(){return this.audioBuffer.length-this.audioBufferReadIndex}playInfo={shapes:[],audios:[],duration:0,rate:16e3,content:""};fps=30;isPlaying=!1;isInited=!1;isIntervalStarted=!1;time=0;idx=0;playShapeFn=(e,t)=>{};lastBlendShapeLength=0;lastBlendShape=[];lastTimedFrameAt=0;lastShapeReceivedAt=0;isTransitioningToIdle=!1;transitionProgress=0;static TRANSITION_DURATION_MS=200;static TRANSITION_FRAMES=6;static MAX_SYNC_DRIFT_MS=500;static END_GRACE_MS=250;static REBASE_COOLDOWN_MS=500;lastRebaseAt=0;audioManager;timerId=null;callbackMap=new Map;isAudioEnded=!1;audioStreamEndedTime=0;static DELAYED_PACKET_THRESHOLD_MS=500;waitingForAudio=!1;isAudioMuted=!1;isAppendingAudio=!1;isDestroyed=!1;totalAudioBytesReceived=0;totalBlendShapesReceived=0;actualFps=30;playbackStartTime=0;framesPlayedSinceStart=0;useAudioOffsetSync=!1;timedBlendShapes=[];firstAudioOffset=0;lastPlayedOffset=-1;totalWaitTime=0;waitStartTime=0;audioPlaybackStartTime=0;isAudioPlaybackStarted=!1;firstAudioDataTime=0;isFirstAudioDataReceived=!1;externalAudioTimeProvider=null;playAudioThroughAudioManager=!0;hasReceivedRealShape=!1;usingDefaultShape=!1;defaultShapeFrameCount=0;planBDelayTimer=null;static PLAN_B_DELAY_MS=100;quickStartMode=!1;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;super(),this.playShapeFn=t,this.fps=e.fps||30,this.actualFps=this.fps,this.time=Math.floor(1e3/this.fps)-1,this.audioManager=new Fu({}),this.audioManager.initialize(),this.audioManager.onPlaybackStarted((()=>{this.isAudioPlaybackStarted?(this.audioPlaybackStartTime,(performance.now()-this.audioPlaybackStartTime).toFixed(0)):(this.audioPlaybackStartTime=performance.now(),this.isAudioPlaybackStarted=!0,this.audioPlaybackStartTime,this.playbackStartTime,(this.audioPlaybackStartTime-this.playbackStartTime).toFixed(0),this.emit("audio-playback-started"))})),this.audioManager.onPlaybackEnded((()=>{this.isPlaying&&(this.isAudioEnded,this.isPlaying,this.playAudioThroughAudioManager,this.playAudioThroughAudioManager&&this.isAudioEnded?this.finishPlayback():this.playAudioThroughAudioManager&&this.isAudioEnded)})),this.audioManager.onBufferLow((e=>{this.audioBuffer.length>0&&(this.audioBuffer.length,this.isAppendingAudio||(this.isAppendingAudio=!0,this.appendAudio().finally((()=>{this.isAppendingAudio=!1}))))}))}checkStartPlay(){if(this.isPlaying)return!1;if(this.isInited)return!0;const e=this.useAudioOffsetSync?this.timedBlendShapes.length:this.blendShapes.length,t=this.audioBuffer.length;if(this.quickStartMode){return!(t<1)}if(this.useAudioOffsetSync){const i=this.externalAudioTimeProvider?0:Wu,n=this.externalAudioTimeProvider?ju:Gu;return!(t<i||e<n)}return!(t<Wu||e<Uu)}startIntervalFPS(e){let t=performance.now();const i=()=>{const n=performance.now()-t,r=Math.floor(1e3/this.actualFps)-1;t+=r,this.timerId=setTimeout(i,Math.max(0,r-n));try{e(this.time)}catch(e){console.error(e)}};i()}addShapes(e,t){if(!this.isDestroyed&&(void 0!==t?(this.useAudioOffsetSync=!0,e.forEach((e=>{0!==e.length&&(0===this.totalBlendShapesReceived&&(this.firstAudioOffset=t),this.timedBlendShapes.push({audioOffset:t,blendShape:e}),this.playInfo.shapes.push(e),this.totalBlendShapesReceived++,this.lastShapeReceivedAt=performance.now(),this.hasReceivedRealShape||(this.hasReceivedRealShape=!0,this.usingDefaultShape&&(this.defaultShapeFrameCount,this.usingDefaultShape=!1)))})),this.isTransitioningToIdle&&(this.isTransitioningToIdle=!1,this.transitionProgress=0)):e.forEach((e=>{this.blendShapes.push(e),0!==e.length&&(this.playInfo.shapes.push(e),this.totalBlendShapesReceived++)})),this.checkStartPlay()&&!this.isIntervalStarted)){this.planBDelayTimer&&(clearTimeout(this.planBDelayTimer),this.planBDelayTimer=null),this.isIntervalStarted=!0,this.playbackStartTime=performance.now(),this.emit("bs-startplay");this.useAudioOffsetSync?this.timedBlendShapes.length:this.blendShapes.length;this.audioBuffer.length,this.useAudioOffsetSync,this.useAudioOffsetSync,this.startIntervalFPS((()=>{this.play()}))}}addBinaryAudio(e){if(!this.isDestroyed){if(this.isAudioEnded&&this.isInited){const e=Date.now()-this.audioStreamEndedTime;if(e<qu.DELAYED_PACKET_THRESHOLD_MS)return;this.autoResetForNewTTS()}if(this.isFirstAudioDataReceived||(this.firstAudioDataTime=performance.now(),this.isFirstAudioDataReceived=!0,this.firstAudioDataTime),this.audioBuffer.push(e),this.totalAudioBytesReceived+=e.byteLength,this.totalAudioBytesReceived===e.byteLength&&(this.useAudioOffsetSync?this.timedBlendShapes.length:this.blendShapes.length,e.byteLength,this.useAudioOffsetSync),this.playAudioThroughAudioManager&&this.isPlaying&&this.unreadAudioCount>0&&(this.isAppendingAudio||(this.isAppendingAudio=!0,this.appendAudio().finally((()=>{this.isAppendingAudio=!1})))),this.waitingForAudio&&this.unreadAudioCount>=zu&&this.unreadAudioCount,this.checkStartPlay()&&!this.isIntervalStarted&&!this.planBDelayTimer){if(this.timedBlendShapes.length>0)return void this.startPlaybackPlanA("audio-arrival");if(this.quickStartMode)return void this.startPlaybackPlanB();this.audioBuffer.length,this.planBDelayTimer=setTimeout((()=>{this.planBDelayTimer=null,this.timedBlendShapes.length>0?this.startPlaybackPlanA("delayed"):this.isIntervalStarted||this.startPlaybackPlanB()}),qu.PLAN_B_DELAY_MS)}}}startPlaybackPlanA(e){if(this.isIntervalStarted)return;this.isIntervalStarted=!0,this.playbackStartTime=performance.now(),this.useAudioOffsetSync=!0,this.emit("bs-startplay");this.timedBlendShapes.length;this.audioBuffer.length,this.hasReceivedRealShape,this.startIntervalFPS((()=>{this.play()}))}startPlaybackPlanB(){this.isIntervalStarted||(this.isIntervalStarted=!0,this.playbackStartTime=performance.now(),this.useAudioOffsetSync=!0,this.audioManager.setFirstPlaybackBuffer(400),this.emit("bs-startplay"),this.audioBuffer.length,this.timedBlendShapes.length,this.hasReceivedRealShape,this.startIntervalFPS((()=>{this.play()})))}markAudioStreamEnded(){this.isAudioEnded=!0,this.audioStreamEndedTime=Date.now(),this.audioManager.notifyStreamEnded();const e=this.playInfo.rate,t=this.totalAudioBytesReceived/(2*e);if(t>0&&this.totalBlendShapesReceived>0){const e=this.totalBlendShapesReceived/t;this.actualFps=Math.max(15,Math.min(120,e)),this.totalAudioBytesReceived,t.toFixed(2),this.totalBlendShapesReceived,e.toFixed(1),this.actualFps.toFixed(1),this.blendShapes.length}}resetSyncState(){this.isAudioEnded=!1,this.audioStreamEndedTime=0,this.audioPlaybackStartTime=0,this.isAudioPlaybackStarted=!1,this.playbackStartTime=0,this.firstAudioDataTime=0,this.isFirstAudioDataReceived=!1,this.firstAudioOffset=0,this.lastPlayedOffset=-1,this.useAudioOffsetSync=!1,this.totalAudioBytesReceived=0,this.totalBlendShapesReceived=0,this.totalWaitTime=0,this.waitStartTime=0,this.lastRebaseAt=0,this.hasReceivedRealShape=!1,this.usingDefaultShape=!1,this.defaultShapeFrameCount=0}async clear(){const e=this.isPlaying,t=this.lastBlendShapeLength>0;if(this.isPlaying=!1,this.isIntervalStarted=!1,this.blendShapes=[],this.audioBuffer=[],this.audioBufferReadIndex=0,this.idx=0,this.isInited=!1,this.waitingForAudio=!1,this.isAppendingAudio=!1,this.lastShapeReceivedAt=0,this.resetSyncState(),this.actualFps=this.fps,this.framesPlayedSinceStart=0,this.timedBlendShapes=[],this.isTransitioningToIdle=!1,this.transitionProgress=0,this.externalAudioTimeProvider=null,this.playInfo={shapes:[],audios:[],duration:0,rate:16e3,content:""},this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.planBDelayTimer&&(clearTimeout(this.planBDelayTimer),this.planBDelayTimer=null),await this.audioManager.stopPlayback(),await this.audioManager.clearBuffer(),t){const e=new Array(this.lastBlendShapeLength).fill(0);this.playShapeFn(e,this.idx++)}this.lastBlendShapeLength=0,this.lastBlendShape=[],e&&this.emit("playend")}async appendAudio(){let e=0;for(;this.audioBufferReadIndex<this.audioBuffer.length&&e<10;){const t=this.audioBuffer[this.audioBufferReadIndex++];await this.audioManager.appendAudio(t),e++}if(this.audioBufferReadIndex>=qu.AUDIO_BUFFER_CLEANUP_THRESHOLD){const e=this.audioBufferReadIndex;"undefined"!=typeof requestIdleCallback?requestIdleCallback((()=>{this.audioBufferReadIndex>=e&&(this.audioBuffer=this.audioBuffer.slice(e),this.audioBufferReadIndex-=e)}),{timeout:100}):setTimeout((()=>{this.audioBufferReadIndex>=e&&(this.audioBuffer=this.audioBuffer.slice(e),this.audioBufferReadIndex-=e)}),0)}this.unreadAudioCount>0&&setTimeout((()=>{this.isAppendingAudio||(this.isAppendingAudio=!0,this.appendAudio().finally((()=>{this.isAppendingAudio=!1})))}),0)}async play(){if(this.isPlaying=!0,this.isTransitioningToIdle)return void this.playTransitionFrame();const e=this.useAudioOffsetSync?this.timedBlendShapes.length:this.blendShapes.length;if(0===e){if(!this.useAudioOffsetSync||this.isAudioEnded){if(this.useAudioOffsetSync&&this.isAudioEnded){const e=performance.now();if(this.lastShapeReceivedAt>0&&e-this.lastShapeReceivedAt<qu.END_GRACE_MS)return;return void this.finishPlayback()}return void this.finishPlayback()}!this.usingDefaultShape&&this.isInited&&(this.usingDefaultShape=!0,this.hasReceivedRealShape&&this.lastBlendShape.length),this.usingDefaultShape&&(this.defaultShapeFrameCount++,this.hasReceivedRealShape&&this.lastBlendShape.length>0?this.playShapeFn([...this.lastBlendShape],this.idx++):(this.playShapeFn([...Vu],this.idx++),this.lastBlendShapeLength=Vu.length))}if(0===this.unreadAudioCount&&!this.isAudioEnded&&this.isInited)if(this.playAudioThroughAudioManager)this.waitingForAudio=!1;else{if(!this.useAudioOffsetSync)return void(this.waitingForAudio||(this.isAudioEnded,this.waitingForAudio=!0,this.waitStartTime=performance.now()));if(this.externalAudioTimeProvider)this.waitingForAudio=!1;else{this.waitingForAudio||(this.waitingForAudio=!0,this.waitStartTime=performance.now());const e=performance.now()-this.waitStartTime,t=Hu;if(e<t)return;e<t+50&&e.toFixed(0)}}if(this.waitingForAudio){const e=zu;if(!(this.unreadAudioCount>=e||this.isAudioEnded))return;{const e=performance.now()-this.waitStartTime;this.playAudioThroughAudioManager||(this.totalWaitTime+=e),e.toFixed(0),this.totalWaitTime.toFixed(0),this.audioBuffer.length,this.playAudioThroughAudioManager,this.waitingForAudio=!1}}const t=this.isInited;this.isInited=!0;if(this.audioBufferReadIndex<this.audioBuffer.length&&(!this.externalAudioTimeProvider||this.playAudioThroughAudioManager)){if(!t){const e=this.audioBuffer[this.audioBufferReadIndex++];await this.audioManager.playAudio(e),this.emit("playstart")}this.isAppendingAudio||(this.isAppendingAudio=!0,this.appendAudio().finally((()=>{this.isAppendingAudio=!1})))}if(this.useAudioOffsetSync)this.playTimedBlendShape();else for(;this.blendShapes.length>0;){const[e]=this.blendShapes.splice(0,1);if(!e||1!==e.length){e&&(this.lastBlendShapeLength=e.length,this.lastBlendShape=[...e],this.playShapeFn(e,this.idx++));break}this.invokeCallback(e[0].toString())}}startMouthCloseTransition(){return this.finishPlayback(),0}findAndPlayFrame(e,t,i){let n=null,r=0;for(let t=0;t<this.timedBlendShapes.length;t++){const i=this.timedBlendShapes[t];if(!(i.audioOffset<=e))break;n=i,r=t+1}n&&n.audioOffset!==this.lastPlayedOffset&&(this.idx%30==0&&(e.toFixed(0),n.audioOffset,this.timedBlendShapes.length,this.idx),this.lastPlayedOffset=n.audioOffset,this.lastBlendShapeLength=n.blendShape.length,this.lastBlendShape=[...n.blendShape],this.playShapeFn(n.blendShape,this.idx++),this.lastTimedFrameAt=performance.now(),r>0&&this.timedBlendShapes.splice(0,r))}playTimedBlendShape(){if(0===this.timedBlendShapes.length)return;const e=this.externalAudioTimeProvider?this.externalAudioTimeProvider():NaN;if(!Number.isNaN(e)){let t=this.firstAudioOffset+e;this.isAudioEnded&&this.timedBlendShapes.length>0&&(t=this.timedBlendShapes[this.timedBlendShapes.length-1].audioOffset);const i=this.timedBlendShapes.find((e=>e.audioOffset<=t));if(i){const n=e-(i.audioOffset-this.firstAudioOffset),r=performance.now();Math.abs(n)>qu.MAX_SYNC_DRIFT_MS&&r-this.lastRebaseAt>qu.REBASE_COOLDOWN_MS&&(this.firstAudioOffset=i.audioOffset-e,this.lastRebaseAt=r,n.toFixed(0),this.firstAudioOffset.toFixed(0),t=this.firstAudioOffset+e)}return void this.findAndPlayFrame(t,"external clock",{audioTimeMs:e.toFixed(0)+"ms"})}let t;if(this.isAudioPlaybackStarted)t=this.audioPlaybackStartTime;else if(this.playAudioThroughAudioManager)t=this.playbackStartTime;else if(this.isFirstAudioDataReceived){const e=150;t=this.firstAudioDataTime+e}else t=this.playbackStartTime;const i=this.playAudioThroughAudioManager?performance.now()-t:performance.now()-t-this.totalWaitTime,n=this.firstAudioOffset+i;this.findAndPlayFrame(n,"internal clock",{elapsed:i.toFixed(0)+"ms",totalWaitTime:this.totalWaitTime.toFixed(0)+"ms"})}playTransitionFrame(){this.transitionProgress++;const e=Math.min(this.transitionProgress/qu.TRANSITION_FRAMES,1),t=1-(1-e)*(1-e),i=this.lastBlendShape.map((e=>e*(1-t)));(1===this.transitionProgress||e>=1)&&((100*e).toFixed(0),(100*t).toFixed(0),this.transitionProgress),this.playShapeFn(i,this.idx++),e>=1&&(this.isTransitioningToIdle=!1,this.transitionProgress=0,this.finishPlayback())}finishPlayback(){if(this.isPlaying=!1,this.isIntervalStarted=!1,this.quickStartMode=!1,this.lastBlendShapeLength>0){const e=new Array(this.lastBlendShapeLength).fill(0);this.lastBlendShape=[...e],this.playShapeFn(e,this.idx++)}this.emit("playend"),this.timerId&&(clearTimeout(this.timerId),this.timerId=null)}getPlayInfo(){const e=Math.ceil(this.playInfo.shapes.length/this.fps*1e3);return this.playInfo.duration=e,this.playInfo}async setAudioRate(e){this.playInfo.rate=e,await this.audioManager.setRate(e)}setExternalAudioTimeProvider(e){this.externalAudioTimeProvider=e}setPlayAudioThroughAudioManager(e){this.playAudioThroughAudioManager=e}async setAudioMuted(e){this.isAudioMuted=e,await this.audioManager.setMuted(e)}duckAudio(e,t){this.audioManager.duckOutput(e,t)}async enableAudio(){await this.audioManager.enableAudio()}autoResetForNewTTS(){this.resetSyncState(),this.playbackStartTime=performance.now(),this.timedBlendShapes=[],this.audioManager.resetJitterBuffer(),this.audioManager.notifyStreamStarted()}prepareForNewTTS(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];const t=this.isPlaying,i=this.isIntervalStarted;this.quickStartMode=e,this.isInited,this.isAudioEnded,this.audioBuffer.length,this.useAudioOffsetSync?this.timedBlendShapes.length:this.blendShapes.length,this.isPlaying=!1,this.isIntervalStarted=!1,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.planBDelayTimer&&(clearTimeout(this.planBDelayTimer),this.planBDelayTimer=null),this.blendShapes=[],this.audioBuffer=[],this.audioBufferReadIndex=0,this.timedBlendShapes=[],this.idx=0,this.isInited=!1,this.waitingForAudio=!1,this.isAppendingAudio=!1,this.lastShapeReceivedAt=0,this.resetSyncState(),this.actualFps=this.fps,this.framesPlayedSinceStart=0,this.isTransitioningToIdle=!1,this.transitionProgress=0,this.playInfo={shapes:[],audios:[],duration:0,rate:this.playInfo.rate,content:""},this.lastBlendShapeLength=0,this.lastBlendShape=[],(t||i)&&(this.audioManager.stopPlayback(),this.audioManager.clearBuffer()),this.audioManager.resetJitterBuffer(),this.audioManager.setFirstPlaybackBuffer(0),this.audioManager.notifyStreamStarted()}getPlayingStatus(){return this.isPlaying}getBlendShapes(){return this.useAudioOffsetSync?this.timedBlendShapes.map((e=>e.blendShape)):this.blendShapes}registerCallback(e,t){this.callbackMap.set(`${e}`,t),this.blendShapes.push([e])}invokeCallback(e){const t=this.callbackMap.get(e);if(t){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];t(...n),this.callbackMap.delete(e)}}async destroy(){this.isDestroyed||(this.isDestroyed=!0,await this.clear(),await this.audioManager.dispose(),this.callbackMap.clear(),this.clearListeners())}}var Yu,Ku=new class{events=new Map;on(e,t){this.events.set(e,[...this.events.get(e)||[],t])}off(e,t){t?this.events.set(e,(this.events.get(e)||[]).filter((e=>e!==t))):this.events.delete(e)}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];(this.events.get(e)||[]).forEach((e=>e(...i)))}};!function(e){e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.SOCKET_OPEN="socket_open",e.AUTHENTICATED="authenticated",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed"}(Yu||(Yu={}));class Xu{static IOS_AUDIO_MODES=["baseline","aec","aec_full"];config;ws=null;state=Yu.DISCONNECTED;reconnectAttempts=0;reconnectTimer=null;heartbeatTimer=null;heartbeatPongTimer=null;isDestroyed=!1;updateTokenWarnedOnce=!1;connectInFlight=null;lastStateSyncFrame="";lastVoiceInteractionConfigFrame="";authenticationCount=0;_sessionId="";get sessionId(){return this._sessionId}llmCallback=null;ttsCallback=null;asrCallback=null;serverPushTTSCallback=null;webrtcSDPCallback=null;webrtcICECallback=null;currentTTSSampleRate=16e3;peerConnection=null;dataChannel=null;remoteAudioElement=null;isWebRTCReady=!1;localAudioTrack=null;webrtcReconnectAttempts=0;webrtcReconnectTimer=null;webrtcASRCallback=null;isWebRTCReconnecting=!1;isCreatingWebRTC=!1;static WEBRTC_MAX_RECONNECT_ATTEMPTS=3;static WEBRTC_RECONNECT_INTERVAL=3e3;webrtcStatsTimer=null;lastInboundStats=null;ttsDataChannelCallback=null;vadAudioContext=null;vadAnalyser=null;vadSourceNode=null;vadDetectionTimer=null;vadCallback=null;vadEnabled=!1;vadEnergyHistory=[];vadConsecutiveSpikes=0;vadWarmupComplete=!1;audioLevelCallback=null;audioLevelTimer=null;static AUDIO_LEVEL_INTERVAL=60;static VAD_DETECTION_INTERVAL=50;static VAD_WINDOW_SIZE=30;static VAD_SPIKE_THRESHOLD=4;static VAD_MIN_ABSOLUTE_RMS=10;static VAD_CONSECUTIVE_SPIKES_REQUIRED=2;static VAD_MIN_WARMUP_SAMPLES=12;static VAD_WARMUP_STABILITY_THRESHOLD=6;ttsDumpEnabled=!1;ttsDumpActive=!1;ttsDumpSampleRate=null;ttsDumpChunks=[];ttsDumpTotalBytes=0;ttsDumpSeq=0;ttsDumpFinalizeTimer=null;ttsDumpLastUrl=null;ttsDumpLastFilename=null;constructor(e){if(this.config={url:e.url,token:e.token,audioProfile:e.audioProfile??"asr_priority",iosAudioMode:e.iosAudioMode??"baseline",autoReconnect:!1!==e.autoReconnect,reconnectInterval:e.reconnectInterval||3e3,maxReconnectAttempts:e.maxReconnectAttempts||5,heartbeatInterval:e.heartbeatInterval||3e4,connectTimeout:e.connectTimeout??1e4,iceServers:e.iceServers||[],authMethod:e.authMethod??"url"},"undefined"!=typeof window){const e=new URLSearchParams(window.location.search);this.ttsDumpEnabled="1"===e.get("dumpTTS")||"1"===window.localStorage.getItem("dumpTTS"),this.ttsDumpEnabled}}resolveIOSAudioMode(){if(Xu.IOS_AUDIO_MODES.includes(this.config.iosAudioMode))return this.config.iosAudioMode;if("undefined"!=typeof window){const e=new URLSearchParams(window.location.search).get("iosAudio");if(e&&Xu.IOS_AUDIO_MODES.includes(e))return e;const t=window.__QT_IOS_AUDIO_MODE__;if("string"==typeof t&&Xu.IOS_AUDIO_MODES.includes(t))return t}return"baseline"}buildIOSAudioConstraints(e){switch(e){case"aec":return{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!1,channelCount:1,sampleRate:16e3};case"aec_full":return{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,sampleRate:16e3};default:return{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,channelCount:1,sampleRate:16e3}}}async connect(){if(this.isConnected()||this.state===Yu.CONNECTING)return console.warn("[GatewayService] Already connected or connecting"),this.connectInFlight?this.connectInFlight:void 0;this.setState(Yu.CONNECTING);const e=new Promise(((e,t)=>{const i=this.config.connectTimeout??1e4;let n=null,r=!1;const s=e=>{r||(r=!0,n&&(clearTimeout(n),n=null),e())};n=setTimeout((()=>{s((()=>{console.error("[GatewayService] Connection timeout"),this.ws?.close(),this.setState(Yu.DISCONNECTED),t(new Error("WebSocket connection timeout"))}))}),i);try{const i=this.buildWebSocketUrl();this.ws=new WebSocket(i),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{this.reconnectAttempts=0,this.setState(Yu.SOCKET_OPEN),this.startHeartbeat(),this.sendLogin().then((()=>{this.setState(Yu.AUTHENTICATED),this.authenticationCount++,this.authenticationCount>1&&this.replaySessionDirectives(),Ku.emit(ds.GATEWAY_CONNECTED),s((()=>e()))})).catch((e=>{console.error("[GatewayService] login failed:",e),this.stopHeartbeat(),this.ws?.close(),this.setState(Yu.DISCONNECTED),s((()=>t(e)))}))},this.ws.onmessage=e=>{this.handleMessage(e)};const n=this.ws;this.ws.onerror=e=>{this.ws===n?(console.error("[GatewayService] Connection error:",{error:e,readyState:this.ws?.readyState,url:this.ws?.url}),Ku.emit(ds.GATEWAY_ERROR,{code:"CONNECTION_ERROR",msg:"WebSocket connection error",details:e}),s((()=>t(e)))):console.warn("[GatewayService] ignoring stale onerror from superseded socket")},this.ws.onclose=e=>{this.ws===n?(console.warn("[GatewayService] Connection closed:",{code:e.code,reason:e.reason,wasClean:e.wasClean,readyState:this.ws?.readyState,url:this.ws?.url}),this.handleClose()):console.warn("[GatewayService] ignoring stale onclose from superseded socket",{code:e.code,reason:e.reason})}}catch(e){console.error("[GatewayService] Failed to create WebSocket:",e),this.setState(Yu.DISCONNECTED),Ku.emit(ds.GATEWAY_ERROR,{code:"CREATE_WEBSOCKET_ERROR",msg:"Failed to create WebSocket",details:e}),s((()=>t(e)))}}));return this.connectInFlight=e.finally((()=>{this.connectInFlight===e&&(this.connectInFlight=null)})),this.connectInFlight}disconnect(){this.isDestroyed=!0,this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(),this.ws=null),this.setState(Yu.CLOSED),Ku.emit(ds.GATEWAY_DISCONNECTED)}async reconnect(){if(!this.isDestroyed){if(this.reconnectAttempts>=this.config.maxReconnectAttempts)return console.error("[GatewayService] Max reconnect attempts reached"),Ku.emit(ds.GATEWAY_ERROR,{code:"MAX_RECONNECT_ATTEMPTS",msg:"Max reconnect attempts reached",details:{attempts:this.reconnectAttempts}}),void this.handleError(new Error("Max reconnect attempts reached"));this.reconnectAttempts++,this.setState(Yu.RECONNECTING),Ku.emit(ds.GATEWAY_RECONNECTING),this.reconnectAttempts,this.config.maxReconnectAttempts;try{await this.connect()}catch(e){console.error("[GatewayService] Reconnect failed:",e),this.scheduleReconnect()}}}async sendLLMChat(e,t){if(!this.isConnected())throw new Error("WebSocket is not connected");const i={query:e.query,inputs:{character_id:e.inputs.character_id,chat_id:e.inputs.chat_id||"",tts_enabled:!1!==e.inputs.tts_enabled,a2f_enabled:!1!==e.inputs.a2f_enabled,chunk_type:e.inputs.chunk_type||"stream_sentence",use_webrtc_tts:e.inputs.use_webrtc_tts||!1}};if(this.llmCallback)try{this.llmCallback({type:"end",data:"Request superseded by new request"})}catch(e){}this.llmCallback=t||null;const n="1001"+JSON.stringify(i);this.ws.send(n)}sendToolAction(e,t,i){if(!this.isConnected())return void console.warn("[GatewayService] Cannot send tool action: not connected");const n=JSON.stringify({tool:e,action:t,data:i});this.ws.send("1041"+n)}async sendTTS(e,t){if(!this.isConnected())throw new Error("WebSocket is not connected");const i={...e,a2f_enabled:!1!==e.a2f_enabled};if(this.ttsCallback)try{this.ttsCallback({type:"end",data:"Request superseded by new request"})}catch(e){}this.ttsCallback=t||null;const n="1002"+JSON.stringify(i);this.ws.send(n)}sendTextToAudio(e,t,i){if(!this.isConnected())return void console.warn("[GatewayService] sendTextToAudio: WebSocket not connected");const n={character_id:t,text:e,use_webrtc_tts:i?.useWebRTCTTS??!0,a2f_enabled:i?.a2fEnabled??!0,synthetic:!0},r="1002"+JSON.stringify(n);this.ws.send(r)}setServerPushTTSCallback(e){this.serverPushTTSCallback=e}clearTTSCallback(){this.ttsCallback&&(this.ttsCallback=null)}async sendASRSync(e,t){if(!this.isConnected())throw new Error("WebSocket is not connected");t&&(this.asrCallback=t);const i=(new TextEncoder).encode("1003"),n=new Uint8Array(i.length+e.byteLength);n.set(i,0),n.set(new Uint8Array(e),i.length),this.ws.send(n.buffer),e.byteLength}async sendASRAudio(e,t){if(!this.isConnected())throw new Error("WebSocket is not connected");t&&(this.asrCallback=t);const i=(new TextEncoder).encode("1018"),n=new Uint8Array(i.length+e.byteLength);n.set(i,0),n.set(new Uint8Array(e),i.length),this.ws.send(n.buffer),e.byteLength}async stopASR(){if(!this.isConnected())throw new Error("WebSocket is not connected");this.ws.send("1019")}async sendWebRTCSDP(e,t){if(!this.isConnected())throw new Error("WebSocket is not connected");t&&(this.webrtcSDPCallback=t);const i="1021"+JSON.stringify(e);this.ws.send(i),e.type,e.sdp.length,e.sdp.substring(0,200)}async sendWebRTCICE(e){if(!this.isConnected())throw new Error("WebSocket is not connected");const t={type:"candidate",candidate:e.candidate,sdpMid:e.sdpMid,sdpMLineIndex:e.sdpMLineIndex};e.usernameFragment&&(t.usernameFragment=e.usernameFragment);const i="1023"+JSON.stringify(t);this.ws.send(i),e.candidate.substring(0,80),e.sdpMid,e.sdpMLineIndex}async createWebRTCConnection(e){if(!this.isConnected())throw new Error("WebSocket is not connected");if(this.isCreatingWebRTC){for(console.warn("[GatewayService] WebRTC 连接正在创建中,忽略重复请求");this.isCreatingWebRTC;)await new Promise((e=>setTimeout(e,100)));if(this.peerConnection)return this.peerConnection;throw new Error("WebRTC connection creation failed")}this.isCreatingWebRTC=!0,e&&(this.asrCallback=e,this.webrtcASRCallback=e);let t=[];if(this.config.iceServers&&this.config.iceServers.length>0)t=this.config.iceServers;else{let e="",i="",n="";try{e=process.env.ROLLUP_TURN_URL||"",i=process.env.ROLLUP_TURN_USERNAME||"",n=process.env.ROLLUP_TURN_CREDENTIAL||""}catch{console.warn("[GatewayService] ROLLUP_TURN_* 未注入,使用 STUN-only ICE 配置")}e&&i&&n&&t.push({urls:e,username:i,credential:n}),t.push({urls:"stun:stun.l.google.com:19302"})}const i={iceServers:t};let n;try{n=new RTCPeerConnection(i)}catch(e){throw this.isCreatingWebRTC=!1,e}this.peerConnection=n,this.peerConnection.onicecandidate=e=>{e.candidate&&(e.candidate.candidate,e.candidate.sdpMid,e.candidate.sdpMLineIndex,this.sendWebRTCICE({candidate:e.candidate.candidate,sdpMid:e.candidate.sdpMid||"",sdpMLineIndex:e.candidate.sdpMLineIndex||0,usernameFragment:e.candidate.usernameFragment||void 0}))},this.peerConnection.onconnectionstatechange=()=>{const e=this.peerConnection?.connectionState;switch(e){case"new":case"connecting":break;case"connected":this.webrtcReconnectAttempts=0,this.isWebRTCReconnecting=!1,this.startWebRTCStatsMonitoring();break;case"disconnected":this.stopWebRTCStatsMonitoring(),this.isWebRTCReconnecting=!1,this.attemptWebRTCReconnect();break;case"failed":console.error("[GatewayService] ❌ WebRTC 连接失败"),this.stopWebRTCStatsMonitoring(),Ku.emit(ds.GATEWAY_ERROR,{code:"WEBRTC_CONNECTION_FAILED",msg:"WebRTC connection failed",details:null}),this.isWebRTCReconnecting=!1,this.attemptWebRTCReconnect();break;case"closed":this.stopWebRTCStatsMonitoring()}},this.peerConnection.oniceconnectionstatechange=()=>{const e=this.peerConnection?.iceConnectionState;switch(e){case"new":case"checking":case"connected":case"completed":case"disconnected":case"closed":break;case"failed":console.error("[GatewayService] ❌ ICE 连接失败")}},this.peerConnection.onicegatheringstatechange=()=>{this.peerConnection},this.peerConnection.onsignalingstatechange=()=>{this.peerConnection},this.dataChannel=this.peerConnection.createDataChannel("tts-audio",{ordered:!0,negotiated:!0,id:0}),this.dataChannel.binaryType="arraybuffer",this.dataChannel.onopen=()=>{this.dataChannel},this.dataChannel.onclose=()=>{},this.dataChannel.onerror=e=>{console.error("[GatewayService] ❌ TTS DataChannel 错误:",e)},this.dataChannel.onmessage=e=>{e.data instanceof ArrayBuffer?(e.data.byteLength,this.ttsDumpEnabled&&(this.ttsDumpActive||this.startTtsDump(this.currentTTSSampleRate),this.appendTtsDump(e.data)),this.ttsDataChannelCallback?this.ttsDataChannelCallback(e.data):console.warn("[GatewayService] ⚠️ DataChannel 收到数据但 ttsDataChannelCallback 未设置")):e.data},this.peerConnection.ontrack=e=>{if(e.track.kind,e.track.id,e.track.label,"audio"===e.track.kind&&e.streams.length>0){this.remoteAudioElement||(this.remoteAudioElement=document.createElement("audio"),this.remoteAudioElement.id="webrtc-remote-audio",this.remoteAudioElement.autoplay=!0,this.remoteAudioElement.muted=!0,this.remoteAudioElement.volume=0,this.remoteAudioElement.style.display="none",document.body.appendChild(this.remoteAudioElement)),this.remoteAudioElement.srcObject=e.streams[0];const t=e.streams[0].getAudioTracks()[0];if(t){t.getSettings()}this.remoteAudioElement.onplay=()=>{Ku.emit(ds.AUDIO_PLAY,{source:"webrtc"})},this.remoteAudioElement.onpause=()=>{Ku.emit(ds.AUDIO_PAUSE,{source:"webrtc"})},this.remoteAudioElement.onended=()=>{},this.remoteAudioElement.onerror=e=>{console.error("[GatewayService] ❌ 远程 TTS 音频播放错误:",e)},this.remoteAudioElement.play().catch((e=>{console.warn("[GatewayService] 自动播放被阻止,需要用户交互:",e)}))}};try{const e=/iPhone|iPad|iPod/.test(navigator.userAgent)||"MacIntel"===navigator.platform&&navigator.maxTouchPoints>1,t=this.resolveIOSAudioMode(),i=e?this.buildIOSAudioConstraints(t):{echoCancellation:!0,noiseSuppression:!0,autoGainControl:"standard"===this.config.audioProfile,channelCount:1,sampleRate:16e3,googEchoCancellation:!0,googAutoGainControl:"standard"===this.config.audioProfile,googNoiseSuppression:!0,googHighpassFilter:!0,googExperimentalNoiseSuppression:!0,googExperimentalEchoCancellation:!0};e||this.config.audioProfile;const n=await navigator.mediaDevices.getUserMedia({audio:i});n.getAudioTracks().length,this.setupVAD(n),n.getTracks().forEach((e=>{this.peerConnection.addTrack(e,n);"audio"===e.kind&&(this.localAudioTrack=e,e.onended=()=>{console.error("[GatewayService] ❌ 麦克风轨道被关闭 (onended)"),console.error("[GatewayService] 轨道状态:",e.readyState,"| enabled:",e.enabled),Ku.emit(ds.GATEWAY_ERROR,{code:"MICROPHONE_ENDED",msg:"麦克风被关闭,可能是浏览器音频会话冲突",details:{readyState:e.readyState,enabled:e.enabled}})},e.onmute=()=>{console.warn("[GatewayService] ⚠️ 麦克风轨道被静音 (onmute)"),console.warn("[GatewayService] 轨道状态:",e.readyState,"| enabled:",e.enabled)},e.onunmute=()=>{}),e.label,e.getSettings()}))}catch(e){throw console.error("[GatewayService] ❌ 获取麦克风失败:",e),this.isCreatingWebRTC=!1,new Error("Failed to access microphone")}try{const e=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(e),e.sdp,await this.sendWebRTCSDP({type:"offer",sdp:e.sdp||""},(async e=>{if(e.type,e.sdp.length,"answer"===e.type&&this.peerConnection){const t=new RTCSessionDescription({type:"answer",sdp:e.sdp});await this.peerConnection.setRemoteDescription(t)}}))}finally{this.isCreatingWebRTC=!1}return this.peerConnection}closeWebRTCConnection(){this.isConnected()&&this.sendWebRTCClose(),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null),this.remoteAudioElement&&(this.remoteAudioElement.srcObject=null,this.remoteAudioElement.parentNode&&this.remoteAudioElement.parentNode.removeChild(this.remoteAudioElement),this.remoteAudioElement=null),this.cleanupVAD(),this.isWebRTCReady=!1,this.localAudioTrack=null,this.isCreatingWebRTC=!1,this.webrtcReconnectTimer&&(clearTimeout(this.webrtcReconnectTimer),this.webrtcReconnectTimer=null),this.webrtcReconnectAttempts=0,this.isWebRTCReconnecting=!1}async attemptWebRTCReconnect(){if(!this.isWebRTCReconnecting)return this.webrtcReconnectAttempts>=Xu.WEBRTC_MAX_RECONNECT_ATTEMPTS?(console.error("[GatewayService] ❌ WebRTC 重连次数已达上限,停止重连"),void Ku.emit(ds.GATEWAY_ERROR,{code:"WEBRTC_RECONNECT_FAILED",msg:"WebRTC reconnection failed after max attempts",details:{attempts:this.webrtcReconnectAttempts}})):void(this.webrtcASRCallback&&this.isConnected()&&(this.isWebRTCReconnecting=!0,this.webrtcReconnectAttempts++,this.webrtcReconnectAttempts,Xu.WEBRTC_MAX_RECONNECT_ATTEMPTS,this.webrtcReconnectTimer=setTimeout((async()=>{try{this.isConnected()&&await this.sendWebRTCClose(),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.peerConnection&&(this.peerConnection.close(),this.peerConnection=null),this.remoteAudioElement&&(this.remoteAudioElement.srcObject=null),this.isWebRTCReady=!1,await new Promise((e=>setTimeout(e,200))),await this.createWebRTCConnection(this.webrtcASRCallback),Ku.emit(ds.VOICE_INTERACTION_WEBRTC_STATE,{state:"reconnected",attempts:this.webrtcReconnectAttempts})}catch(e){console.error("[GatewayService] ❌ WebRTC 重连失败:",e),this.isWebRTCReconnecting=!1,this.attemptWebRTCReconnect()}}),Xu.WEBRTC_RECONNECT_INTERVAL)))}_muteRefCount=0;muteLocalAudio(){this._muteRefCount++,this._muteRefCount,this.localAudioTrack&&1===this._muteRefCount&&(this.localAudioTrack.enabled=!1)}unmuteLocalAudio(){this._muteRefCount=Math.max(0,this._muteRefCount-1),this._muteRefCount,0===this._muteRefCount&&(this.localAudioTrack?(this.localAudioTrack.enabled,this.localAudioTrack.muted,this.localAudioTrack.readyState,Date.now(),this.localAudioTrack.enabled=!0):console.warn("[GatewayService] ⚠️ unmuteLocalAudio: localAudioTrack 不存在!"))}forceUnmuteLocalAudio(){this._muteRefCount=0,this.localAudioTrack&&(this.localAudioTrack.enabled=!0)}isLocalAudioMuted(){return!this.localAudioTrack||!this.localAudioTrack.enabled}setupVAD(e){try{this.vadAudioContext=new AudioContext({sampleRate:16e3}),this.vadAnalyser=this.vadAudioContext.createAnalyser(),this.vadAnalyser.fftSize=256,this.vadAnalyser.smoothingTimeConstant=.3,this.vadSourceNode=this.vadAudioContext.createMediaStreamSource(e),this.vadSourceNode.connect(this.vadAnalyser)}catch(e){console.error("[GatewayService] ❌ VAD 设置失败:",e)}}startVADDetection(e){if(!this.vadAnalyser)return void console.warn("[GatewayService] VAD 分析器未初始化");this.vadCallback=e,this.vadEnabled=!0,this.vadEnergyHistory=[],this.vadConsecutiveSpikes=0,this.vadWarmupComplete=!1;const t=new Uint8Array(this.vadAnalyser.fftSize),i=()=>{if(!this.vadEnabled||!this.vadAnalyser)return;this.vadAnalyser.getByteTimeDomainData(t);let e=0;for(let i=0;i<t.length;i++){const n=t[i]-128;e+=n*n}const n=Math.sqrt(e/t.length);if(this.vadEnergyHistory.push(n),this.vadEnergyHistory.length>Xu.VAD_WINDOW_SIZE&&this.vadEnergyHistory.shift(),!this.vadWarmupComplete){if(this.vadEnergyHistory.length<Xu.VAD_MIN_WARMUP_SAMPLES)return this.vadEnergyHistory.length,n.toFixed(2),void(this.vadDetectionTimer=window.setTimeout(i,Xu.VAD_DETECTION_INTERVAL));const e=this.vadEnergyHistory.slice(-5),t=e.reduce(((e,t)=>e+t),0)/e.length,r=e.reduce(((e,i)=>e+Math.pow(i-t,2)),0)/e.length,s=Math.sqrt(r);if(s>Xu.VAD_WARMUP_STABILITY_THRESHOLD)return this.vadEnergyHistory.length,n.toFixed(2),s.toFixed(2),Xu.VAD_WARMUP_STABILITY_THRESHOLD,void(this.vadDetectionTimer=window.setTimeout(i,Xu.VAD_DETECTION_INTERVAL));this.vadWarmupComplete=!0,this.vadEnergyHistory.length,t.toFixed(2),s.toFixed(2)}const r=this.vadEnergyHistory.slice(0,-1),s=r.reduce(((e,t)=>e+t),0)/r.length,a=r.reduce(((e,t)=>e+Math.pow(t-s,2)),0)/r.length,o=Math.sqrt(a),c=Math.max(s+Xu.VAD_SPIKE_THRESHOLD+2*o,Xu.VAD_MIN_ABSOLUTE_RMS),l=n-s;if(n>c&&l>0){if(this.vadConsecutiveSpikes++,n.toFixed(2),s.toFixed(2),o.toFixed(2),l.toFixed(2),c.toFixed(2),this.vadConsecutiveSpikes,this.vadConsecutiveSpikes>=Xu.VAD_CONSECUTIVE_SPIKES_REQUIRED)return this.vadConsecutiveSpikes,this.vadCallback?.(!0,n),void this.stopVADDetection()}else this.vadConsecutiveSpikes,this.vadConsecutiveSpikes=0;this.vadDetectionTimer=window.setTimeout(i,Xu.VAD_DETECTION_INTERVAL)};i()}stopVADDetection(){this.vadDetectionTimer&&(clearTimeout(this.vadDetectionTimer),this.vadDetectionTimer=null),this.vadEnabled=!1,this.vadCallback=null,this.vadEnergyHistory=[],this.vadConsecutiveSpikes=0,this.vadWarmupComplete=!1}startAudioLevelMonitor(e){if(this.stopAudioLevelMonitor(),!this.vadAnalyser)return;this.audioLevelCallback=e;const t=new Uint8Array(this.vadAnalyser.fftSize),i=()=>{if(!this.audioLevelCallback||!this.vadAnalyser)return;this.vadAnalyser.getByteTimeDomainData(t);let e=0;for(let i=0;i<t.length;i++){const n=t[i]-128;e+=n*n}const n=Math.sqrt(e/t.length),r=Math.min(n/50,1);this.audioLevelCallback(r),this.audioLevelTimer=window.setTimeout(i,Xu.AUDIO_LEVEL_INTERVAL)};i()}stopAudioLevelMonitor(){this.audioLevelTimer&&(clearTimeout(this.audioLevelTimer),this.audioLevelTimer=null),this.audioLevelCallback=null}cleanupVAD(){this.stopVADDetection(),this.stopAudioLevelMonitor(),this.vadSourceNode&&(this.vadSourceNode.disconnect(),this.vadSourceNode=null),this.vadAudioContext&&(this.vadAudioContext.close().catch((()=>{})),this.vadAudioContext=null),this.vadAnalyser=null}async sendWebRTCClose(){if(!this.isConnected())return;this.ws.send("1025")}async sendInterrupt(){if(!this.isConnected())throw new Error("WebSocket is not connected");this.ws.send("1004"),this.llmCallback=null,this.ttsCallback=null}sendTTSPlaybackState(e,t){if(!this.isConnected())return void console.warn("[GatewayService] WebSocket is not connected, skip sendTTSPlaybackState");const i="1026"+JSON.stringify(t?{event:e,context:t}:{event:e});this.ws.send(i)}sendStateSync(e){if(!this.isConnected())return void console.warn("[GatewayService] WebSocket is not connected, skip sendStateSync");const t="1030"+JSON.stringify({state:e});this.lastStateSyncFrame=t,this.ws.send(t)}sendVoiceInteractionConfig(e){if(!this.isConnected())return void console.warn("[GatewayService] Not connected, skip sendVoiceInteractionConfig");const t="1031"+JSON.stringify({wake_words:e.wakeWords,synthetic_texts:e.syntheticTexts??[],voice_engine:e.voiceEngine||"pipeline",character_id:e.characterId||""});this.lastVoiceInteractionConfigFrame=t,this.ws.send(t),e.wakeWords.length,e.syntheticTexts,e.voiceEngine}replaySessionDirectives(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return;this.lastVoiceInteractionConfigFrame&&this.ws.send(this.lastVoiceInteractionConfigFrame),this.lastStateSyncFrame&&this.ws.send(this.lastStateSyncFrame)}setLLMCallback(e){this.llmCallback=e}getState(){return this.state}isConnected(){return this.ws?.readyState===WebSocket.OPEN&&(this.state===Yu.AUTHENTICATED||this.state===Yu.CONNECTED)}updateToken(e){this.updateTokenWarnedOnce||(this.updateTokenWarnedOnce=!0,console.warn("[GatewayService] updateToken() is deprecated; use refreshAuthToken() for same-connection reauth.")),this.refreshAuthToken(e).catch((e=>{console.error("[GatewayService] updateToken shim: refreshAuthToken rejected:",e)}))}async refreshAuthToken(e){if(!e)throw new Error("refreshAuthToken: token required");if(this.isDestroyed)throw new Error("refreshAuthToken: service has been destroyed; create a new instance");this.config.token=e;if(this.ws?.readyState===WebSocket.OPEN)try{return await this.sendLogin(e),this.authenticationCount++,void(this.state!==Yu.AUTHENTICATED&&this.state!==Yu.CONNECTED&&this.setState(Yu.AUTHENTICATED))}catch(e){console.warn("[GatewayService] reauth failed, falling back to reconnect:",e)}try{this.ws?.close()}catch{}this.ws=null,this.stopHeartbeat(),this.setState(Yu.DISCONNECTED),await this.connect()}destroy(){this.webrtcReconnectTimer&&(clearTimeout(this.webrtcReconnectTimer),this.webrtcReconnectTimer=null),this.webrtcStatsTimer&&(clearInterval(this.webrtcStatsTimer),this.webrtcStatsTimer=null),this.ttsDumpFinalizeTimer&&(clearTimeout(this.ttsDumpFinalizeTimer),this.ttsDumpFinalizeTimer=null),this.heartbeatPongTimer&&(clearTimeout(this.heartbeatPongTimer),this.heartbeatPongTimer=null),this.closeWebRTCConnection(),this.disconnect(),this.llmCallback=null,this.ttsCallback=null,this.asrCallback=null,this.webrtcSDPCallback=null,this.webrtcICECallback=null,this.webrtcASRCallback=null}buildWebSocketUrl(){const e=this.config.url;if("message"===this.config.authMethod)return e;const t=e.includes("?")?"&":"?";return`${e}${t}t=${this.config.token}`}async sendLogin(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.config.token;return new Promise(((t,i)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return void i(new Error("WebSocket is not open"));const n=e=>{try{if("string"==typeof e.data){const s=e.data.substring(0,4);if("1007"===s)clearTimeout(r),this.ws?.removeEventListener("message",n),t();else if("5001"===s){clearTimeout(r),this.ws?.removeEventListener("message",n);const t=e.data.substring(4);i(new Error(`Login failed: ${t}`))}}}catch(e){console.error("[GatewayService] Login handler error:",e)}},r=setTimeout((()=>{this.ws?.removeEventListener("message",n),i(new Error("Login timeout"))}),5e3);this.ws.addEventListener("message",n);const s="1000"+e;this.ws.send(s)}))}handleMessage(e){try{const t=e.data;if("string"==typeof t){if(t.length<4)return void console.warn("[GatewayService] Invalid message: too short",t.length);const e=t.substring(0,4),i=t.substring(4);switch(e){case"1005":this.handleWebRTCSDPResponse(i);break;case"1006":this.handleWebRTCICEResponse(i);break;case"1007":this._sessionId=i||"",this._sessionId;break;case"1009":this.handleLLMResponse(i);break;case"1010":this.handleTTSSampleRate(i);break;case"1012":this.handleASRResponse(i);break;case"1014":this.handleA2FResponse(i);break;case"1015":this.handleEndMarker(i);break;case"1016":console.warn("[GatewayService] 收到文本格式的 1016,应该是二进制格式");break;case"1017":this.handleA2FResponseSequence(i);break;case"1020":this.handleCharacterAction(i);break;case"1022":this.handleWebRTCAnswer(i);break;case"1023":this.handleWebRTCICE(i);break;case"1024":this.handleWebRTCReady(i);break;case"1025":this.handleWebRTCClose(i);break;case"1030":try{const e=JSON.parse(i);if(!e?.state){console.warn("[GatewayService] CMD 1030 missing state:",i);break}Ku.emit(ds.GATEWAY_STATE_PUSH,e)}catch(e){console.error("[GatewayService] Failed to parse state push (1030):",e,i)}break;case"1040":try{const e=JSON.parse(i);Ku.emit(ds.TOOL_RESULT,e)}catch(e){console.error("[GatewayService] Failed to parse tool result:",e)}break;case"2001":this.heartbeatPongTimer&&(clearTimeout(this.heartbeatPongTimer),this.heartbeatPongTimer=null);break;case"5000":this.handleSystemError(i);break;case"5001":this.handleLoginError(i);break;case"5002":this.handleBalanceError(i);break;default:console.warn("[GatewayService] Unknown CMD:",e)}}else if(t instanceof ArrayBuffer)try{const e=new Uint8Array(t.slice(0,4)),i=(new TextDecoder).decode(e);"1011"===i?this.handleTTSAudio(t):"1016"===i?this.handleTTSAudioSequence(t):console.warn("[GatewayService] Unknown binary CMD:",i)}catch(e){return void console.error("[GatewayService] Failed to parse binary message:",e)}}catch(e){console.error("[GatewayService] Failed to handle message:",e),this.handleError(e)}}handleLLMResponse(e){this.llmCallback&&this.llmCallback({type:"llm",text:e}),Ku.emit(ds.GATEWAY_MESSAGE,{type:"llm",data:{text:e}})}handleTTSSampleRate(e){const t=parseInt(e,10);this.currentTTSSampleRate=t,this.ttsDumpEnabled&&this.startTtsDump(t),Ku.emit(ds.WEBRTC_TTS_PLAY_START),this.ttsCallback?this.ttsCallback({type:"rate",sampleRate:t}):this.llmCallback?this.llmCallback({type:"tts",sampleRate:t}):this.serverPushTTSCallback&&this.serverPushTTSCallback({type:"rate",sampleRate:t})}handleTTSAudio(e){const t=e.slice(4);this.ttsCallback?this.ttsCallback({type:"audio",audio:t}):this.llmCallback?this.llmCallback({type:"tts",audio:t}):this.serverPushTTSCallback&&this.serverPushTTSCallback({type:"audio",audio:t})}handleTTSAudioSequence(e){const t=new DataView(e.slice(4,12)).getBigUint64(0,!1),i=e.slice(12);t.toString(),i.byteLength,this.ttsCallback?this.ttsCallback({type:"audio",audio:i,sequence:Number(t)}):this.llmCallback&&this.llmCallback({type:"tts",audio:i,sequence:Number(t)})}handleASRResponse(e){let t=e,i=!1;try{const n=JSON.parse(e);"object"==typeof n&&null!==n&&(t=n.text||"",i=!0===n.isFinal)}catch{}this.asrCallback&&this.asrCallback({text:t,isFinal:i}),Ku.emit(ds.GATEWAY_MESSAGE,{type:"asr",data:{text:t,isFinal:i}})}handleA2FResponse(e){try{const{audio_offset:t,blend_shape:i,stream_id:n}=JSON.parse(e);this.ttsCallback?this.ttsCallback({type:"a2f",blendShapes:[i],audioOffset:t,streamId:n}):this.llmCallback&&this.llmCallback({type:"a2f",blendShapes:[i],audioOffset:t,streamId:n})}catch(e){console.error("[GatewayService] Failed to parse A2F data:",e)}}handleA2FResponseSequence(e){try{const t=e.indexOf("{");if(-1===t)return void console.error("[GatewayService] Invalid A2F sequence data format");const i=e.substring(0,t),n=e.substring(t),r=parseInt(i,10),{audio_offset:s,blend_shape:a,stream_id:o}=JSON.parse(n);this.ttsCallback?this.ttsCallback({type:"a2f",blendShapes:[a],sequence:r,audioOffset:s,streamId:o}):this.llmCallback&&this.llmCallback({type:"a2f",blendShapes:[a],sequence:r,audioOffset:s,streamId:o})}catch(e){console.error("[GatewayService] Failed to parse A2F sequence data:",e)}}handleEndMarker(e){"llm"===e?this.llmCallback&&this.llmCallback({type:"end",endType:"llm"}):"tts"===e?(this.ttsDumpEnabled&&this.scheduleFinalizeTtsDump(),this.ttsCallback?this.ttsCallback({type:"end",endType:"tts"}):this.llmCallback?this.llmCallback({type:"end",endType:"tts"}):this.serverPushTTSCallback&&this.serverPushTTSCallback({type:"end",endType:"tts"})):"a2f"===e?this.ttsCallback?this.ttsCallback({type:"end",endType:"a2f"}):this.llmCallback&&this.llmCallback({type:"end",endType:"a2f"}):"asr"===e&&(this.asrCallback,this.asrCallback&&this.asrCallback({text:"",isFinal:!0})),Ku.emit(ds.GATEWAY_MESSAGE,{type:"end",data:{endType:e}})}startTtsDump(e){this.ttsDumpEnabled&&(null!==this.ttsDumpFinalizeTimer&&(window.clearTimeout(this.ttsDumpFinalizeTimer),this.ttsDumpFinalizeTimer=null),this.ttsDumpActive=!0,this.ttsDumpSampleRate=e||this.currentTTSSampleRate||24e3,this.ttsDumpChunks=[],this.ttsDumpTotalBytes=0,this.ttsDumpSeq+=1,this.ttsDumpSeq,this.ttsDumpSampleRate)}appendTtsDump(e){if(!this.ttsDumpEnabled||!this.ttsDumpActive)return;const t=new Uint8Array(e);this.ttsDumpChunks.push(t),this.ttsDumpTotalBytes+=t.byteLength}scheduleFinalizeTtsDump(){this.ttsDumpEnabled&&this.ttsDumpActive&&null===this.ttsDumpFinalizeTimer&&(this.ttsDumpFinalizeTimer=window.setTimeout((()=>{this.ttsDumpFinalizeTimer=null,this.finalizeTtsDump()}),200))}finalizeTtsDump(){if(!this.ttsDumpEnabled||!this.ttsDumpActive)return;const e=this.ttsDumpSampleRate||this.currentTTSSampleRate||24e3,t=this.ttsDumpTotalBytes;if(0===t)return console.warn("[GatewayService] ⚠️ TTS dump skipped (no data)"),void(this.ttsDumpActive=!1);const i=new Uint8Array(t);let n=0;for(const e of this.ttsDumpChunks)i.set(e,n),n+=e.byteLength;const r=this.encodeWavPcm16(i,e,1),s=new Blob([r],{type:"audio/wav"}),a=`tts_dump_${this.ttsDumpSeq}_${e}Hz_${Date.now()}.wav`,o=URL.createObjectURL(s);this.ttsDumpLastUrl=o,this.ttsDumpLastFilename=a,window.__ttsDump={url:o,filename:a,download:()=>{const e=document.createElement("a");e.href=o,e.download=a,document.body.appendChild(e),e.click(),e.remove()}};try{const e=document.createElement("a");e.href=o,e.download=a,document.body.appendChild(e),e.click(),e.remove()}catch(e){console.warn("[GatewayService] ⚠️ Auto-download failed, use window.__ttsDump.download()",e)}this.ttsDumpActive=!1}encodeWavPcm16(e,t,i){const n=2*i,r=t*n,s=e.byteLength,a=new ArrayBuffer(44+s),o=new DataView(a),c=(e,t)=>{for(let i=0;i<t.length;i+=1)o.setUint8(e+i,t.charCodeAt(i))};return c(0,"RIFF"),o.setUint32(4,36+s,!0),c(8,"WAVE"),c(12,"fmt "),o.setUint32(16,16,!0),o.setUint16(20,1,!0),o.setUint16(22,i,!0),o.setUint32(24,t,!0),o.setUint32(28,r,!0),o.setUint16(32,n,!0),o.setUint16(34,16,!0),c(36,"data"),o.setUint32(40,s,!0),new Uint8Array(a,44).set(e),a}handleCharacterAction(e){try{const t=JSON.parse(e);Ku.emit(ds.GATEWAY_MESSAGE,{type:"character_action",data:t})}catch(t){console.error("[GatewayService] ❌ 解析角色动作失败:",t),console.error("[GatewayService] 原始数据:",e)}}handleWebRTCSDPResponse(e){try{const t=JSON.parse(e);t.type,t.sdp,t.sdp?.substring(0,200),this.webrtcSDPCallback&&this.webrtcSDPCallback({type:t.type,sdp:t.sdp}),Ku.emit(ds.GATEWAY_MESSAGE,{type:"webrtc_sdp",data:t})}catch(t){console.error("[GatewayService] ❌ 解析 WebRTC SDP 响应失败:",t),console.error("[GatewayService] 原始数据:",e)}}async handleWebRTCICEResponse(e){try{const t=JSON.parse(e);if(t.candidate,t.sdpMid,t.sdpMLineIndex,this.webrtcICECallback&&this.webrtcICECallback({candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex,usernameFragment:t.usernameFragment}),this.peerConnection&&t.candidate){const e=new RTCIceCandidate({candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex});await this.peerConnection.addIceCandidate(e)}Ku.emit(ds.GATEWAY_MESSAGE,{type:"webrtc_ice",data:t})}catch(t){console.error("[GatewayService] ❌ 处理 WebRTC ICE 响应失败:",t),console.error("[GatewayService] 原始数据:",e)}}async handleWebRTCAnswer(e){try{const t=JSON.parse(e);if(t.sdp,this.peerConnection&&t.sdp){const e=new RTCSessionDescription({type:"answer",sdp:t.sdp});await this.peerConnection.setRemoteDescription(e)}Ku.emit(ds.GATEWAY_MESSAGE,{type:"webrtc_answer",data:t})}catch(e){console.error("[GatewayService] ❌ 处理 WebRTC Answer 失败:",e)}}async handleWebRTCICE(e){try{const t=JSON.parse(e);if(t.candidate,this.peerConnection&&t.candidate){const e=new RTCIceCandidate({candidate:t.candidate,sdpMid:t.sdpMid,sdpMLineIndex:t.sdpMLineIndex});await this.peerConnection.addIceCandidate(e)}Ku.emit(ds.GATEWAY_MESSAGE,{type:"webrtc_ice",data:t})}catch(e){console.error("[GatewayService] ❌ 处理 WebRTC ICE 失败:",e)}}handleWebRTCReady(e){try{const t=JSON.parse(e);t.session_id,t.ready,this.isWebRTCReady=!0,Ku.emit(ds.VOICE_INTERACTION_WEBRTC_STATE,{state:"ready",sessionId:t.session_id})}catch(e){console.error("[GatewayService] ❌ 处理 WebRTC Ready 失败:",e)}}handleWebRTCClose(e){this.isWebRTCReady=!1,this.remoteAudioElement&&(this.remoteAudioElement.pause(),this.remoteAudioElement.srcObject=null),Ku.emit(ds.VOICE_INTERACTION_WEBRTC_STATE,{state:"closed",reason:e})}isWebRTCConnected(){return this.isWebRTCReady&&"connected"===this.peerConnection?.connectionState}getRemoteAudioElement(){return this.remoteAudioElement}resumeRemoteAudio(){}setTTSDataChannelCallback(e){this.ttsDataChannelCallback=e}setRemoteAudioMuted(e){this.remoteAudioElement&&(this.remoteAudioElement.muted=e,this.remoteAudioElement.volume=e?0:1)}isTTSDataChannelReady(){return null!==this.dataChannel&&"open"===this.dataChannel.readyState}startWebRTCStatsMonitoring(){if(this.webrtcStatsTimer)return;this.lastInboundStats=null;const e=async()=>{if(this.peerConnection)try{(await this.peerConnection.getStats()).forEach((e=>{if("inbound-rtp"===e.type&&"audio"===e.kind){const t=e.packetsReceived||0,i=e.bytesReceived||0,n=(e.packetsLost,e.jitter||0),r=e.timestamp;if(this.lastInboundStats){const e=t-this.lastInboundStats.packetsReceived,s=i-this.lastInboundStats.bytesReceived,a=(r-this.lastInboundStats.timestamp)/1e3;(e>0||s>0)&&(n.toFixed(4),Math.round(8*s/a/1e3))}this.lastInboundStats={packetsReceived:t,bytesReceived:i,timestamp:r}}}))}catch(e){console.error("[GatewayService] Failed to get WebRTC stats:",e)}};this.webrtcStatsTimer=window.setInterval(e,1e3),e()}stopWebRTCStatsMonitoring(){this.webrtcStatsTimer&&(clearInterval(this.webrtcStatsTimer),this.webrtcStatsTimer=null,this.lastInboundStats=null)}async getWebRTCStats(){if(!this.peerConnection)return null;try{const e=await this.peerConnection.getStats();let t=null;return e.forEach((e=>{"inbound-rtp"===e.type&&"audio"===e.kind&&(t={packetsReceived:e.packetsReceived||0,bytesReceived:e.bytesReceived||0,packetsLost:e.packetsLost||0,jitter:e.jitter||0,roundTripTime:e.roundTripTime||0})})),t}catch(e){return console.error("[GatewayService] Failed to get WebRTC stats:",e),null}}static GRPC_CANCEL_PATTERNS=["context canceled","Cancelled","Canceled"];handleSystemError(e){Xu.GRPC_CANCEL_PATTERNS.some((t=>e?.includes(t)))||(console.error("[GatewayService] System error:",e),Ku.emit(ds.GATEWAY_ERROR,{code:"5000",msg:e||"系统异常,请联系管理员",details:null}))}handleLoginError(e){console.error("[GatewayService] Login error:",e),Ku.emit(ds.GATEWAY_ERROR,{code:"5001",msg:e||"登录失败",details:null})}handleBalanceError(e){console.error("[GatewayService] Balance error:",e),Ku.emit(ds.GATEWAY_ERROR,{code:"5002",msg:e||"余额不足请升级订阅",details:null})}handleError(e){console.error("[GatewayService] Error:",e),Ku.emit(ds.GATEWAY_ERROR,{code:"GATEWAY_ERROR",msg:e.message,details:e})}handleClose(){this.stopHeartbeat(),this.setState(Yu.DISCONNECTED),Ku.emit(ds.GATEWAY_DISCONNECTED),this.config.autoReconnect&&!this.isDestroyed&&this.scheduleReconnect()}scheduleReconnect(){this.reconnectTimer||(this.reconnectTimer=window.setTimeout((()=>{this.reconnectTimer=null,this.reconnect()}),this.config.reconnectInterval))}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempts=0}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=window.setInterval((()=>{this.isConnected()&&(this.sendHeartbeat(),this.heartbeatPongTimer&&clearTimeout(this.heartbeatPongTimer),this.heartbeatPongTimer=window.setTimeout((()=>{console.warn("[GatewayService] Heartbeat PONG timeout, connection may be dead"),this.heartbeatPongTimer=null,!1!==this.config.autoReconnect&&this.handleClose()}),5e3))}),this.config.heartbeatInterval)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatPongTimer&&(clearTimeout(this.heartbeatPongTimer),this.heartbeatPongTimer=null)}sendHeartbeat(){if(this.isConnected())try{const e="2000";this.ws.send(e)}catch(e){console.error("[GatewayService] Failed to send heartbeat:",e)}}setState(e){this.state=e}}class $u{deps;debugAudioChunks=[];debugAudioSampleRate=24e3;debugAudioEnabled=!1;debugBlendShapes=[];constructor(e){this.deps=e}get isEnabled(){return this.debugAudioEnabled}reset(){this.debugAudioChunks=[],this.debugBlendShapes=[],this.debugAudioSampleRate=24e3}setSampleRate(e){this.debugAudioSampleRate=e}addAudioChunk(e){this.debugAudioChunks.push(e)}addBlendShapes(e){for(const t of e)this.debugBlendShapes.push([...t])}getChunkCount(){return this.debugAudioChunks.length}getTotalSize(){return this.debugAudioChunks.reduce(((e,t)=>e+t.byteLength),0)}getSampleRate(){return this.debugAudioSampleRate}getBlendShapeCount(){return this.debugBlendShapes.length}enableAudioDebug(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.debugAudioEnabled=e,e||(this.debugAudioChunks=[],this.debugBlendShapes=[])}getDebugAudioInfo(){const e=this.debugAudioChunks.reduce(((e,t)=>e+t.byteLength),0);return{sampleRate:this.debugAudioSampleRate,totalSize:e,chunks:this.debugAudioChunks.length}}downloadDebugAudio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"debug_audio";if(0===this.debugAudioChunks.length)return void console.warn("[AudioDebugger] No debug audio data to download. Make sure to call enableAudioDebug(true) before askStream.");const t=this.mergeAudioChunks(),i=(t.byteLength,this.createWavFile(t,this.debugAudioSampleRate)),n=new Blob([i],{type:"audio/wav"}),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=`${e}_${this.debugAudioSampleRate}Hz.wav`,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(r),this.debugAudioSampleRate}async playDebugAudio(e){if(0===this.debugAudioChunks.length)return void console.warn("[AudioDebugger] No debug audio data to play.");const t=e||this.debugAudioSampleRate,i=this.mergeAudioChunks();i.byteLength;this.debugAudioSampleRate;const n=new AudioContext({sampleRate:t}),r=new Int16Array(i),s=new Float32Array(r.length);for(let e=0;e<r.length;e++)s[e]=r[e]/32768;const a=n.createBuffer(1,s.length,t);a.getChannelData(0).set(s);const o=n.createBufferSource();return o.buffer=a,o.connect(n.destination),new Promise((e=>{o.onended=()=>{n.close(),e()},o.start(),a.duration.toFixed(2)}))}async playDebugAudio2(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(0===this.debugAudioChunks.length)return void console.warn("[AudioDebugger] No debug audio data to play.");const i=this.deps.getFramePlayer();if(!i)return void console.error("[AudioDebugger] framePlayer is not initialized");const n=e||this.debugAudioSampleRate;return this.debugAudioChunks.length,this.debugBlendShapes.length,await i.clear(),await i.setAudioRate(n),i.once("playstart").then((()=>{this.deps.getCore()?.playAction("talk")})),new Promise((e=>{if(i.once("playend").then((()=>{this.deps.getCore()?.stopServerShapes(),this.deps.playIdleAnimation(),e()})),t){let e=0,t=0;const n=()=>{if(e<this.debugAudioChunks.length){const t=this.debugAudioChunks[e];this.debugAudioChunks.length,t.byteLength,i.addBinaryAudio(t),e++}if(t<this.debugBlendShapes.length){const e=Math.min(20,this.debugBlendShapes.length-t),n=this.debugBlendShapes.slice(t,t+e);this.debugBlendShapes.length,i.addShapes(n),t+=e}(e<this.debugAudioChunks.length||t<this.debugBlendShapes.length)&&setTimeout(n,50)};n()}else this.debugAudioChunks.forEach((e=>{i.addBinaryAudio(e)})),this.debugBlendShapes.length,i.addShapes(this.debugBlendShapes)}))}mergeAudioChunks(){const e=this.debugAudioChunks.reduce(((e,t)=>e+t.byteLength),0),t=new ArrayBuffer(e),i=new Uint8Array(t);let n=0;for(const e of this.debugAudioChunks)i.set(new Uint8Array(e),n),n+=e.byteLength;return t}createWavFile(e,t){const i=1*t*16/8,n=e.byteLength,r=44+n,s=new ArrayBuffer(r),a=new DataView(s);return this.writeString(a,0,"RIFF"),a.setUint32(4,r-8,!0),this.writeString(a,8,"WAVE"),this.writeString(a,12,"fmt "),a.setUint32(16,16,!0),a.setUint16(20,1,!0),a.setUint16(22,1,!0),a.setUint32(24,t,!0),a.setUint32(28,i,!0),a.setUint16(32,2,!0),a.setUint16(34,16,!0),this.writeString(a,36,"data"),a.setUint32(40,n,!0),new Uint8Array(s,44).set(new Uint8Array(e)),s}writeString(e,t,i){for(let n=0;n<i.length;n++)e.setUint8(t+n,i.charCodeAt(n))}destroy(){this.debugAudioChunks=[],this.debugBlendShapes=[],this.debugAudioEnabled=!1}}class Zu{deps;webrtcLipSyncFrames=[];webrtcLipSyncAnimationId=null;webrtcTTSStartTime=0;webrtcA2FStreamId=null;lastLipSyncFrameIndex=-1;lipSyncStartTime=0;firstAudioOffset=0;isWebRTCTTSMode=!1;constructor(e){this.deps=e}start(){if(null!==this.webrtcLipSyncAnimationId)return;const e=this.deps.getGatewayService()?.getRemoteAudioElement();if(!e)return void console.warn("[WebRTCLipSync] No remote audio element");this.webrtcTTSStartTime=Date.now(),this.lastLipSyncFrameIndex=-1,this.deps.startTTSPlaying();const t=()=>{if(!this.isWebRTCTTSMode)return void this.stop();const i=1e3*e.currentTime,n=this.firstAudioOffset+i,r=this.findClosestFrame(n);if(-1!==r&&r!==this.lastLipSyncFrameIndex){const e=this.webrtcLipSyncFrames[r],t=this.deps.getCore();e&&t&&(t.playByShapes(e.blendShape,r),this.lastLipSyncFrameIndex=r,r%30==0&&(e.audioOffset,n.toFixed(0),i.toFixed(0),this.webrtcLipSyncFrames.length))}this.webrtcLipSyncAnimationId=requestAnimationFrame(t)};this.webrtcLipSyncAnimationId=requestAnimationFrame(t)}stop(){null!==this.webrtcLipSyncAnimationId&&(cancelAnimationFrame(this.webrtcLipSyncAnimationId),this.webrtcLipSyncAnimationId=null);const e=this.deps.getCurrentTTSText();e&&this.deps.addTTSTextToHistory(e),this.isWebRTCTTSMode=!1,this.deps.onTTSPlaybackFinalized()}addFrame(e,t,i){i&&i!==this.webrtcA2FStreamId?(this.webrtcA2FStreamId=i,this.webrtcLipSyncFrames.length>0&&(this.stop(),this.clearFrames())):!i&&0===e&&this.webrtcLipSyncFrames.length>0&&(this.stop(),this.clearFrames());const n=0===this.webrtcLipSyncFrames.length;n&&(this.lipSyncStartTime=Date.now(),this.firstAudioOffset=e,this.lipSyncStartTime,this.firstAudioOffset),this.webrtcLipSyncFrames.push({audioOffset:e,blendShape:t}),this.webrtcLipSyncFrames.sort(((e,t)=>e.audioOffset-t.audioOffset)),n&&this.isWebRTCTTSMode&&(this.start(),this.deps.getCore()?.playAction("talk"))}clearFrames(){this.webrtcLipSyncFrames=[],this.lastLipSyncFrameIndex=-1,this.lipSyncStartTime=0,this.firstAudioOffset=0,this.webrtcA2FStreamId=null}findClosestFrame(e){if(0===this.webrtcLipSyncFrames.length)return-1;let t=0,i=this.webrtcLipSyncFrames.length-1;for(;t<i;){const n=Math.floor((t+i)/2);this.webrtcLipSyncFrames[n].audioOffset<e?t=n+1:i=n}return this.webrtcLipSyncFrames[t].audioOffset>e&&t>0?t-1:t}destroy(){null!==this.webrtcLipSyncAnimationId&&(cancelAnimationFrame(this.webrtcLipSyncAnimationId),this.webrtcLipSyncAnimationId=null),this.webrtcLipSyncFrames=[],this.isWebRTCTTSMode=!1}}class Ju{isTTSPlaying=!1;currentTTSText="";lastTTSEndTime=0;ttsPlayStartTime=0;ttsTextHistory=[];playId=0;startPlaying(){return this.isTTSPlaying=!0,this.ttsPlayStartTime=Date.now(),++this.playId}reset(){this.isTTSPlaying=!1,this.lastTTSEndTime=Date.now()}resetIfMatch(e){return this.playId===e&&(this.reset(),!0)}clearCurrentText(){this.currentTTSText=""}appendText(e){this.currentTTSText+=e}isInCooldown(){return Date.now()-this.lastTTSEndTime<2e3}get cooldownMs(){return 2e3}addTextToHistory(e){if(e&&e.trim())for(this.ttsTextHistory.push(e.trim());this.ttsTextHistory.length>5;)this.ttsTextHistory.shift()}destroy(){this.isTTSPlaying=!1,this.currentTTSText="",this.lastTTSEndTime=0,this.ttsPlayStartTime=0,this.ttsTextHistory=[],this.playId=0}}class Qu{deps;voiceCallback=null;asrStream=null;asrAudioContext=null;asrProcessor=null;constructor(e){this.deps=e}async startVoice2Text(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{};try{const t=this.deps.getGatewayService();if(!t||!t.isConnected())return{code:1,msg:"Gateway service is not connected",data:{code:"error",msg:"Gateway service is not connected"}};await this.deps.stop(),this.voiceCallback=e,this.deps.setStatus("prepare2play");try{const e=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3}}),i=new AudioContext({sampleRate:16e3}),n=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);return r.onaudioprocess=e=>{const i=e.inputBuffer.getChannelData(0),n=new Int16Array(i.length);for(let e=0;e<i.length;e++){const t=Math.max(-1,Math.min(1,i[e]));n[e]=t<0?32768*t:32767*t}t.sendASRAudio(n.buffer,(e=>{this.voiceCallback&&(this.voiceCallback({text:e.text,is_final:e.isFinal}),e.isFinal&&(this.voiceCallback=null))})).catch((e=>{console.error("[VoiceToTextManager] Failed to send ASR audio:",e)}))},n.connect(r),r.connect(i.destination),this.asrStream=e,this.asrAudioContext=i,this.asrProcessor=r,{code:0,msg:"success",data:{code:"success",msg:"Voice to text started"}}}catch(e){return console.error("[VoiceToTextManager] Failed to get microphone permission:",e),this.voiceCallback=null,this.deps.setStatus("ready"),{code:1,msg:"Failed to get microphone permission",data:{code:"error",msg:e.message,isUserNotAllow:!0}}}}catch(e){throw console.error("[VoiceToTextManager] startVoice2Text error:",e),this.deps.emit(ds.HUMAN_ERROR,{code:"START_VOICE2TEXT_ERROR",msg:"Failed to start voice to text",details:hc(e)}),e}}async stopVoice2Text(e){try{e&&(this.voiceCallback=e);const t=this.deps.getGatewayService();return t&&t.stopASR(),this.asrStream&&(this.asrStream.getTracks().forEach((e=>e.stop())),this.asrStream=null),this.asrAudioContext&&(await this.asrAudioContext.close(),this.asrAudioContext=null),this.asrProcessor&&(this.asrProcessor.disconnect(),this.asrProcessor=null),{code:0,msg:"success",data:null}}catch(e){throw console.error("[VoiceToTextManager] stopVoice2Text error:",e),this.deps.emit(ds.HUMAN_ERROR,{code:"STOP_VOICE2TEXT_ERROR",msg:"Failed to stop voice to text",details:hc(e)}),e}}dealVoice2Text(e){let t=e;e.is_final&&(t.text=t.text.replace(/([\.|。])$/,"")),this.voiceCallback&&this.voiceCallback(t)}getVoiceCallback(){return this.voiceCallback}setVoiceCallback(e){this.voiceCallback=e}destroy(){this.asrStream&&(this.asrStream.getTracks().forEach((e=>e.stop())),this.asrStream=null),this.asrAudioContext&&(this.asrAudioContext.close().catch((()=>{})),this.asrAudioContext=null),this.asrProcessor&&(this.asrProcessor.disconnect(),this.asrProcessor=null),this.voiceCallback=null}}const ef=class{list=[];isExecute=!1;runList=[];constructor(){}add(e){if("[object AsyncFunction]"!==Object.prototype.toString.call(e))throw new Error("Task mast be AsyncFunction.");this.list.push(e),this.isExecute||this.execute()}execute(){if(this.isExecute=!0,this.list.length>0){const e=this.list.shift();this.runList.push({task:e}),e().then((()=>{this.runList.findIndex((t=>t.task===e))>=0&&this.execute()}))}else this.isExecute=!1}clear(){this.runList=[],this.list=[],this.isExecute=!1}hasRuning(){return this.list.length>0||this.isExecute}},tf=e=>{const t=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"];let i=[];const n=t.length;for(let r=0;r<e;r++){const e=Math.floor(Math.random()*n);i.push(t[e])}return i.join("")};var nf=new class{fps;run_count;time_begin_ms;process_begin_time;target_wait_ms;log_timestamp;trace_name;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:20,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.fps=e,this.run_count=0,this.time_begin_ms=0,this.process_begin_time=0,this.target_wait_ms=1e3/e,this.log_timestamp=0,this.trace_name=t}init(e,t){this.fps=e,this.run_count=0,this.time_begin_ms=Date.now(),this.process_begin_time=0,this.target_wait_ms=1e3/e,this.trace_name=t}terminate(){}begin(){return this.process_begin_time=Date.now(),this.process_begin_time}end(){let e=Date.now(),t=e>this.process_begin_time?e-this.process_begin_time:0,i=this.target_wait_ms>t?this.target_wait_ms-t:2,n=e>this.time_begin_ms?Math.floor((e-this.time_begin_ms+this.target_wait_ms/2)/this.target_wait_ms):0;n>this.run_count?i=0:n<this.run_count&&(i+=this.target_wait_ms/2),i>2*this.target_wait_ms&&(i=2*this.target_wait_ms);if(Math.abs(n-this.run_count)>5){let e=Date.now();e-this.log_timestamp>1e4&&(this.log_timestamp=e,console.warn(`[${this.trace_name}] ideal_count - run_count = ${n-this.run_count}`)),n>this.run_count?this.run_count++:i=this.target_wait_ms/2}else this.run_count++;return i}}(30,"");class rf{callback;pushCallback;buffer="";triggerCharacters=[".","!","?","。","!","?","\n"];minLength=6;messages=[];startPushed=!1;constructor(e,t){this.buffer="",this.startPushed=!1,this.callback=e,this.pushCallback=t}processMessage(e){if(this.messages.push(e),"message_end"===e.event)return this.buffer+=e.answer||"",void this.pushMessage(this.buffer,{isEnd:!0,type:"message",conversation_id:e.conversation_id});if(!e||!e.answer)return;if(this.buffer+=e.answer,this.checkAndDoAction(e.conversation_id))return;if(this.buffer.length<this.minLength)return;const t=this.includeIndex(e.answer);if(t>=0){let i=this.buffer;const n=e.answer.length,r=this.buffer;n>1&&(i=this.buffer.substring(0,this.buffer.length-n+t+1)),this.pushMessage(i,{isEnd:!1,type:"message",conversation_id:e.conversation_id}),n>1&&(this.buffer+=r.substring(r.length-n+t+1))}}includeIndex(e){return e.split("").findIndex((e=>this.triggerCharacters.includes(e)))}pushMessage(e,t){this.callback(e,t),this.buffer="",this.startPushed&&this.executePushCallback()}checkAndDoAction(e){return/^\[#?"?”?.*#?"?“?\]\n?/.test(this.buffer)?(this.pushMessage(this.buffer.replace(/^\[#?"?”?(.*?)"?“?#?\]\n?/,"$1"),{isEnd:!1,type:"action",conversation_id:e}),this.messages=[],!0):!(!this.buffer.startsWith("[#")&&!this.buffer.startsWith('["'))}executePushCallback(){this.startPushed=!0;const e=[...this.messages];0!==e.length&&(this.messages=[],this.pushCallback({code:0,msg:"success",data:e}))}}class sf{deps;exeSequence=new ef;fetchSequence=new ef;probeTimeout=null;callbackTimeout=null;mutilAudios=[];openRecorderTimeout=null;webrtcTTSStartTime=0;constructor(e){this.deps=e}async speak(e,t){if("render-only"===this.deps.getConfig().mode)return Promise.reject(new Error("[Human] render-only 模式下 speak() 不可用:请用第三方 TTS 生成音频+口型后调用 speakByAudioShapes()"));const i=this.deps.getGatewayService();if(!i||!i.isConnected())return Promise.reject(new Error("Gateway service is not connected"));const n=this.deps.getCharacterData();if(!n)return Promise.reject(new Error("Character data is not loaded"));await this.deps.stop();const r=tf(16),s=this.deps.getFramePlayer();await(s?.clear()),s?.once("playstart").then((()=>{this.deps.ttsState.startPlaying();const i=this.deps.getCore();i?.playAction("talk"),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_START,{reqId:r,content:e,conversationId:"",isEnd:!1}),t&&t({event:"bs-playstart",text:e})}));return new Promise(((a,o)=>{let c=!1,l=!1;const h=!1!==this.deps.getConfig().a2fEnabled;let d=!h;const u=setTimeout((()=>{l||(l=!0,console.warn("[Human] speak timeout (60s), force resolve"),this.deps.ttsState.reset(),this.deps.finalizeTTSPlayback(),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_END,{reqId:r,conversationId:"",isEnd:!0}),o(new Error("speak timeout")))}),6e4);i.sendTTS({character_id:n.id,text:e,a2f_enabled:h,dialect:n.language},(i=>{l||("rate"===i.type&&i.sampleRate?s?.setAudioRate(i.sampleRate):"audio"===i.type&&i.audio?s?.addBinaryAudio(i.audio):"a2f"===i.type&&i.blendShapes&&h?s?.addShapes(i.blendShapes):"end"===i.type&&("tts"===i.endType?c=!0:"a2f"===i.endType&&(d=!0),c&&d&&(setTimeout((()=>{s?.markAudioStreamEnded()}),100),s?.once("playend").then((()=>{if(l)return;l=!0,clearTimeout(u);const i=s.getPlayInfo();this.deps.finalizeTTSPlayback(),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_END,{reqId:r,conversationId:"",isEnd:!0}),t&&t({event:"bs-playend",text:e}),a(i)})))))})).catch((e=>{l||(l=!0,clearTimeout(u),console.error("[Human] speak error:",e),this.deps.ttsState.reset(),this.deps.playIdleAnimation(),this.deps.emit(ds.HUMAN_ERROR,{code:"SPEAK_ERROR",msg:"Failed to speak text",details:e}),o(e))}))}))}async askCommand(e,t){const i=this.deps.getCharacterData();if(!i)return void t({code:99,msg:"接口数据异常",data:[]});const n=new rf((async(i,n)=>{if("action"===n.type&&e.commandType){const n=i.split(",").filter((t=>t.startsWith(e.commandType)));n.length>0&&(t({code:0,msg:"success",data:n}),this.deps.emit(ds.HUMAN_ACTION_PENDING,n))}else;}),(()=>{}));ac(i.id,{...e,language:i?.language},(e=>{if(0===e.code){if("error"===e.data.event)return t({code:98,msg:e.data.message??"接口数据异常",data:[]});n.processMessage(e.data)}else t({code:e.code,msg:e.msg??"接口数据异常",data:[]})})).catch((e=>{console.error("askStream.......err..",e)}))}async askStream(e,t,i){if("render-only"===this.deps.getConfig().mode)return Promise.reject(new Error("[Human] render-only 模式下 askStream() 不可用:LLM 请由接入方用第三方算力实现,再用 speakByAudioShapes() 驱动数字人"));const n=this.deps.getGatewayService();if(!n||!n.isConnected())return Promise.reject(new Error("Gateway service is not connected"));if(!this.deps.getCharacterData())return Promise.reject(new Error("Character data is not loaded"));const r="closed"!==this.deps.getVoiceInteractionState();i?.skipStop||r||await this.deps.stop();const s=e.reqId||tf(16),a=[];let o=e.conversation_id||tf(16);const c=this.deps.getFramePlayer();c?.once("playstart").then((()=>{const e=this.deps.getCore();e?.playAction("talk")}));return"stream_sentence"===e.inputs?.chunk_type?this.askStreamWithSeparateTTS(e,t,s,o,a):this.askStreamWithIntegratedTTS(e,t,s,o,a)}async askStreamWithSeparateTTS(e,t,i,n,r){return this.deps.ttsState.currentTTSText="",new Promise(((s,a)=>{let o=!1,c=0,l=0;const h=this.deps.getGatewayService(),d=this.deps.getCharacterData(),u=this.deps.getFramePlayer();h.sendLLMChat({query:e.message[e.message.length-1].content,inputs:{character_id:d.id,chat_id:e.conversation_id||n,tts_enabled:!1,a2f_enabled:!1,chunk_type:"stream_sentence"}},(e=>{if("llm"===e.type&&e.text){const a=e.text.trim();if(this.deps.ttsState.currentTTSText+=a,t(this.buildMessageCallback("message",n,i,a)),a){c++;const e=c;this.fetchSequence.add((async()=>new Promise(((t,f)=>{let p=!1,m=!1,g=!1;const _=`startplay-${i}-${e}`;u?.registerCallback(_,(()=>{g||(g=!0,this.deps.ttsState.startPlaying(),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_START,{reqId:i,content:a,conversationId:n,isEnd:!1}),a.substring(0,20))})),h.sendTTS({character_id:d.id,text:a,a2f_enabled:!0,xf:3280,dialect:d.language},(h=>{if("rate"===h.type&&h.sampleRate)u?.setAudioRate(h.sampleRate);else if("audio"===h.type&&h.audio)u?.addBinaryAudio(h.audio);else if("a2f"===h.type&&h.blendShapes)u?.addShapes(h.blendShapes);else if("end"===h.type&&("tts"===h.endType?p=!0:"a2f"===h.endType&&(m=!0),p&&m)){setTimeout((()=>{u?.markAudioStreamEnded()}),100);const h=`endplay-${i}-${e}`;u?.registerCallback(h,(()=>{this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_END,{reqId:i,content:a,conversationId:n,isEnd:!1}),a.substring(0,20)})),l++,t(),this.checkAllTasksCompleted(o,c,l,i,n,r,s)}})).catch((e=>{console.error("[Human] TTS error:",e),r.push({errorMessage:e.message,content:a}),l++,f(e),this.checkAllTasksCompleted(o,c,l,i,n,r,s)}))}))))}}else"end"===e.type&&"llm"===e.endType&&(o=!0,t(this.buildMessageCallback("message_end",n,i,"")),this.checkAllTasksCompleted(o,c,l,i,n,r,s))})).catch((e=>{console.error("[Human] askStream LLM error:",e),this.deps.playIdleAnimation(),a(e)}))})).catch((e=>{throw this.deps.playIdleAnimation(),e}))}async askStreamWithIntegratedTTS(e,t,i,n,r){this.deps.audioDebugger.reset();const s=this.deps.getFramePlayer();await(s?.clear()),this.deps.ttsState.currentTTSText="";const a=e.inputs?.use_webrtc_tts||!1,o=!1!==e.inputs?.a2f_enabled;return new Promise(((c,l)=>{let h=!1,d=!1,u=!o,f=!1,p=!1,m=0,g=0,_=!1,y=null,T=null,w=0;let b=0,S=0;const v=this.deps.getGatewayService(),A=this.deps.getCharacterData(),E=this.deps.getConfig(),R=this.deps.getCore(),k=e=>{if(_)return;if(a&&!d)return;const t=Date.now();if(w>0&&t<w){const i=Math.max(w-t+200,200);return y&&clearTimeout(y),void(y=setTimeout((()=>{k(`min-duration-delay:${e}`)}),i))}_=!0,y&&(clearTimeout(y),y=null),T&&(clearTimeout(T),T=null),v?.getWebRTCStats().then((e=>{e&&(e.packetsReceived,e.bytesReceived,e.packetsLost,e.jitter.toFixed(4),e.packetsReceived>0&&(e.packetsLost/(e.packetsReceived+e.packetsLost)*100).toFixed(2))})),this.deps.webrtcLipSync.isWebRTCTTSMode?this.deps.webrtcLipSync.stop():this.deps.ttsState.reset(),v?.sendTTSPlaybackState("playback_ended"),this.deps.flushPendingASRIfReady("webrtc-playback-ended")},x=e=>{if(!a||_||T)return;if(!d||o&&!u)return;const t=v?.getRemoteAudioElement();if(!t)return void k("no-audio-element");S=t.currentTime,b=0;const i=Date.now();S.toFixed(3);const n=()=>{if(_)return void(T=null);if(!d||o&&!u)return void(T=setTimeout(n,500));const r=t.currentTime,s=r-S;if(b%5==0&&(r.toFixed(3),S.toFixed(3),s.toFixed(3),((Date.now()-i)/1e3).toFixed(1),t.paused,t.ended),s>.01?(S=r,b=0):b+=1,b>=20)return r.toFixed(3),((Date.now()-i)/1e3).toFixed(1),t.paused,k(`audio-idle:${e}`),void(T=null);T=setTimeout(n,200)};T=setTimeout(n,200),y=setTimeout((()=>{k(`end-marker-timeout:${e}`)}),12e4)};a&&(this.deps.webrtcLipSync.isWebRTCTTSMode=!0,this.deps.webrtcLipSync.clearFrames(),this.webrtcTTSStartTime=0,s?.prepareForNewTTS(!0)),v.sendLLMChat({query:e.message[e.message.length-1].content,inputs:{character_id:A.id,chat_id:e.conversation_id||n,tts_enabled:!0,a2f_enabled:o,chunk_type:"stream",use_webrtc_tts:a}},(e=>{if("llm"===e.type&&e.text){const r=e.text.trim();this.deps.ttsState.currentTTSText+=r,t(this.buildMessageCallback("message",n,i,r)),f&&this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_START,{reqId:i,content:this.deps.ttsState.currentTTSText,conversationId:n,isEnd:!1})}else if("tts"===e.type)e.sampleRate&&!p&&(e.sampleRate,s?.setAudioRate(e.sampleRate),p=!0,this.deps.audioDebugger.isEnabled&&this.deps.audioDebugger.setSampleRate(e.sampleRate)),e.audio&&(f||(f=!0,this.deps.ttsState.startPlaying(),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_START,{reqId:i,content:this.deps.ttsState.currentTTSText,conversationId:n,isEnd:!1}),a&&(0===this.webrtcTTSStartTime&&(this.webrtcTTSStartTime=Date.now()),w=Math.max(w,this.webrtcTTSStartTime+2e3),R?.playAction("talk"))),this.deps.audioDebugger.isEnabled&&this.deps.audioDebugger.addAudioChunk(e.audio.slice(0)),p||(console.warn("[Human] Audio data received before sample rate, using default 24000"),s?.setAudioRate(24e3),p=!0),s?.addBinaryAudio(e.audio));else if("a2f"===e.type&&e.blendShapes&&o)m++,g+=e.blendShapes.length,this.deps.audioDebugger.isEnabled&&this.deps.audioDebugger.addBlendShapes(e.blendShapes),a&&void 0!==e.audioOffset?(f||(f=!0,this.deps.ttsState.startPlaying(),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_START,{reqId:i,content:"",conversationId:n,isEnd:!1}),0===this.webrtcTTSStartTime&&(this.webrtcTTSStartTime=Date.now()),w=Math.max(w,this.webrtcTTSStartTime+2e3),R?.playAction("talk")),m<=3&&(e.audioOffset,e.blendShapes.length),e.blendShapes.forEach((t=>{this.deps.webrtcLipSync.addFrame(e.audioOffset,t,e.streamId)}))):a&&void 0===e.audioOffset?console.warn("[Human] ⚠️ WebRTC 模式收到 A2F 数据但缺少 audioOffset"):s?.addShapes(e.blendShapes);else if("end"===e.type){if("llm"===e.endType)h=!0,t(this.buildMessageCallback("message_end",n,i,""));else if("tts"===e.endType){d=!0;const e=Date.now();this.webrtcTTSStartTime>0&&this.webrtcTTSStartTime;if(this.deps.ttsState.currentTTSText.length,this.deps.ttsState.currentTTSText.substring(0,50),this.deps.ttsState.currentTTSText.length,this.deps.audioDebugger.isEnabled&&this.deps.audioDebugger.getChunkCount(),this.deps.audioDebugger.isEnabled){const e=this.deps.audioDebugger.getTotalSize();this.deps.audioDebugger.getChunkCount(),this.deps.audioDebugger.getSampleRate(),(e/2/this.deps.audioDebugger.getSampleRate()).toFixed(2)}a&&x("tts-end")}else if("a2f"===e.endType&&(u=!0,a)){const e=E.options?.fps??30,t=Math.ceil(g/e*1e3);0===this.webrtcTTSStartTime&&(this.webrtcTTSStartTime=Date.now()),w=this.webrtcTTSStartTime+Math.max(t,1e3),x("a2f-end")}h&&d&&u&&(setTimeout((()=>{s?.markAudioStreamEnded()}),100),s?.once("playend").then((()=>{const e=s.getPlayInfo();a&&k("frameplayer-playend"),this.deps.ttsState.currentTTSText&&this.deps.ttsState.addTextToHistory(this.deps.ttsState.currentTTSText),this.deps.finalizeTTSPlayback(),a||(v?.sendTTSPlaybackState("playback_ended"),this.deps.flushPendingASRIfReady("frameplayer-playend")),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_END,{reqId:i,content:"",conversationId:n,isEnd:!0}),c({code:0,msg:"success",data:{reqId:i,playInfos:[e],errorInfos:r}})})))}})).catch((e=>{console.error("[Human] askStream integrated mode error:",e),this.deps.ttsState.reset(),this.deps.playIdleAnimation(),l(e)}))})).catch((e=>{throw this.deps.ttsState.reset(),this.deps.playIdleAnimation(),e}))}checkAllTasksCompleted(e,t,i,n,r,s,a){if(e&&t===i){const e=this.deps.getFramePlayer(),t=this.deps.getGatewayService();e?.once("playend").then((()=>{const i=e.getPlayInfo();this.deps.finalizeTTSPlayback(),t?.sendTTSPlaybackState("playback_ended"),this.deps.emit(ds.CHAT_MESSAGE_BS_PLAY_END,{reqId:n,content:"",conversationId:r,isEnd:!0}),a({code:0,msg:"success",data:{reqId:n,playInfos:[i],errorInfos:s}})}))}}async ask(e,t){if("render-only"===this.deps.getConfig().mode)return Promise.reject(new Error("[Human] render-only 模式下 ask() 不可用:LLM 请由接入方用第三方算力实现,再用 speakByAudioShapes() 驱动数字人"));const i=this.deps.getGatewayService();if(!i||!i.isConnected())return Promise.reject(new Error("Gateway service is not connected"));const n=this.deps.getCharacterData();if(!n)return Promise.reject(new Error("Character data is not loaded"));await this.deps.stop();const r=e.reqId||tf(16),s=e.conversation_id||tf(16);let a="";return new Promise(((o,c)=>{i.sendLLMChat({query:e.message[e.message.length-1].content,inputs:{character_id:n.id,chat_id:s,tts_enabled:!1,a2f_enabled:!1,chunk_type:"block"}},(e=>{"llm"===e.type&&e.text?(a+=e.text,t({code:0,msg:"success",data:{event:"message",conversation_id:s,message_id:r,created_at:Date.now(),task_id:r,id:r,answer:e.text}})):"end"===e.type&&"llm"===e.endType&&o({code:0,msg:"success",data:{reqId:r,playInfos:[],errorInfos:[]}})})).catch((e=>{console.error("[Human] ask error:",e),c(e)}))}))}async speakByAudioShapes(e,t){return await this.deps.stop(),this.deps.setStatus("prepare2play"),new Promise((i=>{let n=0;const r=t=>{n++,n===e.length&&i(t)};e.forEach(((e,i)=>{this.exeSequence.add((async()=>{const n=this.createAudio();return await n.setUrl(e),this.mutilAudios.push(n),this.play({shapes:t[i],audio:n}).then(r)}))}))}))}async speakByAudioStreamShapes(e,t,i){await this.deps.stop(),this.deps.setStatus("prepare2play");const n=this.deps.getFramePlayer();return n?(i&&await n.setAudioRate(i),new Promise((i=>{n.once("playend").then((()=>{const e=this.deps.getCore();e?.stopServerShapes(),i(!0)})),e.forEach((e=>{n.addBinaryAudio(e)})),n.addShapes(t)}))):Promise.reject("player is null!")}async speakByAudio(e,t){if(await this.deps.stop(),!t)throw new Error("shapes is null");this.deps.setStatus("prepare2play");const i=this.deps.getAudio();return await i.setUrl(e),this.play({shapes:t,audio:i}).then((()=>!0))}probeTimePlay(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0;if(this.callbackTimeout&&clearTimeout(this.callbackTimeout),t.length>e){nf.begin();const n=this.deps.getCore();n&&n.playByShapes(t[e],e);const r=nf.end();this.probeTimeout=setTimeout((()=>{this.probeTimePlay(e+1,t,i)}),r),this.callbackTimeout=setTimeout((()=>{i&&i({break:!0})}),r+100)}else i&&i()}createAudio(){const e=new pc,t=()=>{this.deps.emit(ds.AUDIO_PLAY)},i=()=>{this.deps.emit(ds.AUDIO_PAUSE),e.off("onplay",t),e.off("onend",n),e.off("onstop",i)},n=()=>{this.deps.emit(ds.AUDIO_PAUSE),e.off("onplay",t),e.off("onstop",i),e.off("onend",n)};return e.on("onplay",t),e.on("onstop",i),e.on("onend",n),e}async setRecorderStatus(e){if("normal"===this.deps.getConfig().mode){this.openRecorderTimeout&&clearTimeout(this.openRecorderTimeout);const t=this.deps.getRecorder();if(!t)return void console.warn("[Human] Recorder is not available, skip setRecorderStatus");const i=this.deps.getStatus();"open"!==e||["prepare2play","playing"].includes(i)?t.closeRecording():this.openRecorderTimeout=setTimeout((()=>{t.requestRecorderPermission()}),500)}}play=async e=>{let{shapes:t,audio:i}=e;return await this.setRecorderStatus("close"),this.deps.setStatus("playing"),i.isLoaded()?i.play():this.deps.emit(ds.HUMAN_ERROR,{code:"playaudio",uri:i.getUrl(),msg:"audio 未加载"}),new Promise((e=>{const i=this.deps.getConfig();nf.init(i.options?.fps??30,"socket"),this.probeTimePlay(0,t,(t=>{this.deps.setStatus("ready"),this.setRecorderStatus("open"),t&&t.break?e(!1):e(!0)}))}))};buildMessageCallback(e,t,i,n){return{code:0,msg:"success",data:[{event:e,conversation_id:t,message_id:i,created_at:Date.now(),task_id:i,id:i,answer:n}]}}muteAllAudio(e){this.mutilAudios.forEach((t=>{t.mute(e)}))}stopPlayback(){this.probeTimeout&&(clearTimeout(this.probeTimeout),this.probeTimeout=null),this.callbackTimeout&&(clearTimeout(this.callbackTimeout),this.callbackTimeout=null),this.exeSequence.clear(),this.fetchSequence.clear(),this.mutilAudios.forEach((e=>{e.pause()})),this.mutilAudios=[]}destroy(){this.exeSequence.clear(),this.fetchSequence.clear(),this.probeTimeout&&(clearTimeout(this.probeTimeout),this.probeTimeout=null),this.callbackTimeout&&(clearTimeout(this.callbackTimeout),this.callbackTimeout=null),this.openRecorderTimeout&&(clearTimeout(this.openRecorderTimeout),this.openRecorderTimeout=null),this.mutilAudios=[],this.webrtcTTSStartTime=0}}class af{static resolveCharacter(e,t){const i=this.getRuntimeModelConfig(t,e.configuration);return{render:this.resolveRenderConfig(i),assets:{aposes:this.filterFilesByType(e.aposes,"apose"),animations:this.filterAnimationFiles(e.animations),scene:this.resolveSceneAsset(e.scene)},behavior:{animationEnabled:this.resolveAnimationEnabled(e.animationEnabled),debug:t.debug??!1,isNotRender:t.isNotRender??!1}}}static resolveOffline(e,t,i){const n=this.getRuntimeModelConfig(i,e);return{render:this.resolveRenderConfig(n),assets:{aposes:this.filterFilesByType(t,"apose"),animations:this.filterAnimationFiles(t),scene:null},behavior:{animationEnabled:!0,debug:i.debug??!1,isNotRender:i.isNotRender??!1}}}static toModelDescription(e){return{name:e.render.name||"",scene:e.render.scene,camera:e.render.camera||{fov:50},orbitControls:e.render.orbitControls||{},lights:e.render.lights||[],model:e.render.model,gridHelper:e.render.gridHelper,dracoPath:e.render.dracoPath,debug:e.behavior.debug}}static getRuntimeModelConfig(e,t){return e.modelConfig||t||{}}static resolveRenderConfig(e){return{name:e.name,scene:e.scene,camera:e.camera,orbitControls:e.orbitControls,lights:Array.isArray(e.lights)?e.lights:[],model:e.model,gridHelper:e.gridHelper,dracoPath:e.dracoPath}}static resolveSceneAsset(e){return e&&"object"==typeof e?{...e,id:e.id,name:e.name,type:e.type,path:e.path,pictures:Array.isArray(e.pictures)?e.pictures:void 0,background:e.background}:null}static filterFilesByType(e,t){return Array.isArray(e)?e.filter((e=>e?.type===t)):[]}static filterAnimationFiles(e){return Array.isArray(e)?e.filter((e=>"animation"===e?.type||"animation_system"===e?.type)):[]}static resolveAnimationEnabled(e){return!1!==e&&"F"!==e&&"false"!==e}}const of=["你好","嗨","hello","hi"],cf={"小":["晓","肖"],"浪":["兰","朗","郎"]};function lf(e){const t=[e],i=[...e];for(let e=0;e<i.length;e++){const n=cf[i[e]];if(n)for(const r of n)t.push(i.slice(0,e).join("")+r+i.slice(e+1).join(""))}return t}function hf(e){return e.replace(/[\s\u3000]+/g,"").replace(/[,。!?、;:\u201c\u201d\u2018\u2019()《》【】\.\,\!\?\;\:\"\'\(\)\[\]\/\\—\-\~\`\@\#\$\%\^\&\*\+\=\|]/g,"").replace(/[A-Za-z]/g,(e=>String.fromCharCode(e.charCodeAt(0)-65248))).toLowerCase()}function df(e,t){const i=hf(e),n=t.filter((e=>!of.includes(e.toLowerCase())));for(const e of n){const t=lf(e);for(const e of t)for(const n of t){const t=hf(e+n);if(i.includes(t))return!0}}return!1}const uf=/^[\s ,。!?、;:“”‘’()《》【】,.\!?;:""''()—\-]+/;function ff(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=[];for(const n of e){if(of.includes(n.toLowerCase())){i.push(n);continue}const e=lf(n);if(i.push(...e),t.doubleWakeWord)for(const t of e)for(const n of e)i.push(t+n)}return t.interruptWords&&i.push(...t.interruptWords),[...new Set(i)]}class pf extends t{name;core=null;config;loading;audio;container="";recorder=null;recorderMessageHandler=null;voiceToTextManager;status;chatOrchestrator;onAnyEvent=null;characterData=null;isNotRender=!1;mode="normal";gatewayService=null;framePlayer=null;camera=null;get sessionId(){return this.gatewayService?.sessionId||""}enableProactiveTTSPlayback(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!this.gatewayService)return void console.warn("[Human] enableProactiveTTSPlayback: gatewayService not ready");if(!e)return this.gatewayService.setServerPushTTSCallback(null),this._proactiveAudioCtx?.close().catch((()=>{})),void(this._proactiveAudioCtx=null);let t=24e3,i=[];this.gatewayService.setServerPushTTSCallback((e=>{if("rate"===e.type&&e.sampleRate)e.sampleRate,t=e.sampleRate,i=[];else if("audio"===e.type&&e.audio)i.push(e.audio);else if("end"===e.type&&"tts"===e.endType){if(0===i.length)return void console.warn("[Human] proactive TTS end but no audio chunks, skip");const e=i.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(e);let r=0;for(const e of i)n.set(new Uint8Array(e),r),r+=e.byteLength;i=[];const s=n.byteLength>>1,a=new Int16Array(n.buffer,n.byteOffset,s),o=new Float32Array(a.length);for(let e=0;e<a.length;e++)o[e]=a[e]/32768;try{if(!this._proactiveAudioCtx){const e=window.AudioContext||window.webkitAudioContext;this._proactiveAudioCtx=new e}const e=this._proactiveAudioCtx;"suspended"===e.state&&e.resume();const i=e.createBuffer(1,o.length,t);i.getChannelData(0).set(o);const n=e.createBufferSource();n.buffer=i,n.connect(e.destination),n.start(0);const r=o.length/t;o.length,r.toFixed(2)}catch(e){console.warn("[Human] proactive TTS audio playback failed:",e)}}}))}_proactiveAudioCtx=null;voiceInteractionConfig=null;voiceInteractionState="closed";voiceInteractionExitTimer=null;exitPromptFired=!1;secondExitTimer=null;exitTimerTurnId=0;voiceInteractionConversationId="";voiceInteractionProcessing=!1;voiceInteractionLastText="";voiceInteractionLastTextTime=0;voiceInteractionTTSMode=null;voiceInteractionWebRTCDisabled=!1;ttsState;eventBusHandlers=[];eventBusModule=null;_destroyed=!1;updateTokenWarnedOnce=!1;degradedNotice;static IDLE_LOOP_MODE=2201;static BARGE_IN_MIN_TEXT_LENGTH=8;static BARGE_IN_COOLDOWN_MS=500;static INTERRUPT_INTENT_WORDS=["停止","停一下","暂停","打住","够了","算了","等一下","等等","不要了","不用了","不说了","别说了","不想听","闭嘴","安静","听我说","让我说","跳过","换个话题","打断","退出","结束"];static GREETING_ONLY_WORDS=of;static CHAR_HOMOPHONES=cf;static generateNameVariants=lf;static normalizeASRText=hf;isDoubleWakeWord(e,t){return df(e,t)}speakDirect(e){return new Promise((t=>{if(!this.gatewayService||!this.gatewayService.isConnected())return console.warn("[Human] speakDirect: Gateway not connected"),void t();let i=!1;const n=this.characterData?.id||this.config?.characterId||"",r=this.voiceInteractionConfig?.a2fEnabled??!0,s=this.ttsState.startPlaying(),a=e=>{i||(i=!0,clearTimeout(o),this.framePlayer?.off("playend",c),this.gatewayService?.clearTTSCallback(),this.ttsState.resetIfMatch(s),this.gatewayService?.sendTTSPlaybackState("playback_ended"),this.emit(ds.VOICE_INTERACTION_PLAY_END),t())},o=setTimeout((()=>a()),1e4);this.framePlayer&&this.framePlayer.prepareForNewTTS();const c=()=>a();this.framePlayer?.on("playend",c),this.gatewayService.sendTTS({character_id:n,text:e,a2f_enabled:r,synthetic:!0},(e=>{i||("rate"===e.type&&e.sampleRate?this.framePlayer?.setAudioRate(e.sampleRate):"audio"===e.type&&e.audio?this.framePlayer?.addBinaryAudio(e.audio):"a2f"===e.type&&e.blendShapes?this.framePlayer?.addShapes(e.blendShapes):"end"===e.type&&"tts"===e.endType&&setTimeout((()=>{this.framePlayer?.markAudioStreamEnded()}),100))})).catch((e=>{console.warn("[Human] speakDirect sendTTS failed:",e),a()}))}))}lastBargeInTime=0;bargeInInProgress=!1;voiceInteractionAskId=0;isAudioDataDiscarding=!1;audioDiscardingTimer=null;static AUDIO_DISCARDING_TIMEOUT_MS=1e4;isFirstUserInput=!0;static CONTINUATION_WINDOW_MS=3e3;static MIN_VALID_TEXT_LENGTH=2;static NOISE_WORDS=["嗯","啊","哦","噢","呃","额","嗯嗯","啊啊","哎","唉","呀","好","好的","嗯好","好嗯","是","是的","对","对的","行","行的","可以","好吧","那","那个","这","这个","玩具","完剧","好奇","豪气","是我的","是我","我的","喂","诶","哈","哈哈","呵","呵呵","嘿","嘿嘿"];asrTextBuffer=[];asrSilenceTimer=null;pendingASRFinal=!1;static ASR_SILENCE_TIMEOUT_MS=2e3;static DUPLICATE_TEXT_WINDOW_MS=5e3;pendingMergeText=null;textMergeTimer=null;textMergeStartTime=0;static TEXT_MERGE_DELAY_MS=1500;static TEXT_MERGE_MAX_DELAY_MS=5e3;ttsPlaySafetyTimer=null;static DEFAULT_TTS_PLAY_SAFETY_TIMEOUT_MS=3e4;framePlayerPlayEndHandler=null;audioDebugger;webrtcLipSync;constructor(e){if(super(),!e.token)throw new Error("Token is required in configuration");var t;this.status="init",this.name="QuanTeHuman",this.audio=mc,this.config=this.mergeConfig(e),e.crypto&&((t=e.crypto).salt&&Ve.enc.Utf8.parse(t.salt),t.iv&&Ve.enc.Utf8.parse(t.iv)),this.setupContainer(e.container),this.degradedNotice=new fs(this.isNotRender?void 0:e.container),this.degradedNotice.syncWithToken(e.token),this.mode=this.config.mode,this.initStorage(),pc.VOLUMN=this.config.audio.volume||1,this.initFramePlayer(),this.ttsState=new Ju,this.voiceToTextManager=new Qu({getGatewayService:()=>this.gatewayService,stop:()=>this.stop(),setStatus:e=>{this.status=e},emit:(e,t)=>this.emit(e,t)}),this.audioDebugger=new $u({getFramePlayer:()=>this.framePlayer,getCore:()=>this.core,playIdleAnimation:()=>this.playIdleAnimation()}),this.webrtcLipSync=new Zu({getGatewayService:()=>this.gatewayService,getCore:()=>this.core,onTTSPlaybackFinalized:()=>this.finalizeTTSPlayback(),addTTSTextToHistory:e=>this.ttsState.addTextToHistory(e),getCurrentTTSText:()=>this.ttsState.currentTTSText,startTTSPlaying:()=>{this.ttsState.startPlaying()}}),this.chatOrchestrator=new sf({getGatewayService:()=>this.gatewayService,getFramePlayer:()=>this.framePlayer,getCore:()=>this.core,getCharacterData:()=>this.characterData,getConfig:()=>this.config,getRecorder:()=>this.recorder,getStatus:()=>this.status,setStatus:e=>{this.status=e},getAudio:()=>this.audio,emit:(e,t)=>this.emit(e,t),ttsState:this.ttsState,audioDebugger:this.audioDebugger,webrtcLipSync:this.webrtcLipSync,stop:()=>this.stop(),finalizeTTSPlayback:()=>this.finalizeTTSPlayback(),playIdleAnimation:()=>this.playIdleAnimation(),flushPendingASRIfReady:e=>this.flushPendingASRIfReady(e),getVoiceInteractionState:()=>this.voiceInteractionState}),"render-only"===this.mode||this.initGatewayService().catch((e=>{console.error("[Human] Failed to initialize Gateway service:",e),this.emit(ds.HUMAN_ERROR,{code:"GATEWAY_INIT_ERROR",msg:"Failed to initialize Gateway service",details:hc(e)})}))}mergeConfig(e){const t={token:e.token,container:"",characterId:"",audio:{volume:1},render:{fps:30,quality:"medium"},iosAudioMode:"baseline",server:{api:process.env.ROLLUP_BASE_API,wss:process.env.ROLLUP_WSS_URL,gateway:process.env.ROLLUP_WSS_URL},questionApiParams:{model:"quan",stream:!1,sentence:!0,max_tokens:256,temperature:.95,sse:!0},text2SpeachApiParams:{role:"xiaoxiao",speed:1,sn:10,model:"paddle2",viseme:"a2f",smooth_method:1,smooth_interations:5},modelConfig:{name:"quante",camera:{fov:50},orbitControls:{minPolarAngle:0,maxPolarAngle:Math.PI}},loading:"",loadingDestroy:!0,options:{fps:30},mode:"normal",voiceModeConfig:{keepActive:!1},isNotRender:!0,debug:!1,crypto:void 0};return Nu(t,e)}setupContainer(e){e?(this.container=e,this.isNotRender=!1):this.isNotRender=!0}initFramePlayer(){this.framePlayer=new qu({fps:this.config.options.fps},((e,t)=>{this.core&&this.core.playByShapes(e,t)}))}clearTTSPlaySafetyTimer(){this.ttsPlaySafetyTimer&&(clearTimeout(this.ttsPlaySafetyTimer),this.ttsPlaySafetyTimer=null)}replaceFramePlayerPlayEndHandler(e){this.framePlayerPlayEndHandler&&(this.framePlayer?.off("playend",this.framePlayerPlayEndHandler),this.framePlayerPlayEndHandler=null),e&&(this.framePlayerPlayEndHandler=e,this.framePlayer?.on("playend",e))}async initGatewayService(){try{const e=this.config.token,t=this.config.server.gateway||process.env.ROLLUP_WSS_URL||"";this.gatewayService=new Xu({url:t,token:e,iosAudioMode:this.config.iosAudioMode,autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5}),this.gatewayService.setTTSDataChannelCallback((()=>{})),this.setupGatewayEventForwarding(),await this.gatewayService.connect()}catch(e){throw console.error("[Human] Failed to initialize Gateway service:",e),e}}setupGatewayEventForwarding(){this.eventBusModule=Ku;const e=[{event:ds.GATEWAY_CONNECTED,handler:()=>{this.emit(ds.GATEWAY_CONNECTED)}},{event:ds.GATEWAY_DISCONNECTED,handler:()=>{this.emit(ds.GATEWAY_DISCONNECTED)}},{event:ds.GATEWAY_RECONNECTING,handler:()=>{this.emit(ds.GATEWAY_RECONNECTING)}},{event:ds.GATEWAY_MESSAGE,handler:e=>{if(this.emit(ds.GATEWAY_MESSAGE,e),"character_action"===e.type&&e.data){const t=e.data,i=[(t.name||"").replace(/\[#(.+)#\]/,"$1")];this.emit(ds.HUMAN_ACTION_PENDING,{actions:i,name:t.name,inputs:t.inputs||{}})}}},{event:ds.GATEWAY_ERROR,handler:e=>{this.emit(ds.HUMAN_ERROR,e)}},{event:ds.VOICE_INTERACTION_WEBRTC_STATE,handler:e=>{"ready"!==e.state?"closed"===e.state&&(this.voiceInteractionWebRTCDisabled=!0,"websocket"!==this.voiceInteractionTTSMode&&(this.voiceInteractionTTSMode="websocket")):this.voiceInteractionWebRTCDisabled||null!==this.voiceInteractionTTSMode||(this.voiceInteractionTTSMode="webrtc")}},{event:ds.WEBRTC_TTS_PLAY_START,handler:()=>{const e=this.ttsState.startPlaying();this.ttsPlaySafetyTimer&&clearTimeout(this.ttsPlaySafetyTimer),this.ttsPlaySafetyTimer=setTimeout((()=>{this.ttsState.resetIfMatch(e)&&(this.replaceFramePlayerPlayEndHandler(null),console.warn("[Human] TTS 播放安全超时,强制重置 isTTSPlaying (playId:",e,")"),this.flushPendingASRIfReady("tts-safety-timeout"),this.emit(ds.VOICE_INTERACTION_PLAY_END))}),this.voiceInteractionConfig?.ttsSafetyTimeoutMs??pf.DEFAULT_TTS_PLAY_SAFETY_TIMEOUT_MS),this.replaceFramePlayerPlayEndHandler((()=>{this.ttsState.resetIfMatch(e)&&(this.clearTTSPlaySafetyTimer(),this.ttsState.currentTTSText&&this.ttsState.addTextToHistory(this.ttsState.currentTTSText),this.flushPendingASRIfReady("frameplayer-playend")),this.replaceFramePlayerPlayEndHandler(null)})),this.isAudioDataDiscarding&&(this.isAudioDataDiscarding=!1,this.audioDiscardingTimer&&(clearTimeout(this.audioDiscardingTimer),this.audioDiscardingTimer=null)),this.isFirstUserInput=!1,this.textMergeTimer&&(clearTimeout(this.textMergeTimer),this.textMergeTimer=null,this.pendingMergeText&&(this.asrTextBuffer=[this.pendingMergeText],this.pendingASRFinal=!0,this.pendingMergeText,this.pendingMergeText=null,this.textMergeStartTime=0))}},{event:ds.WEBRTC_TTS_PLAY_END,handler:()=>{this.clearTTSPlaySafetyTimer(),this.replaceFramePlayerPlayEndHandler(null),this.ttsState.currentTTSText&&this.ttsState.addTextToHistory(this.ttsState.currentTTSText),this.ttsState.reset(),this.flushPendingASRIfReady("webrtc-tts-end")}},{event:ds.TOOL_RESULT,handler:e=>{this.emit(ds.TOOL_RESULT,e)}}];e.forEach((e=>{let{event:t,handler:i}=e;return Ku.on(t,i)})),this.eventBusHandlers=e}async refreshGatewayToken(){try{const e=await(async()=>nc.get("/human-auth/gateway/token",{}))();return 0===e.code&&e.data?(ps.setItem("apigateway-token",e.data),e.data):null}catch(e){return console.error("[Human] Failed to refresh Gateway token:",e),null}}async setCharacterData(e){const t=await(i=e,nc.get(`/human-auth/characters/${i}`,{}));var i;if(0!==t.code)throw new Error(t.msg);return this.characterData=t.data,!0}async setCharacter(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return!1;const r=t.loading||this.config.loading;if(r&&(this.loading&&this.loading.destroy(),this.loading=new i(r,this)),await this.setCharacterData(e),!this.characterData)return!1;this.config.modelConfig=this.characterData.configuration,this.config=Nu(this.config,{modelConfig:this.characterData.configuration},t);const s=af.resolveCharacter(this.characterData,this.config),a=af.toModelDescription(s);if(this.config.modelConfig.name&&"undefined"!=typeof window){const e=`__qt_human_${this.config.modelConfig.name}`;window[e]=this}this.core&&(this.core.destroy(),this.core.offAny(this.onAnyEvent),this.core=null,this.onAnyEvent=null),this.core=new n(this.container,a,this),this.onAnyEvent=(e,t)=>{this.emit(String(e),t)},this.core.onAny(this.onAnyEvent);this.characterData,this.config;const o=[...s.assets.aposes,...s.assets.animations];if(!this.isNotRender){const e=s.assets.scene;if(e?.path){const t=e.path;"glb"===e.type?hs([{bundle:t,name:e.name||"",type:"apose",enabled:!0,code:e.id||"",id:e.id||""}]).then((e=>{this.core?.changeBundle(e[0])})):"video"===e.type?this.core?.setVideoBackground(t):"picture"===e.type?this.core?.loadCubeBackground(e.pictures||[]):"background"===e.type&&"string"==typeof e.background?this.core?.setBackgroundColorOrGradient(e.background):this.core.setBackground(t)}s.behavior.animationEnabled||this.core.muteAction(!0)}return hs(o,(e=>{this.emit(ds.HUMAN_LOAD_PROGRESS,{code:"download",progress:e,total:Math.floor(.99*e)})})).then((e=>this.core.loadBundles(e,(e=>{this.emit(ds.HUMAN_LOAD_PROGRESS,{code:"loaded",progress:e,total:Math.floor(99+.01*e)})})))).then((()=>(this.status="ready",this.emit(ds.HUMAN_READY),this.loading&&this.config.loadingDestroy&&setTimeout((()=>{this.loading.destroy()}),500),this.isNotRender||t.isNotRender||this.startRender(),!0))).catch((e=>(console.error("load model error...",e),!1)))}async speak(e,t){return this.chatOrchestrator.speak(e,t)}async askCommand(e,t){return this.chatOrchestrator.askCommand(e,t)}async askStream(e,t,i){return this.chatOrchestrator.askStream(e,t,i)}async ask(e,t){return this.chatOrchestrator.ask(e,t)}async speakByAudioShapes(e,t){return this.chatOrchestrator.speakByAudioShapes(e,t)}async speakByAudioStreamShapes(e,t,i){return this.chatOrchestrator.speakByAudioStreamShapes(e,t,i)}async speakByAudio(e,t){return this.chatOrchestrator.speakByAudio(e,t)}async startVoice2Text(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:()=>{};return this.voiceToTextManager.startVoice2Text(e)}async stopVoice2Text(e){return this.voiceToTextManager.stopVoice2Text(e)}sendToolAction(e,t,i){this.gatewayService?this.gatewayService.sendToolAction(e,t,i):console.warn("[Human] Cannot send tool action: gateway not initialized")}async stop(){try{return this.chatOrchestrator.stopPlayback(),this.audio.pause(),this.emit(ds.AUDIO_PAUSE),(()=>{for(const[e,t]of Object.entries(sc))t.length>0&&(t.forEach((e=>{try{e instanceof AbortController?e.abort():"object"==typeof(t=e)&&null!==t&&"function"==typeof t.close?e.close():e.cancel("终止请求")}catch(e){console.warn(e.message)}var t})),sc[e]=[])})(),this.gatewayService&&this.gatewayService.isConnected()&&this.gatewayService.sendInterrupt(),this.finalizeTTSPlayback(),this.gatewayService?.sendTTSPlaybackState("playback_ended"),this.framePlayer&&await this.framePlayer.clear(),this.status="ready",!0}catch(e){return console.error("[Human] stop error:",e),this.emit(ds.HUMAN_ERROR,{code:"STOP_ERROR",msg:"Failed to stop",details:hc(e)}),!1}}async stopPlayback(){this.finalizeTTSPlayback(),this.gatewayService?.sendTTSPlaybackState("playback_ended"),this.flushPendingASRIfReady("stop-playback"),this.audio.pause(),this.chatOrchestrator.stopPlayback(),this.emit(ds.AUDIO_PAUSE),this.framePlayer&&await this.framePlayer.clear()}getStatus(){return this.status}initStorage(){ps.setItem(ms,this.config.token),ps.setItem("wss-url",this.config.server.wss),ps.setItem(gs,this.config.server.api),nc.setConfig({baseURL:this.config.server.api})}muteAudio(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];try{pc.MUTED=e,this.audio.mute(e),this.chatOrchestrator.muteAllAudio(e)}catch(e){console.error("[Human] muteAudio error:",e),this.emit(ds.HUMAN_ERROR,{code:"MUTE_AUDIO_ERROR",msg:"Failed to mute/unmute audio",details:hc(e)})}}muteAction(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];try{if(!this.core)return void console.warn("[Human] Core is not initialized, cannot mute action");this.core.muteAction(e)}catch(e){console.error("[Human] muteAction error:",e),this.emit(ds.HUMAN_ERROR,{code:"MUTE_ACTION_ERROR",msg:"Failed to mute/unmute action",details:hc(e)})}}dealVoice2Text(e){this.voiceToTextManager.dealVoice2Text(e)}async enableAudio(){this.framePlayer&&await this.framePlayer.enableAudio()}enableAudioDebug(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.audioDebugger.enableAudioDebug(e)}getDebugAudioInfo(){return this.audioDebugger.getDebugAudioInfo()}downloadDebugAudio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"debug_audio";this.audioDebugger.downloadDebugAudio(e)}async playDebugAudio(e){return this.audioDebugger.playDebugAudio(e)}async playDebugAudio2(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.audioDebugger.playDebugAudio2(e,t)}playIdleAnimation(){this.core?.playAction("idle",{loop:pf.IDLE_LOOP_MODE,repetitions:Number.MAX_SAFE_INTEGER})}finalizeTTSPlayback(){this.ttsState.reset(),this.core?.stopServerShapes(),this.playIdleAnimation()}async destroy(){if(!this._destroyed){this._destroyed=!0;try{if(this.degradedNotice?.destroy(),"closed"!==this.voiceInteractionState&&await this.closeVoiceInteraction(),await this.stop(),this.audioDiscardingTimer&&(clearTimeout(this.audioDiscardingTimer),this.audioDiscardingTimer=null),this.voiceInteractionExitTimer&&(clearTimeout(this.voiceInteractionExitTimer),this.voiceInteractionExitTimer=null),this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null),this.textMergeTimer&&(clearTimeout(this.textMergeTimer),this.textMergeTimer=null),this.clearTTSPlaySafetyTimer(),this.replaceFramePlayerPlayEndHandler(null),this.eventBusModule&&this.eventBusHandlers.length>0&&(this.eventBusHandlers.forEach((e=>{let{event:t,handler:i}=e;this.eventBusModule.off(t,i)})),this.eventBusHandlers=[],this.eventBusModule=null),this.config?.modelConfig?.name&&"undefined"!=typeof window){const e=`__qt_human_${this.config.modelConfig.name}`;window[e]=null}this.recorder&&(this.recorderMessageHandler&&this.recorder.off("message",this.recorderMessageHandler),this.recorder.destroy(),this.recorder=null,this.recorderMessageHandler=null),this.core&&(this.onAnyEvent&&(this.core.offAny(this.onAnyEvent),this.onAnyEvent=null),this.core.destroy(),this.core=null),this.gatewayService&&(this.gatewayService.destroy(),this.gatewayService=null),this.framePlayer&&(await this.framePlayer.clear(),this.framePlayer=null),this.audioDebugger.destroy(),this.webrtcLipSync.destroy(),this.ttsState.destroy(),this.voiceToTextManager.destroy(),this.chatOrchestrator.destroy(),this.camera&&(this.camera.destroy(),this.camera=null),this.loading&&(this.loading.destroy(),this.loading=void 0),this.characterData=null,this.voiceInteractionConfig=null,this.voiceInteractionState="closed",this.voiceInteractionConversationId="",this.status="init"}catch(e){console.error("[Human] destroy error:",e),this.emit(ds.HUMAN_ERROR,{code:"DESTROY_ERROR",msg:"Failed to destroy instance",details:hc(e)})}}}async refreshAuthToken(e){if(!e)throw new Error("Token cannot be empty");if(this.config.token=e,ps.setItem(ms,e),this.degradedNotice?.syncWithToken(e),!this.gatewayService)return void console.warn("[Human] refreshAuthToken called before gatewayService init");let t=null;try{t=await this.refreshGatewayToken()}catch(e){console.warn("[Human] refreshGatewayToken threw; falling back to raw token for gateway reauth:",e)}const i=t||e;t||console.warn("[Human] refreshGatewayToken returned empty; using raw token for gateway reauth (public-page scenario?)"),await this.gatewayService.refreshAuthToken(i)}updateToken(e){this.updateTokenWarnedOnce||(this.updateTokenWarnedOnce=!0,console.warn("[Human] updateToken() is deprecated; use refreshAuthToken() which triggers same-connection reauth.")),this.refreshAuthToken(e).catch((e=>{console.error("[Human] updateToken shim: refreshAuthToken rejected:",e),this.emit(ds.HUMAN_ERROR,{code:"UPDATE_TOKEN_ERROR",msg:"Failed to update token",details:hc(e)})}))}setAngleView(e){let{camera:t}=e;this.core&&t&&this.core.setAngleView({camera:t})}playAction(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.core&&this.core.playAction(e,t),Promise.resolve()}getModelInfo(){return this.core?this.core.getModelInfo():null}async createVoiceConversation(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!this.gatewayService||!this.gatewayService.isConnected())throw new Error("[Human] createVoiceConversation 须在 Gateway 连接后调用(等待 HUMAN_READY)");if(!this.framePlayer)throw new Error("[Human] createVoiceConversation 须在 framePlayer 就绪后调用(等待 HUMAN_READY)");const t=e.characterId||this.characterData?.id;if(!t)throw new Error("[Human] createVoiceConversation 须先 setCharacter,或在 config.characterId 显式传入形象 ID");const{VoiceConversation:i}=await Promise.resolve().then((function(){return Bf}));return new i({...e,gateway:this.gatewayService,renderer:this.core,framePlayer:this.framePlayer,characterId:t})}async openVoiceInteraction(e){if(!this.gatewayService||!this.gatewayService.isConnected())return this.emit(ds.HUMAN_ERROR,{code:"GATEWAY_NOT_CONNECTED",msg:"Gateway service is not connected"}),Promise.reject(new Error("Gateway service is not connected"));if(!this.characterData)return this.emit(ds.HUMAN_ERROR,{code:"CHARACTER_NOT_LOADED",msg:"Character data is not loaded"}),Promise.reject(new Error("Character data is not loaded"));if(this.voiceInteractionConfig={wakeWords:e.wakeWords||[],exitWords:e.exitWords||[],interruptWords:e.interruptWords||[],sampleRate:e.sampleRate||24e3,exitTime:e.exitTime||3e4,keepActive:e.keepActive||!1,autoAsk:!1!==e.autoAsk,silenceTimeout:e.silenceTimeout||1500,a2fEnabled:!1!==e.a2fEnabled,doubleWakeWord:e.doubleWakeWord??!1,wakeConfirmText:e.wakeConfirmText,syntheticTexts:e.syntheticTexts||[],continuousWindowMs:e.continuousWindowMs,gracefulExitPrompt:e.gracefulExitPrompt,gracefulExitEnabled:e.gracefulExitEnabled??!1,bargeInStrictMode:e.bargeInStrictMode??!1,bargeInCooldownMs:e.bargeInCooldownMs,llmTimeoutMs:e.llmTimeoutMs,llmMaxRetry:e.llmMaxRetry,webrtcReconnectInterval:e.webrtcReconnectInterval,webrtcMaxReconnectAttempts:e.webrtcMaxReconnectAttempts,vadGateWindowMs:e.vadGateWindowMs,vadGraceMs:e.vadGraceMs,interruptFollowUpWindowMs:e.interruptFollowUpWindowMs,gracefulExitPhase2Prompt:e.gracefulExitPhase2Prompt,gracefulExitPhase2Silence:e.gracefulExitPhase2Silence,gracefulExitPhase3Silence:e.gracefulExitPhase3Silence,interruptWordFilterMs:e.interruptWordFilterMs,welcomeAsrResumeDelayMs:e.welcomeAsrResumeDelayMs,voiceAskTimeout:e.voiceAskTimeout,ttsSafetyTimeoutMs:e.ttsSafetyTimeoutMs},this.voiceInteractionState=this.voiceInteractionConfig.keepActive?"active":"sleeping",this.voiceInteractionProcessing=!1,this.voiceInteractionLastText="",this.voiceInteractionLastTextTime=0,this.ttsState.clearCurrentText(),this.ttsState.reset(),this.gatewayService&&this.gatewayService.isConnected()){const e=this.voiceInteractionConfig.wakeWords||[],t=[];for(const i of e){if(pf.GREETING_ONLY_WORDS.includes(i.toLowerCase())){t.push(i);continue}const e=pf.generateNameVariants(i);if(t.push(...e),this.voiceInteractionConfig.doubleWakeWord)for(const i of e)for(const n of e)t.push(i+n)}const i=this.voiceInteractionConfig.interruptWords||[];t.push(...i);const n=[...new Set(t)],r=[...new Set([this.voiceInteractionConfig.wakeConfirmText,this.voiceInteractionConfig.gracefulExitPrompt,...this.voiceInteractionConfig.syntheticTexts||[]].filter((e=>"string"==typeof e&&e.trim().length>0)).map((e=>e.trim())))];this.gatewayService.sendVoiceInteractionConfig({wakeWords:n,syntheticTexts:r}),n.length}try{return await this.createVoiceInteractionWebRTC(),this.emit(ds.VOICE_INTERACTION_OPENED,{state:this.voiceInteractionState,config:this.voiceInteractionConfig}),this.voiceInteractionState,this.voiceInteractionTTSMode=null,this.voiceInteractionWebRTCDisabled=!1,!0}catch(e){return console.error("[Human] Failed to open voice interaction:",e),this.emit(ds.HUMAN_ERROR,{code:"VOICE_INTERACTION_OPEN_ERROR",msg:"Failed to open voice interaction",details:hc(e)}),!1}}async closeVoiceInteraction(){try{return this.voiceInteractionExitTimer&&(clearTimeout(this.voiceInteractionExitTimer),this.voiceInteractionExitTimer=null),this.secondExitTimer&&(clearTimeout(this.secondExitTimer),this.secondExitTimer=null),this.exitPromptFired=!1,this.exitTimerTurnId++,this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null),this.asrTextBuffer=[],this.pendingASRFinal=!1,this.voiceInteractionTTSMode=null,this.voiceInteractionWebRTCDisabled=!1,this.textMergeTimer&&(clearTimeout(this.textMergeTimer),this.textMergeTimer=null),this.pendingMergeText=null,this.textMergeStartTime=0,this.clearTTSPlaySafetyTimer(),this.replaceFramePlayerPlayEndHandler(null),this.isFirstUserInput=!0,this.gatewayService&&this.gatewayService.closeWebRTCConnection(),this.voiceInteractionState="closed",this.voiceInteractionConfig=null,this.emit(ds.VOICE_INTERACTION_CLOSED),!0}catch(e){return console.error("[Human] Failed to close voice interaction:",e),this.emit(ds.HUMAN_ERROR,{code:"VOICE_INTERACTION_CLOSE_ERROR",msg:"Failed to close voice interaction",details:hc(e)}),!1}}wakeVoiceInteraction(){"sleeping"===this.voiceInteractionState?this.handleVoiceInteractionWakeup():this.voiceInteractionState}sleepVoiceInteraction(){"active"===this.voiceInteractionState?this.handleVoiceInteractionSleep():this.voiceInteractionState}async createVoiceInteractionWebRTC(){this.emit(ds.VOICE_INTERACTION_AUDIO_START);const e=await this.gatewayService.createWebRTCConnection((e=>{this.handleVoiceInteractionASR(e)}));e.addEventListener("connectionstatechange",(()=>{const t=e.connectionState;this.emit(ds.VOICE_INTERACTION_WEBRTC_STATE,{state:t}),"failed"!==t&&"disconnected"!==t||this.emit(ds.HUMAN_ERROR,{code:"WEBRTC_CONNECTION_FAILED",msg:"WebRTC connection failed or disconnected"})}))}handleVoiceInteractionASR(e){const{text:t,isFinal:i}=e;if(this.bargeInInProgress)return;this.asrTextBuffer.length,this.ttsState.isTTSPlaying,this.voiceInteractionProcessing;const n=Date.now();if(this.ttsState.isTTSPlaying){if(!t||!t.trim())return;const e=t.trim(),i=this.voiceInteractionConfig,r=i?.wakeWords||[],s=i?.interruptWords||[],a=r.filter((e=>!pf.GREETING_ONLY_WORDS.includes(e.toLowerCase()))).flatMap((e=>pf.generateNameVariants(e))),o=[...a,...s];this.voiceInteractionProcessing;if(o.some((t=>t&&e.toLowerCase().includes(t.toLowerCase())))){n-this.lastBargeInTime<pf.BARGE_IN_COOLDOWN_MS||(this.bargeInInProgress=!0,this.triggerBargeIn(e))}}else t&&t.trim()?(this.asrTextBuffer.push(t.trim()),this.asrTextBuffer,this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null),i?this.processCompleteASRText():this.asrSilenceTimer=setTimeout((()=>{this.processCompleteASRText()}),pf.ASR_SILENCE_TIMEOUT_MS)):i&&this.asrTextBuffer.length>0&&this.processCompleteASRText()}flushPendingASRIfReady(e){if(this.ttsState.isTTSPlaying)return;if(!this.pendingASRFinal)return;if(0===this.asrTextBuffer.length)return void(this.pendingASRFinal=!1);this.asrTextBuffer.length,this.pendingASRFinal=!1,this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null);const t=this.asrTextBuffer.join("");this.asrTextBuffer=[],t.trim()&&(this.isNoiseText(t)||this.sendTextToProcess(t))}processCompleteASRText(){this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null),this.pendingASRFinal=!1;const e=this.asrTextBuffer.join("");if(this.asrTextBuffer=[],e.trim()&&!this.isNoiseText(e)){if(this.isFirstUserInput&&!this.ttsState.isTTSPlaying&&"active"===this.voiceInteractionState){this.pendingMergeText=(this.pendingMergeText||"")+e,this.textMergeTimer&&clearTimeout(this.textMergeTimer),this.textMergeStartTime||(this.textMergeStartTime=Date.now());const t=Date.now()-this.textMergeStartTime;return t>=pf.TEXT_MERGE_MAX_DELAY_MS?void this.flushMergedText():(this.pendingMergeText,pf.TEXT_MERGE_MAX_DELAY_MS,void(this.textMergeTimer=setTimeout((()=>{this.flushMergedText()}),pf.TEXT_MERGE_DELAY_MS)))}this.sendTextToProcess(e)}}flushMergedText(){this.textMergeTimer&&(clearTimeout(this.textMergeTimer),this.textMergeTimer=null);const e=this.textMergeStartTime?Date.now()-this.textMergeStartTime:0,t=e>=pf.TEXT_MERGE_MAX_DELAY_MS;if(this.asrTextBuffer.length>0&&!t)return this.asrTextBuffer.length,pf.TEXT_MERGE_MAX_DELAY_MS,void(this.textMergeTimer=setTimeout((()=>{this.flushMergedText()}),pf.TEXT_MERGE_DELAY_MS));if(this.asrTextBuffer.length>0){const e=this.asrTextBuffer.join("");this.asrTextBuffer=[],this.pendingMergeText=(this.pendingMergeText||"")+e}this.pendingMergeText&&(this.pendingMergeText,this.sendTextToProcess(this.pendingMergeText),this.pendingMergeText=null),this.textMergeStartTime=0}sendTextToProcess(e){const t=this.voiceInteractionConfig;if(t)if("sleeping"!==this.voiceInteractionState){if("active"===this.voiceInteractionState){if(!t.keepActive&&this.checkKeywords(e,t.exitWords||[]))return void this.handleVoiceInteractionSleep();if(this.resetVoiceInteractionExitTimer(),this.emit(ds.VOICE2TEXT,{text:e,isFinal:!0}),t.autoAsk&&e.trim()){if(this.voiceInteractionProcessing)return;const i=Date.now()-this.voiceInteractionLastTextTime;if(e.trim()===this.voiceInteractionLastText&&i<pf.DUPLICATE_TEXT_WINDOW_MS)return void pf.DUPLICATE_TEXT_WINDOW_MS;const n=t.wakeWords||[],r=t.interruptWords||[],s=[...n.flatMap((e=>pf.generateNameVariants(e))),...r];let a=e.trim();for(const e of s){const t=new RegExp(`^${oc(e)}[,,。??!!]?\\s*`,"gi");a=a.replace(t,"").trim()}const o=/[\u4e00-\u9fa5a-zA-Z0-9]/.test(a)?a:e.trim();if(o){this.voiceInteractionLastText=e.trim(),this.voiceInteractionLastTextTime=Date.now(),this.voiceInteractionProcessing=!0;const t=this.handleVoiceInteractionAsk(o),i=this.voiceInteractionAskId;t.finally((()=>{i===this.voiceInteractionAskId&&(this.voiceInteractionProcessing=!1)}))}}}}else{const i=t.doubleWakeWord??!1;let n;if(n=i?this.isDoubleWakeWord(e,t.wakeWords||[]):this.checkKeywords(e,t.wakeWords||[]),n){const i=t.wakeConfirmText;if(i)this.handleVoiceInteractionWakeup(!0),this.emit(ds.VOICE_INTERACTION_WAKE_CONFIRM,{text:i}),this.speakDirect(i).then((()=>{"active"===this.voiceInteractionState&&this.resetVoiceInteractionExitTimer()})).catch((e=>{console.warn("[Human] Wake confirm TTS failed:",e),"active"===this.voiceInteractionState&&this.resetVoiceInteractionExitTimer()}));else if(this.handleVoiceInteractionWakeup(),t.autoAsk){this.emit(ds.VOICE2TEXT,{text:e,isFinal:!0}),this.voiceInteractionProcessing=!0,this.voiceInteractionLastText=e.trim(),this.voiceInteractionLastTextTime=Date.now();const t=this.handleVoiceInteractionAsk(e),i=this.voiceInteractionAskId;t.finally((()=>{i===this.voiceInteractionAskId&&(this.voiceInteractionProcessing=!1)}))}return}t.wakeWords}else this.emit(ds.VOICE2TEXT,{text:e,isFinal:!0})}checkKeywords(e,t){if(!t||0===t.length)return!1;const i=e.toLowerCase();return t.some((e=>i.includes(e.toLowerCase())))}containsInterruptIntent(e){if(!e)return!1;const t=e.toLowerCase();return pf.INTERRUPT_INTENT_WORDS.some((e=>t.includes(e.toLowerCase())))}async triggerBargeIn(e){const t=Date.now();if(t-this.lastBargeInTime<pf.BARGE_IN_COOLDOWN_MS)this.bargeInInProgress=!1;else try{if(this.lastBargeInTime=t,++this.voiceInteractionAskId,this.voiceInteractionAskId,this.isAudioDataDiscarding=!0,this.audioDiscardingTimer&&clearTimeout(this.audioDiscardingTimer),this.audioDiscardingTimer=setTimeout((()=>{this.isAudioDataDiscarding&&(this.isAudioDataDiscarding=!1)}),pf.AUDIO_DISCARDING_TIMEOUT_MS),await this.stopPlayback(),this.gatewayService&&this.gatewayService.isConnected()&&this.gatewayService.sendInterrupt(),this.asrTextBuffer=[],this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null),this.pendingASRFinal=!1,this.voiceInteractionProcessing=!1,this.textMergeTimer&&(clearTimeout(this.textMergeTimer),this.textMergeTimer=null),this.pendingMergeText=null,this.textMergeStartTime=0,this.emit(ds.VOICE_INTERACTION_INTERRUPT),this.emit(ds.VOICE_INTERRUPT),this.emit(ds.VOICE_BARGE_IN,{text:e}),await new Promise((e=>setTimeout(e,150))),e.trim()){const t=this.voiceInteractionConfig,i=t?.wakeWords||[],n=t?.interruptWords||[],r=[...i.flatMap((e=>pf.generateNameVariants(e))),...n];let s=e.trim();for(const e of r){const t=new RegExp(`^${oc(e)}[,,。??!!]?\\s*`,"gi");s=s.replace(t,"").trim()}const a=/[\u4e00-\u9fa5a-zA-Z0-9]/.test(s)?s:"";if(a&&(this.voiceInteractionLastText=e.trim(),this.voiceInteractionLastTextTime=Date.now(),this.emit(ds.VOICE2TEXT,{text:a,isFinal:!0,isBargeIn:!0}),t?.autoAsk)){this.voiceInteractionProcessing=!0;const e=this.handleVoiceInteractionAsk(a),t=this.voiceInteractionAskId;e.finally((()=>{t===this.voiceInteractionAskId&&(this.voiceInteractionProcessing=!1)}))}}}finally{setTimeout((()=>{this.bargeInInProgress=!1}),100)}}isNoiseText(e){if(!e)return!0;const t=e.replace(/[,。?!、,.\?!::;;\s]/g,"").toLowerCase();if(t.length<pf.MIN_VALID_TEXT_LENGTH)return t.length,!0;const i=e.trim().replace(/[,。?!、,.\?!::;;]/g,"");return!(!pf.NOISE_WORDS.includes(i)&&!pf.NOISE_WORDS.includes(t))||!!/^(\d+|(.)\2*)$/.test(t)}handleVoiceInteractionWakeup(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.voiceInteractionState="active",this.emit(ds.VOICE_INTERACTION_WAKEUP),this.emit(ds.VOICE_WAKE),e||this.resetVoiceInteractionExitTimer()}handleVoiceInteractionSleep(){this.voiceInteractionState="sleeping",this.voiceInteractionExitTimer&&(clearTimeout(this.voiceInteractionExitTimer),this.voiceInteractionExitTimer=null),this.secondExitTimer&&(clearTimeout(this.secondExitTimer),this.secondExitTimer=null),this.exitPromptFired=!1,this.exitTimerTurnId++,this.voiceInteractionProcessing=!1,this.voiceInteractionLastText="",this.voiceInteractionLastTextTime=0,this.emit(ds.VOICE_INTERACTION_SLEEP),this.emit(ds.VOICE_SLEEP)}handleVoiceInteractionInterrupt(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.stopPlayback(),this.asrSilenceTimer&&(clearTimeout(this.asrSilenceTimer),this.asrSilenceTimer=null),e&&this.gatewayService&&this.gatewayService.isConnected()&&this.gatewayService.sendInterrupt(),e&&(this.voiceInteractionProcessing=!1),this.emit(ds.VOICE_INTERACTION_INTERRUPT),this.emit(ds.VOICE_INTERRUPT)}async handleVoiceInteractionAsk(e){if(!this.characterData)return;const t=++this.voiceInteractionAskId;let i=!1;const n=()=>{i||t!==this.voiceInteractionAskId||(i=!0,this.emit(ds.VOICE_INTERACTION_PLAY_START,{text:e}))};this.on(ds.CHAT_MESSAGE_BS_PLAY_START,n);const r=this.voiceInteractionConfig?.voiceAskTimeout??12e4;try{if(await Promise.race([this.askStream({message:[{role:"user",content:e}],conversation_id:this.voiceInteractionConversationId,inputs:{use_webrtc_tts:!1,a2f_enabled:!1!==this.voiceInteractionConfig?.a2fEnabled}},(e=>{0===e.code&&e.data&&e.data.forEach((e=>{e.conversation_id&&(this.voiceInteractionConversationId=e.conversation_id)}))}),{skipStop:!0}),new Promise(((e,t)=>setTimeout((()=>t(new Error("Voice interaction ask timeout"))),r)))]),this.off(ds.CHAT_MESSAGE_BS_PLAY_START,n),t!==this.voiceInteractionAskId)return void this.voiceInteractionAskId;this.emit(ds.VOICE_INTERACTION_PLAY_END,{text:e}),this.exitPromptFired||this.resetVoiceInteractionExitTimer(),this.isFirstUserInput=!1,this.gatewayService&&this.gatewayService.isConnected()&&this.gatewayService.sendInterrupt()}catch(i){if(this.off(ds.CHAT_MESSAGE_BS_PLAY_START,n),t!==this.voiceInteractionAskId)return void this.voiceInteractionAskId;i instanceof Error&&"Voice interaction ask timeout"===i.message?console.warn("[Human] Voice interaction ask timeout ("+r/1e3+"s)"):(console.error("[Human] Voice interaction ask error:",i),this.emit(ds.HUMAN_ERROR,{code:"VOICE_INTERACTION_ASK_ERROR",msg:"Failed to process voice interaction",details:hc(i)})),this.emit(ds.VOICE_INTERACTION_PLAY_END,{text:e}),this.exitPromptFired||this.resetVoiceInteractionExitTimer()}}resetVoiceInteractionExitTimer(){this.voiceInteractionExitTimer&&(clearTimeout(this.voiceInteractionExitTimer),this.voiceInteractionExitTimer=null),this.secondExitTimer&&(clearTimeout(this.secondExitTimer),this.secondExitTimer=null),this.exitPromptFired=!1;const e=++this.exitTimerTurnId;if(this.voiceInteractionConfig?.keepActive)return;if("active"!==this.voiceInteractionState)return;const t=this.voiceInteractionConfig,i=t?.gracefulExitEnabled??!1,n=t?.continuousWindowMs||t?.exitTime||3e4,r=t?.gracefulExitPrompt||"还有什么要问的吗?";this.voiceInteractionExitTimer=setTimeout((()=>{if(this.exitTimerTurnId===e&&"active"===this.voiceInteractionState)return this.voiceInteractionProcessing||this.ttsState.isTTSPlaying?(this.voiceInteractionProcessing,void this.ttsState.isTTSPlaying):void(i?(this.exitPromptFired=!0,this.emit(ds.VOICE_INTERACTION_EXIT_PROMPT,{text:r}),this.speakDirect(r).finally((()=>{if(this.exitTimerTurnId!==e)return;if("active"!==this.voiceInteractionState)return;this.emit(ds.VOICE_INTERACTION_POST_EXIT_IDLE),this.secondExitTimer=setTimeout((()=>{this.exitTimerTurnId===e&&this.handleVoiceInteractionSleep()}),18e4)}))):this.handleVoiceInteractionSleep())}),n)}offlineRender(e){this.core&&(this.core.destroy(),this.core.offAny(this.onAnyEvent),this.core=null,this.onAnyEvent=null);const t=af.resolveOffline(this.config.modelConfig,e,this.config),i=af.toModelDescription(t),r=[...t.assets.aposes,...t.assets.animations];this.core=new n(this.container,i,this),this.onAnyEvent=(e,t)=>{this.emit(String(e),t)},this.core.onAny(this.onAnyEvent);return hs(r,(e=>{this.emit(ds.HUMAN_LOAD_PROGRESS,{code:"download",progress:e,total:Math.floor(.99*e)})})).then((e=>this.core.loadBundles(e,(e=>{this.emit(ds.HUMAN_LOAD_PROGRESS,{code:"loaded",progress:e,total:Math.floor(99+.01*e)})})))).then((()=>(this.status="ready",this.emit(ds.HUMAN_READY),this.loading&&this.config.loadingDestroy&&setTimeout((()=>{this.loading.destroy()}),500),this.isNotRender||this.core.animate.call(this.core),!0))).catch((e=>(console.error("load model error...",e),!1)))}startRender(){return this.core?(this.core.startRender(),Promise.resolve(!0)):Promise.reject("未初始化渲染对象")}stopRender(){return this.core?(this.core.stopRender(),Promise.resolve(!0)):Promise.reject("未初始化渲染对象")}async closeRecorder(){return"voice"===this.config.mode?(console.warn("[Human] Voice mode recorder has been removed"),Promise.resolve(!0)):this.recorder?this.recorder.close().then((()=>!0)):(console.warn("[Human] Recorder is not available"),Promise.resolve(!0))}async openRecorder(){return"voice"===this.config.mode?(console.warn("[Human] Voice mode recorder has been removed"),Promise.resolve({code:-1,data:{isUserNotAllow:!1},msg:"Voice mode recorder has been removed"})):this.recorder?this.recorder.open():(console.warn("[Human] Recorder is not available"),Promise.resolve({code:-1,data:{isUserNotAllow:!1},msg:"Recorder is not available"}))}async openCamera(e){const{CameraSDK:t}=await import("./index-DKlmJp2N.js"),i=new t({facingMode:"user",features:["face","detection","expression"],...e});return this.camera=i,this.camera.open()}async startFaceRecognition(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.camera&&this.camera.isOpen()?this.camera.startFaceRecognition(e,(e=>{this.emit(ds.CAMERA_FACE_RECOGNITION_RESULT,e)})):Promise.reject("camera is null!")}async stopFaceRecognition(){return!this.camera||!this.camera.isOpen()||this.camera.stopFaceRecognition()}async startBodyDetect(){return!this.camera||!this.camera.isOpen()||this.camera.startBodyDetect((e=>{this.emit(ds.CAMERA_PERSON_TEST_RESULT,e)}))}async stopBodyDetect(){return!this.camera||!this.camera.isOpen()||this.camera.stopBodyDetect()}async startSmileDetection(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.camera&&this.camera.isOpen()?this.camera.startSmileDetection(e,(()=>{this.emit(ds.EXPRESSION_SMILE_DETECTED)}),(e=>{this.emit(ds.EXPRESSION_SMILE_STATE_CHANGED,e)})):Promise.reject("camera is null!")}stopSmileDetection(){return!this.camera||!this.camera.isOpen()||this.camera.stopSmileDetection()}closeCamera(){this.camera&&(this.camera.destroy(),this.camera=null)}}var mf;!function(e){e.IDLE="idle",e.PLAYING="playing",e.PAUSED="paused",e.STOPPED="stopped"}(mf||(mf={}));class gf{ttsTextHistory=[];currentTTSText="";lastTTSEndTime=0;static TTS_HISTORY_SIZE=5;static TTS_ECHO_COOLDOWN_MS=4e3;checkAndExtractFromEcho(e,t){const i=Date.now();if(e.replace(/[,。!?、;:""''()【】《》\s]/g,"").length<5)return{isEcho:!1,extractedText:null};if(t&&this.currentTTSText&&this.isSimilarText(e,this.currentTTSText)){return{isEcho:!0,extractedText:this.extractUserTextFromEcho(e,this.currentTTSText)}}const n=i-this.lastTTSEndTime;if(n<gf.TTS_ECHO_COOLDOWN_MS&&this.currentTTSText&&this.shouldCheckEcho(e,n)&&this.isSimilarText(e,this.currentTTSText)){return{isEcho:!0,extractedText:this.extractUserTextFromEcho(e,this.currentTTSText)}}for(const t of this.ttsTextHistory){const n=i-t.timestamp;if(n<gf.TTS_ECHO_COOLDOWN_MS&&this.shouldCheckEcho(e,n)&&this.isSimilarText(e,t.text)){return{isEcho:!0,extractedText:this.extractUserTextFromEcho(e,t.text)}}}return{isEcho:!1,extractedText:null}}isSimilarText(e,t){if(!e||!t)return!1;const i=e=>e.replace(/[,。!?、;:""''()【】《》\s]/g,"").toLowerCase(),n=i(e),r=i(t);if(n.length<5||r.length<5)return!1;if(n===r)return!0;if(r.includes(n)){if(n.length/r.length>=.3)return!0}if(n.includes(r))return!0;let s=0;for(let e=0;e<r.length;e++)n.includes(r[e])&&s++;return s/r.length>=(n.length<10?.9:.7)&&n.length>=.5*r.length}extractUserTextFromEcho(e,t){if(!e||!t)return e;const i=e=>e.replace(/[,。!?、;:""''()【】《》\s]/g,"").toLowerCase(),n=i(e),r=i(t);if(r.includes(n))return null;if(n.includes(r)){const t=n.indexOf(r),s=t+r.length;if(s<n.length){if(n.substring(s).length>=3){const t=r.substring(r.length-5);let n=-1;for(let r=e.length-1;r>=0;r--){if(i(e.substring(0,r+1)).endsWith(t)){n=r+1;break}}if(n>0&&n<e.length){const t=e.substring(n).trim();if(t.length>=3)return t}}}if(t>0){if(n.substring(0,t).length>=3)return null}}return null}isTextSimilarToTTS(e){if(!this.currentTTSText)return!1;const t=e.replace(/[,。!?、;:""''()【】《》\s]/g,"").toLowerCase(),i=this.currentTTSText.replace(/[,。!?、;:""''()【】《》\s]/g,"").toLowerCase();if(i.includes(t)&&t.length>=2)return!0;if(t.length>=4){let e=0;for(let n=0;n<t.length-1;n++){const r=t.substring(n,n+2);i.includes(r)&&e++}const n=e/(t.length-1);if(n>.6)return(100*n).toFixed(1),!0}return!1}shouldCheckEcho(e,t){if(t<=1500)return!0;return e.replace(/[,。!?、;:""''()【】《》\s]/g,"").length>=10}addTTSToHistory(e){for(this.ttsTextHistory.push({text:e,timestamp:Date.now()});this.ttsTextHistory.length>gf.TTS_HISTORY_SIZE;)this.ttsTextHistory.shift()}setCurrentTTSText(e){this.currentTTSText=e}getCurrentTTSText(){return this.currentTTSText}markTTSEnd(){this.lastTTSEndTime=Date.now()}getLastTTSEndTime(){return this.lastTTSEndTime}reset(){this.ttsTextHistory=[],this.currentTTSText="",this.lastTTSEndTime=0}}class _f{current=null;history=[];static HISTORY_SIZE=20;start(){this.current={t1_silenceDetected:performance.now(),t2_chatRequestSent:0,t3_llmFirstChar:0,t4_ttsFirstData:0,t5_a2fFirstData:0,t6_framePlayerStart:0,t7_audioPlayStart:0}}markChatRequestSent(){this.current&&(this.current.t2_chatRequestSent=performance.now())}markLLMFirstChar(){this.current&&0===this.current.t3_llmFirstChar&&(this.current.t3_llmFirstChar=performance.now())}markTTSFirstData(){this.current&&0===this.current.t4_ttsFirstData&&(this.current.t4_ttsFirstData=performance.now())}markA2FFirstData(){this.current&&0===this.current.t5_a2fFirstData&&(this.current.t5_a2fFirstData=performance.now())}markFramePlayerStart(){this.current&&0===this.current.t6_framePlayerStart&&(this.current.t6_framePlayerStart=performance.now())}markAudioPlayStart(){this.current&&(this.current.t7_audioPlayStart=performance.now(),this.print(),this.history.push({...this.current}),this.history.length>_f.HISTORY_SIZE&&this.history.shift(),this.current=null)}reset(){this.current=null}get isActive(){return null!==this.current}getHistory(){return this.history}print(){if(!this.current)return;const e=this.current,t=e.t1_silenceDetected,i=e.t2_chatRequestSent-t,n=e.t3_llmFirstChar-e.t2_chatRequestSent,r=e.t4_ttsFirstData-e.t3_llmFirstChar,s=e.t5_a2fFirstData-e.t4_ttsFirstData,a=e.t6_framePlayerStart-e.t5_a2fFirstData,o=e.t7_audioPlayStart-e.t6_framePlayerStart,c=e.t7_audioPlayStart-t;i.toFixed(0),n.toFixed(0),r.toFixed(0),s.toFixed(0),a.toFixed(0),o.toFixed(0),c.toFixed(0)}}const yf={completeSentence:0,question:0,partial:800,shortText:1200,minCompleteSentenceLength:4,defaultTimeout:1500},Tf=/[,。!?、;:""''()【】《》\s]/g,wf=["嗯","啊","哦","噢","呃","额","嗯嗯","啊啊","哎","唉","呀","好","好的","嗯好","好嗯","是","是的","对","对的","行","行的","可以","好吧","那","那个","这","这个","喂","诶","哈","哈哈","呵","呵呵","嘿","嘿嘿","不急","知道","知道了","明白","明白了","收到","了解","等一下","稍等","来了","走了","去吧","好好","慢点","谢谢","不客气","没事","没关系","没问题","随便","说什么","干什么","怎么了","谁啊","在哪","去哪"],bf=2,Sf=new Set(["对","好","行","是","好的","可以","没错","是的","对啊","好啊","行啊","那没错","没问题","继续","继续讲","然后呢","再讲","讲下","说下","还有呢","为什么呀","真的吗","是吗","不是","不对"]),vf=new Set(["你好","您好","嗨","早上好","下午好","晚上好","你好呀","你好啊","你好哇","晚安","拜拜","再见","拜","晚安啦","晚安了","拜拜啦","再见啦","帮我","来吧","开始","停止","暂停"]),Af=new Set(["我要","就是","那个","那么","然后","然后让","嗯后","嗯呢","那个呢","这个呢","一会","一会儿"]),Ef=[/^那个.{0,2}$/,/^这个.{0,2}$/,/^就是.{0,2}$/,/^然后.{0,2}$/,/^我要.{0,2}$/,/^一会.{0,2}$/];function Rf(e){return e.replace(Tf,"")}function kf(e){const t=Rf(e);return t.length<2||!(!wf.includes(e)&&!wf.includes(t))}function xf(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(Lf(e,t))return!0;const n=Rf(e);return!!vf.has(n)||(n.length>=4||!(!i.allowShortFollowUp||!Cf(e)))}function Cf(e){const t=Rf(e);return!!t&&(!!Sf.has(t)||!(t.length<bf)&&[/^继续.{0,4}$/,/^然后呢?$/,/^再(讲|说).{0,3}$/,/^讲下.{0,3}$/,/^说下.{0,3}$/,/^还有呢?$/,/^为什么呀?$/,/^真的?吗?$/,/^是吗$/,/^不是.{0,2}$/,/^不对.{0,2}$/].some((e=>e.test(t))))}function If(e){const t=Rf(e);return!t||(!!["嗯","啊","哦","噢","呃","额","哎","诶"].includes(t)||!Sf.has(t)&&(t.length<=1||(!!Af.has(t)||!!(t.length<=4&&Ef.some((e=>e.test(t)))))))}function Pf(e,t){return!(!e||!t)&&(t.includes(e)||e.includes(t))}function Df(e){if(e.endsWith("?")||e.endsWith("?"))return!0;return["什么","怎么","为什么","哪里","哪个","谁","几","多少","是不是","能不能","可不可以","会不会","有没有","吗","呢","吧"].some((t=>e.includes(t)))}function Of(e){if(0===e.length)return"";if(1===e.length)return e[0];const t=[];let i="";for(const n of e)n.trim()&&(i&&Pf(n,i)?n.length>i.length&&(t.pop(),t.push(n),i=n):(t.push(n),i=n));return t.join("")}function Lf(e,t){const i=e.toLowerCase();return t.some((e=>i.includes(e.toLowerCase())))}class Mf extends t{_config;_state="SLEEPING";_conversationId="";_isStarted=!1;isTransitioning=!1;pendingTransition=null;textBuffer=[];committedTranscript="";silenceTimer=null;idleTimer=null;currentRequestId=null;activeLLMRequestId=null;activeLLMResolve=null;activeLLMReject=null;activeLLMTimeout=null;ttsStartTime=0;lastBargeInTime=0;speakingTextBuffer="";lastUserQuery="";static CONTINUATION_WINDOW_MS=2e3;static BARGE_IN_MIN_TEXT_LENGTH=2;static DEFAULT_BARGE_IN_COOLDOWN_MS=500;static DEFAULT_WELCOME_ASR_RESUME_DELAY_MS=1200;interruptDetectionTimer=null;interruptHintTimer=null;interruptFollowUpTimer=null;welcomeAsrResumeTimer=null;interruptDetectionEnabled=!1;vadGateTimer=null;vadGateActiveUntil=0;vadGateEnabled=!1;lastVadTriggerTime=0;static DEFAULT_VAD_GATE_WINDOW_MS=2500;static VAD_DUCK_GAIN=.02;static VAD_DUCK_MS=800;static DEFAULT_VAD_GRACE_MS=4e3;static VAD_START_DELAY_MS=700;static DEFAULT_INTERRUPT_FOLLOW_UP_WINDOW_MS=6e3;static CORE_INTERRUPT_WORDS=["停一下","等一下","好了"];isPlayingWelcomeTTS=!1;currentPlaybackContext=null;allowFollowUpDuringPlayback=!1;gracefulExitFollowUpBuffer=[];isPlayingInterruptFeedback=!1;isHandlingInterrupt=!1;lastInterruptTime=0;static DEFAULT_INTERRUPT_WORD_FILTER_MS=3e3;isPlayingTTSLocked=!1;dataChannelEndTimer=null;vadStartTimer=null;webrtcReconnectAttempts=0;webrtcReconnectTimer=null;llmRetryCount=0;_isReconnecting=!1;llmRequestCancelled=!1;_asrSuspended=!1;ttsEndTimestampForASRDiag=0;static DEFAULT_MAX_WEBRTC_RECONNECT_ATTEMPTS=3;static DEFAULT_WEBRTC_RECONNECT_INTERVAL=3e3;static DEFAULT_MAX_LLM_RETRY_COUNT=2;static DEFAULT_LLM_TIMEOUT_MS=3e4;echoDetector=new gf;ttsTimeline=new _f;llmDataEnded=!1;ttsDataEnded=!1;a2fDataEnded=!1;webrtcAudioClockBound=!1;currentA2fStreamId=null;lastA2fOffset=-1;a2fOffsetBase=null;ttsPlaybackState=null;activeTTSTransport=null;llmTTSStreamPrepared=!1;static DEFAULT_WAKE_WORDS=["你好"];static DEFAULT_EXIT_WORDS=["退出","再见"];static DEFAULT_INTERRUPT_WORDS=["停","停止","停一下","暂停","打住","好了","行了","够了","算了","可以了","等","等等","等一下","等下","不对","不是","不要","不要了","不用了","不说了","别说了","不想听","闭嘴","安静","我说","我想","我要","我问","听我说","让我","跳过","换个话题","错了","重来","打断","退出","结束","关闭","取消"];static SUPPLEMENT_WORDS=["还有","还有呢","然后呢","继续","接着说","再说说","详细说说","具体说说","展开说说","比如","举个例子","什么意思","加上","另外","补充一下","顺便","对了","哦对了","还想问"];static HARD_INTERRUPT_WORDS=["停","停止","停一下","暂停","打住","好了","行了","够了","算了","可以了","等","等等","等一下","等下","不对","不是","不要","不要了","不用了","不说了","别说了","不想听","闭嘴","安静","我说","我想","我要","我问","听我说","让我","跳过","换个话题","错了","重来","打断","退出","结束","关闭","取消"];static DEFAULT_IDLE_TIMEOUT=6e4;static DEFAULT_SILENCE_TIMEOUT=1500;static DEFAULT_GRACEFUL_EXIT_PROMPT="还有什么要问的吗?";static DEFAULT_GRACEFUL_EXIT_PHASE2_PROMPT="如果没有其他问题,我先休息了哦";static DEFAULT_GRACEFUL_EXIT_PHASE2_SILENCE=6e4;static DEFAULT_GRACEFUL_EXIT_PHASE3_SILENCE=3e4;exitPromptTimer=null;isInPostExitIdle=!1;pendingPostExitIdleEmit=!1;gracefulExitGeneration=0;gracefulExitPhase=0;effectiveInterruptWords=Mf.CORE_INTERRUPT_WORDS;configuredInterruptWords=[];constructor(e){if(super(),!e.gateway)throw new Error("gateway is required");if(!e.framePlayer)throw new Error("framePlayer is required");if(!e.characterId)throw new Error("characterId is required");if(this.configuredInterruptWords=e.interruptWords||[],this._config={gateway:e.gateway,renderer:e.renderer,framePlayer:e.framePlayer,characterId:e.characterId,wakeWords:e.wakeWords||Mf.DEFAULT_WAKE_WORDS,exitWords:e.exitWords||Mf.DEFAULT_EXIT_WORDS,interruptWords:e.interruptWords||Mf.DEFAULT_INTERRUPT_WORDS,idleTimeout:e.idleTimeout??Mf.DEFAULT_IDLE_TIMEOUT,silenceTimeout:e.silenceTimeout??Mf.DEFAULT_SILENCE_TIMEOUT,autoWake:e.autoWake||!1,echoDetection:!1!==e.echoDetection,ttsTransport:e.ttsTransport??"websocket",voiceEngine:e.voiceEngine??"pipeline",bargeInSensitivity:e.bargeInSensitivity||"high",welcomeAsrResumeDelayMs:e.welcomeAsrResumeDelayMs??Mf.DEFAULT_WELCOME_ASR_RESUME_DELAY_MS,animations:{wake:e.animations?.wake,idle:e.animations?.idle||"idle",talk:e.animations?.talk||"talk"},interruptAck:e.interruptAck??"none",interruptFeedback:e.interruptFeedback??"好的",enableInterrupt:this.resolveEnableInterrupt(e.enableInterrupt),onStateChange:e.onStateChange,onTranscript:e.onTranscript,onResponse:e.onResponse,onError:e.onError,doubleWakeWord:e.doubleWakeWord??!1,wakeConfirmText:e.wakeConfirmText,syntheticTexts:(e.syntheticTexts??[]).map((e=>e.trim())).filter(Boolean),gracefulExitEnabled:e.gracefulExitEnabled??!1,gracefulExitPrompt:e.gracefulExitPrompt??Mf.DEFAULT_GRACEFUL_EXIT_PROMPT,gracefulExitPhase2Prompt:e.gracefulExitPhase2Prompt??Mf.DEFAULT_GRACEFUL_EXIT_PHASE2_PROMPT,gracefulExitPhase2Silence:e.gracefulExitPhase2Silence??Mf.DEFAULT_GRACEFUL_EXIT_PHASE2_SILENCE,gracefulExitPhase3Silence:e.gracefulExitPhase3Silence??Mf.DEFAULT_GRACEFUL_EXIT_PHASE3_SILENCE,bargeInStrictMode:e.bargeInStrictMode??!1,continuousWindowMs:e.continuousWindowMs,bargeInCooldownMs:e.bargeInCooldownMs??Mf.DEFAULT_BARGE_IN_COOLDOWN_MS,llmTimeoutMs:e.llmTimeoutMs??Mf.DEFAULT_LLM_TIMEOUT_MS,llmMaxRetry:e.llmMaxRetry??Mf.DEFAULT_MAX_LLM_RETRY_COUNT,webrtcMaxReconnectAttempts:e.webrtcMaxReconnectAttempts??Mf.DEFAULT_MAX_WEBRTC_RECONNECT_ATTEMPTS,webrtcReconnectInterval:e.webrtcReconnectInterval??Mf.DEFAULT_WEBRTC_RECONNECT_INTERVAL,vadGateWindowMs:e.vadGateWindowMs??Mf.DEFAULT_VAD_GATE_WINDOW_MS,vadGraceMs:e.vadGraceMs??Mf.DEFAULT_VAD_GRACE_MS,interruptFollowUpWindowMs:e.interruptFollowUpWindowMs??Mf.DEFAULT_INTERRUPT_FOLLOW_UP_WINDOW_MS,interruptWordFilterMs:e.interruptWordFilterMs??Mf.DEFAULT_INTERRUPT_WORD_FILTER_MS},this._config.enableInterrupt,this.handleASRResult=this.handleASRResult.bind(this),this.handleTTSPlayStart=this.handleTTSPlayStart.bind(this),this.handleTTSPlayEnd=this.handleTTSPlayEnd.bind(this),this.handleAudioPlaybackStart=this.handleAudioPlaybackStart.bind(this),this.handleGatewayDisconnect=this.handleGatewayDisconnect.bind(this),this.handleGatewayReconnecting=this.handleGatewayReconnecting.bind(this),this.handleWebRTCStateChange=this.handleWebRTCStateChange.bind(this),this.handleAnimationEnd=this.handleAnimationEnd.bind(this),this._config.bargeInStrictMode){const e=this._config.wakeWords.filter((e=>!of.includes(e.toLowerCase()))).flatMap((e=>lf(e)));this.effectiveInterruptWords=[...new Set([...e,...this.configuredInterruptWords])],this.effectiveInterruptWords.length}else this.effectiveInterruptWords=[...new Set([...Mf.CORE_INTERRUPT_WORDS,...this._config.interruptWords])]}resolveEnableInterrupt(e){return void 0===e||e}get state(){return this._state}get config(){return this._config}get coreInterruptWords(){return Mf.CORE_INTERRUPT_WORDS}get isStarted(){return this._isStarted}get isReconnecting(){return this._isReconnecting}get conversationId(){return this._conversationId}async start(){if(this._isStarted)console.warn("[VoiceConversation] Already started");else{if(this._conversationId||(this._conversationId=tf(16),this._conversationId),!this._config.gateway.isConnected())throw this.emitError({code:"GATEWAY_DISCONNECTED",message:"Gateway is not connected",recoverable:!1}),new Error("Gateway is not connected");try{await this._config.gateway.createWebRTCConnection(this.handleASRResult),this._config.gateway.setTTSDataChannelCallback((e=>{"webrtc"===this.activeTTSTransport&&(this.ttsTimeline.markTTSFirstData(),this._config.framePlayer.addBinaryAudio(e))})),this._config.framePlayer.setPlayAudioThroughAudioManager(!0),this.registerEventListeners(),this.sendExpandedWakeWords(),this._isStarted=!0,this._config.autoWake?(this.transitionTo("IDLE"),this.emit("wakeUp",{trigger:"manual"}),this._config.wakeConfirmText&&(this.emit("wakeConfirm",{text:this._config.wakeConfirmText}),await this.playTTS(this._config.wakeConfirmText,{synthetic:!0}))):this.transitionTo("SLEEPING")}catch(e){throw console.error("[VoiceConversation] Failed to start:",e),this.emitError({code:"WEBRTC_FAILED",message:"Failed to create WebRTC connection",recoverable:!0}),e}}}async stop(){this._isStarted&&(this.clearSilenceTimer(),this.clearIdleTimer(),this.clearWebRTCReconnectTimer(),this.clearInterruptTimers(),this.clearInterruptFollowUpWindow(),this.clearWelcomeAsrResumeTimer(),this.dataChannelEndTimer&&(clearTimeout(this.dataChannelEndTimer),this.dataChannelEndTimer=null),this.vadStartTimer&&(clearTimeout(this.vadStartTimer),this.vadStartTimer=null),this.interruptDetectionEnabled=!1,this.isPlayingWelcomeTTS=!1,this.currentPlaybackContext=null,this.allowFollowUpDuringPlayback=!1,this.gracefulExitFollowUpBuffer=[],this._asrSuspended=!1,this.activeTTSTransport=null,this.cancelActiveLLMRequest("Voice conversation stopped"),this.unregisterEventListeners(),this._config.gateway.setTTSDataChannelCallback(null),this._config.gateway.closeWebRTCConnection(),await this._config.framePlayer.clear(),this._config.framePlayer.setExternalAudioTimeProvider(null),this._isStarted=!1,this._state="SLEEPING",this.textBuffer=[],this._conversationId="",this.webrtcReconnectAttempts=0,this.llmRetryCount=0,this.webrtcAudioClockBound=!1,this.currentRequestId=null)}wake(){"SLEEPING"===this._state&&(this.transitionTo("IDLE"),this.emit("wakeUp",{trigger:"manual"}))}sleep(){"SLEEPING"!==this._state&&this.handleSleep()}suspendASR(){this._asrSuspended=!0}resumeASR(){this._asrSuspended=!1}async interrupt(){"SPEAKING"!==this._state&&"THINKING"!==this._state||(this.clearInterruptTimers(),this.interruptDetectionEnabled=!1,this.emit("interruptHintHide"),this.isHandlingInterrupt=!0,await this.handleInterrupt(),this.textBuffer=[],this._config.onTranscript?.("",!0),this.emit("interrupted",{text:"",feedback:""}),this.lastInterruptTime=Date.now(),this.isHandlingInterrupt=!1,this.startInterruptFollowUpWindow(),this.transitionTo("LISTENING"))}isGracefulExitPromptContext(e){return"graceful_exit_prompt"===e||"graceful_exit_phase2_prompt"===e}shouldCaptureGracefulExitFollowUp(e){if(!this.allowFollowUpDuringPlayback||!this.isGracefulExitPromptContext(this.currentPlaybackContext))return!1;return!(e.replace(/[,。!?、;:""''()【】《》\s]/g,"").length<4)&&(!kf(e)&&!If(e))}bufferGracefulExitFollowUp(e,t){0===this.gracefulExitFollowUpBuffer.length&&this.clearIdleTimer();const i=this.gracefulExitFollowUpBuffer[this.gracefulExitFollowUpBuffer.length-1];i?Pf(e,i)?e.length>=i.length&&(this.gracefulExitFollowUpBuffer[this.gracefulExitFollowUpBuffer.length-1]=e):i!==e&&this.gracefulExitFollowUpBuffer.push(e):this.gracefulExitFollowUpBuffer.push(e);const n=Of(this.gracefulExitFollowUpBuffer);this._config.onTranscript?.(n,t),this.emit("transcript",{text:n,isFinal:t})}flushGracefulExitFollowUpBuffer(){const e=Of(this.gracefulExitFollowUpBuffer);return this.gracefulExitFollowUpBuffer=[],!!e.trim()&&(this._config.onTranscript?.(e,!0),this.emit("transcript",{text:e,isFinal:!0}),this.sendToLLM(e),!0)}get isASRSuspended(){return this._asrSuspended}async sendText(e){e.trim()?("SLEEPING"===this._state&&this.wake(),"SPEAKING"!==this._state&&"THINKING"!==this._state||await this.handleInterrupt(),this.textBuffer=[],this.clearSilenceTimer(),this.emit("transcript",{text:e,isFinal:!0}),this._config.onTranscript?.(e,!0),this.sendToLLM(e)):console.warn("[VoiceConversation] sendText: empty text, ignored")}async playTTS(e,t){if(e.trim()){this.isPlayingTTSLocked&&await this.handleInterrupt();try{this.isPlayingTTSLocked=!0;const i=!!t?.allowFollowUpDuringPlayback;this.isPlayingWelcomeTTS=!i,this.currentPlaybackContext=t?.playbackContext??null,this.allowFollowUpDuringPlayback=i,this.clearWelcomeAsrResumeTimer(),this.gracefulExitFollowUpBuffer=[],i||(this.suspendASR(),this._config.gateway.muteLocalAudio());"SPEAKING"===this._state||"THINKING"===this._state&&!this.llmDataEnded?await this.handleInterrupt():this._state,this.resetDataEndedFlags(),this.webrtcAudioClockBound=!1,this.lastA2fOffset=-1,this.a2fOffsetBase=null,this.currentA2fStreamId=null,this.echoDetector.setCurrentTTSText(e),this._config.onResponse?.(e),this.emit("response",{text:e});const n=!!t?.synthetic||e.length<=24;this._config.framePlayer.prepareForNewTTS(n);const r=this.shouldUseWebRTCTTS();this.activeTTSTransport=r?"webrtc":"websocket",this._config.ttsTransport;let s=!1;this._config.gateway.sendTTS({character_id:this._config.characterId,text:e,a2f_enabled:!0,dialect:t?.dialect||"中文",use_webrtc_tts:r,...t?.synthetic?{synthetic:!0}:{}},(e=>{try{switch(e.type){case"rate":e.sampleRate&&(s=!0,e.sampleRate,this._config.framePlayer.setAudioRate(e.sampleRate));break;case"audio":e.audio&&(s=!0,this._config.framePlayer.addBinaryAudio(e.audio));break;case"a2f":if(e.blendShapes){s=!0;const t=e.audioOffset||0;this.webrtcAudioClockBound||(this.webrtcAudioClockBound=!0),this._config.framePlayer.addShapes(e.blendShapes,Math.max(0,t))}break;case"end":if(!s){e.endType;break}if("tts"===e.endType){if(this.ttsDataEnded)break;this.ttsDataEnded=!0,this.checkAllDataEnded()}else if("a2f"===e.endType){if(this.a2fDataEnded)break;this.a2fDataEnded=!0,this.checkAllDataEnded()}}}catch(e){console.error("[VoiceConversation] TTS callback error:",e),this.isPlayingTTSLocked=!1,this.isPlayingWelcomeTTS=!1,this.currentPlaybackContext=null,this.allowFollowUpDuringPlayback=!1,this.gracefulExitFollowUpBuffer=[],this.resumeASR(),this._config.gateway.unmuteLocalAudio(),this.transitionTo("IDLE")}}))}catch(e){console.error("[VoiceConversation] playTTS error:",e),this.isPlayingTTSLocked=!1,this.isPlayingWelcomeTTS=!1,this.currentPlaybackContext=null,this.allowFollowUpDuringPlayback=!1,this.gracefulExitFollowUpBuffer=[],this.resumeASR(),this._config.gateway.unmuteLocalAudio(),this.emitError({code:"TTS_FAILED",message:e.message||"TTS playback failed",recoverable:!0})}}else console.warn("[VoiceConversation] playTTS: empty text, ignored")}transitionTo(e){if(this.isTransitioning)return void(this.pendingTransition=e);const t=this._state;if(t!==e){this.isTransitioning=!0;try{this._state=e,this.syncStateToGateway(e),this._config.onStateChange?.(e,t),this.emit("stateChange",{state:e,prevState:t}),this.onEnterState(e,t)}finally{if(this.isTransitioning=!1,this.pendingTransition){const e=this.pendingTransition;this.pendingTransition=null,this.transitionTo(e)}}}}syncStateToGateway(e){this._config.gateway.isConnected()&&this._config.gateway.sendStateSync(e)}onEnterState(e,t){switch("IDLE"===e||"LISTENING"===e?this._config.gateway.startAudioLevelMonitor((e=>{this.emit("audioLevel",{level:e})})):(this._config.gateway.stopAudioLevelMonitor(),"LISTENING"!==t&&"IDLE"!==t||this.emit("audioLevel",{level:0})),e){case"SLEEPING":this.committedTranscript="",this.clearInterruptFollowUpWindow(),this.clearIdleTimer(),this.clearSilenceTimer();break;case"IDLE":this.committedTranscript="",this.clearInterruptFollowUpWindow(),this.isInPostExitIdle?this.pendingPostExitIdleEmit&&(this.pendingPostExitIdleEmit=!1,this.emit("postExitIdle")):this.resetIdleTimer(),this.speakingTextBuffer="","SLEEPING"===t&&this._config.gateway.unmuteLocalAudio(),"SLEEPING"===t&&this._config.animations.wake?(this._config.animations.wake,this._config.renderer?.playAction?.(this._config.animations.wake)):(this._config.animations.idle,this._config.renderer?.playAction?.(this._config.animations.idle,{loop:2201,repetitions:Number.MAX_SAFE_INTEGER}));break;case"LISTENING":this.clearIdleTimer(),this.speakingTextBuffer="";break;case"THINKING":this.clearInterruptFollowUpWindow();break;case"SPEAKING":this.clearInterruptFollowUpWindow(),this.ttsStartTime=Date.now()}}handleASRResult(e){const{text:t,isFinal:i}=e;if(this._asrSuspended)return;if(!t||!t.trim())return void(i&&("LISTENING"===this._state&&this.textBuffer.length>0?(this.textBuffer,this.startSilenceTimer()):"SPEAKING"===this._state&&this.speakingTextBuffer&&(this.speakingTextBuffer,this.shouldTriggerBargeIn(this.speakingTextBuffer,!0)&&(this.speakingTextBuffer,this.handleBargeIn(this.speakingTextBuffer)),this.speakingTextBuffer="")));const n=t.trim();if("SPEAKING"===this._state){if(this.interruptDetectionEnabled){const e=this.echoDetector.getCurrentTTSText();if(e&&this.echoDetector.isSimilarText(n,e));else{const e=n.replace(/[,。!?、;:""''()【】《》\s]/g,""),t=this.effectiveInterruptWords.find((t=>e.includes(t)));if(t){const e=this.matchExplicitInterruptPhrase(n),t=!!e,i=this.hasWakeWordInterrupt(n)&&!t;t||i?this.handleVoiceInterrupt(n):(!this.vadGateEnabled||this.isVadGateOpen()||this.isVadRecent())&&(this.isVadGateOpen(),this.handleVoiceInterrupt(n))}}}return void(this.shouldCaptureGracefulExitFollowUp(n)&&this.bufferGracefulExitFollowUp(n,i))}if(this.ttsEndTimestampForASRDiag>0&&n){Date.now(),this.ttsEndTimestampForASRDiag;this._state,this.ttsEndTimestampForASRDiag,this.ttsEndTimestampForASRDiag=0}const r=this.echoDetector.getLastTTSEndTime();r&&Date.now();if(this._state,!kf(n)||this.shouldAllowShortFollowUp(n)){if(this._config.echoDetection){const e=this.echoDetector.checkAndExtractFromEcho(n,this.isPlayingWelcomeTTS);if(e.isEcho)return void(e.extractedText&&(e.extractedText,this.processASRText(e.extractedText,i)))}switch("LISTENING"!==this._state&&"THINKING"!==this._state&&"IDLE"!==this._state&&this.emit("transcript",{text:n,isFinal:i}),this._state){case"SLEEPING":this.handleASRInSleeping(n);break;case"IDLE":this.handleASRInIdle(n,i);break;case"LISTENING":this.handleASRInListening(n,i);break;case"THINKING":this.handleASRInThinking(n,i)}}}processASRText(e,t){switch("LISTENING"!==this._state&&"THINKING"!==this._state&&this.emit("transcript",{text:e,isFinal:t}),this._state){case"SLEEPING":this.handleASRInSleeping(e);break;case"IDLE":this.handleASRInIdle(e,t);break;case"LISTENING":this.handleASRInListening(e,t);break;case"THINKING":this.handleASRInThinking(e,t)}}clearTranscriptDisplay(){this.emit("transcript",{text:"",isFinal:!1}),this._config.onTranscript?.("",!1)}async handleASRInSleeping(e){const t=this._config.wakeWords;let i;if(this._config.doubleWakeWord)df(e,t)&&(i=t.find((e=>!of.includes(e.toLowerCase())))||t[0]);else{const n=e.toLowerCase();for(const e of t){if(lf(e).find((e=>n.includes(e.toLowerCase())))){i=e;break}}}i&&(this._config.doubleWakeWord,this.transitionTo("IDLE"),this.emit("wakeUp",{trigger:"word",word:i}),this._config.wakeConfirmText&&(this.emit("wakeConfirm",{text:this._config.wakeConfirmText}),await this.playTTS(this._config.wakeConfirmText,{synthetic:!0})))}_isSameUtterance(e,t){if(!e||!t)return!1;if(e.includes(t)||t.includes(e))return!0;const i=Math.min(e.length,t.length);let n=0;for(let r=0;r<i&&e[r]===t[r];r++)n++;return n>=.5*i}_isWakeWordOnly(e){let t=e;const i=[",","。","!","?","、",";",":","“","”","‘","’","(",")","【","】","《","》",",",".","!","?",";",":"," ","\t","\n"];for(const e of i)t=t.split(e).join("");if(0===t.length)return!1;const n=this._expandedWakeWords.length>0?this._expandedWakeWords:this._config.wakeWords;for(const e of n){let n=e;for(const e of i)n=n.split(e).join("");if(!n||0===n.length)continue;let r=t;for(;r.length>0&&-1!==r.indexOf(n);)r=r.replace(n,"");if(0===r.length)return!0}return!1}handleASRInIdle(e,t){if(Lf(e,this._config.exitWords))return void this.handleSleep("word");if(!xf(e,this._config.wakeWords,{allowShortFollowUp:this.shouldAllowShortFollowUp(e)}))return void this.clearTranscriptDisplay();if(If(e)&&!this.shouldAllowShortFollowUp(e))return void this.clearTranscriptDisplay();if(this._isWakeWordOnly(e))return this.textBuffer=[],void this.transitionTo("LISTENING");const i=function(e,t){if(!e||!t||0===t.length)return e;const i=t.filter((e=>!of.includes(e.toLowerCase()))).flatMap((e=>lf(e)));if(0===i.length)return e;const n=[...i].sort(((e,t)=>t.length-e.length));let r=e;for(;;){const e=r.toLowerCase();let t=!1;for(const i of n)if(e.startsWith(i.toLowerCase())){r=r.slice(i.length).replace(uf,""),t=!0;break}if(!t)break}return r.trim()}(e,this._config.wakeWords);if(!i)return this.textBuffer=[],void this.transitionTo("LISTENING");this.textBuffer=[i],this.transitionTo("LISTENING"),this._config.onTranscript?.(i,t),this.emit("transcript",{text:i,isFinal:t}),t&&this.startSilenceTimer()}handleASRInListening(e,t){if(this._isWakeWordOnly(e))return;const i=Date.now()-this.lastInterruptTime;if(this.lastInterruptTime>0&&i<this._config.interruptWordFilterMs){const t=e.replace(/[,。!?、;:""''()【】《》\s]/g,"");if(this.effectiveInterruptWords.some((e=>t===e||t.length<=e.length+2&&t.includes(e))))return}if(this.clearInterruptFollowUpWindow(),Lf(e,this._config.exitWords))return void this.handleSleep("word");if(0===this.textBuffer.length)return this.textBuffer.push(e),void this.emit("transcript",{text:e,isFinal:t});const n=this.textBuffer[this.textBuffer.length-1];t?(n!==e&&(this._isSameUtterance(e,n)?this.textBuffer[this.textBuffer.length-1]=e:this.textBuffer.push(e)),this.startSilenceTimer()):(this.clearSilenceTimer(),n&&this._isSameUtterance(e,n)?this.textBuffer[this.textBuffer.length-1]=e:this.textBuffer.push(e));const r=this.textBuffer.join("");this._config.onTranscript?.(r,t),this.emit("transcript",{text:r,isFinal:t})}async handleASRInThinking(e,t){const i=this.committedTranscript?this.committedTranscript+e:e;if(this._config.onTranscript?.(i,t),this.emit("transcript",{text:i,isFinal:t}),Lf(e,this._config.exitWords))return await this.handleInterrupt(),void await this.handleSleep("word");if(Lf(e,this._config.interruptWords))return await this.handleInterrupt(),this.textBuffer=[e],this.transitionTo("LISTENING"),void this.startSilenceTimer();if(t){e.replace(/[,。!?、;:""''()【】《》\s]/g,"").length>=Mf.BARGE_IN_MIN_TEXT_LENGTH&&(await this.handleInterrupt(),this.textBuffer=[e],this.transitionTo("LISTENING"),this.startSilenceTimer())}}async handleVoiceInterrupt(e){this.clearInterruptTimers(),this.interruptDetectionEnabled=!1,this.emit("interruptHintHide");const t=this._config.interruptFeedback||"好的";this.isHandlingInterrupt=!0;const i="short"===this._config.interruptAck;i&&(this.isPlayingInterruptFeedback=!0),await this.handleInterrupt(),this.textBuffer=[],this._config.onTranscript?.("",!0),this.emit("interrupted",{text:e,feedback:t}),this._config.onResponse?.(""),this._config.onResponse?.(t),i&&(await this.playInterruptFeedback(t),this.isPlayingInterruptFeedback=!1),this.lastInterruptTime=Date.now(),this.isHandlingInterrupt=!1,this.startInterruptFollowUpWindow(),this.transitionTo("LISTENING")}async playInterruptFeedback(e){try{this.resetDataEndedFlags(),this._config.framePlayer.prepareForNewTTS(!0),await new Promise((t=>{const i=setTimeout((()=>{r(),t()}),5e3),n=()=>{r(),t()},r=()=>{clearTimeout(i),this._config.framePlayer.off("playend",n)};this._config.framePlayer.on("playend",n),this._config.gateway.sendTTS({character_id:this._config.characterId,text:e,a2f_enabled:!0,dialect:"中文"},(e=>{"rate"===e.type&&e.sampleRate&&this._config.framePlayer.setAudioRate(e.sampleRate)}))}))}catch(e){console.warn("[VoiceConversation] Interrupt feedback playback failed:",e)}}getBargeInThresholds(){switch(this._config.bargeInSensitivity){case"low":return{cooldownMs:1500,continuationWindowMs:5e3,minTextLength:6};case"medium":return{cooldownMs:1e3,continuationWindowMs:3e3,minTextLength:4};default:return{cooldownMs:this._config.bargeInCooldownMs,continuationWindowMs:Mf.CONTINUATION_WINDOW_MS,minTextLength:Mf.BARGE_IN_MIN_TEXT_LENGTH}}}shouldTriggerBargeIn(e,t){const i=Date.now(),n=this.getBargeInThresholds();if(i-this.lastBargeInTime<n.cooldownMs)return!1;const r=this.matchExplicitInterruptPhrase(e);return!!r}handleBargeIn(e){this.lastBargeInTime=Date.now();const t=this.classifyBargeIn(e);this.emit("bargeIn",{text:e,type:t}),this.isHandlingInterrupt=!0,this.handleBargeInTransition(e,t).catch((e=>{console.error("[VoiceConversation] Barge-in transition failed:",e),this.isHandlingInterrupt=!1,this.transitionTo("IDLE")}))}async handleBargeInTransition(e,t){try{if(await this.handleInterrupt(),"supplement"===t&&this.lastUserQuery){const t=`${this.lastUserQuery},${e}`;this.textBuffer=[t]}else this.textBuffer=[e];this.transitionTo("LISTENING"),this.startSilenceTimer()}finally{this.isHandlingInterrupt=!1}}classifyBargeIn(e){if(this.matchExplicitInterruptPhrase(e,Mf.HARD_INTERRUPT_WORDS))return"interrupt";if(Lf(e,Mf.SUPPLEMENT_WORDS))return"supplement";if(e.replace(/[,。!?、;:""''()【】《》\s]/g,"").length<=5){if(["呢","吗","吧","啊","哦","嗯"].some((t=>e.endsWith(t))))return"supplement"}return"interrupt"}async sendToLLM(e){if(!e.trim())return this.ttsTimeline.reset(),void this.transitionTo("IDLE");this.ttsTimeline.markChatRequestSent(),this.lastUserQuery=e,this.echoDetector.setCurrentTTSText(""),this.transitionTo("THINKING"),this.currentRequestId=this.generateRequestId(),this.llmRetryCount=0,this.cancelActiveLLMRequest("Superseded by new request"),await this.sendToLLMWithRetry(e)}async sendToLLMWithRetry(e){let t="",i=!1;const n=this.currentRequestId;this.llmRequestCancelled=!1;try{await new Promise(((r,s)=>{if(!n)return void s(new Error("LLM request missing id"));if(!this._config.gateway.isConnected())return void s(new Error("Gateway not connected"));this.bindActiveLLMRequest(n,r,s);const a=this.shouldUseWebRTCTTS();this.activeTTSTransport=a?"webrtc":"websocket",this.llmTTSStreamPrepared=!1,this._conversationId,this._config.ttsTransport,this._config.gateway.sendLLMChat({query:e,inputs:{character_id:this._config.characterId,chat_id:this._conversationId||void 0,tts_enabled:!0,a2f_enabled:!0,chunk_type:"stream",use_webrtc_tts:a}},(e=>{try{if(this.llmRequestCancelled)return;if(n!==this.currentRequestId)return;if("llm"===e.type&&this.clearActiveLLMTimeout(n),this.handleLLMResponse(e,(e=>{t+=e,t&&this._config.onResponse?.(t)})),"end"===e.type&&"llm"===e.endType&&!i&&(i=!0,t.length,0===t.length&&"THINKING"===this._state))return this.committedTranscript="",this.clearActiveLLMRequest(n),void this.transitionTo("IDLE");"end"===e.type&&"tts"===e.endType&&this.resolveActiveLLMRequest(n)}catch(e){console.error("[VoiceConversation] LLM callback error:",e),this.clearActiveLLMRequest(n),this.transitionTo("IDLE")}})),this.activeLLMTimeout=setTimeout((()=>{this.llmRequestCancelled=!0,s(new Error("LLM request timeout"))}),this._config.llmTimeoutMs)})),this.llmRetryCount=0}catch(t){const i=t.message;if(this.clearActiveLLMRequest(n),"LLM request cancelled"===i||"LLM request interrupted"===i||"Voice conversation stopped"===i||"Superseded by new request"===i)return;if(console.error(`[VoiceConversation] LLM error (attempt ${this.llmRetryCount+1}):`,i),this.llmRetryCount<this._config.llmMaxRetry&&this.isRetryableError(i))return this.llmRetryCount++,this.llmRetryCount,this._config.llmMaxRetry,await new Promise((e=>setTimeout(e,1e3))),this.sendToLLMWithRetry(e);this.emitError({code:i.includes("timeout")?"LLM_TIMEOUT":"LLM_ERROR",message:i,recoverable:!0}),this.transitionTo("IDLE")}}isRetryableError(e){const t=e.toLowerCase();return["timeout","network","connection","ECONNRESET","ETIMEDOUT"].some((e=>t.includes(e)))}handleLLMResponse(e,t){switch(e.type){case"llm":e.text&&this.ttsTimeline.markLLMFirstChar(),e.text&&(t(e.text),this.echoDetector.setCurrentTTSText(this.echoDetector.getCurrentTTSText()+e.text),this.emit("response",{text:e.text}));break;case"tts":e.audio&&this.ttsTimeline.markTTSFirstData(),"THINKING"!==this._state||this.llmTTSStreamPrepared||(this._config.framePlayer.prepareForNewTTS(),this.resetDataEndedFlags(),this.webrtcAudioClockBound=!1,this.lastA2fOffset=-1,this.a2fOffsetBase=null,this.currentA2fStreamId=null,this.llmTTSStreamPrepared=!0),e.sampleRate&&this._config.framePlayer.setAudioRate(e.sampleRate),e.audio&&("webrtc"===this.activeTTSTransport||this._config.framePlayer.addBinaryAudio(e.audio));break;case"a2f":if(e.blendShapes&&this.ttsTimeline.markA2FFirstData(),e.blendShapes){const t=e.streamId,i="number"==typeof e.audioOffset?e.audioOffset:0,n=this.lastA2fOffset>=0&&i<this.lastA2fOffset;(!!t&&t!==this.currentA2fStreamId||n)&&(this.currentA2fStreamId=t||null,this.lastA2fOffset=-1,this.a2fOffsetBase=null),this.lastA2fOffset=i;const r=Math.max(0,i);this.webrtcAudioClockBound||(this.webrtcAudioClockBound=!0),this._config.framePlayer.addShapes(e.blendShapes,r)}break;case"end":if("llm"===e.endType){if(this.llmDataEnded)break;this.llmDataEnded=!0;const e=this.echoDetector.getCurrentTTSText();e&&this.echoDetector.addTTSToHistory(e)}else if("tts"===e.endType){if(this.ttsDataEnded)break;this.ttsDataEnded=!0,this.checkAllDataEnded()}else if("a2f"===e.endType){if(this.a2fDataEnded)break;this.a2fDataEnded=!0,this.checkAllDataEnded()}}}checkAllDataEnded(){if(this.ttsDataEnded&&this.a2fDataEnded){if(this.dataChannelEndTimer)return;this._config.gateway.clearTTSCallback(),this.dataChannelEndTimer=setTimeout((()=>{this.dataChannelEndTimer=null,this._config.framePlayer.markAudioStreamEnded()}),100)}else this.ttsDataEnded,this.a2fDataEnded}resetDataEndedFlags(){this.llmDataEnded=!1,this.ttsDataEnded=!1,this.a2fDataEnded=!1,this.ttsPlaybackState=null,this.llmTTSStreamPrepared=!1}registerEventListeners(){this._config.framePlayer.on("bs-startplay",this.handleTTSPlayStart),this._config.framePlayer.on("playend",this.handleTTSPlayEnd),this._config.framePlayer.on("audio-playback-started",this.handleAudioPlaybackStart),Ku.on(ds.GATEWAY_DISCONNECTED,this.handleGatewayDisconnect),Ku.on(ds.GATEWAY_RECONNECTING,this.handleGatewayReconnecting),Ku.on(ds.VOICE_INTERACTION_WEBRTC_STATE,this.handleWebRTCStateChange),Ku.on(ds.GATEWAY_STATE_PUSH,this.handleGatewayStatePush),Ku.on(ds.ANIMATION_END,this.handleAnimationEnd)}unregisterEventListeners(){this._config.framePlayer.off("bs-startplay",this.handleTTSPlayStart),this._config.framePlayer.off("playend",this.handleTTSPlayEnd),this._config.framePlayer.off("audio-playback-started",this.handleAudioPlaybackStart),Ku.off(ds.GATEWAY_DISCONNECTED,this.handleGatewayDisconnect),Ku.off(ds.GATEWAY_RECONNECTING,this.handleGatewayReconnecting),Ku.off(ds.VOICE_INTERACTION_WEBRTC_STATE,this.handleWebRTCStateChange),Ku.off(ds.GATEWAY_STATE_PUSH,this.handleGatewayStatePush),Ku.off(ds.ANIMATION_END,this.handleAnimationEnd)}handleGatewayStatePush=e=>{e&&"SLEEPING"===e.state&&"SLEEPING"!==this._state&&(this.exitPromptTimer&&(clearTimeout(this.exitPromptTimer),this.exitPromptTimer=null),this.gracefulExitGeneration++,this.gracefulExitPhase=0,this.isInPostExitIdle=!1,this.pendingPostExitIdleEmit=!1,this.handleSleep("server"))};getRandomTalkAnimation(){const e=this._config.animations.talk;if(Array.isArray(e)){if(0===e.length)return"talk";return e[Math.floor(Math.random()*e.length)]}return e}handleTTSPlayStart(){if("started"===this.ttsPlaybackState)return;this.ttsTimeline.markFramePlayerStart(),this.ttsStartTime=Date.now(),this.ttsPlaybackState="started",this._config.gateway.resumeRemoteAudio(),"SPEAKING"!==this._state&&(this.transitionTo("SPEAKING"),this.emit("speaking",{text:this.isPlayingInterruptFeedback?"":this.echoDetector.getCurrentTTSText()})),this._config.gateway.sendTTSPlaybackState("playback_started",this.currentPlaybackContext??void 0);const e=this.getRandomTalkAnimation();this._config.renderer?.playAction?.(e,{loop:2201,repetitions:Number.MAX_SAFE_INTEGER}),this.isPlayingWelcomeTTS||this.allowFollowUpDuringPlayback&&this.isGracefulExitPromptContext(this.currentPlaybackContext)||this.enableInterruptDetection()}enableInterruptDetection(){if(!this._config.enableInterrupt)return;if("SPEAKING"!==this._state||"started"!==this.ttsPlaybackState)return;this.interruptDetectionEnabled=!0,this.vadGateEnabled=!0,this._config.gateway.unmuteLocalAudio(),this.vadStartTimer=setTimeout((()=>{this.vadStartTimer=null,"SPEAKING"===this._state&&this.interruptDetectionEnabled&&this._config.gateway.startVADDetection(((e,t)=>{e&&"SPEAKING"===this._state&&this.interruptDetectionEnabled&&this.handleVADDirectInterrupt()}))}),Mf.VAD_START_DELAY_MS);const e=this._config.bargeInStrictMode?[...new Set([...this._config.wakeWords.filter((e=>!of.includes(e.toLowerCase()))),...this.configuredInterruptWords])]:[...new Set([...Mf.CORE_INTERRUPT_WORDS,...this.configuredInterruptWords])];this.emit("interruptHintShow",{words:e})}async handleVADDirectInterrupt(){this.openVadGate()}openVadGate(){const e=Date.now();this.vadGateEnabled&&(this.vadGateActiveUntil>e||(this.lastVadTriggerTime=e,this.vadGateActiveUntil=e+this._config.vadGateWindowMs,this.vadGateTimer&&clearTimeout(this.vadGateTimer),this.vadGateTimer=setTimeout((()=>{this.vadGateTimer=null,this.vadGateActiveUntil=0}),this._config.vadGateWindowMs)))}isVadGateOpen(){return this.vadGateActiveUntil>Date.now()}isVadRecent(){return Date.now()-this.lastVadTriggerTime<=this._config.vadGraceMs}matchExplicitInterruptPhrase(e,t){const i=e.replace(/[,。!?、;:""''()【】《》\s]/g,"");if(!i)return null;const n=Df(e),r=this._config.bargeInStrictMode?this.configuredInterruptWords:[...this._config.interruptWords,...Mf.DEFAULT_INTERRUPT_WORDS,...Mf.CORE_INTERRUPT_WORDS],s=[...new Set((t||r).map((e=>e.replace(/[,。!?、;:""''()【】《》\s]/g,""))).filter(Boolean))].sort(((e,t)=>t.length-e.length));for(const e of s){if(i===e)return e;if(!("不是"===e||"不对"===e)||!n){if(i.startsWith(e)||i.endsWith(e))return e;if(e.length>=2&&i.includes(e)&&i.length<=e.length+4)return e}}return null}hasExplicitInterruptIntent(e){return!!this.matchExplicitInterruptPhrase(e)}hasWakeWordInterrupt(e){const t=e.replace(/[,。!?、;:""''()【】《》\s]/g,""),i=this._config.wakeWords.filter((e=>!of.includes(e.toLowerCase()))).flatMap((e=>lf(e)));return[...new Set(i)].some((e=>t.includes(e)))}clearInterruptTimers(){this.interruptDetectionTimer&&(clearTimeout(this.interruptDetectionTimer),this.interruptDetectionTimer=null),this.interruptHintTimer&&(clearTimeout(this.interruptHintTimer),this.interruptHintTimer=null),this.vadGateTimer&&(clearTimeout(this.vadGateTimer),this.vadGateTimer=null),this.vadStartTimer&&(clearTimeout(this.vadStartTimer),this.vadStartTimer=null),this.vadGateActiveUntil=0,this.vadGateEnabled=!1,this.lastVadTriggerTime=0,this._config.gateway.stopVADDetection()}startInterruptFollowUpWindow(){this.clearInterruptFollowUpWindow(),this.interruptFollowUpTimer=setTimeout((()=>{this.interruptFollowUpTimer=null,"LISTENING"===this._state&&0===this.textBuffer.length&&this.transitionTo("IDLE")}),this._config.interruptFollowUpWindowMs)}clearInterruptFollowUpWindow(){this.interruptFollowUpTimer&&(clearTimeout(this.interruptFollowUpTimer),this.interruptFollowUpTimer=null)}handleTTSPlayEnd(){if("ended"===this.ttsPlaybackState)return;this.activeTTSTransport=null,this.isPlayingTTSLocked=!1,this.echoDetector.markTTSEnd(),this.echoDetector.getLastTTSEndTime(),this.ttsEndTimestampForASRDiag=Date.now(),this.ttsEndTimestampForASRDiag,this.ttsPlaybackState="ended",this._config.gateway.sendTTSPlaybackState("playback_ended");const e=this.currentPlaybackContext,t=this.allowFollowUpDuringPlayback;if(this.currentPlaybackContext=null,this.allowFollowUpDuringPlayback=!1,this.clearInterruptTimers(),this.interruptDetectionEnabled&&(this.interruptDetectionEnabled=!1,this.emit("interruptHintHide")),this.emit("speakEnd"),this.isPlayingWelcomeTTS&&(this.isPlayingWelcomeTTS=!1,this.scheduleWelcomeASRResume()),"SPEAKING"===this._state){if(this.echoDetector.setCurrentTTSText(""),this.isHandlingInterrupt||this.isPlayingInterruptFeedback)return;if(t&&this.isGracefulExitPromptContext(e)&&this.flushGracefulExitFollowUpBuffer())return;this._asrSuspended&&(this.resumeASR(),this._config.gateway.unmuteLocalAudio()),this.transitionTo("IDLE")}}scheduleWelcomeASRResume(){this.clearWelcomeAsrResumeTimer(),this.welcomeAsrResumeTimer=setTimeout((()=>{this.welcomeAsrResumeTimer=null,this._asrSuspended&&(this.resumeASR(),this._config.gateway.unmuteLocalAudio())}),this._config.welcomeAsrResumeDelayMs)}clearWelcomeAsrResumeTimer(){this.welcomeAsrResumeTimer&&(clearTimeout(this.welcomeAsrResumeTimer),this.welcomeAsrResumeTimer=null)}handleAudioPlaybackStart(){this.ttsTimeline.markAudioPlayStart()}handleAnimationEnd(e){const t=this._config.animations.wake;t&&e.code===t&&"IDLE"===this._state&&(this._config.animations.idle,this._config.renderer?.playAction?.(this._config.animations.idle,{loop:2201,repetitions:Number.MAX_SAFE_INTEGER}))}handleGatewayDisconnect(){this.emitError({code:"GATEWAY_DISCONNECTED",message:"Gateway connection lost",recoverable:!1}),this.transitionTo("SLEEPING")}handleGatewayReconnecting(){"SPEAKING"===this._state&&this.handleInterrupt()}handleWebRTCStateChange(e){switch(e.state,e.state){case"ready":case"reconnected":this.webrtcReconnectAttempts=0,this._isReconnecting=!1,this.emit("webrtcReady"),this.sendExpandedWakeWords();break;case"disconnected":case"failed":this.attemptWebRTCReconnect();break;case"closed":this._isStarted&&!this._isReconnecting&&this.emitError({code:"WEBRTC_FAILED",message:e.reason||"WebRTC connection closed",recoverable:!0})}}async attemptWebRTCReconnect(){if(!this._isReconnecting){if(this.webrtcReconnectAttempts>=this._config.webrtcMaxReconnectAttempts)return console.error("[VoiceConversation] Max WebRTC reconnect attempts reached"),this.emitError({code:"WEBRTC_FAILED",message:"WebRTC reconnection failed after max attempts",recoverable:!1}),void this.transitionTo("SLEEPING");this._isReconnecting=!0,this.webrtcReconnectAttempts++,this.webrtcReconnectAttempts,this._config.webrtcMaxReconnectAttempts,this.webrtcReconnectTimer=setTimeout((async()=>{try{if(!this._config.gateway.isConnected())return void(this._isReconnecting=!1);await this._config.gateway.createWebRTCConnection(this.handleASRResult),this.webrtcReconnectAttempts=0,this._isReconnecting=!1}catch(e){console.error("[VoiceConversation] WebRTC reconnect failed:",e),this._isReconnecting=!1,this.attemptWebRTCReconnect()}}),this._config.webrtcReconnectInterval)}}clearWebRTCReconnectTimer(){this.webrtcReconnectTimer&&(clearTimeout(this.webrtcReconnectTimer),this.webrtcReconnectTimer=null),this._isReconnecting=!1}_expandedWakeWords=[];sendExpandedWakeWords(){if(this._config.gateway.isConnected()){const e=ff(this._config.wakeWords,{doubleWakeWord:this._config.doubleWakeWord,interruptWords:this._config.interruptWords});this._expandedWakeWords=e;const t=[...new Set([this._config.wakeConfirmText,this._config.gracefulExitPrompt,this._config.gracefulExitPhase2Prompt,...this._config.syntheticTexts].filter((e=>"string"==typeof e&&e.trim().length>0)).map((e=>e.trim())))];this._config.gateway.sendVoiceInteractionConfig({wakeWords:e,syntheticTexts:t,voiceEngine:this._config.voiceEngine,characterId:this._config.characterId})}}async handleSleep(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"manual";this.clearSilenceTimer(),this.clearIdleTimer(),this.textBuffer=[],this.isPlayingWelcomeTTS=!1,"SPEAKING"===this._state&&await this.handleInterrupt(),"server"!==e&&this._config.gateway.muteLocalAudio(),this.transitionTo("SLEEPING"),this.emit("sleep",{trigger:e})}async handleInterrupt(){this.cancelActiveLLMRequest("LLM request interrupted"),this.committedTranscript="",this.clearInterruptTimers(),this.interruptDetectionEnabled&&(this.interruptDetectionEnabled=!1,this.emit("interruptHintHide")),await this._config.framePlayer.clear(),this._config.framePlayer.setExternalAudioTimeProvider(null),this.webrtcAudioClockBound=!1,this.resetDataEndedFlags(),this._config.gateway.unmuteLocalAudio(),this._config.gateway.isConnected()&&await this._config.gateway.sendInterrupt()}shouldAllowShortFollowUp(e){if("IDLE"!==this._state)return!1;if(!Cf(e))return!1;if(this.isInPostExitIdle)return!0;const t=this.echoDetector.getLastTTSEndTime();if(!t)return!1;const i=this._config.continuousWindowMs??8e3;return Date.now()-t<=i}shouldUseWebRTCTTS(){switch(this._config.ttsTransport){case"websocket":return!1;case"webrtc":return!!this._config.gateway.isWebRTCConnected()||(console.warn("[VoiceConversation] WebRTC TTS forced but WebRTC is not connected, falling back to WebSocket TTS"),!1);default:return this._config.gateway.isWebRTCConnected()}}bindActiveLLMRequest(e,t,i){this.clearActiveLLMRequest(e),this.activeLLMRequestId=e,this.activeLLMResolve=t,this.activeLLMReject=i}clearActiveLLMTimeout(e){e&&this.activeLLMRequestId!==e||this.activeLLMTimeout&&(clearTimeout(this.activeLLMTimeout),this.activeLLMTimeout=null)}clearActiveLLMRequest(e){e&&this.activeLLMRequestId!==e||(this.clearActiveLLMTimeout(e??this.activeLLMRequestId),e&&this.activeLLMRequestId!==e||(this.activeLLMRequestId=null,this.activeLLMResolve=null,this.activeLLMReject=null))}resolveActiveLLMRequest(e){if(this.activeLLMRequestId!==e||!this.activeLLMResolve)return;const t=this.activeLLMResolve;this.clearActiveLLMRequest(e),t()}cancelActiveLLMRequest(e){if(this.llmRequestCancelled=!0,!this.activeLLMReject)return void this.clearActiveLLMRequest();const t=this.activeLLMReject,i=this.activeLLMRequestId;this.clearActiveLLMRequest(i),t(new Error(e))}startSilenceTimer(){this.clearSilenceTimer();const e=this.textBuffer.join(""),t=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:yf;if(!e||0===e.trim().length)return t.defaultTimeout;const i=e.trim(),n=Rf(i);if(Df(i))return t.question;if(n.length<t.minCompleteSentenceLength)return t.shortText;const r=i.slice(-1);return"。?!?!.".includes(r)?t.completeSentence:",、;,;".includes(r)||n.length>=10?t.partial:t.defaultTimeout}(e,{...yf,defaultTimeout:this._config.silenceTimeout});e.slice(-20),this.silenceTimer=setTimeout((()=>{this.flushTextBuffer()}),t)}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}flushTextBuffer(){this.ttsTimeline.start();const e=Of(this.textBuffer);if(this.textBuffer=[],this.committedTranscript=e,e.trim()){if(kf(e)&&!this.shouldAllowShortFollowUp(e))return this.ttsTimeline.reset(),void this.transitionTo("IDLE");if(If(e)&&!this.shouldAllowShortFollowUp(e))return this.ttsTimeline.reset(),void this.transitionTo("IDLE");if(this._isWakeWordOnly(e))return this.ttsTimeline.reset(),void this.transitionTo("IDLE");this.sendToLLM(e)}else this.ttsTimeline.reset(),this.transitionTo("IDLE")}resetIdleTimer(){this.clearIdleTimer(),this.isInPostExitIdle=!1;const e=this._config.idleTimeout;this.idleTimer=setTimeout((()=>{this._config.gracefulExitEnabled?this.handleGracefulExitPhase1():this.handleSleep("timeout")}),e)}async handleGracefulExitPhase1(){const e=++this.gracefulExitGeneration;this.gracefulExitPhase=1,await this.playTTS(this._config.gracefulExitPrompt,{synthetic:!0,playbackContext:"graceful_exit_prompt",allowFollowUpDuringPlayback:!0}),await this.waitForGracefulExitPlayEnd(),e===this.gracefulExitGeneration?(this.isInPostExitIdle=!0,this.pendingPostExitIdleEmit=!0,this.exitPromptTimer=setTimeout((()=>{this.isInPostExitIdle&&e===this.gracefulExitGeneration&&this.handleGracefulExitPhase2(e)}),this._config.gracefulExitPhase2Silence)):this.gracefulExitGeneration}async handleGracefulExitPhase2(e){this.gracefulExitPhase=2,await this.playTTS(this._config.gracefulExitPhase2Prompt,{synthetic:!0,playbackContext:"graceful_exit_phase2_prompt",allowFollowUpDuringPlayback:!0}),await this.waitForGracefulExitPlayEnd(),e===this.gracefulExitGeneration?this.exitPromptTimer=setTimeout((()=>{this.isInPostExitIdle&&e===this.gracefulExitGeneration&&(this.gracefulExitPhase=0,this.isInPostExitIdle=!1,this.handleSleep("timeout"))}),this._config.gracefulExitPhase3Silence):this.gracefulExitGeneration}waitForGracefulExitPlayEnd(){return new Promise((e=>{const t=()=>{clearTimeout(i),this._config.framePlayer.off("playend",t),e()},i=setTimeout((()=>{console.warn("[VoiceConversation] Graceful exit: playend timeout, proceeding anyway"),this._config.framePlayer.off("playend",t),e()}),3e4);this._config.framePlayer.on("playend",t)}))}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.exitPromptTimer&&(clearTimeout(this.exitPromptTimer),this.exitPromptTimer=null),this.isInPostExitIdle=!1,this.pendingPostExitIdleEmit=!1,this.gracefulExitPhase=0,this.gracefulExitGeneration++}generateRequestId(){return`vc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}emitError(e){console.error("[VoiceConversation] Error:",e),this._config.onError?.(e),this.emit("error",e)}}var Bf=Object.freeze({__proto__:null,VoiceConversation:Mf});const Nf=["停","停止","停一下","好了","不用了","可以了","stop","ok"];class Ff extends t{_config;_state="SLEEPING";_conversationId="";_isStarted=!1;isTransitioning=!1;pendingTransition=null;textBuffer=[];lastTranscript="";llmResponseText="";echoDetector=new gf;effectiveWakeWords=[];effectiveInterruptWords=[];idleTimer=null;gracefulExitPhase=0;ttsDataEnded=!1;isReceivingTTSAudio=!1;wakeTimestamp=0;ttsEndTimestamp=0;boundHandleTTSPlayStart=null;boundHandleTTSPlayEnd=null;constructor(e){if(super(),this._config={gateway:e.gateway,renderer:e.renderer,framePlayer:e.framePlayer,characterId:e.characterId,wakeWords:e.wakeWords||["你好"],exitWords:e.exitWords||["退出"],interruptWords:e.interruptWords||["停止","stop"],idleTimeout:e.idleTimeout??18e4,autoWake:e.autoWake||!1,echoDetection:!1!==e.echoDetection,doubleWakeWord:e.doubleWakeWord??!0,bargeInStrictMode:e.bargeInStrictMode??!1,continuousWindowMs:e.continuousWindowMs??8e3,gracefulExitEnabled:e.gracefulExitEnabled??!0,gracefulExitPrompt:e.gracefulExitPrompt||"还有什么要问的吗?",animations:e.animations||{idle:"idle",talk:"talk"},onStateChange:e.onStateChange,onTranscript:e.onTranscript,onResponse:e.onResponse,onError:e.onError},this.effectiveWakeWords=ff(this._config.wakeWords,{doubleWakeWord:this._config.doubleWakeWord,interruptWords:this._config.interruptWords}),this._config.bargeInStrictMode){const e=[];for(const t of this._config.wakeWords)of.includes(t.toLowerCase())||e.push(...lf(t));this.effectiveInterruptWords=[...new Set([...e,...this._config.interruptWords])]}else this.effectiveInterruptWords=[...Nf,...this._config.interruptWords]}getState(){return this._state}isStarted(){return this._isStarted}async start(){if(this._isStarted)return;this._conversationId=tf(16),this._conversationId,this._config.framePlayer.setPlayAudioThroughAudioManager(!0),this.boundHandleTTSPlayStart=()=>this.handleTTSPlayStart(),this.boundHandleTTSPlayEnd=()=>this.handleTTSPlayEnd(),this._config.framePlayer.on("bs-startplay",this.boundHandleTTSPlayStart),this._config.framePlayer.on("playend",this.boundHandleTTSPlayEnd);let e=0;this._config.gateway.setTTSDataChannelCallback((t=>{this.isReceivingTTSAudio||(this.isReceivingTTSAudio=!0,e=0,this._config.framePlayer.setAudioRate(24e3),this._config.framePlayer.prepareForNewTTS(!0)),e++,t.byteLength,this._config.framePlayer.addBinaryAudio(t)})),this._config.gateway.setLLMCallback((e=>{this.handleLLMResponse(e)}));try{await this._config.gateway.createWebRTCConnection((e=>{this.handleASRResult(e)}))}catch(e){return console.error("[VoiceConversationE2E] WebRTC failed:",e),void this.emit("error",{code:"WEBRTC_FAILED",message:e?.message||"WebRTC connection failed",recoverable:!1})}this._config.gateway.sendVoiceInteractionConfig({wakeWords:this.effectiveWakeWords,syntheticTexts:[],voiceEngine:"doubao_e2e",characterId:this._config.characterId}),this._isStarted=!0,this.transitionTo(this._config.autoWake?"IDLE":"SLEEPING"),this.emit("webrtcReady")}async stop(){this._isStarted&&(this._isStarted=!1,this.clearIdleTimer(),this.boundHandleTTSPlayStart&&this._config.framePlayer.off("bs-startplay",this.boundHandleTTSPlayStart),this.boundHandleTTSPlayEnd&&this._config.framePlayer.off("playend",this.boundHandleTTSPlayEnd),this._config.gateway.setLLMCallback(null),this._config.gateway.closeWebRTCConnection(),this.transitionTo("SLEEPING"))}destroy(){this.stop(),this.clearListeners()}wake(){"SLEEPING"===this._state&&(this.transitionTo("IDLE"),this.emit("wakeUp",{trigger:"manual"}))}sleep(){this.handleSleep("manual")}async sendText(e){console.warn("[VoiceConversationE2E] sendText not supported in E2E mode")}handleASRResult(e){if(!this._isStarted)return;const{text:t,isFinal:i}=e,n=t?.trim()||"";if(!n||!kf(n)){if(n&&this._config.echoDetection){const e="SPEAKING"===this._state,t=this.echoDetector.checkAndExtractFromEcho(n,e);if(t.isEcho&&!t.extractedText)return}switch(this._state){case"SLEEPING":this.handleASRInSleeping(n);break;case"IDLE":this.handleASRInIdle(n,i);break;case"LISTENING":this.handleASRInListening(n,i);break;case"THINKING":break;case"SPEAKING":this.handleASRInSpeaking(n)}}}handleASRInSleeping(e){if(!e)return;(this._config.doubleWakeWord?df(e,this._config.wakeWords):this.effectiveWakeWords.some((t=>e.includes(t))))&&(this.wakeTimestamp=Date.now(),this.transitionTo("IDLE"),this.emit("wakeUp",{trigger:"word",word:e}))}handleASRInIdle(e,t){if(e){if(this.wakeTimestamp&&Date.now()-this.wakeTimestamp<1e3){if(this._config.wakeWords.some((t=>e.includes(t))))return}this.ttsEndTimestamp&&Date.now()-this.ttsEndTimestamp<1500&&this.echoDetector.isTextSimilarToTTS(e)||(Lf(e,this._config.exitWords)?this.handleSleep("word"):xf(e,this._config.wakeWords)&&(this.textBuffer=[e],this.lastTranscript=e,this.transitionTo("LISTENING"),this.emit("transcript",{text:e,isFinal:!1}),this._config.onTranscript?.(e,!1),t&&this.handleListeningFinal(e)))}}handleASRInListening(e,t){e&&(this.lastTranscript=e,this.emit("transcript",{text:e,isFinal:!1}),this._config.onTranscript?.(e,!1)),t&&this.handleListeningFinal(this.lastTranscript)}handleListeningFinal(e){this.emit("transcript",{text:e,isFinal:!0}),this._config.onTranscript?.(e,!0),this.transitionTo("THINKING"),this.textBuffer=[],this.lastTranscript="",this.llmResponseText=""}handleASRInSpeaking(e){if(!e)return;this.effectiveInterruptWords.some((t=>e.toLowerCase().includes(t.toLowerCase())))&&this.handleInterrupt(e)}handleLLMResponse(e){if(this._isStarted)switch(e.type){case"llm":e.text&&(this.llmResponseText+=e.text,this.emit("response",{text:e.text}),this._config.onResponse?.(this.llmResponseText));break;case"end":"tts"===e.endType&&(this.ttsDataEnded=!0,setTimeout((()=>{this._config.framePlayer.markAudioStreamEnded()}),500)),"llm"===e.endType&&(this.llmResponseText&&this.echoDetector.addTTSToHistory(this.llmResponseText),this.llmResponseText);break;case"tts":break;case"a2f":if(e.blendShapes){const t=e.audioOffset;this._config.framePlayer.addShapes(e.blendShapes,t)}}}handleTTSPlayStart(){if(!this._isStarted)return;const e=Array.isArray(this._config.animations.talk)?this._config.animations.talk[Math.floor(Math.random()*this._config.animations.talk.length)]:this._config.animations.talk;this._config.renderer?.playAction&&this._config.renderer.playAction(e),this.transitionTo("SPEAKING"),this.emit("speaking",{text:this.llmResponseText}),this.emit("interruptHintShow",{words:this.effectiveInterruptWords.slice(0,3)})}handleTTSPlayEnd(){this._isStarted&&(this._config.renderer?.playAction&&this._config.renderer.playAction(this._config.animations.idle),this.echoDetector.markTTSEnd(),this.ttsEndTimestamp=Date.now(),this.ttsDataEnded=!1,this.isReceivingTTSAudio=!1,this.emit("speakEnd"),this.emit("interruptHintHide"),this.transitionTo("IDLE"))}handleInterrupt(e){this._config.framePlayer.clear(),this._config.gateway.sendInterrupt(),this.ttsDataEnded=!1,this.isReceivingTTSAudio=!1,this.llmResponseText="",this.emit("interrupted",{text:e,feedback:""}),this.emit("interruptHintHide"),this._config.renderer?.playAction&&this._config.renderer.playAction(this._config.animations.idle),this.transitionTo("IDLE")}handleSleep(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"manual";this.clearIdleTimer(),this.gracefulExitPhase=0,this.transitionTo("SLEEPING"),this.emit("sleep",{trigger:e})}startIdleTimer(){this.clearIdleTimer();const e=0===this.gracefulExitPhase?this._config.continuousWindowMs:this._config.idleTimeout;this.idleTimer=setTimeout((()=>{"IDLE"===this._state&&(this._config.gracefulExitEnabled&&0===this.gracefulExitPhase?(this.gracefulExitPhase=1,this.emit("postExitIdle"),this.startIdleTimer()):this.handleSleep("timeout"))}),e)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}transitionTo(e){if(this.isTransitioning)return void(this.pendingTransition=e);const t=this._state;if(t!==e&&(this.isTransitioning=!0,this._state=e,this.onEnterState(e,t),this.emit("stateChange",{state:e,prevState:t}),this._config.onStateChange?.(e,t),this._config.gateway.sendStateSync?.(e),this.isTransitioning=!1,this.pendingTransition)){const e=this.pendingTransition;this.pendingTransition=null,this.transitionTo(e)}}onEnterState(e,t){switch("IDLE"===e||"LISTENING"===e?this._config.gateway.startAudioLevelMonitor?.((e=>{this.emit("audioLevel",{level:e})})):(this._config.gateway.stopAudioLevelMonitor?.(),"LISTENING"!==t&&"IDLE"!==t||this.emit("audioLevel",{level:0})),e){case"SLEEPING":this.clearIdleTimer(),this.textBuffer=[],this.lastTranscript="",this.llmResponseText="",this.gracefulExitPhase=0,this._config.gateway.muteLocalAudio?.();break;case"IDLE":this.clearIdleTimer(),this.textBuffer=[],this.lastTranscript="",this.llmResponseText="",this._config.gateway.unmuteLocalAudio?.(),this._config.renderer?.playAction&&this._config.renderer.playAction(this._config.animations.idle),this.startIdleTimer();break;case"LISTENING":this.clearIdleTimer(),this.gracefulExitPhase=0;break;case"THINKING":case"SPEAKING":this.clearIdleTimer()}}}export{ds as E,Xu as G,pf as H,Mf as V,hr as a,Yu as b,r as c,Ff as d,lf as e,ff as f,s as g,nc as h};